three.js 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747
  1. /**
  2. * @license
  3. * Copyright 2010-2021 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 = '136dev';
  12. const MOUSE = {
  13. LEFT: 0,
  14. MIDDLE: 1,
  15. RIGHT: 2,
  16. ROTATE: 0,
  17. DOLLY: 1,
  18. PAN: 2
  19. };
  20. const TOUCH = {
  21. ROTATE: 0,
  22. PAN: 1,
  23. DOLLY_PAN: 2,
  24. DOLLY_ROTATE: 3
  25. };
  26. const CullFaceNone = 0;
  27. const CullFaceBack = 1;
  28. const CullFaceFront = 2;
  29. const CullFaceFrontBack = 3;
  30. const BasicShadowMap = 0;
  31. const PCFShadowMap = 1;
  32. const PCFSoftShadowMap = 2;
  33. const VSMShadowMap = 3;
  34. const FrontSide = 0;
  35. const BackSide = 1;
  36. const DoubleSide = 2;
  37. const FlatShading = 1;
  38. const SmoothShading = 2;
  39. const NoBlending = 0;
  40. const NormalBlending = 1;
  41. const AdditiveBlending = 2;
  42. const SubtractiveBlending = 3;
  43. const MultiplyBlending = 4;
  44. const CustomBlending = 5;
  45. const AddEquation = 100;
  46. const SubtractEquation = 101;
  47. const ReverseSubtractEquation = 102;
  48. const MinEquation = 103;
  49. const MaxEquation = 104;
  50. const ZeroFactor = 200;
  51. const OneFactor = 201;
  52. const SrcColorFactor = 202;
  53. const OneMinusSrcColorFactor = 203;
  54. const SrcAlphaFactor = 204;
  55. const OneMinusSrcAlphaFactor = 205;
  56. const DstAlphaFactor = 206;
  57. const OneMinusDstAlphaFactor = 207;
  58. const DstColorFactor = 208;
  59. const OneMinusDstColorFactor = 209;
  60. const SrcAlphaSaturateFactor = 210;
  61. const NeverDepth = 0;
  62. const AlwaysDepth = 1;
  63. const LessDepth = 2;
  64. const LessEqualDepth = 3;
  65. const EqualDepth = 4;
  66. const GreaterEqualDepth = 5;
  67. const GreaterDepth = 6;
  68. const NotEqualDepth = 7;
  69. const MultiplyOperation = 0;
  70. const MixOperation = 1;
  71. const AddOperation = 2;
  72. const NoToneMapping = 0;
  73. const LinearToneMapping = 1;
  74. const ReinhardToneMapping = 2;
  75. const CineonToneMapping = 3;
  76. const ACESFilmicToneMapping = 4;
  77. const CustomToneMapping = 5;
  78. const UVMapping = 300;
  79. const CubeReflectionMapping = 301;
  80. const CubeRefractionMapping = 302;
  81. const EquirectangularReflectionMapping = 303;
  82. const EquirectangularRefractionMapping = 304;
  83. const CubeUVReflectionMapping = 306;
  84. const CubeUVRefractionMapping = 307;
  85. const RepeatWrapping = 1000;
  86. const ClampToEdgeWrapping = 1001;
  87. const MirroredRepeatWrapping = 1002;
  88. const NearestFilter = 1003;
  89. const NearestMipmapNearestFilter = 1004;
  90. const NearestMipMapNearestFilter = 1004;
  91. const NearestMipmapLinearFilter = 1005;
  92. const NearestMipMapLinearFilter = 1005;
  93. const LinearFilter = 1006;
  94. const LinearMipmapNearestFilter = 1007;
  95. const LinearMipMapNearestFilter = 1007;
  96. const LinearMipmapLinearFilter = 1008;
  97. const LinearMipMapLinearFilter = 1008;
  98. const UnsignedByteType = 1009;
  99. const ByteType = 1010;
  100. const ShortType = 1011;
  101. const UnsignedShortType = 1012;
  102. const IntType = 1013;
  103. const UnsignedIntType = 1014;
  104. const FloatType = 1015;
  105. const HalfFloatType = 1016;
  106. const UnsignedShort4444Type = 1017;
  107. const UnsignedShort5551Type = 1018;
  108. const UnsignedShort565Type = 1019;
  109. const UnsignedInt248Type = 1020;
  110. const AlphaFormat = 1021;
  111. const RGBFormat = 1022;
  112. const RGBAFormat = 1023;
  113. const LuminanceFormat = 1024;
  114. const LuminanceAlphaFormat = 1025;
  115. const RGBEFormat = RGBAFormat;
  116. const DepthFormat = 1026;
  117. const DepthStencilFormat = 1027;
  118. const RedFormat = 1028;
  119. const RedIntegerFormat = 1029;
  120. const RGFormat = 1030;
  121. const RGIntegerFormat = 1031;
  122. const RGBIntegerFormat = 1032;
  123. const RGBAIntegerFormat = 1033;
  124. const RGB_S3TC_DXT1_Format = 33776;
  125. const RGBA_S3TC_DXT1_Format = 33777;
  126. const RGBA_S3TC_DXT3_Format = 33778;
  127. const RGBA_S3TC_DXT5_Format = 33779;
  128. const RGB_PVRTC_4BPPV1_Format = 35840;
  129. const RGB_PVRTC_2BPPV1_Format = 35841;
  130. const RGBA_PVRTC_4BPPV1_Format = 35842;
  131. const RGBA_PVRTC_2BPPV1_Format = 35843;
  132. const RGB_ETC1_Format = 36196;
  133. const RGB_ETC2_Format = 37492;
  134. const RGBA_ETC2_EAC_Format = 37496;
  135. const RGBA_ASTC_4x4_Format = 37808;
  136. const RGBA_ASTC_5x4_Format = 37809;
  137. const RGBA_ASTC_5x5_Format = 37810;
  138. const RGBA_ASTC_6x5_Format = 37811;
  139. const RGBA_ASTC_6x6_Format = 37812;
  140. const RGBA_ASTC_8x5_Format = 37813;
  141. const RGBA_ASTC_8x6_Format = 37814;
  142. const RGBA_ASTC_8x8_Format = 37815;
  143. const RGBA_ASTC_10x5_Format = 37816;
  144. const RGBA_ASTC_10x6_Format = 37817;
  145. const RGBA_ASTC_10x8_Format = 37818;
  146. const RGBA_ASTC_10x10_Format = 37819;
  147. const RGBA_ASTC_12x10_Format = 37820;
  148. const RGBA_ASTC_12x12_Format = 37821;
  149. const RGBA_BPTC_Format = 36492;
  150. const SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  151. const SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  152. const SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  153. const SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  154. const SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  155. const SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  156. const SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  157. const SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  158. const SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  159. const SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  160. const SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  161. const SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  162. const SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  163. const SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  164. const LoopOnce = 2200;
  165. const LoopRepeat = 2201;
  166. const LoopPingPong = 2202;
  167. const InterpolateDiscrete = 2300;
  168. const InterpolateLinear = 2301;
  169. const InterpolateSmooth = 2302;
  170. const ZeroCurvatureEnding = 2400;
  171. const ZeroSlopeEnding = 2401;
  172. const WrapAroundEnding = 2402;
  173. const NormalAnimationBlendMode = 2500;
  174. const AdditiveAnimationBlendMode = 2501;
  175. const TrianglesDrawMode = 0;
  176. const TriangleStripDrawMode = 1;
  177. const TriangleFanDrawMode = 2;
  178. const LinearEncoding = 3000;
  179. const sRGBEncoding = 3001;
  180. const GammaEncoding = 3007;
  181. const RGBEEncoding = 3002;
  182. const RGBM7Encoding = 3004;
  183. const RGBM16Encoding = 3005;
  184. const RGBDEncoding = 3006;
  185. const BasicDepthPacking = 3200;
  186. const RGBADepthPacking = 3201;
  187. const TangentSpaceNormalMap = 0;
  188. const ObjectSpaceNormalMap = 1;
  189. const ZeroStencilOp = 0;
  190. const KeepStencilOp = 7680;
  191. const ReplaceStencilOp = 7681;
  192. const IncrementStencilOp = 7682;
  193. const DecrementStencilOp = 7683;
  194. const IncrementWrapStencilOp = 34055;
  195. const DecrementWrapStencilOp = 34056;
  196. const InvertStencilOp = 5386;
  197. const NeverStencilFunc = 512;
  198. const LessStencilFunc = 513;
  199. const EqualStencilFunc = 514;
  200. const LessEqualStencilFunc = 515;
  201. const GreaterStencilFunc = 516;
  202. const NotEqualStencilFunc = 517;
  203. const GreaterEqualStencilFunc = 518;
  204. const AlwaysStencilFunc = 519;
  205. const StaticDrawUsage = 35044;
  206. const DynamicDrawUsage = 35048;
  207. const StreamDrawUsage = 35040;
  208. const StaticReadUsage = 35045;
  209. const DynamicReadUsage = 35049;
  210. const StreamReadUsage = 35041;
  211. const StaticCopyUsage = 35046;
  212. const DynamicCopyUsage = 35050;
  213. const StreamCopyUsage = 35042;
  214. const GLSL1 = '100';
  215. const GLSL3 = '300 es';
  216. /**
  217. * https://github.com/mrdoob/eventdispatcher.js/
  218. */
  219. class EventDispatcher {
  220. addEventListener(type, listener) {
  221. if (this._listeners === undefined) this._listeners = {};
  222. const listeners = this._listeners;
  223. if (listeners[type] === undefined) {
  224. listeners[type] = [];
  225. }
  226. if (listeners[type].indexOf(listener) === -1) {
  227. listeners[type].push(listener);
  228. }
  229. }
  230. hasEventListener(type, listener) {
  231. if (this._listeners === undefined) return false;
  232. const listeners = this._listeners;
  233. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  234. }
  235. removeEventListener(type, listener) {
  236. if (this._listeners === undefined) return;
  237. const listeners = this._listeners;
  238. const listenerArray = listeners[type];
  239. if (listenerArray !== undefined) {
  240. const index = listenerArray.indexOf(listener);
  241. if (index !== -1) {
  242. listenerArray.splice(index, 1);
  243. }
  244. }
  245. }
  246. dispatchEvent(event) {
  247. if (this._listeners === undefined) return;
  248. const listeners = this._listeners;
  249. const listenerArray = listeners[event.type];
  250. if (listenerArray !== undefined) {
  251. event.target = this; // Make a copy, in case listeners are removed while iterating.
  252. const array = listenerArray.slice(0);
  253. for (let i = 0, l = array.length; i < l; i++) {
  254. array[i].call(this, event);
  255. }
  256. event.target = null;
  257. }
  258. }
  259. }
  260. const _lut = [];
  261. for (let i = 0; i < 256; i++) {
  262. _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
  263. }
  264. let _seed = 1234567;
  265. const DEG2RAD = Math.PI / 180;
  266. const RAD2DEG = 180 / Math.PI; // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  267. function generateUUID() {
  268. const d0 = Math.random() * 0xffffffff | 0;
  269. const d1 = Math.random() * 0xffffffff | 0;
  270. const d2 = Math.random() * 0xffffffff | 0;
  271. const d3 = Math.random() * 0xffffffff | 0;
  272. const uuid = _lut[d0 & 0xff] + _lut[d0 >> 8 & 0xff] + _lut[d0 >> 16 & 0xff] + _lut[d0 >> 24 & 0xff] + '-' + _lut[d1 & 0xff] + _lut[d1 >> 8 & 0xff] + '-' + _lut[d1 >> 16 & 0x0f | 0x40] + _lut[d1 >> 24 & 0xff] + '-' + _lut[d2 & 0x3f | 0x80] + _lut[d2 >> 8 & 0xff] + '-' + _lut[d2 >> 16 & 0xff] + _lut[d2 >> 24 & 0xff] + _lut[d3 & 0xff] + _lut[d3 >> 8 & 0xff] + _lut[d3 >> 16 & 0xff] + _lut[d3 >> 24 & 0xff]; // .toUpperCase() here flattens concatenated strings to save heap memory space.
  273. return uuid.toUpperCase();
  274. }
  275. function clamp(value, min, max) {
  276. return Math.max(min, Math.min(max, value));
  277. } // compute euclidian modulo of m % n
  278. // https://en.wikipedia.org/wiki/Modulo_operation
  279. function euclideanModulo(n, m) {
  280. return (n % m + m) % m;
  281. } // Linear mapping from range <a1, a2> to range <b1, b2>
  282. function mapLinear(x, a1, a2, b1, b2) {
  283. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  284. } // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  285. function inverseLerp(x, y, value) {
  286. if (x !== y) {
  287. return (value - x) / (y - x);
  288. } else {
  289. return 0;
  290. }
  291. } // https://en.wikipedia.org/wiki/Linear_interpolation
  292. function lerp(x, y, t) {
  293. return (1 - t) * x + t * y;
  294. } // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  295. function damp(x, y, lambda, dt) {
  296. return lerp(x, y, 1 - Math.exp(-lambda * dt));
  297. } // https://www.desmos.com/calculator/vcsjnyz7x4
  298. function pingpong(x, length = 1) {
  299. return length - Math.abs(euclideanModulo(x, length * 2) - length);
  300. } // http://en.wikipedia.org/wiki/Smoothstep
  301. function smoothstep(x, min, max) {
  302. if (x <= min) return 0;
  303. if (x >= max) return 1;
  304. x = (x - min) / (max - min);
  305. return x * x * (3 - 2 * x);
  306. }
  307. function smootherstep(x, min, max) {
  308. if (x <= min) return 0;
  309. if (x >= max) return 1;
  310. x = (x - min) / (max - min);
  311. return x * x * x * (x * (x * 6 - 15) + 10);
  312. } // Random integer from <low, high> interval
  313. function randInt(low, high) {
  314. return low + Math.floor(Math.random() * (high - low + 1));
  315. } // Random float from <low, high> interval
  316. function randFloat(low, high) {
  317. return low + Math.random() * (high - low);
  318. } // Random float from <-range/2, range/2> interval
  319. function randFloatSpread(range) {
  320. return range * (0.5 - Math.random());
  321. } // Deterministic pseudo-random float in the interval [ 0, 1 ]
  322. function seededRandom(s) {
  323. if (s !== undefined) _seed = s % 2147483647; // Park-Miller algorithm
  324. _seed = _seed * 16807 % 2147483647;
  325. return (_seed - 1) / 2147483646;
  326. }
  327. function degToRad(degrees) {
  328. return degrees * DEG2RAD;
  329. }
  330. function radToDeg(radians) {
  331. return radians * RAD2DEG;
  332. }
  333. function isPowerOfTwo(value) {
  334. return (value & value - 1) === 0 && value !== 0;
  335. }
  336. function ceilPowerOfTwo(value) {
  337. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  338. }
  339. function floorPowerOfTwo(value) {
  340. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  341. }
  342. function setQuaternionFromProperEuler(q, a, b, c, order) {
  343. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  344. // rotations are applied to the axes in the order specified by 'order'
  345. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  346. // angles are in radians
  347. const cos = Math.cos;
  348. const sin = Math.sin;
  349. const c2 = cos(b / 2);
  350. const s2 = sin(b / 2);
  351. const c13 = cos((a + c) / 2);
  352. const s13 = sin((a + c) / 2);
  353. const c1_3 = cos((a - c) / 2);
  354. const s1_3 = sin((a - c) / 2);
  355. const c3_1 = cos((c - a) / 2);
  356. const s3_1 = sin((c - a) / 2);
  357. switch (order) {
  358. case 'XYX':
  359. q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
  360. break;
  361. case 'YZY':
  362. q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
  363. break;
  364. case 'ZXZ':
  365. q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
  366. break;
  367. case 'XZX':
  368. q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
  369. break;
  370. case 'YXY':
  371. q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
  372. break;
  373. case 'ZYZ':
  374. q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
  375. break;
  376. default:
  377. console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order);
  378. }
  379. }
  380. var MathUtils = /*#__PURE__*/Object.freeze({
  381. __proto__: null,
  382. DEG2RAD: DEG2RAD,
  383. RAD2DEG: RAD2DEG,
  384. generateUUID: generateUUID,
  385. clamp: clamp,
  386. euclideanModulo: euclideanModulo,
  387. mapLinear: mapLinear,
  388. inverseLerp: inverseLerp,
  389. lerp: lerp,
  390. damp: damp,
  391. pingpong: pingpong,
  392. smoothstep: smoothstep,
  393. smootherstep: smootherstep,
  394. randInt: randInt,
  395. randFloat: randFloat,
  396. randFloatSpread: randFloatSpread,
  397. seededRandom: seededRandom,
  398. degToRad: degToRad,
  399. radToDeg: radToDeg,
  400. isPowerOfTwo: isPowerOfTwo,
  401. ceilPowerOfTwo: ceilPowerOfTwo,
  402. floorPowerOfTwo: floorPowerOfTwo,
  403. setQuaternionFromProperEuler: setQuaternionFromProperEuler
  404. });
  405. class Vector2 {
  406. constructor(x = 0, y = 0) {
  407. this.x = x;
  408. this.y = y;
  409. }
  410. get width() {
  411. return this.x;
  412. }
  413. set width(value) {
  414. this.x = value;
  415. }
  416. get height() {
  417. return this.y;
  418. }
  419. set height(value) {
  420. this.y = value;
  421. }
  422. set(x, y) {
  423. this.x = x;
  424. this.y = y;
  425. return this;
  426. }
  427. setScalar(scalar) {
  428. this.x = scalar;
  429. this.y = scalar;
  430. return this;
  431. }
  432. setX(x) {
  433. this.x = x;
  434. return this;
  435. }
  436. setY(y) {
  437. this.y = y;
  438. return this;
  439. }
  440. setComponent(index, value) {
  441. switch (index) {
  442. case 0:
  443. this.x = value;
  444. break;
  445. case 1:
  446. this.y = value;
  447. break;
  448. default:
  449. throw new Error('index is out of range: ' + index);
  450. }
  451. return this;
  452. }
  453. getComponent(index) {
  454. switch (index) {
  455. case 0:
  456. return this.x;
  457. case 1:
  458. return this.y;
  459. default:
  460. throw new Error('index is out of range: ' + index);
  461. }
  462. }
  463. clone() {
  464. return new this.constructor(this.x, this.y);
  465. }
  466. copy(v) {
  467. this.x = v.x;
  468. this.y = v.y;
  469. return this;
  470. }
  471. add(v, w) {
  472. if (w !== undefined) {
  473. console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  474. return this.addVectors(v, w);
  475. }
  476. this.x += v.x;
  477. this.y += v.y;
  478. return this;
  479. }
  480. addScalar(s) {
  481. this.x += s;
  482. this.y += s;
  483. return this;
  484. }
  485. addVectors(a, b) {
  486. this.x = a.x + b.x;
  487. this.y = a.y + b.y;
  488. return this;
  489. }
  490. addScaledVector(v, s) {
  491. this.x += v.x * s;
  492. this.y += v.y * s;
  493. return this;
  494. }
  495. sub(v, w) {
  496. if (w !== undefined) {
  497. console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  498. return this.subVectors(v, w);
  499. }
  500. this.x -= v.x;
  501. this.y -= v.y;
  502. return this;
  503. }
  504. subScalar(s) {
  505. this.x -= s;
  506. this.y -= s;
  507. return this;
  508. }
  509. subVectors(a, b) {
  510. this.x = a.x - b.x;
  511. this.y = a.y - b.y;
  512. return this;
  513. }
  514. multiply(v) {
  515. this.x *= v.x;
  516. this.y *= v.y;
  517. return this;
  518. }
  519. multiplyScalar(scalar) {
  520. this.x *= scalar;
  521. this.y *= scalar;
  522. return this;
  523. }
  524. divide(v) {
  525. this.x /= v.x;
  526. this.y /= v.y;
  527. return this;
  528. }
  529. divideScalar(scalar) {
  530. return this.multiplyScalar(1 / scalar);
  531. }
  532. applyMatrix3(m) {
  533. const x = this.x,
  534. y = this.y;
  535. const e = m.elements;
  536. this.x = e[0] * x + e[3] * y + e[6];
  537. this.y = e[1] * x + e[4] * y + e[7];
  538. return this;
  539. }
  540. min(v) {
  541. this.x = Math.min(this.x, v.x);
  542. this.y = Math.min(this.y, v.y);
  543. return this;
  544. }
  545. max(v) {
  546. this.x = Math.max(this.x, v.x);
  547. this.y = Math.max(this.y, v.y);
  548. return this;
  549. }
  550. clamp(min, max) {
  551. // assumes min < max, componentwise
  552. this.x = Math.max(min.x, Math.min(max.x, this.x));
  553. this.y = Math.max(min.y, Math.min(max.y, this.y));
  554. return this;
  555. }
  556. clampScalar(minVal, maxVal) {
  557. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  558. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  559. return this;
  560. }
  561. clampLength(min, max) {
  562. const length = this.length();
  563. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  564. }
  565. floor() {
  566. this.x = Math.floor(this.x);
  567. this.y = Math.floor(this.y);
  568. return this;
  569. }
  570. ceil() {
  571. this.x = Math.ceil(this.x);
  572. this.y = Math.ceil(this.y);
  573. return this;
  574. }
  575. round() {
  576. this.x = Math.round(this.x);
  577. this.y = Math.round(this.y);
  578. return this;
  579. }
  580. roundToZero() {
  581. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  582. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  583. return this;
  584. }
  585. negate() {
  586. this.x = -this.x;
  587. this.y = -this.y;
  588. return this;
  589. }
  590. dot(v) {
  591. return this.x * v.x + this.y * v.y;
  592. }
  593. cross(v) {
  594. return this.x * v.y - this.y * v.x;
  595. }
  596. lengthSq() {
  597. return this.x * this.x + this.y * this.y;
  598. }
  599. length() {
  600. return Math.sqrt(this.x * this.x + this.y * this.y);
  601. }
  602. manhattanLength() {
  603. return Math.abs(this.x) + Math.abs(this.y);
  604. }
  605. normalize() {
  606. return this.divideScalar(this.length() || 1);
  607. }
  608. angle() {
  609. // computes the angle in radians with respect to the positive x-axis
  610. const angle = Math.atan2(-this.y, -this.x) + Math.PI;
  611. return angle;
  612. }
  613. distanceTo(v) {
  614. return Math.sqrt(this.distanceToSquared(v));
  615. }
  616. distanceToSquared(v) {
  617. const dx = this.x - v.x,
  618. dy = this.y - v.y;
  619. return dx * dx + dy * dy;
  620. }
  621. manhattanDistanceTo(v) {
  622. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  623. }
  624. setLength(length) {
  625. return this.normalize().multiplyScalar(length);
  626. }
  627. lerp(v, alpha) {
  628. this.x += (v.x - this.x) * alpha;
  629. this.y += (v.y - this.y) * alpha;
  630. return this;
  631. }
  632. lerpVectors(v1, v2, alpha) {
  633. this.x = v1.x + (v2.x - v1.x) * alpha;
  634. this.y = v1.y + (v2.y - v1.y) * alpha;
  635. return this;
  636. }
  637. equals(v) {
  638. return v.x === this.x && v.y === this.y;
  639. }
  640. fromArray(array, offset = 0) {
  641. this.x = array[offset];
  642. this.y = array[offset + 1];
  643. return this;
  644. }
  645. toArray(array = [], offset = 0) {
  646. array[offset] = this.x;
  647. array[offset + 1] = this.y;
  648. return array;
  649. }
  650. fromBufferAttribute(attribute, index, offset) {
  651. if (offset !== undefined) {
  652. console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
  653. }
  654. this.x = attribute.getX(index);
  655. this.y = attribute.getY(index);
  656. return this;
  657. }
  658. rotateAround(center, angle) {
  659. const c = Math.cos(angle),
  660. s = Math.sin(angle);
  661. const x = this.x - center.x;
  662. const y = this.y - center.y;
  663. this.x = x * c - y * s + center.x;
  664. this.y = x * s + y * c + center.y;
  665. return this;
  666. }
  667. random() {
  668. this.x = Math.random();
  669. this.y = Math.random();
  670. return this;
  671. }
  672. *[Symbol.iterator]() {
  673. yield this.x;
  674. yield this.y;
  675. }
  676. }
  677. Vector2.prototype.isVector2 = true;
  678. class Matrix3 {
  679. constructor() {
  680. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  681. if (arguments.length > 0) {
  682. console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
  683. }
  684. }
  685. set(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  686. const te = this.elements;
  687. te[0] = n11;
  688. te[1] = n21;
  689. te[2] = n31;
  690. te[3] = n12;
  691. te[4] = n22;
  692. te[5] = n32;
  693. te[6] = n13;
  694. te[7] = n23;
  695. te[8] = n33;
  696. return this;
  697. }
  698. identity() {
  699. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  700. return this;
  701. }
  702. copy(m) {
  703. const te = this.elements;
  704. const me = m.elements;
  705. te[0] = me[0];
  706. te[1] = me[1];
  707. te[2] = me[2];
  708. te[3] = me[3];
  709. te[4] = me[4];
  710. te[5] = me[5];
  711. te[6] = me[6];
  712. te[7] = me[7];
  713. te[8] = me[8];
  714. return this;
  715. }
  716. extractBasis(xAxis, yAxis, zAxis) {
  717. xAxis.setFromMatrix3Column(this, 0);
  718. yAxis.setFromMatrix3Column(this, 1);
  719. zAxis.setFromMatrix3Column(this, 2);
  720. return this;
  721. }
  722. setFromMatrix4(m) {
  723. const me = m.elements;
  724. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  725. return this;
  726. }
  727. multiply(m) {
  728. return this.multiplyMatrices(this, m);
  729. }
  730. premultiply(m) {
  731. return this.multiplyMatrices(m, this);
  732. }
  733. multiplyMatrices(a, b) {
  734. const ae = a.elements;
  735. const be = b.elements;
  736. const te = this.elements;
  737. const a11 = ae[0],
  738. a12 = ae[3],
  739. a13 = ae[6];
  740. const a21 = ae[1],
  741. a22 = ae[4],
  742. a23 = ae[7];
  743. const a31 = ae[2],
  744. a32 = ae[5],
  745. a33 = ae[8];
  746. const b11 = be[0],
  747. b12 = be[3],
  748. b13 = be[6];
  749. const b21 = be[1],
  750. b22 = be[4],
  751. b23 = be[7];
  752. const b31 = be[2],
  753. b32 = be[5],
  754. b33 = be[8];
  755. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  756. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  757. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  758. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  759. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  760. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  761. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  762. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  763. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  764. return this;
  765. }
  766. multiplyScalar(s) {
  767. const te = this.elements;
  768. te[0] *= s;
  769. te[3] *= s;
  770. te[6] *= s;
  771. te[1] *= s;
  772. te[4] *= s;
  773. te[7] *= s;
  774. te[2] *= s;
  775. te[5] *= s;
  776. te[8] *= s;
  777. return this;
  778. }
  779. determinant() {
  780. const te = this.elements;
  781. const a = te[0],
  782. b = te[1],
  783. c = te[2],
  784. d = te[3],
  785. e = te[4],
  786. f = te[5],
  787. g = te[6],
  788. h = te[7],
  789. i = te[8];
  790. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  791. }
  792. invert() {
  793. const te = this.elements,
  794. n11 = te[0],
  795. n21 = te[1],
  796. n31 = te[2],
  797. n12 = te[3],
  798. n22 = te[4],
  799. n32 = te[5],
  800. n13 = te[6],
  801. n23 = te[7],
  802. n33 = te[8],
  803. t11 = n33 * n22 - n32 * n23,
  804. t12 = n32 * n13 - n33 * n12,
  805. t13 = n23 * n12 - n22 * n13,
  806. det = n11 * t11 + n21 * t12 + n31 * t13;
  807. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  808. const detInv = 1 / det;
  809. te[0] = t11 * detInv;
  810. te[1] = (n31 * n23 - n33 * n21) * detInv;
  811. te[2] = (n32 * n21 - n31 * n22) * detInv;
  812. te[3] = t12 * detInv;
  813. te[4] = (n33 * n11 - n31 * n13) * detInv;
  814. te[5] = (n31 * n12 - n32 * n11) * detInv;
  815. te[6] = t13 * detInv;
  816. te[7] = (n21 * n13 - n23 * n11) * detInv;
  817. te[8] = (n22 * n11 - n21 * n12) * detInv;
  818. return this;
  819. }
  820. transpose() {
  821. let tmp;
  822. const m = this.elements;
  823. tmp = m[1];
  824. m[1] = m[3];
  825. m[3] = tmp;
  826. tmp = m[2];
  827. m[2] = m[6];
  828. m[6] = tmp;
  829. tmp = m[5];
  830. m[5] = m[7];
  831. m[7] = tmp;
  832. return this;
  833. }
  834. getNormalMatrix(matrix4) {
  835. return this.setFromMatrix4(matrix4).invert().transpose();
  836. }
  837. transposeIntoArray(r) {
  838. const m = this.elements;
  839. r[0] = m[0];
  840. r[1] = m[3];
  841. r[2] = m[6];
  842. r[3] = m[1];
  843. r[4] = m[4];
  844. r[5] = m[7];
  845. r[6] = m[2];
  846. r[7] = m[5];
  847. r[8] = m[8];
  848. return this;
  849. }
  850. setUvTransform(tx, ty, sx, sy, rotation, cx, cy) {
  851. const c = Math.cos(rotation);
  852. const s = Math.sin(rotation);
  853. this.set(sx * c, sx * s, -sx * (c * cx + s * cy) + cx + tx, -sy * s, sy * c, -sy * (-s * cx + c * cy) + cy + ty, 0, 0, 1);
  854. return this;
  855. }
  856. scale(sx, sy) {
  857. const te = this.elements;
  858. te[0] *= sx;
  859. te[3] *= sx;
  860. te[6] *= sx;
  861. te[1] *= sy;
  862. te[4] *= sy;
  863. te[7] *= sy;
  864. return this;
  865. }
  866. rotate(theta) {
  867. const c = Math.cos(theta);
  868. const s = Math.sin(theta);
  869. const te = this.elements;
  870. const a11 = te[0],
  871. a12 = te[3],
  872. a13 = te[6];
  873. const a21 = te[1],
  874. a22 = te[4],
  875. a23 = te[7];
  876. te[0] = c * a11 + s * a21;
  877. te[3] = c * a12 + s * a22;
  878. te[6] = c * a13 + s * a23;
  879. te[1] = -s * a11 + c * a21;
  880. te[4] = -s * a12 + c * a22;
  881. te[7] = -s * a13 + c * a23;
  882. return this;
  883. }
  884. translate(tx, ty) {
  885. const te = this.elements;
  886. te[0] += tx * te[2];
  887. te[3] += tx * te[5];
  888. te[6] += tx * te[8];
  889. te[1] += ty * te[2];
  890. te[4] += ty * te[5];
  891. te[7] += ty * te[8];
  892. return this;
  893. }
  894. equals(matrix) {
  895. const te = this.elements;
  896. const me = matrix.elements;
  897. for (let i = 0; i < 9; i++) {
  898. if (te[i] !== me[i]) return false;
  899. }
  900. return true;
  901. }
  902. fromArray(array, offset = 0) {
  903. for (let i = 0; i < 9; i++) {
  904. this.elements[i] = array[i + offset];
  905. }
  906. return this;
  907. }
  908. toArray(array = [], offset = 0) {
  909. const te = this.elements;
  910. array[offset] = te[0];
  911. array[offset + 1] = te[1];
  912. array[offset + 2] = te[2];
  913. array[offset + 3] = te[3];
  914. array[offset + 4] = te[4];
  915. array[offset + 5] = te[5];
  916. array[offset + 6] = te[6];
  917. array[offset + 7] = te[7];
  918. array[offset + 8] = te[8];
  919. return array;
  920. }
  921. clone() {
  922. return new this.constructor().fromArray(this.elements);
  923. }
  924. }
  925. Matrix3.prototype.isMatrix3 = true;
  926. function arrayMax(array) {
  927. if (array.length === 0) return -Infinity;
  928. let max = array[0];
  929. for (let i = 1, l = array.length; i < l; ++i) {
  930. if (array[i] > max) max = array[i];
  931. }
  932. return max;
  933. }
  934. const TYPED_ARRAYS = {
  935. Int8Array: Int8Array,
  936. Uint8Array: Uint8Array,
  937. Uint8ClampedArray: Uint8ClampedArray,
  938. Int16Array: Int16Array,
  939. Uint16Array: Uint16Array,
  940. Int32Array: Int32Array,
  941. Uint32Array: Uint32Array,
  942. Float32Array: Float32Array,
  943. Float64Array: Float64Array
  944. };
  945. function getTypedArray(type, buffer) {
  946. return new TYPED_ARRAYS[type](buffer);
  947. }
  948. function createElementNS(name) {
  949. return document.createElementNS('http://www.w3.org/1999/xhtml', name);
  950. }
  951. let _canvas;
  952. class ImageUtils {
  953. static getDataURL(image) {
  954. if (/^data:/i.test(image.src)) {
  955. return image.src;
  956. }
  957. if (typeof HTMLCanvasElement == 'undefined') {
  958. return image.src;
  959. }
  960. let canvas;
  961. if (image instanceof HTMLCanvasElement) {
  962. canvas = image;
  963. } else {
  964. if (_canvas === undefined) _canvas = createElementNS('canvas');
  965. _canvas.width = image.width;
  966. _canvas.height = image.height;
  967. const context = _canvas.getContext('2d');
  968. if (image instanceof ImageData) {
  969. context.putImageData(image, 0, 0);
  970. } else {
  971. context.drawImage(image, 0, 0, image.width, image.height);
  972. }
  973. canvas = _canvas;
  974. }
  975. if (canvas.width > 2048 || canvas.height > 2048) {
  976. console.warn('THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image);
  977. return canvas.toDataURL('image/jpeg', 0.6);
  978. } else {
  979. return canvas.toDataURL('image/png');
  980. }
  981. }
  982. }
  983. let textureId = 0;
  984. class Texture extends EventDispatcher {
  985. constructor(image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = 1, encoding = LinearEncoding) {
  986. super();
  987. Object.defineProperty(this, 'id', {
  988. value: textureId++
  989. });
  990. this.uuid = generateUUID();
  991. this.name = '';
  992. this.image = image;
  993. this.mipmaps = [];
  994. this.mapping = mapping;
  995. this.wrapS = wrapS;
  996. this.wrapT = wrapT;
  997. this.magFilter = magFilter;
  998. this.minFilter = minFilter;
  999. this.anisotropy = anisotropy;
  1000. this.format = format;
  1001. this.internalFormat = null;
  1002. this.type = type;
  1003. this.offset = new Vector2(0, 0);
  1004. this.repeat = new Vector2(1, 1);
  1005. this.center = new Vector2(0, 0);
  1006. this.rotation = 0;
  1007. this.matrixAutoUpdate = true;
  1008. this.matrix = new Matrix3();
  1009. this.generateMipmaps = true;
  1010. this.premultiplyAlpha = false;
  1011. this.flipY = true;
  1012. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1013. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1014. //
  1015. // Also changing the encoding after already used by a Material will not automatically make the Material
  1016. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1017. this.encoding = encoding;
  1018. this.userData = {};
  1019. this.version = 0;
  1020. this.onUpdate = null;
  1021. this.isRenderTargetTexture = false;
  1022. }
  1023. updateMatrix() {
  1024. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  1025. }
  1026. clone() {
  1027. return new this.constructor().copy(this);
  1028. }
  1029. copy(source) {
  1030. this.name = source.name;
  1031. this.image = source.image;
  1032. this.mipmaps = source.mipmaps.slice(0);
  1033. this.mapping = source.mapping;
  1034. this.wrapS = source.wrapS;
  1035. this.wrapT = source.wrapT;
  1036. this.magFilter = source.magFilter;
  1037. this.minFilter = source.minFilter;
  1038. this.anisotropy = source.anisotropy;
  1039. this.format = source.format;
  1040. this.internalFormat = source.internalFormat;
  1041. this.type = source.type;
  1042. this.offset.copy(source.offset);
  1043. this.repeat.copy(source.repeat);
  1044. this.center.copy(source.center);
  1045. this.rotation = source.rotation;
  1046. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1047. this.matrix.copy(source.matrix);
  1048. this.generateMipmaps = source.generateMipmaps;
  1049. this.premultiplyAlpha = source.premultiplyAlpha;
  1050. this.flipY = source.flipY;
  1051. this.unpackAlignment = source.unpackAlignment;
  1052. this.encoding = source.encoding;
  1053. this.userData = JSON.parse(JSON.stringify(source.userData));
  1054. return this;
  1055. }
  1056. toJSON(meta) {
  1057. const isRootObject = meta === undefined || typeof meta === 'string';
  1058. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  1059. return meta.textures[this.uuid];
  1060. }
  1061. const output = {
  1062. metadata: {
  1063. version: 4.5,
  1064. type: 'Texture',
  1065. generator: 'Texture.toJSON'
  1066. },
  1067. uuid: this.uuid,
  1068. name: this.name,
  1069. mapping: this.mapping,
  1070. repeat: [this.repeat.x, this.repeat.y],
  1071. offset: [this.offset.x, this.offset.y],
  1072. center: [this.center.x, this.center.y],
  1073. rotation: this.rotation,
  1074. wrap: [this.wrapS, this.wrapT],
  1075. format: this.format,
  1076. type: this.type,
  1077. encoding: this.encoding,
  1078. minFilter: this.minFilter,
  1079. magFilter: this.magFilter,
  1080. anisotropy: this.anisotropy,
  1081. flipY: this.flipY,
  1082. premultiplyAlpha: this.premultiplyAlpha,
  1083. unpackAlignment: this.unpackAlignment
  1084. };
  1085. if (this.image !== undefined) {
  1086. // TODO: Move to THREE.Image
  1087. const image = this.image;
  1088. if (image.uuid === undefined) {
  1089. image.uuid = generateUUID(); // UGH
  1090. }
  1091. if (!isRootObject && meta.images[image.uuid] === undefined) {
  1092. let url;
  1093. if (Array.isArray(image)) {
  1094. // process array of images e.g. CubeTexture
  1095. url = [];
  1096. for (let i = 0, l = image.length; i < l; i++) {
  1097. // check cube texture with data textures
  1098. if (image[i].isDataTexture) {
  1099. url.push(serializeImage(image[i].image));
  1100. } else {
  1101. url.push(serializeImage(image[i]));
  1102. }
  1103. }
  1104. } else {
  1105. // process single image
  1106. url = serializeImage(image);
  1107. }
  1108. meta.images[image.uuid] = {
  1109. uuid: image.uuid,
  1110. url: url
  1111. };
  1112. }
  1113. output.image = image.uuid;
  1114. }
  1115. if (JSON.stringify(this.userData) !== '{}') output.userData = this.userData;
  1116. if (!isRootObject) {
  1117. meta.textures[this.uuid] = output;
  1118. }
  1119. return output;
  1120. }
  1121. dispose() {
  1122. this.dispatchEvent({
  1123. type: 'dispose'
  1124. });
  1125. }
  1126. transformUv(uv) {
  1127. if (this.mapping !== UVMapping) return uv;
  1128. uv.applyMatrix3(this.matrix);
  1129. if (uv.x < 0 || uv.x > 1) {
  1130. switch (this.wrapS) {
  1131. case RepeatWrapping:
  1132. uv.x = uv.x - Math.floor(uv.x);
  1133. break;
  1134. case ClampToEdgeWrapping:
  1135. uv.x = uv.x < 0 ? 0 : 1;
  1136. break;
  1137. case MirroredRepeatWrapping:
  1138. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  1139. uv.x = Math.ceil(uv.x) - uv.x;
  1140. } else {
  1141. uv.x = uv.x - Math.floor(uv.x);
  1142. }
  1143. break;
  1144. }
  1145. }
  1146. if (uv.y < 0 || uv.y > 1) {
  1147. switch (this.wrapT) {
  1148. case RepeatWrapping:
  1149. uv.y = uv.y - Math.floor(uv.y);
  1150. break;
  1151. case ClampToEdgeWrapping:
  1152. uv.y = uv.y < 0 ? 0 : 1;
  1153. break;
  1154. case MirroredRepeatWrapping:
  1155. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  1156. uv.y = Math.ceil(uv.y) - uv.y;
  1157. } else {
  1158. uv.y = uv.y - Math.floor(uv.y);
  1159. }
  1160. break;
  1161. }
  1162. }
  1163. if (this.flipY) {
  1164. uv.y = 1 - uv.y;
  1165. }
  1166. return uv;
  1167. }
  1168. set needsUpdate(value) {
  1169. if (value === true) this.version++;
  1170. }
  1171. }
  1172. Texture.DEFAULT_IMAGE = undefined;
  1173. Texture.DEFAULT_MAPPING = UVMapping;
  1174. Texture.prototype.isTexture = true;
  1175. function serializeImage(image) {
  1176. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  1177. // default images
  1178. return ImageUtils.getDataURL(image);
  1179. } else {
  1180. if (image.data) {
  1181. // images of DataTexture
  1182. return {
  1183. data: Array.prototype.slice.call(image.data),
  1184. width: image.width,
  1185. height: image.height,
  1186. type: image.data.constructor.name
  1187. };
  1188. } else {
  1189. console.warn('THREE.Texture: Unable to serialize Texture.');
  1190. return {};
  1191. }
  1192. }
  1193. }
  1194. class Vector4 {
  1195. constructor(x = 0, y = 0, z = 0, w = 1) {
  1196. this.x = x;
  1197. this.y = y;
  1198. this.z = z;
  1199. this.w = w;
  1200. }
  1201. get width() {
  1202. return this.z;
  1203. }
  1204. set width(value) {
  1205. this.z = value;
  1206. }
  1207. get height() {
  1208. return this.w;
  1209. }
  1210. set height(value) {
  1211. this.w = value;
  1212. }
  1213. set(x, y, z, w) {
  1214. this.x = x;
  1215. this.y = y;
  1216. this.z = z;
  1217. this.w = w;
  1218. return this;
  1219. }
  1220. setScalar(scalar) {
  1221. this.x = scalar;
  1222. this.y = scalar;
  1223. this.z = scalar;
  1224. this.w = scalar;
  1225. return this;
  1226. }
  1227. setX(x) {
  1228. this.x = x;
  1229. return this;
  1230. }
  1231. setY(y) {
  1232. this.y = y;
  1233. return this;
  1234. }
  1235. setZ(z) {
  1236. this.z = z;
  1237. return this;
  1238. }
  1239. setW(w) {
  1240. this.w = w;
  1241. return this;
  1242. }
  1243. setComponent(index, value) {
  1244. switch (index) {
  1245. case 0:
  1246. this.x = value;
  1247. break;
  1248. case 1:
  1249. this.y = value;
  1250. break;
  1251. case 2:
  1252. this.z = value;
  1253. break;
  1254. case 3:
  1255. this.w = value;
  1256. break;
  1257. default:
  1258. throw new Error('index is out of range: ' + index);
  1259. }
  1260. return this;
  1261. }
  1262. getComponent(index) {
  1263. switch (index) {
  1264. case 0:
  1265. return this.x;
  1266. case 1:
  1267. return this.y;
  1268. case 2:
  1269. return this.z;
  1270. case 3:
  1271. return this.w;
  1272. default:
  1273. throw new Error('index is out of range: ' + index);
  1274. }
  1275. }
  1276. clone() {
  1277. return new this.constructor(this.x, this.y, this.z, this.w);
  1278. }
  1279. copy(v) {
  1280. this.x = v.x;
  1281. this.y = v.y;
  1282. this.z = v.z;
  1283. this.w = v.w !== undefined ? v.w : 1;
  1284. return this;
  1285. }
  1286. add(v, w) {
  1287. if (w !== undefined) {
  1288. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  1289. return this.addVectors(v, w);
  1290. }
  1291. this.x += v.x;
  1292. this.y += v.y;
  1293. this.z += v.z;
  1294. this.w += v.w;
  1295. return this;
  1296. }
  1297. addScalar(s) {
  1298. this.x += s;
  1299. this.y += s;
  1300. this.z += s;
  1301. this.w += s;
  1302. return this;
  1303. }
  1304. addVectors(a, b) {
  1305. this.x = a.x + b.x;
  1306. this.y = a.y + b.y;
  1307. this.z = a.z + b.z;
  1308. this.w = a.w + b.w;
  1309. return this;
  1310. }
  1311. addScaledVector(v, s) {
  1312. this.x += v.x * s;
  1313. this.y += v.y * s;
  1314. this.z += v.z * s;
  1315. this.w += v.w * s;
  1316. return this;
  1317. }
  1318. sub(v, w) {
  1319. if (w !== undefined) {
  1320. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  1321. return this.subVectors(v, w);
  1322. }
  1323. this.x -= v.x;
  1324. this.y -= v.y;
  1325. this.z -= v.z;
  1326. this.w -= v.w;
  1327. return this;
  1328. }
  1329. subScalar(s) {
  1330. this.x -= s;
  1331. this.y -= s;
  1332. this.z -= s;
  1333. this.w -= s;
  1334. return this;
  1335. }
  1336. subVectors(a, b) {
  1337. this.x = a.x - b.x;
  1338. this.y = a.y - b.y;
  1339. this.z = a.z - b.z;
  1340. this.w = a.w - b.w;
  1341. return this;
  1342. }
  1343. multiply(v) {
  1344. this.x *= v.x;
  1345. this.y *= v.y;
  1346. this.z *= v.z;
  1347. this.w *= v.w;
  1348. return this;
  1349. }
  1350. multiplyScalar(scalar) {
  1351. this.x *= scalar;
  1352. this.y *= scalar;
  1353. this.z *= scalar;
  1354. this.w *= scalar;
  1355. return this;
  1356. }
  1357. applyMatrix4(m) {
  1358. const x = this.x,
  1359. y = this.y,
  1360. z = this.z,
  1361. w = this.w;
  1362. const e = m.elements;
  1363. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1364. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1365. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1366. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1367. return this;
  1368. }
  1369. divideScalar(scalar) {
  1370. return this.multiplyScalar(1 / scalar);
  1371. }
  1372. setAxisAngleFromQuaternion(q) {
  1373. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1374. // q is assumed to be normalized
  1375. this.w = 2 * Math.acos(q.w);
  1376. const s = Math.sqrt(1 - q.w * q.w);
  1377. if (s < 0.0001) {
  1378. this.x = 1;
  1379. this.y = 0;
  1380. this.z = 0;
  1381. } else {
  1382. this.x = q.x / s;
  1383. this.y = q.y / s;
  1384. this.z = q.z / s;
  1385. }
  1386. return this;
  1387. }
  1388. setAxisAngleFromRotationMatrix(m) {
  1389. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1390. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1391. let angle, x, y, z; // variables for result
  1392. const epsilon = 0.01,
  1393. // margin to allow for rounding errors
  1394. epsilon2 = 0.1,
  1395. // margin to distinguish between 0 and 180 degrees
  1396. te = m.elements,
  1397. m11 = te[0],
  1398. m12 = te[4],
  1399. m13 = te[8],
  1400. m21 = te[1],
  1401. m22 = te[5],
  1402. m23 = te[9],
  1403. m31 = te[2],
  1404. m32 = te[6],
  1405. m33 = te[10];
  1406. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  1407. // singularity found
  1408. // first check for identity matrix which must have +1 for all terms
  1409. // in leading diagonal and zero in other terms
  1410. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  1411. // this singularity is identity matrix so angle = 0
  1412. this.set(1, 0, 0, 0);
  1413. return this; // zero angle, arbitrary axis
  1414. } // otherwise this singularity is angle = 180
  1415. angle = Math.PI;
  1416. const xx = (m11 + 1) / 2;
  1417. const yy = (m22 + 1) / 2;
  1418. const zz = (m33 + 1) / 2;
  1419. const xy = (m12 + m21) / 4;
  1420. const xz = (m13 + m31) / 4;
  1421. const yz = (m23 + m32) / 4;
  1422. if (xx > yy && xx > zz) {
  1423. // m11 is the largest diagonal term
  1424. if (xx < epsilon) {
  1425. x = 0;
  1426. y = 0.707106781;
  1427. z = 0.707106781;
  1428. } else {
  1429. x = Math.sqrt(xx);
  1430. y = xy / x;
  1431. z = xz / x;
  1432. }
  1433. } else if (yy > zz) {
  1434. // m22 is the largest diagonal term
  1435. if (yy < epsilon) {
  1436. x = 0.707106781;
  1437. y = 0;
  1438. z = 0.707106781;
  1439. } else {
  1440. y = Math.sqrt(yy);
  1441. x = xy / y;
  1442. z = yz / y;
  1443. }
  1444. } else {
  1445. // m33 is the largest diagonal term so base result on this
  1446. if (zz < epsilon) {
  1447. x = 0.707106781;
  1448. y = 0.707106781;
  1449. z = 0;
  1450. } else {
  1451. z = Math.sqrt(zz);
  1452. x = xz / z;
  1453. y = yz / z;
  1454. }
  1455. }
  1456. this.set(x, y, z, angle);
  1457. return this; // return 180 deg rotation
  1458. } // as we have reached here there are no singularities so we can handle normally
  1459. let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  1460. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1461. // caught by singularity test above, but I've left it in just in case
  1462. this.x = (m32 - m23) / s;
  1463. this.y = (m13 - m31) / s;
  1464. this.z = (m21 - m12) / s;
  1465. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  1466. return this;
  1467. }
  1468. min(v) {
  1469. this.x = Math.min(this.x, v.x);
  1470. this.y = Math.min(this.y, v.y);
  1471. this.z = Math.min(this.z, v.z);
  1472. this.w = Math.min(this.w, v.w);
  1473. return this;
  1474. }
  1475. max(v) {
  1476. this.x = Math.max(this.x, v.x);
  1477. this.y = Math.max(this.y, v.y);
  1478. this.z = Math.max(this.z, v.z);
  1479. this.w = Math.max(this.w, v.w);
  1480. return this;
  1481. }
  1482. clamp(min, max) {
  1483. // assumes min < max, componentwise
  1484. this.x = Math.max(min.x, Math.min(max.x, this.x));
  1485. this.y = Math.max(min.y, Math.min(max.y, this.y));
  1486. this.z = Math.max(min.z, Math.min(max.z, this.z));
  1487. this.w = Math.max(min.w, Math.min(max.w, this.w));
  1488. return this;
  1489. }
  1490. clampScalar(minVal, maxVal) {
  1491. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  1492. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  1493. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  1494. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  1495. return this;
  1496. }
  1497. clampLength(min, max) {
  1498. const length = this.length();
  1499. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  1500. }
  1501. floor() {
  1502. this.x = Math.floor(this.x);
  1503. this.y = Math.floor(this.y);
  1504. this.z = Math.floor(this.z);
  1505. this.w = Math.floor(this.w);
  1506. return this;
  1507. }
  1508. ceil() {
  1509. this.x = Math.ceil(this.x);
  1510. this.y = Math.ceil(this.y);
  1511. this.z = Math.ceil(this.z);
  1512. this.w = Math.ceil(this.w);
  1513. return this;
  1514. }
  1515. round() {
  1516. this.x = Math.round(this.x);
  1517. this.y = Math.round(this.y);
  1518. this.z = Math.round(this.z);
  1519. this.w = Math.round(this.w);
  1520. return this;
  1521. }
  1522. roundToZero() {
  1523. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  1524. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  1525. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  1526. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  1527. return this;
  1528. }
  1529. negate() {
  1530. this.x = -this.x;
  1531. this.y = -this.y;
  1532. this.z = -this.z;
  1533. this.w = -this.w;
  1534. return this;
  1535. }
  1536. dot(v) {
  1537. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1538. }
  1539. lengthSq() {
  1540. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1541. }
  1542. length() {
  1543. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1544. }
  1545. manhattanLength() {
  1546. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  1547. }
  1548. normalize() {
  1549. return this.divideScalar(this.length() || 1);
  1550. }
  1551. setLength(length) {
  1552. return this.normalize().multiplyScalar(length);
  1553. }
  1554. lerp(v, alpha) {
  1555. this.x += (v.x - this.x) * alpha;
  1556. this.y += (v.y - this.y) * alpha;
  1557. this.z += (v.z - this.z) * alpha;
  1558. this.w += (v.w - this.w) * alpha;
  1559. return this;
  1560. }
  1561. lerpVectors(v1, v2, alpha) {
  1562. this.x = v1.x + (v2.x - v1.x) * alpha;
  1563. this.y = v1.y + (v2.y - v1.y) * alpha;
  1564. this.z = v1.z + (v2.z - v1.z) * alpha;
  1565. this.w = v1.w + (v2.w - v1.w) * alpha;
  1566. return this;
  1567. }
  1568. equals(v) {
  1569. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  1570. }
  1571. fromArray(array, offset = 0) {
  1572. this.x = array[offset];
  1573. this.y = array[offset + 1];
  1574. this.z = array[offset + 2];
  1575. this.w = array[offset + 3];
  1576. return this;
  1577. }
  1578. toArray(array = [], offset = 0) {
  1579. array[offset] = this.x;
  1580. array[offset + 1] = this.y;
  1581. array[offset + 2] = this.z;
  1582. array[offset + 3] = this.w;
  1583. return array;
  1584. }
  1585. fromBufferAttribute(attribute, index, offset) {
  1586. if (offset !== undefined) {
  1587. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  1588. }
  1589. this.x = attribute.getX(index);
  1590. this.y = attribute.getY(index);
  1591. this.z = attribute.getZ(index);
  1592. this.w = attribute.getW(index);
  1593. return this;
  1594. }
  1595. random() {
  1596. this.x = Math.random();
  1597. this.y = Math.random();
  1598. this.z = Math.random();
  1599. this.w = Math.random();
  1600. return this;
  1601. }
  1602. *[Symbol.iterator]() {
  1603. yield this.x;
  1604. yield this.y;
  1605. yield this.z;
  1606. yield this.w;
  1607. }
  1608. }
  1609. Vector4.prototype.isVector4 = true;
  1610. /*
  1611. In options, we can specify:
  1612. * Texture parameters for an auto-generated target texture
  1613. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1614. */
  1615. class WebGLRenderTarget extends EventDispatcher {
  1616. constructor(width, height, options = {}) {
  1617. super();
  1618. this.width = width;
  1619. this.height = height;
  1620. this.depth = 1;
  1621. this.scissor = new Vector4(0, 0, width, height);
  1622. this.scissorTest = false;
  1623. this.viewport = new Vector4(0, 0, width, height);
  1624. this.texture = new Texture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  1625. this.texture.isRenderTargetTexture = true;
  1626. this.texture.image = {
  1627. width: width,
  1628. height: height,
  1629. depth: 1
  1630. };
  1631. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  1632. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  1633. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  1634. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1635. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  1636. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1637. }
  1638. setTexture(texture) {
  1639. texture.image = {
  1640. width: this.width,
  1641. height: this.height,
  1642. depth: this.depth
  1643. };
  1644. this.texture = texture;
  1645. }
  1646. setSize(width, height, depth = 1) {
  1647. if (this.width !== width || this.height !== height || this.depth !== depth) {
  1648. this.width = width;
  1649. this.height = height;
  1650. this.depth = depth;
  1651. this.texture.image.width = width;
  1652. this.texture.image.height = height;
  1653. this.texture.image.depth = depth;
  1654. this.dispose();
  1655. }
  1656. this.viewport.set(0, 0, width, height);
  1657. this.scissor.set(0, 0, width, height);
  1658. }
  1659. clone() {
  1660. return new this.constructor().copy(this);
  1661. }
  1662. copy(source) {
  1663. this.width = source.width;
  1664. this.height = source.height;
  1665. this.depth = source.depth;
  1666. this.viewport.copy(source.viewport);
  1667. this.texture = source.texture.clone();
  1668. this.texture.image = { ...this.texture.image
  1669. }; // See #20328.
  1670. this.depthBuffer = source.depthBuffer;
  1671. this.stencilBuffer = source.stencilBuffer;
  1672. this.depthTexture = source.depthTexture;
  1673. return this;
  1674. }
  1675. dispose() {
  1676. this.dispatchEvent({
  1677. type: 'dispose'
  1678. });
  1679. }
  1680. }
  1681. WebGLRenderTarget.prototype.isWebGLRenderTarget = true;
  1682. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  1683. constructor(width, height, count) {
  1684. super(width, height);
  1685. const texture = this.texture;
  1686. this.texture = [];
  1687. for (let i = 0; i < count; i++) {
  1688. this.texture[i] = texture.clone();
  1689. }
  1690. }
  1691. setSize(width, height, depth = 1) {
  1692. if (this.width !== width || this.height !== height || this.depth !== depth) {
  1693. this.width = width;
  1694. this.height = height;
  1695. this.depth = depth;
  1696. for (let i = 0, il = this.texture.length; i < il; i++) {
  1697. this.texture[i].image.width = width;
  1698. this.texture[i].image.height = height;
  1699. this.texture[i].image.depth = depth;
  1700. }
  1701. this.dispose();
  1702. }
  1703. this.viewport.set(0, 0, width, height);
  1704. this.scissor.set(0, 0, width, height);
  1705. return this;
  1706. }
  1707. copy(source) {
  1708. this.dispose();
  1709. this.width = source.width;
  1710. this.height = source.height;
  1711. this.depth = source.depth;
  1712. this.viewport.set(0, 0, this.width, this.height);
  1713. this.scissor.set(0, 0, this.width, this.height);
  1714. this.depthBuffer = source.depthBuffer;
  1715. this.stencilBuffer = source.stencilBuffer;
  1716. this.depthTexture = source.depthTexture;
  1717. this.texture.length = 0;
  1718. for (let i = 0, il = source.texture.length; i < il; i++) {
  1719. this.texture[i] = source.texture[i].clone();
  1720. }
  1721. return this;
  1722. }
  1723. }
  1724. WebGLMultipleRenderTargets.prototype.isWebGLMultipleRenderTargets = true;
  1725. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  1726. constructor(width, height, options = {}) {
  1727. super(width, height, options);
  1728. this.samples = 4;
  1729. this.ignoreDepthForMultisampleCopy = options.ignoreDepth !== undefined ? options.ignoreDepth : true;
  1730. this.useRenderToTexture = options.useRenderToTexture !== undefined ? options.useRenderToTexture : false;
  1731. this.useRenderbuffer = this.useRenderToTexture === false;
  1732. }
  1733. copy(source) {
  1734. super.copy.call(this, source);
  1735. this.samples = source.samples;
  1736. this.useRenderToTexture = source.useRenderToTexture;
  1737. this.useRenderbuffer = source.useRenderbuffer;
  1738. return this;
  1739. }
  1740. }
  1741. WebGLMultisampleRenderTarget.prototype.isWebGLMultisampleRenderTarget = true;
  1742. class Quaternion {
  1743. constructor(x = 0, y = 0, z = 0, w = 1) {
  1744. this._x = x;
  1745. this._y = y;
  1746. this._z = z;
  1747. this._w = w;
  1748. }
  1749. static slerp(qa, qb, qm, t) {
  1750. console.warn('THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead.');
  1751. return qm.slerpQuaternions(qa, qb, t);
  1752. }
  1753. static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  1754. // fuzz-free, array-based Quaternion SLERP operation
  1755. let x0 = src0[srcOffset0 + 0],
  1756. y0 = src0[srcOffset0 + 1],
  1757. z0 = src0[srcOffset0 + 2],
  1758. w0 = src0[srcOffset0 + 3];
  1759. const x1 = src1[srcOffset1 + 0],
  1760. y1 = src1[srcOffset1 + 1],
  1761. z1 = src1[srcOffset1 + 2],
  1762. w1 = src1[srcOffset1 + 3];
  1763. if (t === 0) {
  1764. dst[dstOffset + 0] = x0;
  1765. dst[dstOffset + 1] = y0;
  1766. dst[dstOffset + 2] = z0;
  1767. dst[dstOffset + 3] = w0;
  1768. return;
  1769. }
  1770. if (t === 1) {
  1771. dst[dstOffset + 0] = x1;
  1772. dst[dstOffset + 1] = y1;
  1773. dst[dstOffset + 2] = z1;
  1774. dst[dstOffset + 3] = w1;
  1775. return;
  1776. }
  1777. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  1778. let s = 1 - t;
  1779. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1780. dir = cos >= 0 ? 1 : -1,
  1781. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  1782. if (sqrSin > Number.EPSILON) {
  1783. const sin = Math.sqrt(sqrSin),
  1784. len = Math.atan2(sin, cos * dir);
  1785. s = Math.sin(s * len) / sin;
  1786. t = Math.sin(t * len) / sin;
  1787. }
  1788. const tDir = t * dir;
  1789. x0 = x0 * s + x1 * tDir;
  1790. y0 = y0 * s + y1 * tDir;
  1791. z0 = z0 * s + z1 * tDir;
  1792. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  1793. if (s === 1 - t) {
  1794. const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  1795. x0 *= f;
  1796. y0 *= f;
  1797. z0 *= f;
  1798. w0 *= f;
  1799. }
  1800. }
  1801. dst[dstOffset] = x0;
  1802. dst[dstOffset + 1] = y0;
  1803. dst[dstOffset + 2] = z0;
  1804. dst[dstOffset + 3] = w0;
  1805. }
  1806. static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
  1807. const x0 = src0[srcOffset0];
  1808. const y0 = src0[srcOffset0 + 1];
  1809. const z0 = src0[srcOffset0 + 2];
  1810. const w0 = src0[srcOffset0 + 3];
  1811. const x1 = src1[srcOffset1];
  1812. const y1 = src1[srcOffset1 + 1];
  1813. const z1 = src1[srcOffset1 + 2];
  1814. const w1 = src1[srcOffset1 + 3];
  1815. dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  1816. dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  1817. dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  1818. dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  1819. return dst;
  1820. }
  1821. get x() {
  1822. return this._x;
  1823. }
  1824. set x(value) {
  1825. this._x = value;
  1826. this._onChangeCallback();
  1827. }
  1828. get y() {
  1829. return this._y;
  1830. }
  1831. set y(value) {
  1832. this._y = value;
  1833. this._onChangeCallback();
  1834. }
  1835. get z() {
  1836. return this._z;
  1837. }
  1838. set z(value) {
  1839. this._z = value;
  1840. this._onChangeCallback();
  1841. }
  1842. get w() {
  1843. return this._w;
  1844. }
  1845. set w(value) {
  1846. this._w = value;
  1847. this._onChangeCallback();
  1848. }
  1849. set(x, y, z, w) {
  1850. this._x = x;
  1851. this._y = y;
  1852. this._z = z;
  1853. this._w = w;
  1854. this._onChangeCallback();
  1855. return this;
  1856. }
  1857. clone() {
  1858. return new this.constructor(this._x, this._y, this._z, this._w);
  1859. }
  1860. copy(quaternion) {
  1861. this._x = quaternion.x;
  1862. this._y = quaternion.y;
  1863. this._z = quaternion.z;
  1864. this._w = quaternion.w;
  1865. this._onChangeCallback();
  1866. return this;
  1867. }
  1868. setFromEuler(euler, update) {
  1869. if (!(euler && euler.isEuler)) {
  1870. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  1871. }
  1872. const x = euler._x,
  1873. y = euler._y,
  1874. z = euler._z,
  1875. order = euler._order; // http://www.mathworks.com/matlabcentral/fileexchange/
  1876. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1877. // content/SpinCalc.m
  1878. const cos = Math.cos;
  1879. const sin = Math.sin;
  1880. const c1 = cos(x / 2);
  1881. const c2 = cos(y / 2);
  1882. const c3 = cos(z / 2);
  1883. const s1 = sin(x / 2);
  1884. const s2 = sin(y / 2);
  1885. const s3 = sin(z / 2);
  1886. switch (order) {
  1887. case 'XYZ':
  1888. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1889. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1890. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1891. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1892. break;
  1893. case 'YXZ':
  1894. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1895. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1896. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1897. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1898. break;
  1899. case 'ZXY':
  1900. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1901. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1902. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1903. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1904. break;
  1905. case 'ZYX':
  1906. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1907. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1908. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1909. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1910. break;
  1911. case 'YZX':
  1912. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1913. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1914. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1915. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1916. break;
  1917. case 'XZY':
  1918. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1919. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1920. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1921. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1922. break;
  1923. default:
  1924. console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
  1925. }
  1926. if (update !== false) this._onChangeCallback();
  1927. return this;
  1928. }
  1929. setFromAxisAngle(axis, angle) {
  1930. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1931. // assumes axis is normalized
  1932. const halfAngle = angle / 2,
  1933. s = Math.sin(halfAngle);
  1934. this._x = axis.x * s;
  1935. this._y = axis.y * s;
  1936. this._z = axis.z * s;
  1937. this._w = Math.cos(halfAngle);
  1938. this._onChangeCallback();
  1939. return this;
  1940. }
  1941. setFromRotationMatrix(m) {
  1942. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1943. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1944. const te = m.elements,
  1945. m11 = te[0],
  1946. m12 = te[4],
  1947. m13 = te[8],
  1948. m21 = te[1],
  1949. m22 = te[5],
  1950. m23 = te[9],
  1951. m31 = te[2],
  1952. m32 = te[6],
  1953. m33 = te[10],
  1954. trace = m11 + m22 + m33;
  1955. if (trace > 0) {
  1956. const s = 0.5 / Math.sqrt(trace + 1.0);
  1957. this._w = 0.25 / s;
  1958. this._x = (m32 - m23) * s;
  1959. this._y = (m13 - m31) * s;
  1960. this._z = (m21 - m12) * s;
  1961. } else if (m11 > m22 && m11 > m33) {
  1962. const s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1963. this._w = (m32 - m23) / s;
  1964. this._x = 0.25 * s;
  1965. this._y = (m12 + m21) / s;
  1966. this._z = (m13 + m31) / s;
  1967. } else if (m22 > m33) {
  1968. const s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1969. this._w = (m13 - m31) / s;
  1970. this._x = (m12 + m21) / s;
  1971. this._y = 0.25 * s;
  1972. this._z = (m23 + m32) / s;
  1973. } else {
  1974. const s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1975. this._w = (m21 - m12) / s;
  1976. this._x = (m13 + m31) / s;
  1977. this._y = (m23 + m32) / s;
  1978. this._z = 0.25 * s;
  1979. }
  1980. this._onChangeCallback();
  1981. return this;
  1982. }
  1983. setFromUnitVectors(vFrom, vTo) {
  1984. // assumes direction vectors vFrom and vTo are normalized
  1985. let r = vFrom.dot(vTo) + 1;
  1986. if (r < Number.EPSILON) {
  1987. // vFrom and vTo point in opposite directions
  1988. r = 0;
  1989. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  1990. this._x = -vFrom.y;
  1991. this._y = vFrom.x;
  1992. this._z = 0;
  1993. this._w = r;
  1994. } else {
  1995. this._x = 0;
  1996. this._y = -vFrom.z;
  1997. this._z = vFrom.y;
  1998. this._w = r;
  1999. }
  2000. } else {
  2001. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2002. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2003. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2004. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2005. this._w = r;
  2006. }
  2007. return this.normalize();
  2008. }
  2009. angleTo(q) {
  2010. return 2 * Math.acos(Math.abs(clamp(this.dot(q), -1, 1)));
  2011. }
  2012. rotateTowards(q, step) {
  2013. const angle = this.angleTo(q);
  2014. if (angle === 0) return this;
  2015. const t = Math.min(1, step / angle);
  2016. this.slerp(q, t);
  2017. return this;
  2018. }
  2019. identity() {
  2020. return this.set(0, 0, 0, 1);
  2021. }
  2022. invert() {
  2023. // quaternion is assumed to have unit length
  2024. return this.conjugate();
  2025. }
  2026. conjugate() {
  2027. this._x *= -1;
  2028. this._y *= -1;
  2029. this._z *= -1;
  2030. this._onChangeCallback();
  2031. return this;
  2032. }
  2033. dot(v) {
  2034. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2035. }
  2036. lengthSq() {
  2037. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2038. }
  2039. length() {
  2040. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  2041. }
  2042. normalize() {
  2043. let l = this.length();
  2044. if (l === 0) {
  2045. this._x = 0;
  2046. this._y = 0;
  2047. this._z = 0;
  2048. this._w = 1;
  2049. } else {
  2050. l = 1 / l;
  2051. this._x = this._x * l;
  2052. this._y = this._y * l;
  2053. this._z = this._z * l;
  2054. this._w = this._w * l;
  2055. }
  2056. this._onChangeCallback();
  2057. return this;
  2058. }
  2059. multiply(q, p) {
  2060. if (p !== undefined) {
  2061. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  2062. return this.multiplyQuaternions(q, p);
  2063. }
  2064. return this.multiplyQuaternions(this, q);
  2065. }
  2066. premultiply(q) {
  2067. return this.multiplyQuaternions(q, this);
  2068. }
  2069. multiplyQuaternions(a, b) {
  2070. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2071. const qax = a._x,
  2072. qay = a._y,
  2073. qaz = a._z,
  2074. qaw = a._w;
  2075. const qbx = b._x,
  2076. qby = b._y,
  2077. qbz = b._z,
  2078. qbw = b._w;
  2079. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2080. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2081. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2082. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2083. this._onChangeCallback();
  2084. return this;
  2085. }
  2086. slerp(qb, t) {
  2087. if (t === 0) return this;
  2088. if (t === 1) return this.copy(qb);
  2089. const x = this._x,
  2090. y = this._y,
  2091. z = this._z,
  2092. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2093. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2094. if (cosHalfTheta < 0) {
  2095. this._w = -qb._w;
  2096. this._x = -qb._x;
  2097. this._y = -qb._y;
  2098. this._z = -qb._z;
  2099. cosHalfTheta = -cosHalfTheta;
  2100. } else {
  2101. this.copy(qb);
  2102. }
  2103. if (cosHalfTheta >= 1.0) {
  2104. this._w = w;
  2105. this._x = x;
  2106. this._y = y;
  2107. this._z = z;
  2108. return this;
  2109. }
  2110. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2111. if (sqrSinHalfTheta <= Number.EPSILON) {
  2112. const s = 1 - t;
  2113. this._w = s * w + t * this._w;
  2114. this._x = s * x + t * this._x;
  2115. this._y = s * y + t * this._y;
  2116. this._z = s * z + t * this._z;
  2117. this.normalize();
  2118. this._onChangeCallback();
  2119. return this;
  2120. }
  2121. const sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2122. const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2123. const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2124. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2125. this._w = w * ratioA + this._w * ratioB;
  2126. this._x = x * ratioA + this._x * ratioB;
  2127. this._y = y * ratioA + this._y * ratioB;
  2128. this._z = z * ratioA + this._z * ratioB;
  2129. this._onChangeCallback();
  2130. return this;
  2131. }
  2132. slerpQuaternions(qa, qb, t) {
  2133. this.copy(qa).slerp(qb, t);
  2134. }
  2135. random() {
  2136. // Derived from http://planning.cs.uiuc.edu/node198.html
  2137. // Note, this source uses w, x, y, z ordering,
  2138. // so we swap the order below.
  2139. const u1 = Math.random();
  2140. const sqrt1u1 = Math.sqrt(1 - u1);
  2141. const sqrtu1 = Math.sqrt(u1);
  2142. const u2 = 2 * Math.PI * Math.random();
  2143. const u3 = 2 * Math.PI * Math.random();
  2144. return this.set(sqrt1u1 * Math.cos(u2), sqrtu1 * Math.sin(u3), sqrtu1 * Math.cos(u3), sqrt1u1 * Math.sin(u2));
  2145. }
  2146. equals(quaternion) {
  2147. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2148. }
  2149. fromArray(array, offset = 0) {
  2150. this._x = array[offset];
  2151. this._y = array[offset + 1];
  2152. this._z = array[offset + 2];
  2153. this._w = array[offset + 3];
  2154. this._onChangeCallback();
  2155. return this;
  2156. }
  2157. toArray(array = [], offset = 0) {
  2158. array[offset] = this._x;
  2159. array[offset + 1] = this._y;
  2160. array[offset + 2] = this._z;
  2161. array[offset + 3] = this._w;
  2162. return array;
  2163. }
  2164. fromBufferAttribute(attribute, index) {
  2165. this._x = attribute.getX(index);
  2166. this._y = attribute.getY(index);
  2167. this._z = attribute.getZ(index);
  2168. this._w = attribute.getW(index);
  2169. return this;
  2170. }
  2171. _onChange(callback) {
  2172. this._onChangeCallback = callback;
  2173. return this;
  2174. }
  2175. _onChangeCallback() {}
  2176. }
  2177. Quaternion.prototype.isQuaternion = true;
  2178. class Vector3 {
  2179. constructor(x = 0, y = 0, z = 0) {
  2180. this.x = x;
  2181. this.y = y;
  2182. this.z = z;
  2183. }
  2184. set(x, y, z) {
  2185. if (z === undefined) z = this.z; // sprite.scale.set(x,y)
  2186. this.x = x;
  2187. this.y = y;
  2188. this.z = z;
  2189. return this;
  2190. }
  2191. setScalar(scalar) {
  2192. this.x = scalar;
  2193. this.y = scalar;
  2194. this.z = scalar;
  2195. return this;
  2196. }
  2197. setX(x) {
  2198. this.x = x;
  2199. return this;
  2200. }
  2201. setY(y) {
  2202. this.y = y;
  2203. return this;
  2204. }
  2205. setZ(z) {
  2206. this.z = z;
  2207. return this;
  2208. }
  2209. setComponent(index, value) {
  2210. switch (index) {
  2211. case 0:
  2212. this.x = value;
  2213. break;
  2214. case 1:
  2215. this.y = value;
  2216. break;
  2217. case 2:
  2218. this.z = value;
  2219. break;
  2220. default:
  2221. throw new Error('index is out of range: ' + index);
  2222. }
  2223. return this;
  2224. }
  2225. getComponent(index) {
  2226. switch (index) {
  2227. case 0:
  2228. return this.x;
  2229. case 1:
  2230. return this.y;
  2231. case 2:
  2232. return this.z;
  2233. default:
  2234. throw new Error('index is out of range: ' + index);
  2235. }
  2236. }
  2237. clone() {
  2238. return new this.constructor(this.x, this.y, this.z);
  2239. }
  2240. copy(v) {
  2241. this.x = v.x;
  2242. this.y = v.y;
  2243. this.z = v.z;
  2244. return this;
  2245. }
  2246. add(v, w) {
  2247. if (w !== undefined) {
  2248. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2249. return this.addVectors(v, w);
  2250. }
  2251. this.x += v.x;
  2252. this.y += v.y;
  2253. this.z += v.z;
  2254. return this;
  2255. }
  2256. addScalar(s) {
  2257. this.x += s;
  2258. this.y += s;
  2259. this.z += s;
  2260. return this;
  2261. }
  2262. addVectors(a, b) {
  2263. this.x = a.x + b.x;
  2264. this.y = a.y + b.y;
  2265. this.z = a.z + b.z;
  2266. return this;
  2267. }
  2268. addScaledVector(v, s) {
  2269. this.x += v.x * s;
  2270. this.y += v.y * s;
  2271. this.z += v.z * s;
  2272. return this;
  2273. }
  2274. sub(v, w) {
  2275. if (w !== undefined) {
  2276. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2277. return this.subVectors(v, w);
  2278. }
  2279. this.x -= v.x;
  2280. this.y -= v.y;
  2281. this.z -= v.z;
  2282. return this;
  2283. }
  2284. subScalar(s) {
  2285. this.x -= s;
  2286. this.y -= s;
  2287. this.z -= s;
  2288. return this;
  2289. }
  2290. subVectors(a, b) {
  2291. this.x = a.x - b.x;
  2292. this.y = a.y - b.y;
  2293. this.z = a.z - b.z;
  2294. return this;
  2295. }
  2296. multiply(v, w) {
  2297. if (w !== undefined) {
  2298. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  2299. return this.multiplyVectors(v, w);
  2300. }
  2301. this.x *= v.x;
  2302. this.y *= v.y;
  2303. this.z *= v.z;
  2304. return this;
  2305. }
  2306. multiplyScalar(scalar) {
  2307. this.x *= scalar;
  2308. this.y *= scalar;
  2309. this.z *= scalar;
  2310. return this;
  2311. }
  2312. multiplyVectors(a, b) {
  2313. this.x = a.x * b.x;
  2314. this.y = a.y * b.y;
  2315. this.z = a.z * b.z;
  2316. return this;
  2317. }
  2318. applyEuler(euler) {
  2319. if (!(euler && euler.isEuler)) {
  2320. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2321. }
  2322. return this.applyQuaternion(_quaternion$4.setFromEuler(euler));
  2323. }
  2324. applyAxisAngle(axis, angle) {
  2325. return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle));
  2326. }
  2327. applyMatrix3(m) {
  2328. const x = this.x,
  2329. y = this.y,
  2330. z = this.z;
  2331. const e = m.elements;
  2332. this.x = e[0] * x + e[3] * y + e[6] * z;
  2333. this.y = e[1] * x + e[4] * y + e[7] * z;
  2334. this.z = e[2] * x + e[5] * y + e[8] * z;
  2335. return this;
  2336. }
  2337. applyNormalMatrix(m) {
  2338. return this.applyMatrix3(m).normalize();
  2339. }
  2340. applyMatrix4(m) {
  2341. const x = this.x,
  2342. y = this.y,
  2343. z = this.z;
  2344. const e = m.elements;
  2345. const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2346. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2347. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2348. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2349. return this;
  2350. }
  2351. applyQuaternion(q) {
  2352. const x = this.x,
  2353. y = this.y,
  2354. z = this.z;
  2355. const qx = q.x,
  2356. qy = q.y,
  2357. qz = q.z,
  2358. qw = q.w; // calculate quat * vector
  2359. const ix = qw * x + qy * z - qz * y;
  2360. const iy = qw * y + qz * x - qx * z;
  2361. const iz = qw * z + qx * y - qy * x;
  2362. const iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  2363. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2364. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2365. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2366. return this;
  2367. }
  2368. project(camera) {
  2369. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  2370. }
  2371. unproject(camera) {
  2372. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  2373. }
  2374. transformDirection(m) {
  2375. // input: THREE.Matrix4 affine matrix
  2376. // vector interpreted as a direction
  2377. const x = this.x,
  2378. y = this.y,
  2379. z = this.z;
  2380. const e = m.elements;
  2381. this.x = e[0] * x + e[4] * y + e[8] * z;
  2382. this.y = e[1] * x + e[5] * y + e[9] * z;
  2383. this.z = e[2] * x + e[6] * y + e[10] * z;
  2384. return this.normalize();
  2385. }
  2386. divide(v) {
  2387. this.x /= v.x;
  2388. this.y /= v.y;
  2389. this.z /= v.z;
  2390. return this;
  2391. }
  2392. divideScalar(scalar) {
  2393. return this.multiplyScalar(1 / scalar);
  2394. }
  2395. min(v) {
  2396. this.x = Math.min(this.x, v.x);
  2397. this.y = Math.min(this.y, v.y);
  2398. this.z = Math.min(this.z, v.z);
  2399. return this;
  2400. }
  2401. max(v) {
  2402. this.x = Math.max(this.x, v.x);
  2403. this.y = Math.max(this.y, v.y);
  2404. this.z = Math.max(this.z, v.z);
  2405. return this;
  2406. }
  2407. clamp(min, max) {
  2408. // assumes min < max, componentwise
  2409. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2410. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2411. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2412. return this;
  2413. }
  2414. clampScalar(minVal, maxVal) {
  2415. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2416. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2417. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2418. return this;
  2419. }
  2420. clampLength(min, max) {
  2421. const length = this.length();
  2422. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2423. }
  2424. floor() {
  2425. this.x = Math.floor(this.x);
  2426. this.y = Math.floor(this.y);
  2427. this.z = Math.floor(this.z);
  2428. return this;
  2429. }
  2430. ceil() {
  2431. this.x = Math.ceil(this.x);
  2432. this.y = Math.ceil(this.y);
  2433. this.z = Math.ceil(this.z);
  2434. return this;
  2435. }
  2436. round() {
  2437. this.x = Math.round(this.x);
  2438. this.y = Math.round(this.y);
  2439. this.z = Math.round(this.z);
  2440. return this;
  2441. }
  2442. roundToZero() {
  2443. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2444. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2445. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2446. return this;
  2447. }
  2448. negate() {
  2449. this.x = -this.x;
  2450. this.y = -this.y;
  2451. this.z = -this.z;
  2452. return this;
  2453. }
  2454. dot(v) {
  2455. return this.x * v.x + this.y * v.y + this.z * v.z;
  2456. } // TODO lengthSquared?
  2457. lengthSq() {
  2458. return this.x * this.x + this.y * this.y + this.z * this.z;
  2459. }
  2460. length() {
  2461. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2462. }
  2463. manhattanLength() {
  2464. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  2465. }
  2466. normalize() {
  2467. return this.divideScalar(this.length() || 1);
  2468. }
  2469. setLength(length) {
  2470. return this.normalize().multiplyScalar(length);
  2471. }
  2472. lerp(v, alpha) {
  2473. this.x += (v.x - this.x) * alpha;
  2474. this.y += (v.y - this.y) * alpha;
  2475. this.z += (v.z - this.z) * alpha;
  2476. return this;
  2477. }
  2478. lerpVectors(v1, v2, alpha) {
  2479. this.x = v1.x + (v2.x - v1.x) * alpha;
  2480. this.y = v1.y + (v2.y - v1.y) * alpha;
  2481. this.z = v1.z + (v2.z - v1.z) * alpha;
  2482. return this;
  2483. }
  2484. cross(v, w) {
  2485. if (w !== undefined) {
  2486. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  2487. return this.crossVectors(v, w);
  2488. }
  2489. return this.crossVectors(this, v);
  2490. }
  2491. crossVectors(a, b) {
  2492. const ax = a.x,
  2493. ay = a.y,
  2494. az = a.z;
  2495. const bx = b.x,
  2496. by = b.y,
  2497. bz = b.z;
  2498. this.x = ay * bz - az * by;
  2499. this.y = az * bx - ax * bz;
  2500. this.z = ax * by - ay * bx;
  2501. return this;
  2502. }
  2503. projectOnVector(v) {
  2504. const denominator = v.lengthSq();
  2505. if (denominator === 0) return this.set(0, 0, 0);
  2506. const scalar = v.dot(this) / denominator;
  2507. return this.copy(v).multiplyScalar(scalar);
  2508. }
  2509. projectOnPlane(planeNormal) {
  2510. _vector$c.copy(this).projectOnVector(planeNormal);
  2511. return this.sub(_vector$c);
  2512. }
  2513. reflect(normal) {
  2514. // reflect incident vector off plane orthogonal to normal
  2515. // normal is assumed to have unit length
  2516. return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal)));
  2517. }
  2518. angleTo(v) {
  2519. const denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  2520. if (denominator === 0) return Math.PI / 2;
  2521. const theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  2522. return Math.acos(clamp(theta, -1, 1));
  2523. }
  2524. distanceTo(v) {
  2525. return Math.sqrt(this.distanceToSquared(v));
  2526. }
  2527. distanceToSquared(v) {
  2528. const dx = this.x - v.x,
  2529. dy = this.y - v.y,
  2530. dz = this.z - v.z;
  2531. return dx * dx + dy * dy + dz * dz;
  2532. }
  2533. manhattanDistanceTo(v) {
  2534. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  2535. }
  2536. setFromSpherical(s) {
  2537. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  2538. }
  2539. setFromSphericalCoords(radius, phi, theta) {
  2540. const sinPhiRadius = Math.sin(phi) * radius;
  2541. this.x = sinPhiRadius * Math.sin(theta);
  2542. this.y = Math.cos(phi) * radius;
  2543. this.z = sinPhiRadius * Math.cos(theta);
  2544. return this;
  2545. }
  2546. setFromCylindrical(c) {
  2547. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  2548. }
  2549. setFromCylindricalCoords(radius, theta, y) {
  2550. this.x = radius * Math.sin(theta);
  2551. this.y = y;
  2552. this.z = radius * Math.cos(theta);
  2553. return this;
  2554. }
  2555. setFromMatrixPosition(m) {
  2556. const e = m.elements;
  2557. this.x = e[12];
  2558. this.y = e[13];
  2559. this.z = e[14];
  2560. return this;
  2561. }
  2562. setFromMatrixScale(m) {
  2563. const sx = this.setFromMatrixColumn(m, 0).length();
  2564. const sy = this.setFromMatrixColumn(m, 1).length();
  2565. const sz = this.setFromMatrixColumn(m, 2).length();
  2566. this.x = sx;
  2567. this.y = sy;
  2568. this.z = sz;
  2569. return this;
  2570. }
  2571. setFromMatrixColumn(m, index) {
  2572. return this.fromArray(m.elements, index * 4);
  2573. }
  2574. setFromMatrix3Column(m, index) {
  2575. return this.fromArray(m.elements, index * 3);
  2576. }
  2577. equals(v) {
  2578. return v.x === this.x && v.y === this.y && v.z === this.z;
  2579. }
  2580. fromArray(array, offset = 0) {
  2581. this.x = array[offset];
  2582. this.y = array[offset + 1];
  2583. this.z = array[offset + 2];
  2584. return this;
  2585. }
  2586. toArray(array = [], offset = 0) {
  2587. array[offset] = this.x;
  2588. array[offset + 1] = this.y;
  2589. array[offset + 2] = this.z;
  2590. return array;
  2591. }
  2592. fromBufferAttribute(attribute, index, offset) {
  2593. if (offset !== undefined) {
  2594. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  2595. }
  2596. this.x = attribute.getX(index);
  2597. this.y = attribute.getY(index);
  2598. this.z = attribute.getZ(index);
  2599. return this;
  2600. }
  2601. random() {
  2602. this.x = Math.random();
  2603. this.y = Math.random();
  2604. this.z = Math.random();
  2605. return this;
  2606. }
  2607. randomDirection() {
  2608. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  2609. const u = (Math.random() - 0.5) * 2;
  2610. const t = Math.random() * Math.PI * 2;
  2611. const f = Math.sqrt(1 - u ** 2);
  2612. this.x = f * Math.cos(t);
  2613. this.y = f * Math.sin(t);
  2614. this.z = u;
  2615. return this;
  2616. }
  2617. *[Symbol.iterator]() {
  2618. yield this.x;
  2619. yield this.y;
  2620. yield this.z;
  2621. }
  2622. }
  2623. Vector3.prototype.isVector3 = true;
  2624. const _vector$c = /*@__PURE__*/new Vector3();
  2625. const _quaternion$4 = /*@__PURE__*/new Quaternion();
  2626. class Box3 {
  2627. constructor(min = new Vector3(+Infinity, +Infinity, +Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity)) {
  2628. this.min = min;
  2629. this.max = max;
  2630. }
  2631. set(min, max) {
  2632. this.min.copy(min);
  2633. this.max.copy(max);
  2634. return this;
  2635. }
  2636. setFromArray(array) {
  2637. let minX = +Infinity;
  2638. let minY = +Infinity;
  2639. let minZ = +Infinity;
  2640. let maxX = -Infinity;
  2641. let maxY = -Infinity;
  2642. let maxZ = -Infinity;
  2643. for (let i = 0, l = array.length; i < l; i += 3) {
  2644. const x = array[i];
  2645. const y = array[i + 1];
  2646. const z = array[i + 2];
  2647. if (x < minX) minX = x;
  2648. if (y < minY) minY = y;
  2649. if (z < minZ) minZ = z;
  2650. if (x > maxX) maxX = x;
  2651. if (y > maxY) maxY = y;
  2652. if (z > maxZ) maxZ = z;
  2653. }
  2654. this.min.set(minX, minY, minZ);
  2655. this.max.set(maxX, maxY, maxZ);
  2656. return this;
  2657. }
  2658. setFromBufferAttribute(attribute) {
  2659. let minX = +Infinity;
  2660. let minY = +Infinity;
  2661. let minZ = +Infinity;
  2662. let maxX = -Infinity;
  2663. let maxY = -Infinity;
  2664. let maxZ = -Infinity;
  2665. for (let i = 0, l = attribute.count; i < l; i++) {
  2666. const x = attribute.getX(i);
  2667. const y = attribute.getY(i);
  2668. const z = attribute.getZ(i);
  2669. if (x < minX) minX = x;
  2670. if (y < minY) minY = y;
  2671. if (z < minZ) minZ = z;
  2672. if (x > maxX) maxX = x;
  2673. if (y > maxY) maxY = y;
  2674. if (z > maxZ) maxZ = z;
  2675. }
  2676. this.min.set(minX, minY, minZ);
  2677. this.max.set(maxX, maxY, maxZ);
  2678. return this;
  2679. }
  2680. setFromPoints(points) {
  2681. this.makeEmpty();
  2682. for (let i = 0, il = points.length; i < il; i++) {
  2683. this.expandByPoint(points[i]);
  2684. }
  2685. return this;
  2686. }
  2687. setFromCenterAndSize(center, size) {
  2688. const halfSize = _vector$b.copy(size).multiplyScalar(0.5);
  2689. this.min.copy(center).sub(halfSize);
  2690. this.max.copy(center).add(halfSize);
  2691. return this;
  2692. }
  2693. setFromObject(object) {
  2694. this.makeEmpty();
  2695. return this.expandByObject(object);
  2696. }
  2697. clone() {
  2698. return new this.constructor().copy(this);
  2699. }
  2700. copy(box) {
  2701. this.min.copy(box.min);
  2702. this.max.copy(box.max);
  2703. return this;
  2704. }
  2705. makeEmpty() {
  2706. this.min.x = this.min.y = this.min.z = +Infinity;
  2707. this.max.x = this.max.y = this.max.z = -Infinity;
  2708. return this;
  2709. }
  2710. isEmpty() {
  2711. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2712. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  2713. }
  2714. getCenter(target) {
  2715. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  2716. }
  2717. getSize(target) {
  2718. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  2719. }
  2720. expandByPoint(point) {
  2721. this.min.min(point);
  2722. this.max.max(point);
  2723. return this;
  2724. }
  2725. expandByVector(vector) {
  2726. this.min.sub(vector);
  2727. this.max.add(vector);
  2728. return this;
  2729. }
  2730. expandByScalar(scalar) {
  2731. this.min.addScalar(-scalar);
  2732. this.max.addScalar(scalar);
  2733. return this;
  2734. }
  2735. expandByObject(object) {
  2736. // Computes the world-axis-aligned bounding box of an object (including its children),
  2737. // accounting for both the object's, and children's, world transforms
  2738. object.updateWorldMatrix(false, false);
  2739. const geometry = object.geometry;
  2740. if (geometry !== undefined) {
  2741. if (geometry.boundingBox === null) {
  2742. geometry.computeBoundingBox();
  2743. }
  2744. _box$3.copy(geometry.boundingBox);
  2745. _box$3.applyMatrix4(object.matrixWorld);
  2746. this.union(_box$3);
  2747. }
  2748. const children = object.children;
  2749. for (let i = 0, l = children.length; i < l; i++) {
  2750. this.expandByObject(children[i]);
  2751. }
  2752. return this;
  2753. }
  2754. containsPoint(point) {
  2755. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y || point.z < this.min.z || point.z > this.max.z ? false : true;
  2756. }
  2757. containsBox(box) {
  2758. return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y && this.min.z <= box.min.z && box.max.z <= this.max.z;
  2759. }
  2760. getParameter(point, target) {
  2761. // This can potentially have a divide by zero if the box
  2762. // has a size dimension of 0.
  2763. return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y), (point.z - this.min.z) / (this.max.z - this.min.z));
  2764. }
  2765. intersectsBox(box) {
  2766. // using 6 splitting planes to rule out intersections.
  2767. return box.max.x < this.min.x || box.min.x > this.max.x || box.max.y < this.min.y || box.min.y > this.max.y || box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  2768. }
  2769. intersectsSphere(sphere) {
  2770. // Find the point on the AABB closest to the sphere center.
  2771. this.clampPoint(sphere.center, _vector$b); // If that point is inside the sphere, the AABB and sphere intersect.
  2772. return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  2773. }
  2774. intersectsPlane(plane) {
  2775. // We compute the minimum and maximum dot product values. If those values
  2776. // are on the same side (back or front) of the plane, then there is no intersection.
  2777. let min, max;
  2778. if (plane.normal.x > 0) {
  2779. min = plane.normal.x * this.min.x;
  2780. max = plane.normal.x * this.max.x;
  2781. } else {
  2782. min = plane.normal.x * this.max.x;
  2783. max = plane.normal.x * this.min.x;
  2784. }
  2785. if (plane.normal.y > 0) {
  2786. min += plane.normal.y * this.min.y;
  2787. max += plane.normal.y * this.max.y;
  2788. } else {
  2789. min += plane.normal.y * this.max.y;
  2790. max += plane.normal.y * this.min.y;
  2791. }
  2792. if (plane.normal.z > 0) {
  2793. min += plane.normal.z * this.min.z;
  2794. max += plane.normal.z * this.max.z;
  2795. } else {
  2796. min += plane.normal.z * this.max.z;
  2797. max += plane.normal.z * this.min.z;
  2798. }
  2799. return min <= -plane.constant && max >= -plane.constant;
  2800. }
  2801. intersectsTriangle(triangle) {
  2802. if (this.isEmpty()) {
  2803. return false;
  2804. } // compute box center and extents
  2805. this.getCenter(_center);
  2806. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  2807. _v0$2.subVectors(triangle.a, _center);
  2808. _v1$7.subVectors(triangle.b, _center);
  2809. _v2$3.subVectors(triangle.c, _center); // compute edge vectors for triangle
  2810. _f0.subVectors(_v1$7, _v0$2);
  2811. _f1.subVectors(_v2$3, _v1$7);
  2812. _f2.subVectors(_v0$2, _v2$3); // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2813. // 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
  2814. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2815. let axes = [0, -_f0.z, _f0.y, 0, -_f1.z, _f1.y, 0, -_f2.z, _f2.y, _f0.z, 0, -_f0.x, _f1.z, 0, -_f1.x, _f2.z, 0, -_f2.x, -_f0.y, _f0.x, 0, -_f1.y, _f1.x, 0, -_f2.y, _f2.x, 0];
  2816. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  2817. return false;
  2818. } // test 3 face normals from the aabb
  2819. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  2820. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  2821. return false;
  2822. } // finally testing the face normal of the triangle
  2823. // use already existing triangle edge vectors here
  2824. _triangleNormal.crossVectors(_f0, _f1);
  2825. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  2826. return satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents);
  2827. }
  2828. clampPoint(point, target) {
  2829. return target.copy(point).clamp(this.min, this.max);
  2830. }
  2831. distanceToPoint(point) {
  2832. const clampedPoint = _vector$b.copy(point).clamp(this.min, this.max);
  2833. return clampedPoint.sub(point).length();
  2834. }
  2835. getBoundingSphere(target) {
  2836. this.getCenter(target.center);
  2837. target.radius = this.getSize(_vector$b).length() * 0.5;
  2838. return target;
  2839. }
  2840. intersect(box) {
  2841. this.min.max(box.min);
  2842. this.max.min(box.max); // 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.
  2843. if (this.isEmpty()) this.makeEmpty();
  2844. return this;
  2845. }
  2846. union(box) {
  2847. this.min.min(box.min);
  2848. this.max.max(box.max);
  2849. return this;
  2850. }
  2851. applyMatrix4(matrix) {
  2852. // transform of empty box is an empty box.
  2853. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2854. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  2855. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  2856. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  2857. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  2858. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  2859. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  2860. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  2861. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  2862. this.setFromPoints(_points);
  2863. return this;
  2864. }
  2865. translate(offset) {
  2866. this.min.add(offset);
  2867. this.max.add(offset);
  2868. return this;
  2869. }
  2870. equals(box) {
  2871. return box.min.equals(this.min) && box.max.equals(this.max);
  2872. }
  2873. }
  2874. Box3.prototype.isBox3 = true;
  2875. const _points = [/*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3()];
  2876. const _vector$b = /*@__PURE__*/new Vector3();
  2877. const _box$3 = /*@__PURE__*/new Box3(); // triangle centered vertices
  2878. const _v0$2 = /*@__PURE__*/new Vector3();
  2879. const _v1$7 = /*@__PURE__*/new Vector3();
  2880. const _v2$3 = /*@__PURE__*/new Vector3(); // triangle edge vectors
  2881. const _f0 = /*@__PURE__*/new Vector3();
  2882. const _f1 = /*@__PURE__*/new Vector3();
  2883. const _f2 = /*@__PURE__*/new Vector3();
  2884. const _center = /*@__PURE__*/new Vector3();
  2885. const _extents = /*@__PURE__*/new Vector3();
  2886. const _triangleNormal = /*@__PURE__*/new Vector3();
  2887. const _testAxis = /*@__PURE__*/new Vector3();
  2888. function satForAxes(axes, v0, v1, v2, extents) {
  2889. for (let i = 0, j = axes.length - 3; i <= j; i += 3) {
  2890. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  2891. const r = extents.x * Math.abs(_testAxis.x) + extents.y * Math.abs(_testAxis.y) + extents.z * Math.abs(_testAxis.z); // project all 3 vertices of the triangle onto the seperating axis
  2892. const p0 = v0.dot(_testAxis);
  2893. const p1 = v1.dot(_testAxis);
  2894. const p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  2895. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  2896. // points of the projected triangle are outside the projected half-length of the aabb
  2897. // the axis is seperating and we can exit
  2898. return false;
  2899. }
  2900. }
  2901. return true;
  2902. }
  2903. const _box$2 = /*@__PURE__*/new Box3();
  2904. const _v1$6 = /*@__PURE__*/new Vector3();
  2905. const _toFarthestPoint = /*@__PURE__*/new Vector3();
  2906. const _toPoint = /*@__PURE__*/new Vector3();
  2907. class Sphere {
  2908. constructor(center = new Vector3(), radius = -1) {
  2909. this.center = center;
  2910. this.radius = radius;
  2911. }
  2912. set(center, radius) {
  2913. this.center.copy(center);
  2914. this.radius = radius;
  2915. return this;
  2916. }
  2917. setFromPoints(points, optionalCenter) {
  2918. const center = this.center;
  2919. if (optionalCenter !== undefined) {
  2920. center.copy(optionalCenter);
  2921. } else {
  2922. _box$2.setFromPoints(points).getCenter(center);
  2923. }
  2924. let maxRadiusSq = 0;
  2925. for (let i = 0, il = points.length; i < il; i++) {
  2926. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  2927. }
  2928. this.radius = Math.sqrt(maxRadiusSq);
  2929. return this;
  2930. }
  2931. copy(sphere) {
  2932. this.center.copy(sphere.center);
  2933. this.radius = sphere.radius;
  2934. return this;
  2935. }
  2936. isEmpty() {
  2937. return this.radius < 0;
  2938. }
  2939. makeEmpty() {
  2940. this.center.set(0, 0, 0);
  2941. this.radius = -1;
  2942. return this;
  2943. }
  2944. containsPoint(point) {
  2945. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  2946. }
  2947. distanceToPoint(point) {
  2948. return point.distanceTo(this.center) - this.radius;
  2949. }
  2950. intersectsSphere(sphere) {
  2951. const radiusSum = this.radius + sphere.radius;
  2952. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  2953. }
  2954. intersectsBox(box) {
  2955. return box.intersectsSphere(this);
  2956. }
  2957. intersectsPlane(plane) {
  2958. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  2959. }
  2960. clampPoint(point, target) {
  2961. const deltaLengthSq = this.center.distanceToSquared(point);
  2962. target.copy(point);
  2963. if (deltaLengthSq > this.radius * this.radius) {
  2964. target.sub(this.center).normalize();
  2965. target.multiplyScalar(this.radius).add(this.center);
  2966. }
  2967. return target;
  2968. }
  2969. getBoundingBox(target) {
  2970. if (this.isEmpty()) {
  2971. // Empty sphere produces empty bounding box
  2972. target.makeEmpty();
  2973. return target;
  2974. }
  2975. target.set(this.center, this.center);
  2976. target.expandByScalar(this.radius);
  2977. return target;
  2978. }
  2979. applyMatrix4(matrix) {
  2980. this.center.applyMatrix4(matrix);
  2981. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2982. return this;
  2983. }
  2984. translate(offset) {
  2985. this.center.add(offset);
  2986. return this;
  2987. }
  2988. expandByPoint(point) {
  2989. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  2990. _toPoint.subVectors(point, this.center);
  2991. const lengthSq = _toPoint.lengthSq();
  2992. if (lengthSq > this.radius * this.radius) {
  2993. const length = Math.sqrt(lengthSq);
  2994. const missingRadiusHalf = (length - this.radius) * 0.5; // Nudge this sphere towards the target point. Add half the missing distance to radius,
  2995. // and the other half to position. This gives a tighter enclosure, instead of if
  2996. // the whole missing distance were just added to radius.
  2997. this.center.add(_toPoint.multiplyScalar(missingRadiusHalf / length));
  2998. this.radius += missingRadiusHalf;
  2999. }
  3000. return this;
  3001. }
  3002. union(sphere) {
  3003. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  3004. // To enclose another sphere into this sphere, we only need to enclose two points:
  3005. // 1) Enclose the farthest point on the other sphere into this sphere.
  3006. // 2) Enclose the opposite point of the farthest point into this sphere.
  3007. if (this.center.equals(sphere.center) === true) {
  3008. _toFarthestPoint.set(0, 0, 1).multiplyScalar(sphere.radius);
  3009. } else {
  3010. _toFarthestPoint.subVectors(sphere.center, this.center).normalize().multiplyScalar(sphere.radius);
  3011. }
  3012. this.expandByPoint(_v1$6.copy(sphere.center).add(_toFarthestPoint));
  3013. this.expandByPoint(_v1$6.copy(sphere.center).sub(_toFarthestPoint));
  3014. return this;
  3015. }
  3016. equals(sphere) {
  3017. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  3018. }
  3019. clone() {
  3020. return new this.constructor().copy(this);
  3021. }
  3022. }
  3023. const _vector$a = /*@__PURE__*/new Vector3();
  3024. const _segCenter = /*@__PURE__*/new Vector3();
  3025. const _segDir = /*@__PURE__*/new Vector3();
  3026. const _diff = /*@__PURE__*/new Vector3();
  3027. const _edge1 = /*@__PURE__*/new Vector3();
  3028. const _edge2 = /*@__PURE__*/new Vector3();
  3029. const _normal$1 = /*@__PURE__*/new Vector3();
  3030. class Ray {
  3031. constructor(origin = new Vector3(), direction = new Vector3(0, 0, -1)) {
  3032. this.origin = origin;
  3033. this.direction = direction;
  3034. }
  3035. set(origin, direction) {
  3036. this.origin.copy(origin);
  3037. this.direction.copy(direction);
  3038. return this;
  3039. }
  3040. copy(ray) {
  3041. this.origin.copy(ray.origin);
  3042. this.direction.copy(ray.direction);
  3043. return this;
  3044. }
  3045. at(t, target) {
  3046. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  3047. }
  3048. lookAt(v) {
  3049. this.direction.copy(v).sub(this.origin).normalize();
  3050. return this;
  3051. }
  3052. recast(t) {
  3053. this.origin.copy(this.at(t, _vector$a));
  3054. return this;
  3055. }
  3056. closestPointToPoint(point, target) {
  3057. target.subVectors(point, this.origin);
  3058. const directionDistance = target.dot(this.direction);
  3059. if (directionDistance < 0) {
  3060. return target.copy(this.origin);
  3061. }
  3062. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3063. }
  3064. distanceToPoint(point) {
  3065. return Math.sqrt(this.distanceSqToPoint(point));
  3066. }
  3067. distanceSqToPoint(point) {
  3068. const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  3069. if (directionDistance < 0) {
  3070. return this.origin.distanceToSquared(point);
  3071. }
  3072. _vector$a.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3073. return _vector$a.distanceToSquared(point);
  3074. }
  3075. distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  3076. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3077. // It returns the min distance between the ray and the segment
  3078. // defined by v0 and v1
  3079. // It can also set two optional targets :
  3080. // - The closest point on the ray
  3081. // - The closest point on the segment
  3082. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  3083. _segDir.copy(v1).sub(v0).normalize();
  3084. _diff.copy(this.origin).sub(_segCenter);
  3085. const segExtent = v0.distanceTo(v1) * 0.5;
  3086. const a01 = -this.direction.dot(_segDir);
  3087. const b0 = _diff.dot(this.direction);
  3088. const b1 = -_diff.dot(_segDir);
  3089. const c = _diff.lengthSq();
  3090. const det = Math.abs(1 - a01 * a01);
  3091. let s0, s1, sqrDist, extDet;
  3092. if (det > 0) {
  3093. // The ray and segment are not parallel.
  3094. s0 = a01 * b1 - b0;
  3095. s1 = a01 * b0 - b1;
  3096. extDet = segExtent * det;
  3097. if (s0 >= 0) {
  3098. if (s1 >= -extDet) {
  3099. if (s1 <= extDet) {
  3100. // region 0
  3101. // Minimum at interior points of ray and segment.
  3102. const invDet = 1 / det;
  3103. s0 *= invDet;
  3104. s1 *= invDet;
  3105. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  3106. } else {
  3107. // region 1
  3108. s1 = segExtent;
  3109. s0 = Math.max(0, -(a01 * s1 + b0));
  3110. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3111. }
  3112. } else {
  3113. // region 5
  3114. s1 = -segExtent;
  3115. s0 = Math.max(0, -(a01 * s1 + b0));
  3116. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3117. }
  3118. } else {
  3119. if (s1 <= -extDet) {
  3120. // region 4
  3121. s0 = Math.max(0, -(-a01 * segExtent + b0));
  3122. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3123. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3124. } else if (s1 <= extDet) {
  3125. // region 3
  3126. s0 = 0;
  3127. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  3128. sqrDist = s1 * (s1 + 2 * b1) + c;
  3129. } else {
  3130. // region 2
  3131. s0 = Math.max(0, -(a01 * segExtent + b0));
  3132. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3133. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3134. }
  3135. }
  3136. } else {
  3137. // Ray and segment are parallel.
  3138. s1 = a01 > 0 ? -segExtent : segExtent;
  3139. s0 = Math.max(0, -(a01 * s1 + b0));
  3140. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3141. }
  3142. if (optionalPointOnRay) {
  3143. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  3144. }
  3145. if (optionalPointOnSegment) {
  3146. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  3147. }
  3148. return sqrDist;
  3149. }
  3150. intersectSphere(sphere, target) {
  3151. _vector$a.subVectors(sphere.center, this.origin);
  3152. const tca = _vector$a.dot(this.direction);
  3153. const d2 = _vector$a.dot(_vector$a) - tca * tca;
  3154. const radius2 = sphere.radius * sphere.radius;
  3155. if (d2 > radius2) return null;
  3156. const thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  3157. const t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  3158. const t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  3159. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  3160. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3161. // in order to always return an intersect point that is in front of the ray.
  3162. if (t0 < 0) return this.at(t1, target); // else t0 is in front of the ray, so return the first collision point scaled by t0
  3163. return this.at(t0, target);
  3164. }
  3165. intersectsSphere(sphere) {
  3166. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  3167. }
  3168. distanceToPlane(plane) {
  3169. const denominator = plane.normal.dot(this.direction);
  3170. if (denominator === 0) {
  3171. // line is coplanar, return origin
  3172. if (plane.distanceToPoint(this.origin) === 0) {
  3173. return 0;
  3174. } // Null is preferable to undefined since undefined means.... it is undefined
  3175. return null;
  3176. }
  3177. const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  3178. return t >= 0 ? t : null;
  3179. }
  3180. intersectPlane(plane, target) {
  3181. const t = this.distanceToPlane(plane);
  3182. if (t === null) {
  3183. return null;
  3184. }
  3185. return this.at(t, target);
  3186. }
  3187. intersectsPlane(plane) {
  3188. // check if the ray lies on the plane first
  3189. const distToPoint = plane.distanceToPoint(this.origin);
  3190. if (distToPoint === 0) {
  3191. return true;
  3192. }
  3193. const denominator = plane.normal.dot(this.direction);
  3194. if (denominator * distToPoint < 0) {
  3195. return true;
  3196. } // ray origin is behind the plane (and is pointing behind it)
  3197. return false;
  3198. }
  3199. intersectBox(box, target) {
  3200. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3201. const invdirx = 1 / this.direction.x,
  3202. invdiry = 1 / this.direction.y,
  3203. invdirz = 1 / this.direction.z;
  3204. const origin = this.origin;
  3205. if (invdirx >= 0) {
  3206. tmin = (box.min.x - origin.x) * invdirx;
  3207. tmax = (box.max.x - origin.x) * invdirx;
  3208. } else {
  3209. tmin = (box.max.x - origin.x) * invdirx;
  3210. tmax = (box.min.x - origin.x) * invdirx;
  3211. }
  3212. if (invdiry >= 0) {
  3213. tymin = (box.min.y - origin.y) * invdiry;
  3214. tymax = (box.max.y - origin.y) * invdiry;
  3215. } else {
  3216. tymin = (box.max.y - origin.y) * invdiry;
  3217. tymax = (box.min.y - origin.y) * invdiry;
  3218. }
  3219. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  3220. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3221. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  3222. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  3223. if (invdirz >= 0) {
  3224. tzmin = (box.min.z - origin.z) * invdirz;
  3225. tzmax = (box.max.z - origin.z) * invdirz;
  3226. } else {
  3227. tzmin = (box.max.z - origin.z) * invdirz;
  3228. tzmax = (box.min.z - origin.z) * invdirz;
  3229. }
  3230. if (tmin > tzmax || tzmin > tmax) return null;
  3231. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  3232. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  3233. if (tmax < 0) return null;
  3234. return this.at(tmin >= 0 ? tmin : tmax, target);
  3235. }
  3236. intersectsBox(box) {
  3237. return this.intersectBox(box, _vector$a) !== null;
  3238. }
  3239. intersectTriangle(a, b, c, backfaceCulling, target) {
  3240. // Compute the offset origin, edges, and normal.
  3241. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3242. _edge1.subVectors(b, a);
  3243. _edge2.subVectors(c, a);
  3244. _normal$1.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3245. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3246. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3247. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3248. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3249. let DdN = this.direction.dot(_normal$1);
  3250. let sign;
  3251. if (DdN > 0) {
  3252. if (backfaceCulling) return null;
  3253. sign = 1;
  3254. } else if (DdN < 0) {
  3255. sign = -1;
  3256. DdN = -DdN;
  3257. } else {
  3258. return null;
  3259. }
  3260. _diff.subVectors(this.origin, a);
  3261. const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  3262. if (DdQxE2 < 0) {
  3263. return null;
  3264. }
  3265. const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  3266. if (DdE1xQ < 0) {
  3267. return null;
  3268. } // b1+b2 > 1, no intersection
  3269. if (DdQxE2 + DdE1xQ > DdN) {
  3270. return null;
  3271. } // Line intersects triangle, check if ray does.
  3272. const QdN = -sign * _diff.dot(_normal$1); // t < 0, no intersection
  3273. if (QdN < 0) {
  3274. return null;
  3275. } // Ray intersects triangle.
  3276. return this.at(QdN / DdN, target);
  3277. }
  3278. applyMatrix4(matrix4) {
  3279. this.origin.applyMatrix4(matrix4);
  3280. this.direction.transformDirection(matrix4);
  3281. return this;
  3282. }
  3283. equals(ray) {
  3284. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  3285. }
  3286. clone() {
  3287. return new this.constructor().copy(this);
  3288. }
  3289. }
  3290. class Matrix4 {
  3291. constructor() {
  3292. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  3293. if (arguments.length > 0) {
  3294. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  3295. }
  3296. }
  3297. set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  3298. const te = this.elements;
  3299. te[0] = n11;
  3300. te[4] = n12;
  3301. te[8] = n13;
  3302. te[12] = n14;
  3303. te[1] = n21;
  3304. te[5] = n22;
  3305. te[9] = n23;
  3306. te[13] = n24;
  3307. te[2] = n31;
  3308. te[6] = n32;
  3309. te[10] = n33;
  3310. te[14] = n34;
  3311. te[3] = n41;
  3312. te[7] = n42;
  3313. te[11] = n43;
  3314. te[15] = n44;
  3315. return this;
  3316. }
  3317. identity() {
  3318. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3319. return this;
  3320. }
  3321. clone() {
  3322. return new Matrix4().fromArray(this.elements);
  3323. }
  3324. copy(m) {
  3325. const te = this.elements;
  3326. const me = m.elements;
  3327. te[0] = me[0];
  3328. te[1] = me[1];
  3329. te[2] = me[2];
  3330. te[3] = me[3];
  3331. te[4] = me[4];
  3332. te[5] = me[5];
  3333. te[6] = me[6];
  3334. te[7] = me[7];
  3335. te[8] = me[8];
  3336. te[9] = me[9];
  3337. te[10] = me[10];
  3338. te[11] = me[11];
  3339. te[12] = me[12];
  3340. te[13] = me[13];
  3341. te[14] = me[14];
  3342. te[15] = me[15];
  3343. return this;
  3344. }
  3345. copyPosition(m) {
  3346. const te = this.elements,
  3347. me = m.elements;
  3348. te[12] = me[12];
  3349. te[13] = me[13];
  3350. te[14] = me[14];
  3351. return this;
  3352. }
  3353. setFromMatrix3(m) {
  3354. const me = m.elements;
  3355. this.set(me[0], me[3], me[6], 0, me[1], me[4], me[7], 0, me[2], me[5], me[8], 0, 0, 0, 0, 1);
  3356. return this;
  3357. }
  3358. extractBasis(xAxis, yAxis, zAxis) {
  3359. xAxis.setFromMatrixColumn(this, 0);
  3360. yAxis.setFromMatrixColumn(this, 1);
  3361. zAxis.setFromMatrixColumn(this, 2);
  3362. return this;
  3363. }
  3364. makeBasis(xAxis, yAxis, zAxis) {
  3365. this.set(xAxis.x, yAxis.x, zAxis.x, 0, xAxis.y, yAxis.y, zAxis.y, 0, xAxis.z, yAxis.z, zAxis.z, 0, 0, 0, 0, 1);
  3366. return this;
  3367. }
  3368. extractRotation(m) {
  3369. // this method does not support reflection matrices
  3370. const te = this.elements;
  3371. const me = m.elements;
  3372. const scaleX = 1 / _v1$5.setFromMatrixColumn(m, 0).length();
  3373. const scaleY = 1 / _v1$5.setFromMatrixColumn(m, 1).length();
  3374. const scaleZ = 1 / _v1$5.setFromMatrixColumn(m, 2).length();
  3375. te[0] = me[0] * scaleX;
  3376. te[1] = me[1] * scaleX;
  3377. te[2] = me[2] * scaleX;
  3378. te[3] = 0;
  3379. te[4] = me[4] * scaleY;
  3380. te[5] = me[5] * scaleY;
  3381. te[6] = me[6] * scaleY;
  3382. te[7] = 0;
  3383. te[8] = me[8] * scaleZ;
  3384. te[9] = me[9] * scaleZ;
  3385. te[10] = me[10] * scaleZ;
  3386. te[11] = 0;
  3387. te[12] = 0;
  3388. te[13] = 0;
  3389. te[14] = 0;
  3390. te[15] = 1;
  3391. return this;
  3392. }
  3393. makeRotationFromEuler(euler) {
  3394. if (!(euler && euler.isEuler)) {
  3395. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  3396. }
  3397. const te = this.elements;
  3398. const x = euler.x,
  3399. y = euler.y,
  3400. z = euler.z;
  3401. const a = Math.cos(x),
  3402. b = Math.sin(x);
  3403. const c = Math.cos(y),
  3404. d = Math.sin(y);
  3405. const e = Math.cos(z),
  3406. f = Math.sin(z);
  3407. if (euler.order === 'XYZ') {
  3408. const ae = a * e,
  3409. af = a * f,
  3410. be = b * e,
  3411. bf = b * f;
  3412. te[0] = c * e;
  3413. te[4] = -c * f;
  3414. te[8] = d;
  3415. te[1] = af + be * d;
  3416. te[5] = ae - bf * d;
  3417. te[9] = -b * c;
  3418. te[2] = bf - ae * d;
  3419. te[6] = be + af * d;
  3420. te[10] = a * c;
  3421. } else if (euler.order === 'YXZ') {
  3422. const ce = c * e,
  3423. cf = c * f,
  3424. de = d * e,
  3425. df = d * f;
  3426. te[0] = ce + df * b;
  3427. te[4] = de * b - cf;
  3428. te[8] = a * d;
  3429. te[1] = a * f;
  3430. te[5] = a * e;
  3431. te[9] = -b;
  3432. te[2] = cf * b - de;
  3433. te[6] = df + ce * b;
  3434. te[10] = a * c;
  3435. } else if (euler.order === 'ZXY') {
  3436. const ce = c * e,
  3437. cf = c * f,
  3438. de = d * e,
  3439. df = d * f;
  3440. te[0] = ce - df * b;
  3441. te[4] = -a * f;
  3442. te[8] = de + cf * b;
  3443. te[1] = cf + de * b;
  3444. te[5] = a * e;
  3445. te[9] = df - ce * b;
  3446. te[2] = -a * d;
  3447. te[6] = b;
  3448. te[10] = a * c;
  3449. } else if (euler.order === 'ZYX') {
  3450. const ae = a * e,
  3451. af = a * f,
  3452. be = b * e,
  3453. bf = b * f;
  3454. te[0] = c * e;
  3455. te[4] = be * d - af;
  3456. te[8] = ae * d + bf;
  3457. te[1] = c * f;
  3458. te[5] = bf * d + ae;
  3459. te[9] = af * d - be;
  3460. te[2] = -d;
  3461. te[6] = b * c;
  3462. te[10] = a * c;
  3463. } else if (euler.order === 'YZX') {
  3464. const ac = a * c,
  3465. ad = a * d,
  3466. bc = b * c,
  3467. bd = b * d;
  3468. te[0] = c * e;
  3469. te[4] = bd - ac * f;
  3470. te[8] = bc * f + ad;
  3471. te[1] = f;
  3472. te[5] = a * e;
  3473. te[9] = -b * e;
  3474. te[2] = -d * e;
  3475. te[6] = ad * f + bc;
  3476. te[10] = ac - bd * f;
  3477. } else if (euler.order === 'XZY') {
  3478. const ac = a * c,
  3479. ad = a * d,
  3480. bc = b * c,
  3481. bd = b * d;
  3482. te[0] = c * e;
  3483. te[4] = -f;
  3484. te[8] = d * e;
  3485. te[1] = ac * f + bd;
  3486. te[5] = a * e;
  3487. te[9] = ad * f - bc;
  3488. te[2] = bc * f - ad;
  3489. te[6] = b * e;
  3490. te[10] = bd * f + ac;
  3491. } // bottom row
  3492. te[3] = 0;
  3493. te[7] = 0;
  3494. te[11] = 0; // last column
  3495. te[12] = 0;
  3496. te[13] = 0;
  3497. te[14] = 0;
  3498. te[15] = 1;
  3499. return this;
  3500. }
  3501. makeRotationFromQuaternion(q) {
  3502. return this.compose(_zero, q, _one);
  3503. }
  3504. lookAt(eye, target, up) {
  3505. const te = this.elements;
  3506. _z.subVectors(eye, target);
  3507. if (_z.lengthSq() === 0) {
  3508. // eye and target are in the same position
  3509. _z.z = 1;
  3510. }
  3511. _z.normalize();
  3512. _x.crossVectors(up, _z);
  3513. if (_x.lengthSq() === 0) {
  3514. // up and z are parallel
  3515. if (Math.abs(up.z) === 1) {
  3516. _z.x += 0.0001;
  3517. } else {
  3518. _z.z += 0.0001;
  3519. }
  3520. _z.normalize();
  3521. _x.crossVectors(up, _z);
  3522. }
  3523. _x.normalize();
  3524. _y.crossVectors(_z, _x);
  3525. te[0] = _x.x;
  3526. te[4] = _y.x;
  3527. te[8] = _z.x;
  3528. te[1] = _x.y;
  3529. te[5] = _y.y;
  3530. te[9] = _z.y;
  3531. te[2] = _x.z;
  3532. te[6] = _y.z;
  3533. te[10] = _z.z;
  3534. return this;
  3535. }
  3536. multiply(m, n) {
  3537. if (n !== undefined) {
  3538. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  3539. return this.multiplyMatrices(m, n);
  3540. }
  3541. return this.multiplyMatrices(this, m);
  3542. }
  3543. premultiply(m) {
  3544. return this.multiplyMatrices(m, this);
  3545. }
  3546. multiplyMatrices(a, b) {
  3547. const ae = a.elements;
  3548. const be = b.elements;
  3549. const te = this.elements;
  3550. const a11 = ae[0],
  3551. a12 = ae[4],
  3552. a13 = ae[8],
  3553. a14 = ae[12];
  3554. const a21 = ae[1],
  3555. a22 = ae[5],
  3556. a23 = ae[9],
  3557. a24 = ae[13];
  3558. const a31 = ae[2],
  3559. a32 = ae[6],
  3560. a33 = ae[10],
  3561. a34 = ae[14];
  3562. const a41 = ae[3],
  3563. a42 = ae[7],
  3564. a43 = ae[11],
  3565. a44 = ae[15];
  3566. const b11 = be[0],
  3567. b12 = be[4],
  3568. b13 = be[8],
  3569. b14 = be[12];
  3570. const b21 = be[1],
  3571. b22 = be[5],
  3572. b23 = be[9],
  3573. b24 = be[13];
  3574. const b31 = be[2],
  3575. b32 = be[6],
  3576. b33 = be[10],
  3577. b34 = be[14];
  3578. const b41 = be[3],
  3579. b42 = be[7],
  3580. b43 = be[11],
  3581. b44 = be[15];
  3582. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3583. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3584. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3585. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3586. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3587. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3588. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3589. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3590. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3591. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3592. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3593. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3594. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3595. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3596. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3597. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3598. return this;
  3599. }
  3600. multiplyScalar(s) {
  3601. const te = this.elements;
  3602. te[0] *= s;
  3603. te[4] *= s;
  3604. te[8] *= s;
  3605. te[12] *= s;
  3606. te[1] *= s;
  3607. te[5] *= s;
  3608. te[9] *= s;
  3609. te[13] *= s;
  3610. te[2] *= s;
  3611. te[6] *= s;
  3612. te[10] *= s;
  3613. te[14] *= s;
  3614. te[3] *= s;
  3615. te[7] *= s;
  3616. te[11] *= s;
  3617. te[15] *= s;
  3618. return this;
  3619. }
  3620. determinant() {
  3621. const te = this.elements;
  3622. const n11 = te[0],
  3623. n12 = te[4],
  3624. n13 = te[8],
  3625. n14 = te[12];
  3626. const n21 = te[1],
  3627. n22 = te[5],
  3628. n23 = te[9],
  3629. n24 = te[13];
  3630. const n31 = te[2],
  3631. n32 = te[6],
  3632. n33 = te[10],
  3633. n34 = te[14];
  3634. const n41 = te[3],
  3635. n42 = te[7],
  3636. n43 = te[11],
  3637. n44 = te[15]; //TODO: make this more efficient
  3638. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3639. return n41 * (+n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34) + n42 * (+n11 * n23 * n34 - n11 * n24 * n33 + n14 * n21 * n33 - n13 * n21 * n34 + n13 * n24 * n31 - n14 * n23 * n31) + n43 * (+n11 * n24 * n32 - n11 * n22 * n34 - n14 * n21 * n32 + n12 * n21 * n34 + n14 * n22 * n31 - n12 * n24 * n31) + n44 * (-n13 * n22 * n31 - n11 * n23 * n32 + n11 * n22 * n33 + n13 * n21 * n32 - n12 * n21 * n33 + n12 * n23 * n31);
  3640. }
  3641. transpose() {
  3642. const te = this.elements;
  3643. let tmp;
  3644. tmp = te[1];
  3645. te[1] = te[4];
  3646. te[4] = tmp;
  3647. tmp = te[2];
  3648. te[2] = te[8];
  3649. te[8] = tmp;
  3650. tmp = te[6];
  3651. te[6] = te[9];
  3652. te[9] = tmp;
  3653. tmp = te[3];
  3654. te[3] = te[12];
  3655. te[12] = tmp;
  3656. tmp = te[7];
  3657. te[7] = te[13];
  3658. te[13] = tmp;
  3659. tmp = te[11];
  3660. te[11] = te[14];
  3661. te[14] = tmp;
  3662. return this;
  3663. }
  3664. setPosition(x, y, z) {
  3665. const te = this.elements;
  3666. if (x.isVector3) {
  3667. te[12] = x.x;
  3668. te[13] = x.y;
  3669. te[14] = x.z;
  3670. } else {
  3671. te[12] = x;
  3672. te[13] = y;
  3673. te[14] = z;
  3674. }
  3675. return this;
  3676. }
  3677. invert() {
  3678. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3679. const te = this.elements,
  3680. n11 = te[0],
  3681. n21 = te[1],
  3682. n31 = te[2],
  3683. n41 = te[3],
  3684. n12 = te[4],
  3685. n22 = te[5],
  3686. n32 = te[6],
  3687. n42 = te[7],
  3688. n13 = te[8],
  3689. n23 = te[9],
  3690. n33 = te[10],
  3691. n43 = te[11],
  3692. n14 = te[12],
  3693. n24 = te[13],
  3694. n34 = te[14],
  3695. n44 = te[15],
  3696. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3697. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3698. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3699. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3700. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3701. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  3702. const detInv = 1 / det;
  3703. te[0] = t11 * detInv;
  3704. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  3705. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  3706. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  3707. te[4] = t12 * detInv;
  3708. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  3709. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  3710. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  3711. te[8] = t13 * detInv;
  3712. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  3713. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  3714. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  3715. te[12] = t14 * detInv;
  3716. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  3717. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  3718. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  3719. return this;
  3720. }
  3721. scale(v) {
  3722. const te = this.elements;
  3723. const x = v.x,
  3724. y = v.y,
  3725. z = v.z;
  3726. te[0] *= x;
  3727. te[4] *= y;
  3728. te[8] *= z;
  3729. te[1] *= x;
  3730. te[5] *= y;
  3731. te[9] *= z;
  3732. te[2] *= x;
  3733. te[6] *= y;
  3734. te[10] *= z;
  3735. te[3] *= x;
  3736. te[7] *= y;
  3737. te[11] *= z;
  3738. return this;
  3739. }
  3740. getMaxScaleOnAxis() {
  3741. const te = this.elements;
  3742. const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  3743. const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  3744. const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  3745. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  3746. }
  3747. makeTranslation(x, y, z) {
  3748. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  3749. return this;
  3750. }
  3751. makeRotationX(theta) {
  3752. const c = Math.cos(theta),
  3753. s = Math.sin(theta);
  3754. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  3755. return this;
  3756. }
  3757. makeRotationY(theta) {
  3758. const c = Math.cos(theta),
  3759. s = Math.sin(theta);
  3760. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  3761. return this;
  3762. }
  3763. makeRotationZ(theta) {
  3764. const c = Math.cos(theta),
  3765. s = Math.sin(theta);
  3766. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3767. return this;
  3768. }
  3769. makeRotationAxis(axis, angle) {
  3770. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3771. const c = Math.cos(angle);
  3772. const s = Math.sin(angle);
  3773. const t = 1 - c;
  3774. const x = axis.x,
  3775. y = axis.y,
  3776. z = axis.z;
  3777. const tx = t * x,
  3778. ty = t * y;
  3779. this.set(tx * x + c, tx * y - s * z, tx * z + s * y, 0, tx * y + s * z, ty * y + c, ty * z - s * x, 0, tx * z - s * y, ty * z + s * x, t * z * z + c, 0, 0, 0, 0, 1);
  3780. return this;
  3781. }
  3782. makeScale(x, y, z) {
  3783. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  3784. return this;
  3785. }
  3786. makeShear(xy, xz, yx, yz, zx, zy) {
  3787. this.set(1, yx, zx, 0, xy, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1);
  3788. return this;
  3789. }
  3790. compose(position, quaternion, scale) {
  3791. const te = this.elements;
  3792. const x = quaternion._x,
  3793. y = quaternion._y,
  3794. z = quaternion._z,
  3795. w = quaternion._w;
  3796. const x2 = x + x,
  3797. y2 = y + y,
  3798. z2 = z + z;
  3799. const xx = x * x2,
  3800. xy = x * y2,
  3801. xz = x * z2;
  3802. const yy = y * y2,
  3803. yz = y * z2,
  3804. zz = z * z2;
  3805. const wx = w * x2,
  3806. wy = w * y2,
  3807. wz = w * z2;
  3808. const sx = scale.x,
  3809. sy = scale.y,
  3810. sz = scale.z;
  3811. te[0] = (1 - (yy + zz)) * sx;
  3812. te[1] = (xy + wz) * sx;
  3813. te[2] = (xz - wy) * sx;
  3814. te[3] = 0;
  3815. te[4] = (xy - wz) * sy;
  3816. te[5] = (1 - (xx + zz)) * sy;
  3817. te[6] = (yz + wx) * sy;
  3818. te[7] = 0;
  3819. te[8] = (xz + wy) * sz;
  3820. te[9] = (yz - wx) * sz;
  3821. te[10] = (1 - (xx + yy)) * sz;
  3822. te[11] = 0;
  3823. te[12] = position.x;
  3824. te[13] = position.y;
  3825. te[14] = position.z;
  3826. te[15] = 1;
  3827. return this;
  3828. }
  3829. decompose(position, quaternion, scale) {
  3830. const te = this.elements;
  3831. let sx = _v1$5.set(te[0], te[1], te[2]).length();
  3832. const sy = _v1$5.set(te[4], te[5], te[6]).length();
  3833. const sz = _v1$5.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  3834. const det = this.determinant();
  3835. if (det < 0) sx = -sx;
  3836. position.x = te[12];
  3837. position.y = te[13];
  3838. position.z = te[14]; // scale the rotation part
  3839. _m1$2.copy(this);
  3840. const invSX = 1 / sx;
  3841. const invSY = 1 / sy;
  3842. const invSZ = 1 / sz;
  3843. _m1$2.elements[0] *= invSX;
  3844. _m1$2.elements[1] *= invSX;
  3845. _m1$2.elements[2] *= invSX;
  3846. _m1$2.elements[4] *= invSY;
  3847. _m1$2.elements[5] *= invSY;
  3848. _m1$2.elements[6] *= invSY;
  3849. _m1$2.elements[8] *= invSZ;
  3850. _m1$2.elements[9] *= invSZ;
  3851. _m1$2.elements[10] *= invSZ;
  3852. quaternion.setFromRotationMatrix(_m1$2);
  3853. scale.x = sx;
  3854. scale.y = sy;
  3855. scale.z = sz;
  3856. return this;
  3857. }
  3858. makePerspective(left, right, top, bottom, near, far) {
  3859. if (far === undefined) {
  3860. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  3861. }
  3862. const te = this.elements;
  3863. const x = 2 * near / (right - left);
  3864. const y = 2 * near / (top - bottom);
  3865. const a = (right + left) / (right - left);
  3866. const b = (top + bottom) / (top - bottom);
  3867. const c = -(far + near) / (far - near);
  3868. const d = -2 * far * near / (far - near);
  3869. te[0] = x;
  3870. te[4] = 0;
  3871. te[8] = a;
  3872. te[12] = 0;
  3873. te[1] = 0;
  3874. te[5] = y;
  3875. te[9] = b;
  3876. te[13] = 0;
  3877. te[2] = 0;
  3878. te[6] = 0;
  3879. te[10] = c;
  3880. te[14] = d;
  3881. te[3] = 0;
  3882. te[7] = 0;
  3883. te[11] = -1;
  3884. te[15] = 0;
  3885. return this;
  3886. }
  3887. makeOrthographic(left, right, top, bottom, near, far) {
  3888. const te = this.elements;
  3889. const w = 1.0 / (right - left);
  3890. const h = 1.0 / (top - bottom);
  3891. const p = 1.0 / (far - near);
  3892. const x = (right + left) * w;
  3893. const y = (top + bottom) * h;
  3894. const z = (far + near) * p;
  3895. te[0] = 2 * w;
  3896. te[4] = 0;
  3897. te[8] = 0;
  3898. te[12] = -x;
  3899. te[1] = 0;
  3900. te[5] = 2 * h;
  3901. te[9] = 0;
  3902. te[13] = -y;
  3903. te[2] = 0;
  3904. te[6] = 0;
  3905. te[10] = -2 * p;
  3906. te[14] = -z;
  3907. te[3] = 0;
  3908. te[7] = 0;
  3909. te[11] = 0;
  3910. te[15] = 1;
  3911. return this;
  3912. }
  3913. equals(matrix) {
  3914. const te = this.elements;
  3915. const me = matrix.elements;
  3916. for (let i = 0; i < 16; i++) {
  3917. if (te[i] !== me[i]) return false;
  3918. }
  3919. return true;
  3920. }
  3921. fromArray(array, offset = 0) {
  3922. for (let i = 0; i < 16; i++) {
  3923. this.elements[i] = array[i + offset];
  3924. }
  3925. return this;
  3926. }
  3927. toArray(array = [], offset = 0) {
  3928. const te = this.elements;
  3929. array[offset] = te[0];
  3930. array[offset + 1] = te[1];
  3931. array[offset + 2] = te[2];
  3932. array[offset + 3] = te[3];
  3933. array[offset + 4] = te[4];
  3934. array[offset + 5] = te[5];
  3935. array[offset + 6] = te[6];
  3936. array[offset + 7] = te[7];
  3937. array[offset + 8] = te[8];
  3938. array[offset + 9] = te[9];
  3939. array[offset + 10] = te[10];
  3940. array[offset + 11] = te[11];
  3941. array[offset + 12] = te[12];
  3942. array[offset + 13] = te[13];
  3943. array[offset + 14] = te[14];
  3944. array[offset + 15] = te[15];
  3945. return array;
  3946. }
  3947. }
  3948. Matrix4.prototype.isMatrix4 = true;
  3949. const _v1$5 = /*@__PURE__*/new Vector3();
  3950. const _m1$2 = /*@__PURE__*/new Matrix4();
  3951. const _zero = /*@__PURE__*/new Vector3(0, 0, 0);
  3952. const _one = /*@__PURE__*/new Vector3(1, 1, 1);
  3953. const _x = /*@__PURE__*/new Vector3();
  3954. const _y = /*@__PURE__*/new Vector3();
  3955. const _z = /*@__PURE__*/new Vector3();
  3956. const _matrix$1 = /*@__PURE__*/new Matrix4();
  3957. const _quaternion$3 = /*@__PURE__*/new Quaternion();
  3958. class Euler {
  3959. constructor(x = 0, y = 0, z = 0, order = Euler.DefaultOrder) {
  3960. this._x = x;
  3961. this._y = y;
  3962. this._z = z;
  3963. this._order = order;
  3964. }
  3965. get x() {
  3966. return this._x;
  3967. }
  3968. set x(value) {
  3969. this._x = value;
  3970. this._onChangeCallback();
  3971. }
  3972. get y() {
  3973. return this._y;
  3974. }
  3975. set y(value) {
  3976. this._y = value;
  3977. this._onChangeCallback();
  3978. }
  3979. get z() {
  3980. return this._z;
  3981. }
  3982. set z(value) {
  3983. this._z = value;
  3984. this._onChangeCallback();
  3985. }
  3986. get order() {
  3987. return this._order;
  3988. }
  3989. set order(value) {
  3990. this._order = value;
  3991. this._onChangeCallback();
  3992. }
  3993. set(x, y, z, order = this._order) {
  3994. this._x = x;
  3995. this._y = y;
  3996. this._z = z;
  3997. this._order = order;
  3998. this._onChangeCallback();
  3999. return this;
  4000. }
  4001. clone() {
  4002. return new this.constructor(this._x, this._y, this._z, this._order);
  4003. }
  4004. copy(euler) {
  4005. this._x = euler._x;
  4006. this._y = euler._y;
  4007. this._z = euler._z;
  4008. this._order = euler._order;
  4009. this._onChangeCallback();
  4010. return this;
  4011. }
  4012. setFromRotationMatrix(m, order = this._order, update = true) {
  4013. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4014. const te = m.elements;
  4015. const m11 = te[0],
  4016. m12 = te[4],
  4017. m13 = te[8];
  4018. const m21 = te[1],
  4019. m22 = te[5],
  4020. m23 = te[9];
  4021. const m31 = te[2],
  4022. m32 = te[6],
  4023. m33 = te[10];
  4024. switch (order) {
  4025. case 'XYZ':
  4026. this._y = Math.asin(clamp(m13, -1, 1));
  4027. if (Math.abs(m13) < 0.9999999) {
  4028. this._x = Math.atan2(-m23, m33);
  4029. this._z = Math.atan2(-m12, m11);
  4030. } else {
  4031. this._x = Math.atan2(m32, m22);
  4032. this._z = 0;
  4033. }
  4034. break;
  4035. case 'YXZ':
  4036. this._x = Math.asin(-clamp(m23, -1, 1));
  4037. if (Math.abs(m23) < 0.9999999) {
  4038. this._y = Math.atan2(m13, m33);
  4039. this._z = Math.atan2(m21, m22);
  4040. } else {
  4041. this._y = Math.atan2(-m31, m11);
  4042. this._z = 0;
  4043. }
  4044. break;
  4045. case 'ZXY':
  4046. this._x = Math.asin(clamp(m32, -1, 1));
  4047. if (Math.abs(m32) < 0.9999999) {
  4048. this._y = Math.atan2(-m31, m33);
  4049. this._z = Math.atan2(-m12, m22);
  4050. } else {
  4051. this._y = 0;
  4052. this._z = Math.atan2(m21, m11);
  4053. }
  4054. break;
  4055. case 'ZYX':
  4056. this._y = Math.asin(-clamp(m31, -1, 1));
  4057. if (Math.abs(m31) < 0.9999999) {
  4058. this._x = Math.atan2(m32, m33);
  4059. this._z = Math.atan2(m21, m11);
  4060. } else {
  4061. this._x = 0;
  4062. this._z = Math.atan2(-m12, m22);
  4063. }
  4064. break;
  4065. case 'YZX':
  4066. this._z = Math.asin(clamp(m21, -1, 1));
  4067. if (Math.abs(m21) < 0.9999999) {
  4068. this._x = Math.atan2(-m23, m22);
  4069. this._y = Math.atan2(-m31, m11);
  4070. } else {
  4071. this._x = 0;
  4072. this._y = Math.atan2(m13, m33);
  4073. }
  4074. break;
  4075. case 'XZY':
  4076. this._z = Math.asin(-clamp(m12, -1, 1));
  4077. if (Math.abs(m12) < 0.9999999) {
  4078. this._x = Math.atan2(m32, m22);
  4079. this._y = Math.atan2(m13, m11);
  4080. } else {
  4081. this._x = Math.atan2(-m23, m33);
  4082. this._y = 0;
  4083. }
  4084. break;
  4085. default:
  4086. console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
  4087. }
  4088. this._order = order;
  4089. if (update === true) this._onChangeCallback();
  4090. return this;
  4091. }
  4092. setFromQuaternion(q, order, update) {
  4093. _matrix$1.makeRotationFromQuaternion(q);
  4094. return this.setFromRotationMatrix(_matrix$1, order, update);
  4095. }
  4096. setFromVector3(v, order = this._order) {
  4097. return this.set(v.x, v.y, v.z, order);
  4098. }
  4099. reorder(newOrder) {
  4100. // WARNING: this discards revolution information -bhouston
  4101. _quaternion$3.setFromEuler(this);
  4102. return this.setFromQuaternion(_quaternion$3, newOrder);
  4103. }
  4104. equals(euler) {
  4105. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4106. }
  4107. fromArray(array) {
  4108. this._x = array[0];
  4109. this._y = array[1];
  4110. this._z = array[2];
  4111. if (array[3] !== undefined) this._order = array[3];
  4112. this._onChangeCallback();
  4113. return this;
  4114. }
  4115. toArray(array = [], offset = 0) {
  4116. array[offset] = this._x;
  4117. array[offset + 1] = this._y;
  4118. array[offset + 2] = this._z;
  4119. array[offset + 3] = this._order;
  4120. return array;
  4121. }
  4122. toVector3(optionalResult) {
  4123. if (optionalResult) {
  4124. return optionalResult.set(this._x, this._y, this._z);
  4125. } else {
  4126. return new Vector3(this._x, this._y, this._z);
  4127. }
  4128. }
  4129. _onChange(callback) {
  4130. this._onChangeCallback = callback;
  4131. return this;
  4132. }
  4133. _onChangeCallback() {}
  4134. }
  4135. Euler.prototype.isEuler = true;
  4136. Euler.DefaultOrder = 'XYZ';
  4137. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4138. class Layers {
  4139. constructor() {
  4140. this.mask = 1 | 0;
  4141. }
  4142. set(channel) {
  4143. this.mask = (1 << channel | 0) >>> 0;
  4144. }
  4145. enable(channel) {
  4146. this.mask |= 1 << channel | 0;
  4147. }
  4148. enableAll() {
  4149. this.mask = 0xffffffff | 0;
  4150. }
  4151. toggle(channel) {
  4152. this.mask ^= 1 << channel | 0;
  4153. }
  4154. disable(channel) {
  4155. this.mask &= ~(1 << channel | 0);
  4156. }
  4157. disableAll() {
  4158. this.mask = 0;
  4159. }
  4160. test(layers) {
  4161. return (this.mask & layers.mask) !== 0;
  4162. }
  4163. isEnabled(channel) {
  4164. return (this.mask & (1 << channel | 0)) !== 0;
  4165. }
  4166. }
  4167. let _object3DId = 0;
  4168. const _v1$4 = /*@__PURE__*/new Vector3();
  4169. const _q1 = /*@__PURE__*/new Quaternion();
  4170. const _m1$1 = /*@__PURE__*/new Matrix4();
  4171. const _target = /*@__PURE__*/new Vector3();
  4172. const _position$3 = /*@__PURE__*/new Vector3();
  4173. const _scale$2 = /*@__PURE__*/new Vector3();
  4174. const _quaternion$2 = /*@__PURE__*/new Quaternion();
  4175. const _xAxis = /*@__PURE__*/new Vector3(1, 0, 0);
  4176. const _yAxis = /*@__PURE__*/new Vector3(0, 1, 0);
  4177. const _zAxis = /*@__PURE__*/new Vector3(0, 0, 1);
  4178. const _addedEvent = {
  4179. type: 'added'
  4180. };
  4181. const _removedEvent = {
  4182. type: 'removed'
  4183. };
  4184. class Object3D extends EventDispatcher {
  4185. constructor() {
  4186. super();
  4187. Object.defineProperty(this, 'id', {
  4188. value: _object3DId++
  4189. });
  4190. this.uuid = generateUUID();
  4191. this.name = '';
  4192. this.type = 'Object3D';
  4193. this.parent = null;
  4194. this.children = [];
  4195. this.up = Object3D.DefaultUp.clone();
  4196. const position = new Vector3();
  4197. const rotation = new Euler();
  4198. const quaternion = new Quaternion();
  4199. const scale = new Vector3(1, 1, 1);
  4200. function onRotationChange() {
  4201. quaternion.setFromEuler(rotation, false);
  4202. }
  4203. function onQuaternionChange() {
  4204. rotation.setFromQuaternion(quaternion, undefined, false);
  4205. }
  4206. rotation._onChange(onRotationChange);
  4207. quaternion._onChange(onQuaternionChange);
  4208. Object.defineProperties(this, {
  4209. position: {
  4210. configurable: true,
  4211. enumerable: true,
  4212. value: position
  4213. },
  4214. rotation: {
  4215. configurable: true,
  4216. enumerable: true,
  4217. value: rotation
  4218. },
  4219. quaternion: {
  4220. configurable: true,
  4221. enumerable: true,
  4222. value: quaternion
  4223. },
  4224. scale: {
  4225. configurable: true,
  4226. enumerable: true,
  4227. value: scale
  4228. },
  4229. modelViewMatrix: {
  4230. value: new Matrix4()
  4231. },
  4232. normalMatrix: {
  4233. value: new Matrix3()
  4234. }
  4235. });
  4236. this.matrix = new Matrix4();
  4237. this.matrixWorld = new Matrix4();
  4238. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4239. this.matrixWorldNeedsUpdate = false;
  4240. this.layers = new Layers();
  4241. this.visible = true;
  4242. this.castShadow = false;
  4243. this.receiveShadow = false;
  4244. this.frustumCulled = true;
  4245. this.renderOrder = 0;
  4246. this.animations = [];
  4247. this.userData = {};
  4248. }
  4249. onBeforeRender() {}
  4250. onAfterRender() {}
  4251. applyMatrix4(matrix) {
  4252. if (this.matrixAutoUpdate) this.updateMatrix();
  4253. this.matrix.premultiply(matrix);
  4254. this.matrix.decompose(this.position, this.quaternion, this.scale);
  4255. }
  4256. applyQuaternion(q) {
  4257. this.quaternion.premultiply(q);
  4258. return this;
  4259. }
  4260. setRotationFromAxisAngle(axis, angle) {
  4261. // assumes axis is normalized
  4262. this.quaternion.setFromAxisAngle(axis, angle);
  4263. }
  4264. setRotationFromEuler(euler) {
  4265. this.quaternion.setFromEuler(euler, true);
  4266. }
  4267. setRotationFromMatrix(m) {
  4268. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4269. this.quaternion.setFromRotationMatrix(m);
  4270. }
  4271. setRotationFromQuaternion(q) {
  4272. // assumes q is normalized
  4273. this.quaternion.copy(q);
  4274. }
  4275. rotateOnAxis(axis, angle) {
  4276. // rotate object on axis in object space
  4277. // axis is assumed to be normalized
  4278. _q1.setFromAxisAngle(axis, angle);
  4279. this.quaternion.multiply(_q1);
  4280. return this;
  4281. }
  4282. rotateOnWorldAxis(axis, angle) {
  4283. // rotate object on axis in world space
  4284. // axis is assumed to be normalized
  4285. // method assumes no rotated parent
  4286. _q1.setFromAxisAngle(axis, angle);
  4287. this.quaternion.premultiply(_q1);
  4288. return this;
  4289. }
  4290. rotateX(angle) {
  4291. return this.rotateOnAxis(_xAxis, angle);
  4292. }
  4293. rotateY(angle) {
  4294. return this.rotateOnAxis(_yAxis, angle);
  4295. }
  4296. rotateZ(angle) {
  4297. return this.rotateOnAxis(_zAxis, angle);
  4298. }
  4299. translateOnAxis(axis, distance) {
  4300. // translate object by distance along axis in object space
  4301. // axis is assumed to be normalized
  4302. _v1$4.copy(axis).applyQuaternion(this.quaternion);
  4303. this.position.add(_v1$4.multiplyScalar(distance));
  4304. return this;
  4305. }
  4306. translateX(distance) {
  4307. return this.translateOnAxis(_xAxis, distance);
  4308. }
  4309. translateY(distance) {
  4310. return this.translateOnAxis(_yAxis, distance);
  4311. }
  4312. translateZ(distance) {
  4313. return this.translateOnAxis(_zAxis, distance);
  4314. }
  4315. localToWorld(vector) {
  4316. return vector.applyMatrix4(this.matrixWorld);
  4317. }
  4318. worldToLocal(vector) {
  4319. return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
  4320. }
  4321. lookAt(x, y, z) {
  4322. // This method does not support objects having non-uniformly-scaled parent(s)
  4323. if (x.isVector3) {
  4324. _target.copy(x);
  4325. } else {
  4326. _target.set(x, y, z);
  4327. }
  4328. const parent = this.parent;
  4329. this.updateWorldMatrix(true, false);
  4330. _position$3.setFromMatrixPosition(this.matrixWorld);
  4331. if (this.isCamera || this.isLight) {
  4332. _m1$1.lookAt(_position$3, _target, this.up);
  4333. } else {
  4334. _m1$1.lookAt(_target, _position$3, this.up);
  4335. }
  4336. this.quaternion.setFromRotationMatrix(_m1$1);
  4337. if (parent) {
  4338. _m1$1.extractRotation(parent.matrixWorld);
  4339. _q1.setFromRotationMatrix(_m1$1);
  4340. this.quaternion.premultiply(_q1.invert());
  4341. }
  4342. }
  4343. add(object) {
  4344. if (arguments.length > 1) {
  4345. for (let i = 0; i < arguments.length; i++) {
  4346. this.add(arguments[i]);
  4347. }
  4348. return this;
  4349. }
  4350. if (object === this) {
  4351. console.error('THREE.Object3D.add: object can\'t be added as a child of itself.', object);
  4352. return this;
  4353. }
  4354. if (object && object.isObject3D) {
  4355. if (object.parent !== null) {
  4356. object.parent.remove(object);
  4357. }
  4358. object.parent = this;
  4359. this.children.push(object);
  4360. object.dispatchEvent(_addedEvent);
  4361. } else {
  4362. console.error('THREE.Object3D.add: object not an instance of THREE.Object3D.', object);
  4363. }
  4364. return this;
  4365. }
  4366. remove(object) {
  4367. if (arguments.length > 1) {
  4368. for (let i = 0; i < arguments.length; i++) {
  4369. this.remove(arguments[i]);
  4370. }
  4371. return this;
  4372. }
  4373. const index = this.children.indexOf(object);
  4374. if (index !== -1) {
  4375. object.parent = null;
  4376. this.children.splice(index, 1);
  4377. object.dispatchEvent(_removedEvent);
  4378. }
  4379. return this;
  4380. }
  4381. removeFromParent() {
  4382. const parent = this.parent;
  4383. if (parent !== null) {
  4384. parent.remove(this);
  4385. }
  4386. return this;
  4387. }
  4388. clear() {
  4389. for (let i = 0; i < this.children.length; i++) {
  4390. const object = this.children[i];
  4391. object.parent = null;
  4392. object.dispatchEvent(_removedEvent);
  4393. }
  4394. this.children.length = 0;
  4395. return this;
  4396. }
  4397. attach(object) {
  4398. // adds object as a child of this, while maintaining the object's world transform
  4399. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4400. this.updateWorldMatrix(true, false);
  4401. _m1$1.copy(this.matrixWorld).invert();
  4402. if (object.parent !== null) {
  4403. object.parent.updateWorldMatrix(true, false);
  4404. _m1$1.multiply(object.parent.matrixWorld);
  4405. }
  4406. object.applyMatrix4(_m1$1);
  4407. this.add(object);
  4408. object.updateWorldMatrix(false, true);
  4409. return this;
  4410. }
  4411. getObjectById(id) {
  4412. return this.getObjectByProperty('id', id);
  4413. }
  4414. getObjectByName(name) {
  4415. return this.getObjectByProperty('name', name);
  4416. }
  4417. getObjectByProperty(name, value) {
  4418. if (this[name] === value) return this;
  4419. for (let i = 0, l = this.children.length; i < l; i++) {
  4420. const child = this.children[i];
  4421. const object = child.getObjectByProperty(name, value);
  4422. if (object !== undefined) {
  4423. return object;
  4424. }
  4425. }
  4426. return undefined;
  4427. }
  4428. getWorldPosition(target) {
  4429. this.updateWorldMatrix(true, false);
  4430. return target.setFromMatrixPosition(this.matrixWorld);
  4431. }
  4432. getWorldQuaternion(target) {
  4433. this.updateWorldMatrix(true, false);
  4434. this.matrixWorld.decompose(_position$3, target, _scale$2);
  4435. return target;
  4436. }
  4437. getWorldScale(target) {
  4438. this.updateWorldMatrix(true, false);
  4439. this.matrixWorld.decompose(_position$3, _quaternion$2, target);
  4440. return target;
  4441. }
  4442. getWorldDirection(target) {
  4443. this.updateWorldMatrix(true, false);
  4444. const e = this.matrixWorld.elements;
  4445. return target.set(e[8], e[9], e[10]).normalize();
  4446. }
  4447. raycast() {}
  4448. traverse(callback) {
  4449. callback(this);
  4450. const children = this.children;
  4451. for (let i = 0, l = children.length; i < l; i++) {
  4452. children[i].traverse(callback);
  4453. }
  4454. }
  4455. traverseVisible(callback) {
  4456. if (this.visible === false) return;
  4457. callback(this);
  4458. const children = this.children;
  4459. for (let i = 0, l = children.length; i < l; i++) {
  4460. children[i].traverseVisible(callback);
  4461. }
  4462. }
  4463. traverseAncestors(callback) {
  4464. const parent = this.parent;
  4465. if (parent !== null) {
  4466. callback(parent);
  4467. parent.traverseAncestors(callback);
  4468. }
  4469. }
  4470. updateMatrix() {
  4471. this.matrix.compose(this.position, this.quaternion, this.scale);
  4472. this.matrixWorldNeedsUpdate = true;
  4473. }
  4474. updateMatrixWorld(force) {
  4475. if (this.matrixAutoUpdate) this.updateMatrix();
  4476. if (this.matrixWorldNeedsUpdate || force) {
  4477. if (this.parent === null) {
  4478. this.matrixWorld.copy(this.matrix);
  4479. } else {
  4480. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4481. }
  4482. this.matrixWorldNeedsUpdate = false;
  4483. force = true;
  4484. } // update children
  4485. const children = this.children;
  4486. for (let i = 0, l = children.length; i < l; i++) {
  4487. children[i].updateMatrixWorld(force);
  4488. }
  4489. }
  4490. updateWorldMatrix(updateParents, updateChildren) {
  4491. const parent = this.parent;
  4492. if (updateParents === true && parent !== null) {
  4493. parent.updateWorldMatrix(true, false);
  4494. }
  4495. if (this.matrixAutoUpdate) this.updateMatrix();
  4496. if (this.parent === null) {
  4497. this.matrixWorld.copy(this.matrix);
  4498. } else {
  4499. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4500. } // update children
  4501. if (updateChildren === true) {
  4502. const children = this.children;
  4503. for (let i = 0, l = children.length; i < l; i++) {
  4504. children[i].updateWorldMatrix(false, true);
  4505. }
  4506. }
  4507. }
  4508. toJSON(meta) {
  4509. // meta is a string when called from JSON.stringify
  4510. const isRootObject = meta === undefined || typeof meta === 'string';
  4511. const output = {}; // meta is a hash used to collect geometries, materials.
  4512. // not providing it implies that this is the root object
  4513. // being serialized.
  4514. if (isRootObject) {
  4515. // initialize meta obj
  4516. meta = {
  4517. geometries: {},
  4518. materials: {},
  4519. textures: {},
  4520. images: {},
  4521. shapes: {},
  4522. skeletons: {},
  4523. animations: {}
  4524. };
  4525. output.metadata = {
  4526. version: 4.5,
  4527. type: 'Object',
  4528. generator: 'Object3D.toJSON'
  4529. };
  4530. } // standard Object3D serialization
  4531. const object = {};
  4532. object.uuid = this.uuid;
  4533. object.type = this.type;
  4534. if (this.name !== '') object.name = this.name;
  4535. if (this.castShadow === true) object.castShadow = true;
  4536. if (this.receiveShadow === true) object.receiveShadow = true;
  4537. if (this.visible === false) object.visible = false;
  4538. if (this.frustumCulled === false) object.frustumCulled = false;
  4539. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  4540. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  4541. object.layers = this.layers.mask;
  4542. object.matrix = this.matrix.toArray();
  4543. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  4544. if (this.isInstancedMesh) {
  4545. object.type = 'InstancedMesh';
  4546. object.count = this.count;
  4547. object.instanceMatrix = this.instanceMatrix.toJSON();
  4548. if (this.instanceColor !== null) object.instanceColor = this.instanceColor.toJSON();
  4549. } //
  4550. function serialize(library, element) {
  4551. if (library[element.uuid] === undefined) {
  4552. library[element.uuid] = element.toJSON(meta);
  4553. }
  4554. return element.uuid;
  4555. }
  4556. if (this.isScene) {
  4557. if (this.background) {
  4558. if (this.background.isColor) {
  4559. object.background = this.background.toJSON();
  4560. } else if (this.background.isTexture) {
  4561. object.background = this.background.toJSON(meta).uuid;
  4562. }
  4563. }
  4564. if (this.environment && this.environment.isTexture) {
  4565. object.environment = this.environment.toJSON(meta).uuid;
  4566. }
  4567. } else if (this.isMesh || this.isLine || this.isPoints) {
  4568. object.geometry = serialize(meta.geometries, this.geometry);
  4569. const parameters = this.geometry.parameters;
  4570. if (parameters !== undefined && parameters.shapes !== undefined) {
  4571. const shapes = parameters.shapes;
  4572. if (Array.isArray(shapes)) {
  4573. for (let i = 0, l = shapes.length; i < l; i++) {
  4574. const shape = shapes[i];
  4575. serialize(meta.shapes, shape);
  4576. }
  4577. } else {
  4578. serialize(meta.shapes, shapes);
  4579. }
  4580. }
  4581. }
  4582. if (this.isSkinnedMesh) {
  4583. object.bindMode = this.bindMode;
  4584. object.bindMatrix = this.bindMatrix.toArray();
  4585. if (this.skeleton !== undefined) {
  4586. serialize(meta.skeletons, this.skeleton);
  4587. object.skeleton = this.skeleton.uuid;
  4588. }
  4589. }
  4590. if (this.material !== undefined) {
  4591. if (Array.isArray(this.material)) {
  4592. const uuids = [];
  4593. for (let i = 0, l = this.material.length; i < l; i++) {
  4594. uuids.push(serialize(meta.materials, this.material[i]));
  4595. }
  4596. object.material = uuids;
  4597. } else {
  4598. object.material = serialize(meta.materials, this.material);
  4599. }
  4600. } //
  4601. if (this.children.length > 0) {
  4602. object.children = [];
  4603. for (let i = 0; i < this.children.length; i++) {
  4604. object.children.push(this.children[i].toJSON(meta).object);
  4605. }
  4606. } //
  4607. if (this.animations.length > 0) {
  4608. object.animations = [];
  4609. for (let i = 0; i < this.animations.length; i++) {
  4610. const animation = this.animations[i];
  4611. object.animations.push(serialize(meta.animations, animation));
  4612. }
  4613. }
  4614. if (isRootObject) {
  4615. const geometries = extractFromCache(meta.geometries);
  4616. const materials = extractFromCache(meta.materials);
  4617. const textures = extractFromCache(meta.textures);
  4618. const images = extractFromCache(meta.images);
  4619. const shapes = extractFromCache(meta.shapes);
  4620. const skeletons = extractFromCache(meta.skeletons);
  4621. const animations = extractFromCache(meta.animations);
  4622. if (geometries.length > 0) output.geometries = geometries;
  4623. if (materials.length > 0) output.materials = materials;
  4624. if (textures.length > 0) output.textures = textures;
  4625. if (images.length > 0) output.images = images;
  4626. if (shapes.length > 0) output.shapes = shapes;
  4627. if (skeletons.length > 0) output.skeletons = skeletons;
  4628. if (animations.length > 0) output.animations = animations;
  4629. }
  4630. output.object = object;
  4631. return output; // extract data from the cache hash
  4632. // remove metadata on each item
  4633. // and return as array
  4634. function extractFromCache(cache) {
  4635. const values = [];
  4636. for (const key in cache) {
  4637. const data = cache[key];
  4638. delete data.metadata;
  4639. values.push(data);
  4640. }
  4641. return values;
  4642. }
  4643. }
  4644. clone(recursive) {
  4645. return new this.constructor().copy(this, recursive);
  4646. }
  4647. copy(source, recursive = true) {
  4648. this.name = source.name;
  4649. this.up.copy(source.up);
  4650. this.position.copy(source.position);
  4651. this.rotation.order = source.rotation.order;
  4652. this.quaternion.copy(source.quaternion);
  4653. this.scale.copy(source.scale);
  4654. this.matrix.copy(source.matrix);
  4655. this.matrixWorld.copy(source.matrixWorld);
  4656. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4657. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4658. this.layers.mask = source.layers.mask;
  4659. this.visible = source.visible;
  4660. this.castShadow = source.castShadow;
  4661. this.receiveShadow = source.receiveShadow;
  4662. this.frustumCulled = source.frustumCulled;
  4663. this.renderOrder = source.renderOrder;
  4664. this.userData = JSON.parse(JSON.stringify(source.userData));
  4665. if (recursive === true) {
  4666. for (let i = 0; i < source.children.length; i++) {
  4667. const child = source.children[i];
  4668. this.add(child.clone());
  4669. }
  4670. }
  4671. return this;
  4672. }
  4673. }
  4674. Object3D.DefaultUp = new Vector3(0, 1, 0);
  4675. Object3D.DefaultMatrixAutoUpdate = true;
  4676. Object3D.prototype.isObject3D = true;
  4677. const _v0$1 = /*@__PURE__*/new Vector3();
  4678. const _v1$3 = /*@__PURE__*/new Vector3();
  4679. const _v2$2 = /*@__PURE__*/new Vector3();
  4680. const _v3$1 = /*@__PURE__*/new Vector3();
  4681. const _vab = /*@__PURE__*/new Vector3();
  4682. const _vac = /*@__PURE__*/new Vector3();
  4683. const _vbc = /*@__PURE__*/new Vector3();
  4684. const _vap = /*@__PURE__*/new Vector3();
  4685. const _vbp = /*@__PURE__*/new Vector3();
  4686. const _vcp = /*@__PURE__*/new Vector3();
  4687. class Triangle {
  4688. constructor(a = new Vector3(), b = new Vector3(), c = new Vector3()) {
  4689. this.a = a;
  4690. this.b = b;
  4691. this.c = c;
  4692. }
  4693. static getNormal(a, b, c, target) {
  4694. target.subVectors(c, b);
  4695. _v0$1.subVectors(a, b);
  4696. target.cross(_v0$1);
  4697. const targetLengthSq = target.lengthSq();
  4698. if (targetLengthSq > 0) {
  4699. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  4700. }
  4701. return target.set(0, 0, 0);
  4702. } // static/instance method to calculate barycentric coordinates
  4703. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4704. static getBarycoord(point, a, b, c, target) {
  4705. _v0$1.subVectors(c, a);
  4706. _v1$3.subVectors(b, a);
  4707. _v2$2.subVectors(point, a);
  4708. const dot00 = _v0$1.dot(_v0$1);
  4709. const dot01 = _v0$1.dot(_v1$3);
  4710. const dot02 = _v0$1.dot(_v2$2);
  4711. const dot11 = _v1$3.dot(_v1$3);
  4712. const dot12 = _v1$3.dot(_v2$2);
  4713. const denom = dot00 * dot11 - dot01 * dot01; // collinear or singular triangle
  4714. if (denom === 0) {
  4715. // arbitrary location outside of triangle?
  4716. // not sure if this is the best idea, maybe should be returning undefined
  4717. return target.set(-2, -1, -1);
  4718. }
  4719. const invDenom = 1 / denom;
  4720. const u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  4721. const v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  4722. return target.set(1 - u - v, v, u);
  4723. }
  4724. static containsPoint(point, a, b, c) {
  4725. this.getBarycoord(point, a, b, c, _v3$1);
  4726. return _v3$1.x >= 0 && _v3$1.y >= 0 && _v3$1.x + _v3$1.y <= 1;
  4727. }
  4728. static getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
  4729. this.getBarycoord(point, p1, p2, p3, _v3$1);
  4730. target.set(0, 0);
  4731. target.addScaledVector(uv1, _v3$1.x);
  4732. target.addScaledVector(uv2, _v3$1.y);
  4733. target.addScaledVector(uv3, _v3$1.z);
  4734. return target;
  4735. }
  4736. static isFrontFacing(a, b, c, direction) {
  4737. _v0$1.subVectors(c, b);
  4738. _v1$3.subVectors(a, b); // strictly front facing
  4739. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  4740. }
  4741. set(a, b, c) {
  4742. this.a.copy(a);
  4743. this.b.copy(b);
  4744. this.c.copy(c);
  4745. return this;
  4746. }
  4747. setFromPointsAndIndices(points, i0, i1, i2) {
  4748. this.a.copy(points[i0]);
  4749. this.b.copy(points[i1]);
  4750. this.c.copy(points[i2]);
  4751. return this;
  4752. }
  4753. setFromAttributeAndIndices(attribute, i0, i1, i2) {
  4754. this.a.fromBufferAttribute(attribute, i0);
  4755. this.b.fromBufferAttribute(attribute, i1);
  4756. this.c.fromBufferAttribute(attribute, i2);
  4757. return this;
  4758. }
  4759. clone() {
  4760. return new this.constructor().copy(this);
  4761. }
  4762. copy(triangle) {
  4763. this.a.copy(triangle.a);
  4764. this.b.copy(triangle.b);
  4765. this.c.copy(triangle.c);
  4766. return this;
  4767. }
  4768. getArea() {
  4769. _v0$1.subVectors(this.c, this.b);
  4770. _v1$3.subVectors(this.a, this.b);
  4771. return _v0$1.cross(_v1$3).length() * 0.5;
  4772. }
  4773. getMidpoint(target) {
  4774. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  4775. }
  4776. getNormal(target) {
  4777. return Triangle.getNormal(this.a, this.b, this.c, target);
  4778. }
  4779. getPlane(target) {
  4780. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  4781. }
  4782. getBarycoord(point, target) {
  4783. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  4784. }
  4785. getUV(point, uv1, uv2, uv3, target) {
  4786. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  4787. }
  4788. containsPoint(point) {
  4789. return Triangle.containsPoint(point, this.a, this.b, this.c);
  4790. }
  4791. isFrontFacing(direction) {
  4792. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  4793. }
  4794. intersectsBox(box) {
  4795. return box.intersectsTriangle(this);
  4796. }
  4797. closestPointToPoint(p, target) {
  4798. const a = this.a,
  4799. b = this.b,
  4800. c = this.c;
  4801. let v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4802. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4803. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4804. // basically, we're distinguishing which of the voronoi regions of the triangle
  4805. // the point lies in with the minimum amount of redundant computation.
  4806. _vab.subVectors(b, a);
  4807. _vac.subVectors(c, a);
  4808. _vap.subVectors(p, a);
  4809. const d1 = _vab.dot(_vap);
  4810. const d2 = _vac.dot(_vap);
  4811. if (d1 <= 0 && d2 <= 0) {
  4812. // vertex region of A; barycentric coords (1, 0, 0)
  4813. return target.copy(a);
  4814. }
  4815. _vbp.subVectors(p, b);
  4816. const d3 = _vab.dot(_vbp);
  4817. const d4 = _vac.dot(_vbp);
  4818. if (d3 >= 0 && d4 <= d3) {
  4819. // vertex region of B; barycentric coords (0, 1, 0)
  4820. return target.copy(b);
  4821. }
  4822. const vc = d1 * d4 - d3 * d2;
  4823. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  4824. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  4825. return target.copy(a).addScaledVector(_vab, v);
  4826. }
  4827. _vcp.subVectors(p, c);
  4828. const d5 = _vab.dot(_vcp);
  4829. const d6 = _vac.dot(_vcp);
  4830. if (d6 >= 0 && d5 <= d6) {
  4831. // vertex region of C; barycentric coords (0, 0, 1)
  4832. return target.copy(c);
  4833. }
  4834. const vb = d5 * d2 - d1 * d6;
  4835. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  4836. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  4837. return target.copy(a).addScaledVector(_vac, w);
  4838. }
  4839. const va = d3 * d6 - d5 * d4;
  4840. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  4841. _vbc.subVectors(c, b);
  4842. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  4843. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  4844. } // face region
  4845. const denom = 1 / (va + vb + vc); // u = va * denom
  4846. v = vb * denom;
  4847. w = vc * denom;
  4848. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  4849. }
  4850. equals(triangle) {
  4851. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  4852. }
  4853. }
  4854. let materialId = 0;
  4855. class Material extends EventDispatcher {
  4856. constructor() {
  4857. super();
  4858. Object.defineProperty(this, 'id', {
  4859. value: materialId++
  4860. });
  4861. this.uuid = generateUUID();
  4862. this.name = '';
  4863. this.type = 'Material';
  4864. this.fog = true;
  4865. this.blending = NormalBlending;
  4866. this.side = FrontSide;
  4867. this.vertexColors = false;
  4868. this.opacity = 1;
  4869. this.format = RGBAFormat;
  4870. this.transparent = false;
  4871. this.blendSrc = SrcAlphaFactor;
  4872. this.blendDst = OneMinusSrcAlphaFactor;
  4873. this.blendEquation = AddEquation;
  4874. this.blendSrcAlpha = null;
  4875. this.blendDstAlpha = null;
  4876. this.blendEquationAlpha = null;
  4877. this.depthFunc = LessEqualDepth;
  4878. this.depthTest = true;
  4879. this.depthWrite = true;
  4880. this.stencilWriteMask = 0xff;
  4881. this.stencilFunc = AlwaysStencilFunc;
  4882. this.stencilRef = 0;
  4883. this.stencilFuncMask = 0xff;
  4884. this.stencilFail = KeepStencilOp;
  4885. this.stencilZFail = KeepStencilOp;
  4886. this.stencilZPass = KeepStencilOp;
  4887. this.stencilWrite = false;
  4888. this.clippingPlanes = null;
  4889. this.clipIntersection = false;
  4890. this.clipShadows = false;
  4891. this.shadowSide = null;
  4892. this.colorWrite = true;
  4893. this.precision = null; // override the renderer's default precision for this material
  4894. this.polygonOffset = false;
  4895. this.polygonOffsetFactor = 0;
  4896. this.polygonOffsetUnits = 0;
  4897. this.dithering = false;
  4898. this.alphaToCoverage = false;
  4899. this.premultipliedAlpha = false;
  4900. this.visible = true;
  4901. this.toneMapped = true;
  4902. this.userData = {};
  4903. this.version = 0;
  4904. this._alphaTest = 0;
  4905. }
  4906. get alphaTest() {
  4907. return this._alphaTest;
  4908. }
  4909. set alphaTest(value) {
  4910. if (this._alphaTest > 0 !== value > 0) {
  4911. this.version++;
  4912. }
  4913. this._alphaTest = value;
  4914. }
  4915. onBuild() {}
  4916. onBeforeRender() {}
  4917. onBeforeCompile() {}
  4918. customProgramCacheKey() {
  4919. return this.onBeforeCompile.toString();
  4920. }
  4921. setValues(values) {
  4922. if (values === undefined) return;
  4923. for (const key in values) {
  4924. const newValue = values[key];
  4925. if (newValue === undefined) {
  4926. console.warn('THREE.Material: \'' + key + '\' parameter is undefined.');
  4927. continue;
  4928. } // for backward compatability if shading is set in the constructor
  4929. if (key === 'shading') {
  4930. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  4931. this.flatShading = newValue === FlatShading ? true : false;
  4932. continue;
  4933. }
  4934. const currentValue = this[key];
  4935. if (currentValue === undefined) {
  4936. console.warn('THREE.' + this.type + ': \'' + key + '\' is not a property of this material.');
  4937. continue;
  4938. }
  4939. if (currentValue && currentValue.isColor) {
  4940. currentValue.set(newValue);
  4941. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  4942. currentValue.copy(newValue);
  4943. } else {
  4944. this[key] = newValue;
  4945. }
  4946. }
  4947. }
  4948. toJSON(meta) {
  4949. const isRoot = meta === undefined || typeof meta === 'string';
  4950. if (isRoot) {
  4951. meta = {
  4952. textures: {},
  4953. images: {}
  4954. };
  4955. }
  4956. const data = {
  4957. metadata: {
  4958. version: 4.5,
  4959. type: 'Material',
  4960. generator: 'Material.toJSON'
  4961. }
  4962. }; // standard Material serialization
  4963. data.uuid = this.uuid;
  4964. data.type = this.type;
  4965. if (this.name !== '') data.name = this.name;
  4966. if (this.color && this.color.isColor) data.color = this.color.getHex();
  4967. if (this.roughness !== undefined) data.roughness = this.roughness;
  4968. if (this.metalness !== undefined) data.metalness = this.metalness;
  4969. if (this.sheen !== undefined) data.sheen = this.sheen;
  4970. if (this.sheenColor && this.sheenColor.isColor) data.sheenColor = this.sheenColor.getHex();
  4971. if (this.sheenRoughness !== undefined) data.sheenRoughness = this.sheenRoughness;
  4972. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  4973. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  4974. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  4975. if (this.specularIntensity !== undefined) data.specularIntensity = this.specularIntensity;
  4976. if (this.specularColor && this.specularColor.isColor) data.specularColor = this.specularColor.getHex();
  4977. if (this.shininess !== undefined) data.shininess = this.shininess;
  4978. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  4979. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  4980. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  4981. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  4982. }
  4983. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  4984. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  4985. }
  4986. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  4987. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  4988. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  4989. }
  4990. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  4991. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  4992. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  4993. if (this.lightMap && this.lightMap.isTexture) {
  4994. data.lightMap = this.lightMap.toJSON(meta).uuid;
  4995. data.lightMapIntensity = this.lightMapIntensity;
  4996. }
  4997. if (this.aoMap && this.aoMap.isTexture) {
  4998. data.aoMap = this.aoMap.toJSON(meta).uuid;
  4999. data.aoMapIntensity = this.aoMapIntensity;
  5000. }
  5001. if (this.bumpMap && this.bumpMap.isTexture) {
  5002. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  5003. data.bumpScale = this.bumpScale;
  5004. }
  5005. if (this.normalMap && this.normalMap.isTexture) {
  5006. data.normalMap = this.normalMap.toJSON(meta).uuid;
  5007. data.normalMapType = this.normalMapType;
  5008. data.normalScale = this.normalScale.toArray();
  5009. }
  5010. if (this.displacementMap && this.displacementMap.isTexture) {
  5011. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  5012. data.displacementScale = this.displacementScale;
  5013. data.displacementBias = this.displacementBias;
  5014. }
  5015. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  5016. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  5017. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  5018. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  5019. if (this.specularIntensityMap && this.specularIntensityMap.isTexture) data.specularIntensityMap = this.specularIntensityMap.toJSON(meta).uuid;
  5020. if (this.specularColorMap && this.specularColorMap.isTexture) data.specularColorMap = this.specularColorMap.toJSON(meta).uuid;
  5021. if (this.envMap && this.envMap.isTexture) {
  5022. data.envMap = this.envMap.toJSON(meta).uuid;
  5023. if (this.combine !== undefined) data.combine = this.combine;
  5024. }
  5025. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  5026. if (this.reflectivity !== undefined) data.reflectivity = this.reflectivity;
  5027. if (this.refractionRatio !== undefined) data.refractionRatio = this.refractionRatio;
  5028. if (this.gradientMap && this.gradientMap.isTexture) {
  5029. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  5030. }
  5031. if (this.transmission !== undefined) data.transmission = this.transmission;
  5032. if (this.transmissionMap && this.transmissionMap.isTexture) data.transmissionMap = this.transmissionMap.toJSON(meta).uuid;
  5033. if (this.thickness !== undefined) data.thickness = this.thickness;
  5034. if (this.thicknessMap && this.thicknessMap.isTexture) data.thicknessMap = this.thicknessMap.toJSON(meta).uuid;
  5035. if (this.attenuationDistance !== undefined) data.attenuationDistance = this.attenuationDistance;
  5036. if (this.attenuationColor !== undefined) data.attenuationColor = this.attenuationColor.getHex();
  5037. if (this.size !== undefined) data.size = this.size;
  5038. if (this.shadowSide !== null) data.shadowSide = this.shadowSide;
  5039. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  5040. if (this.blending !== NormalBlending) data.blending = this.blending;
  5041. if (this.side !== FrontSide) data.side = this.side;
  5042. if (this.vertexColors) data.vertexColors = true;
  5043. if (this.opacity < 1) data.opacity = this.opacity;
  5044. if (this.format !== RGBAFormat) data.format = this.format;
  5045. if (this.transparent === true) data.transparent = this.transparent;
  5046. data.depthFunc = this.depthFunc;
  5047. data.depthTest = this.depthTest;
  5048. data.depthWrite = this.depthWrite;
  5049. data.colorWrite = this.colorWrite;
  5050. data.stencilWrite = this.stencilWrite;
  5051. data.stencilWriteMask = this.stencilWriteMask;
  5052. data.stencilFunc = this.stencilFunc;
  5053. data.stencilRef = this.stencilRef;
  5054. data.stencilFuncMask = this.stencilFuncMask;
  5055. data.stencilFail = this.stencilFail;
  5056. data.stencilZFail = this.stencilZFail;
  5057. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  5058. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  5059. if (this.polygonOffset === true) data.polygonOffset = true;
  5060. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5061. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5062. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  5063. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  5064. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  5065. if (this.scale !== undefined) data.scale = this.scale;
  5066. if (this.dithering === true) data.dithering = true;
  5067. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  5068. if (this.alphaToCoverage === true) data.alphaToCoverage = this.alphaToCoverage;
  5069. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  5070. if (this.wireframe === true) data.wireframe = this.wireframe;
  5071. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  5072. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  5073. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  5074. if (this.flatShading === true) data.flatShading = this.flatShading;
  5075. if (this.visible === false) data.visible = false;
  5076. if (this.toneMapped === false) data.toneMapped = false;
  5077. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  5078. function extractFromCache(cache) {
  5079. const values = [];
  5080. for (const key in cache) {
  5081. const data = cache[key];
  5082. delete data.metadata;
  5083. values.push(data);
  5084. }
  5085. return values;
  5086. }
  5087. if (isRoot) {
  5088. const textures = extractFromCache(meta.textures);
  5089. const images = extractFromCache(meta.images);
  5090. if (textures.length > 0) data.textures = textures;
  5091. if (images.length > 0) data.images = images;
  5092. }
  5093. return data;
  5094. }
  5095. clone() {
  5096. return new this.constructor().copy(this);
  5097. }
  5098. copy(source) {
  5099. this.name = source.name;
  5100. this.fog = source.fog;
  5101. this.blending = source.blending;
  5102. this.side = source.side;
  5103. this.vertexColors = source.vertexColors;
  5104. this.opacity = source.opacity;
  5105. this.format = source.format;
  5106. this.transparent = source.transparent;
  5107. this.blendSrc = source.blendSrc;
  5108. this.blendDst = source.blendDst;
  5109. this.blendEquation = source.blendEquation;
  5110. this.blendSrcAlpha = source.blendSrcAlpha;
  5111. this.blendDstAlpha = source.blendDstAlpha;
  5112. this.blendEquationAlpha = source.blendEquationAlpha;
  5113. this.depthFunc = source.depthFunc;
  5114. this.depthTest = source.depthTest;
  5115. this.depthWrite = source.depthWrite;
  5116. this.stencilWriteMask = source.stencilWriteMask;
  5117. this.stencilFunc = source.stencilFunc;
  5118. this.stencilRef = source.stencilRef;
  5119. this.stencilFuncMask = source.stencilFuncMask;
  5120. this.stencilFail = source.stencilFail;
  5121. this.stencilZFail = source.stencilZFail;
  5122. this.stencilZPass = source.stencilZPass;
  5123. this.stencilWrite = source.stencilWrite;
  5124. const srcPlanes = source.clippingPlanes;
  5125. let dstPlanes = null;
  5126. if (srcPlanes !== null) {
  5127. const n = srcPlanes.length;
  5128. dstPlanes = new Array(n);
  5129. for (let i = 0; i !== n; ++i) {
  5130. dstPlanes[i] = srcPlanes[i].clone();
  5131. }
  5132. }
  5133. this.clippingPlanes = dstPlanes;
  5134. this.clipIntersection = source.clipIntersection;
  5135. this.clipShadows = source.clipShadows;
  5136. this.shadowSide = source.shadowSide;
  5137. this.colorWrite = source.colorWrite;
  5138. this.precision = source.precision;
  5139. this.polygonOffset = source.polygonOffset;
  5140. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5141. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5142. this.dithering = source.dithering;
  5143. this.alphaTest = source.alphaTest;
  5144. this.alphaToCoverage = source.alphaToCoverage;
  5145. this.premultipliedAlpha = source.premultipliedAlpha;
  5146. this.visible = source.visible;
  5147. this.toneMapped = source.toneMapped;
  5148. this.userData = JSON.parse(JSON.stringify(source.userData));
  5149. return this;
  5150. }
  5151. dispose() {
  5152. this.dispatchEvent({
  5153. type: 'dispose'
  5154. });
  5155. }
  5156. set needsUpdate(value) {
  5157. if (value === true) this.version++;
  5158. }
  5159. }
  5160. Material.prototype.isMaterial = true;
  5161. const _colorKeywords = {
  5162. 'aliceblue': 0xF0F8FF,
  5163. 'antiquewhite': 0xFAEBD7,
  5164. 'aqua': 0x00FFFF,
  5165. 'aquamarine': 0x7FFFD4,
  5166. 'azure': 0xF0FFFF,
  5167. 'beige': 0xF5F5DC,
  5168. 'bisque': 0xFFE4C4,
  5169. 'black': 0x000000,
  5170. 'blanchedalmond': 0xFFEBCD,
  5171. 'blue': 0x0000FF,
  5172. 'blueviolet': 0x8A2BE2,
  5173. 'brown': 0xA52A2A,
  5174. 'burlywood': 0xDEB887,
  5175. 'cadetblue': 0x5F9EA0,
  5176. 'chartreuse': 0x7FFF00,
  5177. 'chocolate': 0xD2691E,
  5178. 'coral': 0xFF7F50,
  5179. 'cornflowerblue': 0x6495ED,
  5180. 'cornsilk': 0xFFF8DC,
  5181. 'crimson': 0xDC143C,
  5182. 'cyan': 0x00FFFF,
  5183. 'darkblue': 0x00008B,
  5184. 'darkcyan': 0x008B8B,
  5185. 'darkgoldenrod': 0xB8860B,
  5186. 'darkgray': 0xA9A9A9,
  5187. 'darkgreen': 0x006400,
  5188. 'darkgrey': 0xA9A9A9,
  5189. 'darkkhaki': 0xBDB76B,
  5190. 'darkmagenta': 0x8B008B,
  5191. 'darkolivegreen': 0x556B2F,
  5192. 'darkorange': 0xFF8C00,
  5193. 'darkorchid': 0x9932CC,
  5194. 'darkred': 0x8B0000,
  5195. 'darksalmon': 0xE9967A,
  5196. 'darkseagreen': 0x8FBC8F,
  5197. 'darkslateblue': 0x483D8B,
  5198. 'darkslategray': 0x2F4F4F,
  5199. 'darkslategrey': 0x2F4F4F,
  5200. 'darkturquoise': 0x00CED1,
  5201. 'darkviolet': 0x9400D3,
  5202. 'deeppink': 0xFF1493,
  5203. 'deepskyblue': 0x00BFFF,
  5204. 'dimgray': 0x696969,
  5205. 'dimgrey': 0x696969,
  5206. 'dodgerblue': 0x1E90FF,
  5207. 'firebrick': 0xB22222,
  5208. 'floralwhite': 0xFFFAF0,
  5209. 'forestgreen': 0x228B22,
  5210. 'fuchsia': 0xFF00FF,
  5211. 'gainsboro': 0xDCDCDC,
  5212. 'ghostwhite': 0xF8F8FF,
  5213. 'gold': 0xFFD700,
  5214. 'goldenrod': 0xDAA520,
  5215. 'gray': 0x808080,
  5216. 'green': 0x008000,
  5217. 'greenyellow': 0xADFF2F,
  5218. 'grey': 0x808080,
  5219. 'honeydew': 0xF0FFF0,
  5220. 'hotpink': 0xFF69B4,
  5221. 'indianred': 0xCD5C5C,
  5222. 'indigo': 0x4B0082,
  5223. 'ivory': 0xFFFFF0,
  5224. 'khaki': 0xF0E68C,
  5225. 'lavender': 0xE6E6FA,
  5226. 'lavenderblush': 0xFFF0F5,
  5227. 'lawngreen': 0x7CFC00,
  5228. 'lemonchiffon': 0xFFFACD,
  5229. 'lightblue': 0xADD8E6,
  5230. 'lightcoral': 0xF08080,
  5231. 'lightcyan': 0xE0FFFF,
  5232. 'lightgoldenrodyellow': 0xFAFAD2,
  5233. 'lightgray': 0xD3D3D3,
  5234. 'lightgreen': 0x90EE90,
  5235. 'lightgrey': 0xD3D3D3,
  5236. 'lightpink': 0xFFB6C1,
  5237. 'lightsalmon': 0xFFA07A,
  5238. 'lightseagreen': 0x20B2AA,
  5239. 'lightskyblue': 0x87CEFA,
  5240. 'lightslategray': 0x778899,
  5241. 'lightslategrey': 0x778899,
  5242. 'lightsteelblue': 0xB0C4DE,
  5243. 'lightyellow': 0xFFFFE0,
  5244. 'lime': 0x00FF00,
  5245. 'limegreen': 0x32CD32,
  5246. 'linen': 0xFAF0E6,
  5247. 'magenta': 0xFF00FF,
  5248. 'maroon': 0x800000,
  5249. 'mediumaquamarine': 0x66CDAA,
  5250. 'mediumblue': 0x0000CD,
  5251. 'mediumorchid': 0xBA55D3,
  5252. 'mediumpurple': 0x9370DB,
  5253. 'mediumseagreen': 0x3CB371,
  5254. 'mediumslateblue': 0x7B68EE,
  5255. 'mediumspringgreen': 0x00FA9A,
  5256. 'mediumturquoise': 0x48D1CC,
  5257. 'mediumvioletred': 0xC71585,
  5258. 'midnightblue': 0x191970,
  5259. 'mintcream': 0xF5FFFA,
  5260. 'mistyrose': 0xFFE4E1,
  5261. 'moccasin': 0xFFE4B5,
  5262. 'navajowhite': 0xFFDEAD,
  5263. 'navy': 0x000080,
  5264. 'oldlace': 0xFDF5E6,
  5265. 'olive': 0x808000,
  5266. 'olivedrab': 0x6B8E23,
  5267. 'orange': 0xFFA500,
  5268. 'orangered': 0xFF4500,
  5269. 'orchid': 0xDA70D6,
  5270. 'palegoldenrod': 0xEEE8AA,
  5271. 'palegreen': 0x98FB98,
  5272. 'paleturquoise': 0xAFEEEE,
  5273. 'palevioletred': 0xDB7093,
  5274. 'papayawhip': 0xFFEFD5,
  5275. 'peachpuff': 0xFFDAB9,
  5276. 'peru': 0xCD853F,
  5277. 'pink': 0xFFC0CB,
  5278. 'plum': 0xDDA0DD,
  5279. 'powderblue': 0xB0E0E6,
  5280. 'purple': 0x800080,
  5281. 'rebeccapurple': 0x663399,
  5282. 'red': 0xFF0000,
  5283. 'rosybrown': 0xBC8F8F,
  5284. 'royalblue': 0x4169E1,
  5285. 'saddlebrown': 0x8B4513,
  5286. 'salmon': 0xFA8072,
  5287. 'sandybrown': 0xF4A460,
  5288. 'seagreen': 0x2E8B57,
  5289. 'seashell': 0xFFF5EE,
  5290. 'sienna': 0xA0522D,
  5291. 'silver': 0xC0C0C0,
  5292. 'skyblue': 0x87CEEB,
  5293. 'slateblue': 0x6A5ACD,
  5294. 'slategray': 0x708090,
  5295. 'slategrey': 0x708090,
  5296. 'snow': 0xFFFAFA,
  5297. 'springgreen': 0x00FF7F,
  5298. 'steelblue': 0x4682B4,
  5299. 'tan': 0xD2B48C,
  5300. 'teal': 0x008080,
  5301. 'thistle': 0xD8BFD8,
  5302. 'tomato': 0xFF6347,
  5303. 'turquoise': 0x40E0D0,
  5304. 'violet': 0xEE82EE,
  5305. 'wheat': 0xF5DEB3,
  5306. 'white': 0xFFFFFF,
  5307. 'whitesmoke': 0xF5F5F5,
  5308. 'yellow': 0xFFFF00,
  5309. 'yellowgreen': 0x9ACD32
  5310. };
  5311. const _hslA = {
  5312. h: 0,
  5313. s: 0,
  5314. l: 0
  5315. };
  5316. const _hslB = {
  5317. h: 0,
  5318. s: 0,
  5319. l: 0
  5320. };
  5321. function hue2rgb(p, q, t) {
  5322. if (t < 0) t += 1;
  5323. if (t > 1) t -= 1;
  5324. if (t < 1 / 6) return p + (q - p) * 6 * t;
  5325. if (t < 1 / 2) return q;
  5326. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  5327. return p;
  5328. }
  5329. function SRGBToLinear(c) {
  5330. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  5331. }
  5332. function LinearToSRGB(c) {
  5333. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  5334. }
  5335. class Color {
  5336. constructor(r, g, b) {
  5337. if (g === undefined && b === undefined) {
  5338. // r is THREE.Color, hex or string
  5339. return this.set(r);
  5340. }
  5341. return this.setRGB(r, g, b);
  5342. }
  5343. set(value) {
  5344. if (value && value.isColor) {
  5345. this.copy(value);
  5346. } else if (typeof value === 'number') {
  5347. this.setHex(value);
  5348. } else if (typeof value === 'string') {
  5349. this.setStyle(value);
  5350. }
  5351. return this;
  5352. }
  5353. setScalar(scalar) {
  5354. this.r = scalar;
  5355. this.g = scalar;
  5356. this.b = scalar;
  5357. return this;
  5358. }
  5359. setHex(hex) {
  5360. hex = Math.floor(hex);
  5361. this.r = (hex >> 16 & 255) / 255;
  5362. this.g = (hex >> 8 & 255) / 255;
  5363. this.b = (hex & 255) / 255;
  5364. return this;
  5365. }
  5366. setRGB(r, g, b) {
  5367. this.r = r;
  5368. this.g = g;
  5369. this.b = b;
  5370. return this;
  5371. }
  5372. setHSL(h, s, l) {
  5373. // h,s,l ranges are in 0.0 - 1.0
  5374. h = euclideanModulo(h, 1);
  5375. s = clamp(s, 0, 1);
  5376. l = clamp(l, 0, 1);
  5377. if (s === 0) {
  5378. this.r = this.g = this.b = l;
  5379. } else {
  5380. const p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  5381. const q = 2 * l - p;
  5382. this.r = hue2rgb(q, p, h + 1 / 3);
  5383. this.g = hue2rgb(q, p, h);
  5384. this.b = hue2rgb(q, p, h - 1 / 3);
  5385. }
  5386. return this;
  5387. }
  5388. setStyle(style) {
  5389. function handleAlpha(string) {
  5390. if (string === undefined) return;
  5391. if (parseFloat(string) < 1) {
  5392. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  5393. }
  5394. }
  5395. let m;
  5396. if (m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style)) {
  5397. // rgb / hsl
  5398. let color;
  5399. const name = m[1];
  5400. const components = m[2];
  5401. switch (name) {
  5402. case 'rgb':
  5403. case 'rgba':
  5404. if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5405. // rgb(255,0,0) rgba(255,0,0,0.5)
  5406. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  5407. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  5408. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  5409. handleAlpha(color[4]);
  5410. return this;
  5411. }
  5412. if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5413. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5414. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  5415. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  5416. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  5417. handleAlpha(color[4]);
  5418. return this;
  5419. }
  5420. break;
  5421. case 'hsl':
  5422. case 'hsla':
  5423. if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5424. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5425. const h = parseFloat(color[1]) / 360;
  5426. const s = parseInt(color[2], 10) / 100;
  5427. const l = parseInt(color[3], 10) / 100;
  5428. handleAlpha(color[4]);
  5429. return this.setHSL(h, s, l);
  5430. }
  5431. break;
  5432. }
  5433. } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) {
  5434. // hex color
  5435. const hex = m[1];
  5436. const size = hex.length;
  5437. if (size === 3) {
  5438. // #ff0
  5439. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  5440. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  5441. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  5442. return this;
  5443. } else if (size === 6) {
  5444. // #ff0000
  5445. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  5446. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  5447. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  5448. return this;
  5449. }
  5450. }
  5451. if (style && style.length > 0) {
  5452. return this.setColorName(style);
  5453. }
  5454. return this;
  5455. }
  5456. setColorName(style) {
  5457. // color keywords
  5458. const hex = _colorKeywords[style.toLowerCase()];
  5459. if (hex !== undefined) {
  5460. // red
  5461. this.setHex(hex);
  5462. } else {
  5463. // unknown color
  5464. console.warn('THREE.Color: Unknown color ' + style);
  5465. }
  5466. return this;
  5467. }
  5468. clone() {
  5469. return new this.constructor(this.r, this.g, this.b);
  5470. }
  5471. copy(color) {
  5472. this.r = color.r;
  5473. this.g = color.g;
  5474. this.b = color.b;
  5475. return this;
  5476. }
  5477. copyGammaToLinear(color, gammaFactor = 2.0) {
  5478. this.r = Math.pow(color.r, gammaFactor);
  5479. this.g = Math.pow(color.g, gammaFactor);
  5480. this.b = Math.pow(color.b, gammaFactor);
  5481. return this;
  5482. }
  5483. copyLinearToGamma(color, gammaFactor = 2.0) {
  5484. const safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  5485. this.r = Math.pow(color.r, safeInverse);
  5486. this.g = Math.pow(color.g, safeInverse);
  5487. this.b = Math.pow(color.b, safeInverse);
  5488. return this;
  5489. }
  5490. convertGammaToLinear(gammaFactor) {
  5491. this.copyGammaToLinear(this, gammaFactor);
  5492. return this;
  5493. }
  5494. convertLinearToGamma(gammaFactor) {
  5495. this.copyLinearToGamma(this, gammaFactor);
  5496. return this;
  5497. }
  5498. copySRGBToLinear(color) {
  5499. this.r = SRGBToLinear(color.r);
  5500. this.g = SRGBToLinear(color.g);
  5501. this.b = SRGBToLinear(color.b);
  5502. return this;
  5503. }
  5504. copyLinearToSRGB(color) {
  5505. this.r = LinearToSRGB(color.r);
  5506. this.g = LinearToSRGB(color.g);
  5507. this.b = LinearToSRGB(color.b);
  5508. return this;
  5509. }
  5510. convertSRGBToLinear() {
  5511. this.copySRGBToLinear(this);
  5512. return this;
  5513. }
  5514. convertLinearToSRGB() {
  5515. this.copyLinearToSRGB(this);
  5516. return this;
  5517. }
  5518. getHex() {
  5519. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  5520. }
  5521. getHexString() {
  5522. return ('000000' + this.getHex().toString(16)).slice(-6);
  5523. }
  5524. getHSL(target) {
  5525. // h,s,l ranges are in 0.0 - 1.0
  5526. const r = this.r,
  5527. g = this.g,
  5528. b = this.b;
  5529. const max = Math.max(r, g, b);
  5530. const min = Math.min(r, g, b);
  5531. let hue, saturation;
  5532. const lightness = (min + max) / 2.0;
  5533. if (min === max) {
  5534. hue = 0;
  5535. saturation = 0;
  5536. } else {
  5537. const delta = max - min;
  5538. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  5539. switch (max) {
  5540. case r:
  5541. hue = (g - b) / delta + (g < b ? 6 : 0);
  5542. break;
  5543. case g:
  5544. hue = (b - r) / delta + 2;
  5545. break;
  5546. case b:
  5547. hue = (r - g) / delta + 4;
  5548. break;
  5549. }
  5550. hue /= 6;
  5551. }
  5552. target.h = hue;
  5553. target.s = saturation;
  5554. target.l = lightness;
  5555. return target;
  5556. }
  5557. getStyle() {
  5558. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  5559. }
  5560. offsetHSL(h, s, l) {
  5561. this.getHSL(_hslA);
  5562. _hslA.h += h;
  5563. _hslA.s += s;
  5564. _hslA.l += l;
  5565. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  5566. return this;
  5567. }
  5568. add(color) {
  5569. this.r += color.r;
  5570. this.g += color.g;
  5571. this.b += color.b;
  5572. return this;
  5573. }
  5574. addColors(color1, color2) {
  5575. this.r = color1.r + color2.r;
  5576. this.g = color1.g + color2.g;
  5577. this.b = color1.b + color2.b;
  5578. return this;
  5579. }
  5580. addScalar(s) {
  5581. this.r += s;
  5582. this.g += s;
  5583. this.b += s;
  5584. return this;
  5585. }
  5586. sub(color) {
  5587. this.r = Math.max(0, this.r - color.r);
  5588. this.g = Math.max(0, this.g - color.g);
  5589. this.b = Math.max(0, this.b - color.b);
  5590. return this;
  5591. }
  5592. multiply(color) {
  5593. this.r *= color.r;
  5594. this.g *= color.g;
  5595. this.b *= color.b;
  5596. return this;
  5597. }
  5598. multiplyScalar(s) {
  5599. this.r *= s;
  5600. this.g *= s;
  5601. this.b *= s;
  5602. return this;
  5603. }
  5604. lerp(color, alpha) {
  5605. this.r += (color.r - this.r) * alpha;
  5606. this.g += (color.g - this.g) * alpha;
  5607. this.b += (color.b - this.b) * alpha;
  5608. return this;
  5609. }
  5610. lerpColors(color1, color2, alpha) {
  5611. this.r = color1.r + (color2.r - color1.r) * alpha;
  5612. this.g = color1.g + (color2.g - color1.g) * alpha;
  5613. this.b = color1.b + (color2.b - color1.b) * alpha;
  5614. return this;
  5615. }
  5616. lerpHSL(color, alpha) {
  5617. this.getHSL(_hslA);
  5618. color.getHSL(_hslB);
  5619. const h = lerp(_hslA.h, _hslB.h, alpha);
  5620. const s = lerp(_hslA.s, _hslB.s, alpha);
  5621. const l = lerp(_hslA.l, _hslB.l, alpha);
  5622. this.setHSL(h, s, l);
  5623. return this;
  5624. }
  5625. equals(c) {
  5626. return c.r === this.r && c.g === this.g && c.b === this.b;
  5627. }
  5628. fromArray(array, offset = 0) {
  5629. this.r = array[offset];
  5630. this.g = array[offset + 1];
  5631. this.b = array[offset + 2];
  5632. return this;
  5633. }
  5634. toArray(array = [], offset = 0) {
  5635. array[offset] = this.r;
  5636. array[offset + 1] = this.g;
  5637. array[offset + 2] = this.b;
  5638. return array;
  5639. }
  5640. fromBufferAttribute(attribute, index) {
  5641. this.r = attribute.getX(index);
  5642. this.g = attribute.getY(index);
  5643. this.b = attribute.getZ(index);
  5644. if (attribute.normalized === true) {
  5645. // assuming Uint8Array
  5646. this.r /= 255;
  5647. this.g /= 255;
  5648. this.b /= 255;
  5649. }
  5650. return this;
  5651. }
  5652. toJSON() {
  5653. return this.getHex();
  5654. }
  5655. }
  5656. Color.NAMES = _colorKeywords;
  5657. Color.prototype.isColor = true;
  5658. Color.prototype.r = 1;
  5659. Color.prototype.g = 1;
  5660. Color.prototype.b = 1;
  5661. /**
  5662. * parameters = {
  5663. * color: <hex>,
  5664. * opacity: <float>,
  5665. * map: new THREE.Texture( <Image> ),
  5666. *
  5667. * lightMap: new THREE.Texture( <Image> ),
  5668. * lightMapIntensity: <float>
  5669. *
  5670. * aoMap: new THREE.Texture( <Image> ),
  5671. * aoMapIntensity: <float>
  5672. *
  5673. * specularMap: new THREE.Texture( <Image> ),
  5674. *
  5675. * alphaMap: new THREE.Texture( <Image> ),
  5676. *
  5677. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  5678. * combine: THREE.Multiply,
  5679. * reflectivity: <float>,
  5680. * refractionRatio: <float>,
  5681. *
  5682. * depthTest: <bool>,
  5683. * depthWrite: <bool>,
  5684. *
  5685. * wireframe: <boolean>,
  5686. * wireframeLinewidth: <float>,
  5687. * }
  5688. */
  5689. class MeshBasicMaterial extends Material {
  5690. constructor(parameters) {
  5691. super();
  5692. this.type = 'MeshBasicMaterial';
  5693. this.color = new Color(0xffffff); // emissive
  5694. this.map = null;
  5695. this.lightMap = null;
  5696. this.lightMapIntensity = 1.0;
  5697. this.aoMap = null;
  5698. this.aoMapIntensity = 1.0;
  5699. this.specularMap = null;
  5700. this.alphaMap = null;
  5701. this.envMap = null;
  5702. this.combine = MultiplyOperation;
  5703. this.reflectivity = 1;
  5704. this.refractionRatio = 0.98;
  5705. this.wireframe = false;
  5706. this.wireframeLinewidth = 1;
  5707. this.wireframeLinecap = 'round';
  5708. this.wireframeLinejoin = 'round';
  5709. this.setValues(parameters);
  5710. }
  5711. copy(source) {
  5712. super.copy(source);
  5713. this.color.copy(source.color);
  5714. this.map = source.map;
  5715. this.lightMap = source.lightMap;
  5716. this.lightMapIntensity = source.lightMapIntensity;
  5717. this.aoMap = source.aoMap;
  5718. this.aoMapIntensity = source.aoMapIntensity;
  5719. this.specularMap = source.specularMap;
  5720. this.alphaMap = source.alphaMap;
  5721. this.envMap = source.envMap;
  5722. this.combine = source.combine;
  5723. this.reflectivity = source.reflectivity;
  5724. this.refractionRatio = source.refractionRatio;
  5725. this.wireframe = source.wireframe;
  5726. this.wireframeLinewidth = source.wireframeLinewidth;
  5727. this.wireframeLinecap = source.wireframeLinecap;
  5728. this.wireframeLinejoin = source.wireframeLinejoin;
  5729. return this;
  5730. }
  5731. }
  5732. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  5733. const _vector$9 = /*@__PURE__*/new Vector3();
  5734. const _vector2$1 = /*@__PURE__*/new Vector2();
  5735. class BufferAttribute {
  5736. constructor(array, itemSize, normalized) {
  5737. if (Array.isArray(array)) {
  5738. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  5739. }
  5740. this.name = '';
  5741. this.array = array;
  5742. this.itemSize = itemSize;
  5743. this.count = array !== undefined ? array.length / itemSize : 0;
  5744. this.normalized = normalized === true;
  5745. this.usage = StaticDrawUsage;
  5746. this.updateRange = {
  5747. offset: 0,
  5748. count: -1
  5749. };
  5750. this.version = 0;
  5751. }
  5752. onUploadCallback() {}
  5753. set needsUpdate(value) {
  5754. if (value === true) this.version++;
  5755. }
  5756. setUsage(value) {
  5757. this.usage = value;
  5758. return this;
  5759. }
  5760. copy(source) {
  5761. this.name = source.name;
  5762. this.array = new source.array.constructor(source.array);
  5763. this.itemSize = source.itemSize;
  5764. this.count = source.count;
  5765. this.normalized = source.normalized;
  5766. this.usage = source.usage;
  5767. return this;
  5768. }
  5769. copyAt(index1, attribute, index2) {
  5770. index1 *= this.itemSize;
  5771. index2 *= attribute.itemSize;
  5772. for (let i = 0, l = this.itemSize; i < l; i++) {
  5773. this.array[index1 + i] = attribute.array[index2 + i];
  5774. }
  5775. return this;
  5776. }
  5777. copyArray(array) {
  5778. this.array.set(array);
  5779. return this;
  5780. }
  5781. copyColorsArray(colors) {
  5782. const array = this.array;
  5783. let offset = 0;
  5784. for (let i = 0, l = colors.length; i < l; i++) {
  5785. let color = colors[i];
  5786. if (color === undefined) {
  5787. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  5788. color = new Color();
  5789. }
  5790. array[offset++] = color.r;
  5791. array[offset++] = color.g;
  5792. array[offset++] = color.b;
  5793. }
  5794. return this;
  5795. }
  5796. copyVector2sArray(vectors) {
  5797. const array = this.array;
  5798. let offset = 0;
  5799. for (let i = 0, l = vectors.length; i < l; i++) {
  5800. let vector = vectors[i];
  5801. if (vector === undefined) {
  5802. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  5803. vector = new Vector2();
  5804. }
  5805. array[offset++] = vector.x;
  5806. array[offset++] = vector.y;
  5807. }
  5808. return this;
  5809. }
  5810. copyVector3sArray(vectors) {
  5811. const array = this.array;
  5812. let offset = 0;
  5813. for (let i = 0, l = vectors.length; i < l; i++) {
  5814. let vector = vectors[i];
  5815. if (vector === undefined) {
  5816. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  5817. vector = new Vector3();
  5818. }
  5819. array[offset++] = vector.x;
  5820. array[offset++] = vector.y;
  5821. array[offset++] = vector.z;
  5822. }
  5823. return this;
  5824. }
  5825. copyVector4sArray(vectors) {
  5826. const array = this.array;
  5827. let offset = 0;
  5828. for (let i = 0, l = vectors.length; i < l; i++) {
  5829. let vector = vectors[i];
  5830. if (vector === undefined) {
  5831. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  5832. vector = new Vector4();
  5833. }
  5834. array[offset++] = vector.x;
  5835. array[offset++] = vector.y;
  5836. array[offset++] = vector.z;
  5837. array[offset++] = vector.w;
  5838. }
  5839. return this;
  5840. }
  5841. applyMatrix3(m) {
  5842. if (this.itemSize === 2) {
  5843. for (let i = 0, l = this.count; i < l; i++) {
  5844. _vector2$1.fromBufferAttribute(this, i);
  5845. _vector2$1.applyMatrix3(m);
  5846. this.setXY(i, _vector2$1.x, _vector2$1.y);
  5847. }
  5848. } else if (this.itemSize === 3) {
  5849. for (let i = 0, l = this.count; i < l; i++) {
  5850. _vector$9.fromBufferAttribute(this, i);
  5851. _vector$9.applyMatrix3(m);
  5852. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5853. }
  5854. }
  5855. return this;
  5856. }
  5857. applyMatrix4(m) {
  5858. for (let i = 0, l = this.count; i < l; i++) {
  5859. _vector$9.x = this.getX(i);
  5860. _vector$9.y = this.getY(i);
  5861. _vector$9.z = this.getZ(i);
  5862. _vector$9.applyMatrix4(m);
  5863. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5864. }
  5865. return this;
  5866. }
  5867. applyNormalMatrix(m) {
  5868. for (let i = 0, l = this.count; i < l; i++) {
  5869. _vector$9.x = this.getX(i);
  5870. _vector$9.y = this.getY(i);
  5871. _vector$9.z = this.getZ(i);
  5872. _vector$9.applyNormalMatrix(m);
  5873. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5874. }
  5875. return this;
  5876. }
  5877. transformDirection(m) {
  5878. for (let i = 0, l = this.count; i < l; i++) {
  5879. _vector$9.x = this.getX(i);
  5880. _vector$9.y = this.getY(i);
  5881. _vector$9.z = this.getZ(i);
  5882. _vector$9.transformDirection(m);
  5883. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5884. }
  5885. return this;
  5886. }
  5887. set(value, offset = 0) {
  5888. this.array.set(value, offset);
  5889. return this;
  5890. }
  5891. getX(index) {
  5892. return this.array[index * this.itemSize];
  5893. }
  5894. setX(index, x) {
  5895. this.array[index * this.itemSize] = x;
  5896. return this;
  5897. }
  5898. getY(index) {
  5899. return this.array[index * this.itemSize + 1];
  5900. }
  5901. setY(index, y) {
  5902. this.array[index * this.itemSize + 1] = y;
  5903. return this;
  5904. }
  5905. getZ(index) {
  5906. return this.array[index * this.itemSize + 2];
  5907. }
  5908. setZ(index, z) {
  5909. this.array[index * this.itemSize + 2] = z;
  5910. return this;
  5911. }
  5912. getW(index) {
  5913. return this.array[index * this.itemSize + 3];
  5914. }
  5915. setW(index, w) {
  5916. this.array[index * this.itemSize + 3] = w;
  5917. return this;
  5918. }
  5919. setXY(index, x, y) {
  5920. index *= this.itemSize;
  5921. this.array[index + 0] = x;
  5922. this.array[index + 1] = y;
  5923. return this;
  5924. }
  5925. setXYZ(index, x, y, z) {
  5926. index *= this.itemSize;
  5927. this.array[index + 0] = x;
  5928. this.array[index + 1] = y;
  5929. this.array[index + 2] = z;
  5930. return this;
  5931. }
  5932. setXYZW(index, x, y, z, w) {
  5933. index *= this.itemSize;
  5934. this.array[index + 0] = x;
  5935. this.array[index + 1] = y;
  5936. this.array[index + 2] = z;
  5937. this.array[index + 3] = w;
  5938. return this;
  5939. }
  5940. onUpload(callback) {
  5941. this.onUploadCallback = callback;
  5942. return this;
  5943. }
  5944. clone() {
  5945. return new this.constructor(this.array, this.itemSize).copy(this);
  5946. }
  5947. toJSON() {
  5948. const data = {
  5949. itemSize: this.itemSize,
  5950. type: this.array.constructor.name,
  5951. array: Array.prototype.slice.call(this.array),
  5952. normalized: this.normalized
  5953. };
  5954. if (this.name !== '') data.name = this.name;
  5955. if (this.usage !== StaticDrawUsage) data.usage = this.usage;
  5956. if (this.updateRange.offset !== 0 || this.updateRange.count !== -1) data.updateRange = this.updateRange;
  5957. return data;
  5958. }
  5959. }
  5960. BufferAttribute.prototype.isBufferAttribute = true; //
  5961. class Int8BufferAttribute extends BufferAttribute {
  5962. constructor(array, itemSize, normalized) {
  5963. super(new Int8Array(array), itemSize, normalized);
  5964. }
  5965. }
  5966. class Uint8BufferAttribute extends BufferAttribute {
  5967. constructor(array, itemSize, normalized) {
  5968. super(new Uint8Array(array), itemSize, normalized);
  5969. }
  5970. }
  5971. class Uint8ClampedBufferAttribute extends BufferAttribute {
  5972. constructor(array, itemSize, normalized) {
  5973. super(new Uint8ClampedArray(array), itemSize, normalized);
  5974. }
  5975. }
  5976. class Int16BufferAttribute extends BufferAttribute {
  5977. constructor(array, itemSize, normalized) {
  5978. super(new Int16Array(array), itemSize, normalized);
  5979. }
  5980. }
  5981. class Uint16BufferAttribute extends BufferAttribute {
  5982. constructor(array, itemSize, normalized) {
  5983. super(new Uint16Array(array), itemSize, normalized);
  5984. }
  5985. }
  5986. class Int32BufferAttribute extends BufferAttribute {
  5987. constructor(array, itemSize, normalized) {
  5988. super(new Int32Array(array), itemSize, normalized);
  5989. }
  5990. }
  5991. class Uint32BufferAttribute extends BufferAttribute {
  5992. constructor(array, itemSize, normalized) {
  5993. super(new Uint32Array(array), itemSize, normalized);
  5994. }
  5995. }
  5996. class Float16BufferAttribute extends BufferAttribute {
  5997. constructor(array, itemSize, normalized) {
  5998. super(new Uint16Array(array), itemSize, normalized);
  5999. }
  6000. }
  6001. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  6002. class Float32BufferAttribute extends BufferAttribute {
  6003. constructor(array, itemSize, normalized) {
  6004. super(new Float32Array(array), itemSize, normalized);
  6005. }
  6006. }
  6007. class Float64BufferAttribute extends BufferAttribute {
  6008. constructor(array, itemSize, normalized) {
  6009. super(new Float64Array(array), itemSize, normalized);
  6010. }
  6011. } //
  6012. let _id$1 = 0;
  6013. const _m1 = /*@__PURE__*/new Matrix4();
  6014. const _obj = /*@__PURE__*/new Object3D();
  6015. const _offset = /*@__PURE__*/new Vector3();
  6016. const _box$1 = /*@__PURE__*/new Box3();
  6017. const _boxMorphTargets = /*@__PURE__*/new Box3();
  6018. const _vector$8 = /*@__PURE__*/new Vector3();
  6019. class BufferGeometry extends EventDispatcher {
  6020. constructor() {
  6021. super();
  6022. Object.defineProperty(this, 'id', {
  6023. value: _id$1++
  6024. });
  6025. this.uuid = generateUUID();
  6026. this.name = '';
  6027. this.type = 'BufferGeometry';
  6028. this.index = null;
  6029. this.attributes = {};
  6030. this.morphAttributes = {};
  6031. this.morphTargetsRelative = false;
  6032. this.groups = [];
  6033. this.boundingBox = null;
  6034. this.boundingSphere = null;
  6035. this.drawRange = {
  6036. start: 0,
  6037. count: Infinity
  6038. };
  6039. this.userData = {};
  6040. }
  6041. getIndex() {
  6042. return this.index;
  6043. }
  6044. setIndex(index) {
  6045. if (Array.isArray(index)) {
  6046. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  6047. } else {
  6048. this.index = index;
  6049. }
  6050. return this;
  6051. }
  6052. getAttribute(name) {
  6053. return this.attributes[name];
  6054. }
  6055. setAttribute(name, attribute) {
  6056. this.attributes[name] = attribute;
  6057. return this;
  6058. }
  6059. deleteAttribute(name) {
  6060. delete this.attributes[name];
  6061. return this;
  6062. }
  6063. hasAttribute(name) {
  6064. return this.attributes[name] !== undefined;
  6065. }
  6066. addGroup(start, count, materialIndex = 0) {
  6067. this.groups.push({
  6068. start: start,
  6069. count: count,
  6070. materialIndex: materialIndex
  6071. });
  6072. }
  6073. clearGroups() {
  6074. this.groups = [];
  6075. }
  6076. setDrawRange(start, count) {
  6077. this.drawRange.start = start;
  6078. this.drawRange.count = count;
  6079. }
  6080. applyMatrix4(matrix) {
  6081. const position = this.attributes.position;
  6082. if (position !== undefined) {
  6083. position.applyMatrix4(matrix);
  6084. position.needsUpdate = true;
  6085. }
  6086. const normal = this.attributes.normal;
  6087. if (normal !== undefined) {
  6088. const normalMatrix = new Matrix3().getNormalMatrix(matrix);
  6089. normal.applyNormalMatrix(normalMatrix);
  6090. normal.needsUpdate = true;
  6091. }
  6092. const tangent = this.attributes.tangent;
  6093. if (tangent !== undefined) {
  6094. tangent.transformDirection(matrix);
  6095. tangent.needsUpdate = true;
  6096. }
  6097. if (this.boundingBox !== null) {
  6098. this.computeBoundingBox();
  6099. }
  6100. if (this.boundingSphere !== null) {
  6101. this.computeBoundingSphere();
  6102. }
  6103. return this;
  6104. }
  6105. applyQuaternion(q) {
  6106. _m1.makeRotationFromQuaternion(q);
  6107. this.applyMatrix4(_m1);
  6108. return this;
  6109. }
  6110. rotateX(angle) {
  6111. // rotate geometry around world x-axis
  6112. _m1.makeRotationX(angle);
  6113. this.applyMatrix4(_m1);
  6114. return this;
  6115. }
  6116. rotateY(angle) {
  6117. // rotate geometry around world y-axis
  6118. _m1.makeRotationY(angle);
  6119. this.applyMatrix4(_m1);
  6120. return this;
  6121. }
  6122. rotateZ(angle) {
  6123. // rotate geometry around world z-axis
  6124. _m1.makeRotationZ(angle);
  6125. this.applyMatrix4(_m1);
  6126. return this;
  6127. }
  6128. translate(x, y, z) {
  6129. // translate geometry
  6130. _m1.makeTranslation(x, y, z);
  6131. this.applyMatrix4(_m1);
  6132. return this;
  6133. }
  6134. scale(x, y, z) {
  6135. // scale geometry
  6136. _m1.makeScale(x, y, z);
  6137. this.applyMatrix4(_m1);
  6138. return this;
  6139. }
  6140. lookAt(vector) {
  6141. _obj.lookAt(vector);
  6142. _obj.updateMatrix();
  6143. this.applyMatrix4(_obj.matrix);
  6144. return this;
  6145. }
  6146. center() {
  6147. this.computeBoundingBox();
  6148. this.boundingBox.getCenter(_offset).negate();
  6149. this.translate(_offset.x, _offset.y, _offset.z);
  6150. return this;
  6151. }
  6152. setFromPoints(points) {
  6153. const position = [];
  6154. for (let i = 0, l = points.length; i < l; i++) {
  6155. const point = points[i];
  6156. position.push(point.x, point.y, point.z || 0);
  6157. }
  6158. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  6159. return this;
  6160. }
  6161. computeBoundingBox() {
  6162. if (this.boundingBox === null) {
  6163. this.boundingBox = new Box3();
  6164. }
  6165. const position = this.attributes.position;
  6166. const morphAttributesPosition = this.morphAttributes.position;
  6167. if (position && position.isGLBufferAttribute) {
  6168. console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
  6169. this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
  6170. return;
  6171. }
  6172. if (position !== undefined) {
  6173. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  6174. if (morphAttributesPosition) {
  6175. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6176. const morphAttribute = morphAttributesPosition[i];
  6177. _box$1.setFromBufferAttribute(morphAttribute);
  6178. if (this.morphTargetsRelative) {
  6179. _vector$8.addVectors(this.boundingBox.min, _box$1.min);
  6180. this.boundingBox.expandByPoint(_vector$8);
  6181. _vector$8.addVectors(this.boundingBox.max, _box$1.max);
  6182. this.boundingBox.expandByPoint(_vector$8);
  6183. } else {
  6184. this.boundingBox.expandByPoint(_box$1.min);
  6185. this.boundingBox.expandByPoint(_box$1.max);
  6186. }
  6187. }
  6188. }
  6189. } else {
  6190. this.boundingBox.makeEmpty();
  6191. }
  6192. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  6193. console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  6194. }
  6195. }
  6196. computeBoundingSphere() {
  6197. if (this.boundingSphere === null) {
  6198. this.boundingSphere = new Sphere();
  6199. }
  6200. const position = this.attributes.position;
  6201. const morphAttributesPosition = this.morphAttributes.position;
  6202. if (position && position.isGLBufferAttribute) {
  6203. console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
  6204. this.boundingSphere.set(new Vector3(), Infinity);
  6205. return;
  6206. }
  6207. if (position) {
  6208. // first, find the center of the bounding sphere
  6209. const center = this.boundingSphere.center;
  6210. _box$1.setFromBufferAttribute(position); // process morph attributes if present
  6211. if (morphAttributesPosition) {
  6212. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6213. const morphAttribute = morphAttributesPosition[i];
  6214. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  6215. if (this.morphTargetsRelative) {
  6216. _vector$8.addVectors(_box$1.min, _boxMorphTargets.min);
  6217. _box$1.expandByPoint(_vector$8);
  6218. _vector$8.addVectors(_box$1.max, _boxMorphTargets.max);
  6219. _box$1.expandByPoint(_vector$8);
  6220. } else {
  6221. _box$1.expandByPoint(_boxMorphTargets.min);
  6222. _box$1.expandByPoint(_boxMorphTargets.max);
  6223. }
  6224. }
  6225. }
  6226. _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  6227. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6228. let maxRadiusSq = 0;
  6229. for (let i = 0, il = position.count; i < il; i++) {
  6230. _vector$8.fromBufferAttribute(position, i);
  6231. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6232. } // process morph attributes if present
  6233. if (morphAttributesPosition) {
  6234. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6235. const morphAttribute = morphAttributesPosition[i];
  6236. const morphTargetsRelative = this.morphTargetsRelative;
  6237. for (let j = 0, jl = morphAttribute.count; j < jl; j++) {
  6238. _vector$8.fromBufferAttribute(morphAttribute, j);
  6239. if (morphTargetsRelative) {
  6240. _offset.fromBufferAttribute(position, j);
  6241. _vector$8.add(_offset);
  6242. }
  6243. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6244. }
  6245. }
  6246. }
  6247. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  6248. if (isNaN(this.boundingSphere.radius)) {
  6249. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  6250. }
  6251. }
  6252. }
  6253. computeTangents() {
  6254. const index = this.index;
  6255. const attributes = this.attributes; // based on http://www.terathon.com/code/tangent.html
  6256. // (per vertex tangents)
  6257. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  6258. console.error('THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)');
  6259. return;
  6260. }
  6261. const indices = index.array;
  6262. const positions = attributes.position.array;
  6263. const normals = attributes.normal.array;
  6264. const uvs = attributes.uv.array;
  6265. const nVertices = positions.length / 3;
  6266. if (attributes.tangent === undefined) {
  6267. this.setAttribute('tangent', new BufferAttribute(new Float32Array(4 * nVertices), 4));
  6268. }
  6269. const tangents = attributes.tangent.array;
  6270. const tan1 = [],
  6271. tan2 = [];
  6272. for (let i = 0; i < nVertices; i++) {
  6273. tan1[i] = new Vector3();
  6274. tan2[i] = new Vector3();
  6275. }
  6276. const vA = new Vector3(),
  6277. vB = new Vector3(),
  6278. vC = new Vector3(),
  6279. uvA = new Vector2(),
  6280. uvB = new Vector2(),
  6281. uvC = new Vector2(),
  6282. sdir = new Vector3(),
  6283. tdir = new Vector3();
  6284. function handleTriangle(a, b, c) {
  6285. vA.fromArray(positions, a * 3);
  6286. vB.fromArray(positions, b * 3);
  6287. vC.fromArray(positions, c * 3);
  6288. uvA.fromArray(uvs, a * 2);
  6289. uvB.fromArray(uvs, b * 2);
  6290. uvC.fromArray(uvs, c * 2);
  6291. vB.sub(vA);
  6292. vC.sub(vA);
  6293. uvB.sub(uvA);
  6294. uvC.sub(uvA);
  6295. const r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y); // silently ignore degenerate uv triangles having coincident or colinear vertices
  6296. if (!isFinite(r)) return;
  6297. sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
  6298. tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
  6299. tan1[a].add(sdir);
  6300. tan1[b].add(sdir);
  6301. tan1[c].add(sdir);
  6302. tan2[a].add(tdir);
  6303. tan2[b].add(tdir);
  6304. tan2[c].add(tdir);
  6305. }
  6306. let groups = this.groups;
  6307. if (groups.length === 0) {
  6308. groups = [{
  6309. start: 0,
  6310. count: indices.length
  6311. }];
  6312. }
  6313. for (let i = 0, il = groups.length; i < il; ++i) {
  6314. const group = groups[i];
  6315. const start = group.start;
  6316. const count = group.count;
  6317. for (let j = start, jl = start + count; j < jl; j += 3) {
  6318. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  6319. }
  6320. }
  6321. const tmp = new Vector3(),
  6322. tmp2 = new Vector3();
  6323. const n = new Vector3(),
  6324. n2 = new Vector3();
  6325. function handleVertex(v) {
  6326. n.fromArray(normals, v * 3);
  6327. n2.copy(n);
  6328. const t = tan1[v]; // Gram-Schmidt orthogonalize
  6329. tmp.copy(t);
  6330. tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
  6331. tmp2.crossVectors(n2, t);
  6332. const test = tmp2.dot(tan2[v]);
  6333. const w = test < 0.0 ? -1.0 : 1.0;
  6334. tangents[v * 4] = tmp.x;
  6335. tangents[v * 4 + 1] = tmp.y;
  6336. tangents[v * 4 + 2] = tmp.z;
  6337. tangents[v * 4 + 3] = w;
  6338. }
  6339. for (let i = 0, il = groups.length; i < il; ++i) {
  6340. const group = groups[i];
  6341. const start = group.start;
  6342. const count = group.count;
  6343. for (let j = start, jl = start + count; j < jl; j += 3) {
  6344. handleVertex(indices[j + 0]);
  6345. handleVertex(indices[j + 1]);
  6346. handleVertex(indices[j + 2]);
  6347. }
  6348. }
  6349. }
  6350. computeVertexNormals() {
  6351. const index = this.index;
  6352. const positionAttribute = this.getAttribute('position');
  6353. if (positionAttribute !== undefined) {
  6354. let normalAttribute = this.getAttribute('normal');
  6355. if (normalAttribute === undefined) {
  6356. normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
  6357. this.setAttribute('normal', normalAttribute);
  6358. } else {
  6359. // reset existing normals to zero
  6360. for (let i = 0, il = normalAttribute.count; i < il; i++) {
  6361. normalAttribute.setXYZ(i, 0, 0, 0);
  6362. }
  6363. }
  6364. const pA = new Vector3(),
  6365. pB = new Vector3(),
  6366. pC = new Vector3();
  6367. const nA = new Vector3(),
  6368. nB = new Vector3(),
  6369. nC = new Vector3();
  6370. const cb = new Vector3(),
  6371. ab = new Vector3(); // indexed elements
  6372. if (index) {
  6373. for (let i = 0, il = index.count; i < il; i += 3) {
  6374. const vA = index.getX(i + 0);
  6375. const vB = index.getX(i + 1);
  6376. const vC = index.getX(i + 2);
  6377. pA.fromBufferAttribute(positionAttribute, vA);
  6378. pB.fromBufferAttribute(positionAttribute, vB);
  6379. pC.fromBufferAttribute(positionAttribute, vC);
  6380. cb.subVectors(pC, pB);
  6381. ab.subVectors(pA, pB);
  6382. cb.cross(ab);
  6383. nA.fromBufferAttribute(normalAttribute, vA);
  6384. nB.fromBufferAttribute(normalAttribute, vB);
  6385. nC.fromBufferAttribute(normalAttribute, vC);
  6386. nA.add(cb);
  6387. nB.add(cb);
  6388. nC.add(cb);
  6389. normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
  6390. normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
  6391. normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
  6392. }
  6393. } else {
  6394. // non-indexed elements (unconnected triangle soup)
  6395. for (let i = 0, il = positionAttribute.count; i < il; i += 3) {
  6396. pA.fromBufferAttribute(positionAttribute, i + 0);
  6397. pB.fromBufferAttribute(positionAttribute, i + 1);
  6398. pC.fromBufferAttribute(positionAttribute, i + 2);
  6399. cb.subVectors(pC, pB);
  6400. ab.subVectors(pA, pB);
  6401. cb.cross(ab);
  6402. normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z);
  6403. normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z);
  6404. normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z);
  6405. }
  6406. }
  6407. this.normalizeNormals();
  6408. normalAttribute.needsUpdate = true;
  6409. }
  6410. }
  6411. merge(geometry, offset) {
  6412. if (!(geometry && geometry.isBufferGeometry)) {
  6413. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  6414. return;
  6415. }
  6416. if (offset === undefined) {
  6417. offset = 0;
  6418. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  6419. }
  6420. const attributes = this.attributes;
  6421. for (const key in attributes) {
  6422. if (geometry.attributes[key] === undefined) continue;
  6423. const attribute1 = attributes[key];
  6424. const attributeArray1 = attribute1.array;
  6425. const attribute2 = geometry.attributes[key];
  6426. const attributeArray2 = attribute2.array;
  6427. const attributeOffset = attribute2.itemSize * offset;
  6428. const length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  6429. for (let i = 0, j = attributeOffset; i < length; i++, j++) {
  6430. attributeArray1[j] = attributeArray2[i];
  6431. }
  6432. }
  6433. return this;
  6434. }
  6435. normalizeNormals() {
  6436. const normals = this.attributes.normal;
  6437. for (let i = 0, il = normals.count; i < il; i++) {
  6438. _vector$8.fromBufferAttribute(normals, i);
  6439. _vector$8.normalize();
  6440. normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z);
  6441. }
  6442. }
  6443. toNonIndexed() {
  6444. function convertBufferAttribute(attribute, indices) {
  6445. const array = attribute.array;
  6446. const itemSize = attribute.itemSize;
  6447. const normalized = attribute.normalized;
  6448. const array2 = new array.constructor(indices.length * itemSize);
  6449. let index = 0,
  6450. index2 = 0;
  6451. for (let i = 0, l = indices.length; i < l; i++) {
  6452. if (attribute.isInterleavedBufferAttribute) {
  6453. index = indices[i] * attribute.data.stride + attribute.offset;
  6454. } else {
  6455. index = indices[i] * itemSize;
  6456. }
  6457. for (let j = 0; j < itemSize; j++) {
  6458. array2[index2++] = array[index++];
  6459. }
  6460. }
  6461. return new BufferAttribute(array2, itemSize, normalized);
  6462. } //
  6463. if (this.index === null) {
  6464. console.warn('THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.');
  6465. return this;
  6466. }
  6467. const geometry2 = new BufferGeometry();
  6468. const indices = this.index.array;
  6469. const attributes = this.attributes; // attributes
  6470. for (const name in attributes) {
  6471. const attribute = attributes[name];
  6472. const newAttribute = convertBufferAttribute(attribute, indices);
  6473. geometry2.setAttribute(name, newAttribute);
  6474. } // morph attributes
  6475. const morphAttributes = this.morphAttributes;
  6476. for (const name in morphAttributes) {
  6477. const morphArray = [];
  6478. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6479. for (let i = 0, il = morphAttribute.length; i < il; i++) {
  6480. const attribute = morphAttribute[i];
  6481. const newAttribute = convertBufferAttribute(attribute, indices);
  6482. morphArray.push(newAttribute);
  6483. }
  6484. geometry2.morphAttributes[name] = morphArray;
  6485. }
  6486. geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
  6487. const groups = this.groups;
  6488. for (let i = 0, l = groups.length; i < l; i++) {
  6489. const group = groups[i];
  6490. geometry2.addGroup(group.start, group.count, group.materialIndex);
  6491. }
  6492. return geometry2;
  6493. }
  6494. toJSON() {
  6495. const data = {
  6496. metadata: {
  6497. version: 4.5,
  6498. type: 'BufferGeometry',
  6499. generator: 'BufferGeometry.toJSON'
  6500. }
  6501. }; // standard BufferGeometry serialization
  6502. data.uuid = this.uuid;
  6503. data.type = this.type;
  6504. if (this.name !== '') data.name = this.name;
  6505. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  6506. if (this.parameters !== undefined) {
  6507. const parameters = this.parameters;
  6508. for (const key in parameters) {
  6509. if (parameters[key] !== undefined) data[key] = parameters[key];
  6510. }
  6511. return data;
  6512. } // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6513. data.data = {
  6514. attributes: {}
  6515. };
  6516. const index = this.index;
  6517. if (index !== null) {
  6518. data.data.index = {
  6519. type: index.array.constructor.name,
  6520. array: Array.prototype.slice.call(index.array)
  6521. };
  6522. }
  6523. const attributes = this.attributes;
  6524. for (const key in attributes) {
  6525. const attribute = attributes[key];
  6526. data.data.attributes[key] = attribute.toJSON(data.data);
  6527. }
  6528. const morphAttributes = {};
  6529. let hasMorphAttributes = false;
  6530. for (const key in this.morphAttributes) {
  6531. const attributeArray = this.morphAttributes[key];
  6532. const array = [];
  6533. for (let i = 0, il = attributeArray.length; i < il; i++) {
  6534. const attribute = attributeArray[i];
  6535. array.push(attribute.toJSON(data.data));
  6536. }
  6537. if (array.length > 0) {
  6538. morphAttributes[key] = array;
  6539. hasMorphAttributes = true;
  6540. }
  6541. }
  6542. if (hasMorphAttributes) {
  6543. data.data.morphAttributes = morphAttributes;
  6544. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6545. }
  6546. const groups = this.groups;
  6547. if (groups.length > 0) {
  6548. data.data.groups = JSON.parse(JSON.stringify(groups));
  6549. }
  6550. const boundingSphere = this.boundingSphere;
  6551. if (boundingSphere !== null) {
  6552. data.data.boundingSphere = {
  6553. center: boundingSphere.center.toArray(),
  6554. radius: boundingSphere.radius
  6555. };
  6556. }
  6557. return data;
  6558. }
  6559. clone() {
  6560. return new this.constructor().copy(this);
  6561. }
  6562. copy(source) {
  6563. // reset
  6564. this.index = null;
  6565. this.attributes = {};
  6566. this.morphAttributes = {};
  6567. this.groups = [];
  6568. this.boundingBox = null;
  6569. this.boundingSphere = null; // used for storing cloned, shared data
  6570. const data = {}; // name
  6571. this.name = source.name; // index
  6572. const index = source.index;
  6573. if (index !== null) {
  6574. this.setIndex(index.clone(data));
  6575. } // attributes
  6576. const attributes = source.attributes;
  6577. for (const name in attributes) {
  6578. const attribute = attributes[name];
  6579. this.setAttribute(name, attribute.clone(data));
  6580. } // morph attributes
  6581. const morphAttributes = source.morphAttributes;
  6582. for (const name in morphAttributes) {
  6583. const array = [];
  6584. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6585. for (let i = 0, l = morphAttribute.length; i < l; i++) {
  6586. array.push(morphAttribute[i].clone(data));
  6587. }
  6588. this.morphAttributes[name] = array;
  6589. }
  6590. this.morphTargetsRelative = source.morphTargetsRelative; // groups
  6591. const groups = source.groups;
  6592. for (let i = 0, l = groups.length; i < l; i++) {
  6593. const group = groups[i];
  6594. this.addGroup(group.start, group.count, group.materialIndex);
  6595. } // bounding box
  6596. const boundingBox = source.boundingBox;
  6597. if (boundingBox !== null) {
  6598. this.boundingBox = boundingBox.clone();
  6599. } // bounding sphere
  6600. const boundingSphere = source.boundingSphere;
  6601. if (boundingSphere !== null) {
  6602. this.boundingSphere = boundingSphere.clone();
  6603. } // draw range
  6604. this.drawRange.start = source.drawRange.start;
  6605. this.drawRange.count = source.drawRange.count; // user data
  6606. this.userData = source.userData; // geometry generator parameters
  6607. if (source.parameters !== undefined) this.parameters = Object.assign({}, source.parameters);
  6608. return this;
  6609. }
  6610. dispose() {
  6611. this.dispatchEvent({
  6612. type: 'dispose'
  6613. });
  6614. }
  6615. }
  6616. BufferGeometry.prototype.isBufferGeometry = true;
  6617. const _inverseMatrix$2 = /*@__PURE__*/new Matrix4();
  6618. const _ray$2 = /*@__PURE__*/new Ray();
  6619. const _sphere$3 = /*@__PURE__*/new Sphere();
  6620. const _vA$1 = /*@__PURE__*/new Vector3();
  6621. const _vB$1 = /*@__PURE__*/new Vector3();
  6622. const _vC$1 = /*@__PURE__*/new Vector3();
  6623. const _tempA = /*@__PURE__*/new Vector3();
  6624. const _tempB = /*@__PURE__*/new Vector3();
  6625. const _tempC = /*@__PURE__*/new Vector3();
  6626. const _morphA = /*@__PURE__*/new Vector3();
  6627. const _morphB = /*@__PURE__*/new Vector3();
  6628. const _morphC = /*@__PURE__*/new Vector3();
  6629. const _uvA$1 = /*@__PURE__*/new Vector2();
  6630. const _uvB$1 = /*@__PURE__*/new Vector2();
  6631. const _uvC$1 = /*@__PURE__*/new Vector2();
  6632. const _intersectionPoint = /*@__PURE__*/new Vector3();
  6633. const _intersectionPointWorld = /*@__PURE__*/new Vector3();
  6634. class Mesh extends Object3D {
  6635. constructor(geometry = new BufferGeometry(), material = new MeshBasicMaterial()) {
  6636. super();
  6637. this.type = 'Mesh';
  6638. this.geometry = geometry;
  6639. this.material = material;
  6640. this.updateMorphTargets();
  6641. }
  6642. copy(source) {
  6643. super.copy(source);
  6644. if (source.morphTargetInfluences !== undefined) {
  6645. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6646. }
  6647. if (source.morphTargetDictionary !== undefined) {
  6648. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  6649. }
  6650. this.material = source.material;
  6651. this.geometry = source.geometry;
  6652. return this;
  6653. }
  6654. updateMorphTargets() {
  6655. const geometry = this.geometry;
  6656. if (geometry.isBufferGeometry) {
  6657. const morphAttributes = geometry.morphAttributes;
  6658. const keys = Object.keys(morphAttributes);
  6659. if (keys.length > 0) {
  6660. const morphAttribute = morphAttributes[keys[0]];
  6661. if (morphAttribute !== undefined) {
  6662. this.morphTargetInfluences = [];
  6663. this.morphTargetDictionary = {};
  6664. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  6665. const name = morphAttribute[m].name || String(m);
  6666. this.morphTargetInfluences.push(0);
  6667. this.morphTargetDictionary[name] = m;
  6668. }
  6669. }
  6670. }
  6671. } else {
  6672. const morphTargets = geometry.morphTargets;
  6673. if (morphTargets !== undefined && morphTargets.length > 0) {
  6674. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6675. }
  6676. }
  6677. }
  6678. raycast(raycaster, intersects) {
  6679. const geometry = this.geometry;
  6680. const material = this.material;
  6681. const matrixWorld = this.matrixWorld;
  6682. if (material === undefined) return; // Checking boundingSphere distance to ray
  6683. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  6684. _sphere$3.copy(geometry.boundingSphere);
  6685. _sphere$3.applyMatrix4(matrixWorld);
  6686. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  6687. _inverseMatrix$2.copy(matrixWorld).invert();
  6688. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2); // Check boundingBox before continuing
  6689. if (geometry.boundingBox !== null) {
  6690. if (_ray$2.intersectsBox(geometry.boundingBox) === false) return;
  6691. }
  6692. let intersection;
  6693. if (geometry.isBufferGeometry) {
  6694. const index = geometry.index;
  6695. const position = geometry.attributes.position;
  6696. const morphPosition = geometry.morphAttributes.position;
  6697. const morphTargetsRelative = geometry.morphTargetsRelative;
  6698. const uv = geometry.attributes.uv;
  6699. const uv2 = geometry.attributes.uv2;
  6700. const groups = geometry.groups;
  6701. const drawRange = geometry.drawRange;
  6702. if (index !== null) {
  6703. // indexed buffer geometry
  6704. if (Array.isArray(material)) {
  6705. for (let i = 0, il = groups.length; i < il; i++) {
  6706. const group = groups[i];
  6707. const groupMaterial = material[group.materialIndex];
  6708. const start = Math.max(group.start, drawRange.start);
  6709. const end = Math.min(index.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
  6710. for (let j = start, jl = end; j < jl; j += 3) {
  6711. const a = index.getX(j);
  6712. const b = index.getX(j + 1);
  6713. const c = index.getX(j + 2);
  6714. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6715. if (intersection) {
  6716. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  6717. intersection.face.materialIndex = group.materialIndex;
  6718. intersects.push(intersection);
  6719. }
  6720. }
  6721. }
  6722. } else {
  6723. const start = Math.max(0, drawRange.start);
  6724. const end = Math.min(index.count, drawRange.start + drawRange.count);
  6725. for (let i = start, il = end; i < il; i += 3) {
  6726. const a = index.getX(i);
  6727. const b = index.getX(i + 1);
  6728. const c = index.getX(i + 2);
  6729. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6730. if (intersection) {
  6731. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  6732. intersects.push(intersection);
  6733. }
  6734. }
  6735. }
  6736. } else if (position !== undefined) {
  6737. // non-indexed buffer geometry
  6738. if (Array.isArray(material)) {
  6739. for (let i = 0, il = groups.length; i < il; i++) {
  6740. const group = groups[i];
  6741. const groupMaterial = material[group.materialIndex];
  6742. const start = Math.max(group.start, drawRange.start);
  6743. const end = Math.min(position.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
  6744. for (let j = start, jl = end; j < jl; j += 3) {
  6745. const a = j;
  6746. const b = j + 1;
  6747. const c = j + 2;
  6748. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6749. if (intersection) {
  6750. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  6751. intersection.face.materialIndex = group.materialIndex;
  6752. intersects.push(intersection);
  6753. }
  6754. }
  6755. }
  6756. } else {
  6757. const start = Math.max(0, drawRange.start);
  6758. const end = Math.min(position.count, drawRange.start + drawRange.count);
  6759. for (let i = start, il = end; i < il; i += 3) {
  6760. const a = i;
  6761. const b = i + 1;
  6762. const c = i + 2;
  6763. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6764. if (intersection) {
  6765. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  6766. intersects.push(intersection);
  6767. }
  6768. }
  6769. }
  6770. }
  6771. } else if (geometry.isGeometry) {
  6772. console.error('THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6773. }
  6774. }
  6775. }
  6776. Mesh.prototype.isMesh = true;
  6777. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  6778. let intersect;
  6779. if (material.side === BackSide) {
  6780. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  6781. } else {
  6782. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  6783. }
  6784. if (intersect === null) return null;
  6785. _intersectionPointWorld.copy(point);
  6786. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  6787. const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  6788. if (distance < raycaster.near || distance > raycaster.far) return null;
  6789. return {
  6790. distance: distance,
  6791. point: _intersectionPointWorld.clone(),
  6792. object: object
  6793. };
  6794. }
  6795. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  6796. _vA$1.fromBufferAttribute(position, a);
  6797. _vB$1.fromBufferAttribute(position, b);
  6798. _vC$1.fromBufferAttribute(position, c);
  6799. const morphInfluences = object.morphTargetInfluences;
  6800. if (morphPosition && morphInfluences) {
  6801. _morphA.set(0, 0, 0);
  6802. _morphB.set(0, 0, 0);
  6803. _morphC.set(0, 0, 0);
  6804. for (let i = 0, il = morphPosition.length; i < il; i++) {
  6805. const influence = morphInfluences[i];
  6806. const morphAttribute = morphPosition[i];
  6807. if (influence === 0) continue;
  6808. _tempA.fromBufferAttribute(morphAttribute, a);
  6809. _tempB.fromBufferAttribute(morphAttribute, b);
  6810. _tempC.fromBufferAttribute(morphAttribute, c);
  6811. if (morphTargetsRelative) {
  6812. _morphA.addScaledVector(_tempA, influence);
  6813. _morphB.addScaledVector(_tempB, influence);
  6814. _morphC.addScaledVector(_tempC, influence);
  6815. } else {
  6816. _morphA.addScaledVector(_tempA.sub(_vA$1), influence);
  6817. _morphB.addScaledVector(_tempB.sub(_vB$1), influence);
  6818. _morphC.addScaledVector(_tempC.sub(_vC$1), influence);
  6819. }
  6820. }
  6821. _vA$1.add(_morphA);
  6822. _vB$1.add(_morphB);
  6823. _vC$1.add(_morphC);
  6824. }
  6825. if (object.isSkinnedMesh) {
  6826. object.boneTransform(a, _vA$1);
  6827. object.boneTransform(b, _vB$1);
  6828. object.boneTransform(c, _vC$1);
  6829. }
  6830. const intersection = checkIntersection(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint);
  6831. if (intersection) {
  6832. if (uv) {
  6833. _uvA$1.fromBufferAttribute(uv, a);
  6834. _uvB$1.fromBufferAttribute(uv, b);
  6835. _uvC$1.fromBufferAttribute(uv, c);
  6836. intersection.uv = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6837. }
  6838. if (uv2) {
  6839. _uvA$1.fromBufferAttribute(uv2, a);
  6840. _uvB$1.fromBufferAttribute(uv2, b);
  6841. _uvC$1.fromBufferAttribute(uv2, c);
  6842. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6843. }
  6844. const face = {
  6845. a: a,
  6846. b: b,
  6847. c: c,
  6848. normal: new Vector3(),
  6849. materialIndex: 0
  6850. };
  6851. Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal);
  6852. intersection.face = face;
  6853. }
  6854. return intersection;
  6855. }
  6856. class BoxGeometry extends BufferGeometry {
  6857. constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
  6858. super();
  6859. this.type = 'BoxGeometry';
  6860. this.parameters = {
  6861. width: width,
  6862. height: height,
  6863. depth: depth,
  6864. widthSegments: widthSegments,
  6865. heightSegments: heightSegments,
  6866. depthSegments: depthSegments
  6867. };
  6868. const scope = this; // segments
  6869. widthSegments = Math.floor(widthSegments);
  6870. heightSegments = Math.floor(heightSegments);
  6871. depthSegments = Math.floor(depthSegments); // buffers
  6872. const indices = [];
  6873. const vertices = [];
  6874. const normals = [];
  6875. const uvs = []; // helper variables
  6876. let numberOfVertices = 0;
  6877. let groupStart = 0; // build each side of the box geometry
  6878. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  6879. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  6880. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  6881. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  6882. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  6883. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  6884. // build geometry
  6885. this.setIndex(indices);
  6886. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  6887. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  6888. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  6889. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  6890. const segmentWidth = width / gridX;
  6891. const segmentHeight = height / gridY;
  6892. const widthHalf = width / 2;
  6893. const heightHalf = height / 2;
  6894. const depthHalf = depth / 2;
  6895. const gridX1 = gridX + 1;
  6896. const gridY1 = gridY + 1;
  6897. let vertexCounter = 0;
  6898. let groupCount = 0;
  6899. const vector = new Vector3(); // generate vertices, normals and uvs
  6900. for (let iy = 0; iy < gridY1; iy++) {
  6901. const y = iy * segmentHeight - heightHalf;
  6902. for (let ix = 0; ix < gridX1; ix++) {
  6903. const x = ix * segmentWidth - widthHalf; // set values to correct vector component
  6904. vector[u] = x * udir;
  6905. vector[v] = y * vdir;
  6906. vector[w] = depthHalf; // now apply vector to vertex buffer
  6907. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  6908. vector[u] = 0;
  6909. vector[v] = 0;
  6910. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  6911. normals.push(vector.x, vector.y, vector.z); // uvs
  6912. uvs.push(ix / gridX);
  6913. uvs.push(1 - iy / gridY); // counters
  6914. vertexCounter += 1;
  6915. }
  6916. } // indices
  6917. // 1. you need three indices to draw a single face
  6918. // 2. a single segment consists of two faces
  6919. // 3. so we need to generate six (2*3) indices per segment
  6920. for (let iy = 0; iy < gridY; iy++) {
  6921. for (let ix = 0; ix < gridX; ix++) {
  6922. const a = numberOfVertices + ix + gridX1 * iy;
  6923. const b = numberOfVertices + ix + gridX1 * (iy + 1);
  6924. const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  6925. const d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  6926. indices.push(a, b, d);
  6927. indices.push(b, c, d); // increase counter
  6928. groupCount += 6;
  6929. }
  6930. } // add a group to the geometry. this will ensure multi material support
  6931. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  6932. groupStart += groupCount; // update total number of vertices
  6933. numberOfVertices += vertexCounter;
  6934. }
  6935. }
  6936. static fromJSON(data) {
  6937. return new BoxGeometry(data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  6938. }
  6939. }
  6940. /**
  6941. * Uniform Utilities
  6942. */
  6943. function cloneUniforms(src) {
  6944. const dst = {};
  6945. for (const u in src) {
  6946. dst[u] = {};
  6947. for (const p in src[u]) {
  6948. const property = src[u][p];
  6949. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion)) {
  6950. dst[u][p] = property.clone();
  6951. } else if (Array.isArray(property)) {
  6952. dst[u][p] = property.slice();
  6953. } else {
  6954. dst[u][p] = property;
  6955. }
  6956. }
  6957. }
  6958. return dst;
  6959. }
  6960. function mergeUniforms(uniforms) {
  6961. const merged = {};
  6962. for (let u = 0; u < uniforms.length; u++) {
  6963. const tmp = cloneUniforms(uniforms[u]);
  6964. for (const p in tmp) {
  6965. merged[p] = tmp[p];
  6966. }
  6967. }
  6968. return merged;
  6969. } // Legacy
  6970. const UniformsUtils = {
  6971. clone: cloneUniforms,
  6972. merge: mergeUniforms
  6973. };
  6974. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  6975. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  6976. /**
  6977. * parameters = {
  6978. * defines: { "label" : "value" },
  6979. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  6980. *
  6981. * fragmentShader: <string>,
  6982. * vertexShader: <string>,
  6983. *
  6984. * wireframe: <boolean>,
  6985. * wireframeLinewidth: <float>,
  6986. *
  6987. * lights: <bool>
  6988. * }
  6989. */
  6990. class ShaderMaterial extends Material {
  6991. constructor(parameters) {
  6992. super();
  6993. this.type = 'ShaderMaterial';
  6994. this.defines = {};
  6995. this.uniforms = {};
  6996. this.vertexShader = default_vertex;
  6997. this.fragmentShader = default_fragment;
  6998. this.linewidth = 1;
  6999. this.wireframe = false;
  7000. this.wireframeLinewidth = 1;
  7001. this.fog = false; // set to use scene fog
  7002. this.lights = false; // set to use scene lights
  7003. this.clipping = false; // set to use user-defined clipping planes
  7004. this.extensions = {
  7005. derivatives: false,
  7006. // set to use derivatives
  7007. fragDepth: false,
  7008. // set to use fragment depth values
  7009. drawBuffers: false,
  7010. // set to use draw buffers
  7011. shaderTextureLOD: false // set to use shader texture LOD
  7012. }; // When rendered geometry doesn't include these attributes but the material does,
  7013. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7014. this.defaultAttributeValues = {
  7015. 'color': [1, 1, 1],
  7016. 'uv': [0, 0],
  7017. 'uv2': [0, 0]
  7018. };
  7019. this.index0AttributeName = undefined;
  7020. this.uniformsNeedUpdate = false;
  7021. this.glslVersion = null;
  7022. if (parameters !== undefined) {
  7023. if (parameters.attributes !== undefined) {
  7024. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  7025. }
  7026. this.setValues(parameters);
  7027. }
  7028. }
  7029. copy(source) {
  7030. super.copy(source);
  7031. this.fragmentShader = source.fragmentShader;
  7032. this.vertexShader = source.vertexShader;
  7033. this.uniforms = cloneUniforms(source.uniforms);
  7034. this.defines = Object.assign({}, source.defines);
  7035. this.wireframe = source.wireframe;
  7036. this.wireframeLinewidth = source.wireframeLinewidth;
  7037. this.lights = source.lights;
  7038. this.clipping = source.clipping;
  7039. this.extensions = Object.assign({}, source.extensions);
  7040. this.glslVersion = source.glslVersion;
  7041. return this;
  7042. }
  7043. toJSON(meta) {
  7044. const data = super.toJSON(meta);
  7045. data.glslVersion = this.glslVersion;
  7046. data.uniforms = {};
  7047. for (const name in this.uniforms) {
  7048. const uniform = this.uniforms[name];
  7049. const value = uniform.value;
  7050. if (value && value.isTexture) {
  7051. data.uniforms[name] = {
  7052. type: 't',
  7053. value: value.toJSON(meta).uuid
  7054. };
  7055. } else if (value && value.isColor) {
  7056. data.uniforms[name] = {
  7057. type: 'c',
  7058. value: value.getHex()
  7059. };
  7060. } else if (value && value.isVector2) {
  7061. data.uniforms[name] = {
  7062. type: 'v2',
  7063. value: value.toArray()
  7064. };
  7065. } else if (value && value.isVector3) {
  7066. data.uniforms[name] = {
  7067. type: 'v3',
  7068. value: value.toArray()
  7069. };
  7070. } else if (value && value.isVector4) {
  7071. data.uniforms[name] = {
  7072. type: 'v4',
  7073. value: value.toArray()
  7074. };
  7075. } else if (value && value.isMatrix3) {
  7076. data.uniforms[name] = {
  7077. type: 'm3',
  7078. value: value.toArray()
  7079. };
  7080. } else if (value && value.isMatrix4) {
  7081. data.uniforms[name] = {
  7082. type: 'm4',
  7083. value: value.toArray()
  7084. };
  7085. } else {
  7086. data.uniforms[name] = {
  7087. value: value
  7088. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7089. }
  7090. }
  7091. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  7092. data.vertexShader = this.vertexShader;
  7093. data.fragmentShader = this.fragmentShader;
  7094. const extensions = {};
  7095. for (const key in this.extensions) {
  7096. if (this.extensions[key] === true) extensions[key] = true;
  7097. }
  7098. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  7099. return data;
  7100. }
  7101. }
  7102. ShaderMaterial.prototype.isShaderMaterial = true;
  7103. class Camera extends Object3D {
  7104. constructor() {
  7105. super();
  7106. this.type = 'Camera';
  7107. this.matrixWorldInverse = new Matrix4();
  7108. this.projectionMatrix = new Matrix4();
  7109. this.projectionMatrixInverse = new Matrix4();
  7110. }
  7111. copy(source, recursive) {
  7112. super.copy(source, recursive);
  7113. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  7114. this.projectionMatrix.copy(source.projectionMatrix);
  7115. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  7116. return this;
  7117. }
  7118. getWorldDirection(target) {
  7119. this.updateWorldMatrix(true, false);
  7120. const e = this.matrixWorld.elements;
  7121. return target.set(-e[8], -e[9], -e[10]).normalize();
  7122. }
  7123. updateMatrixWorld(force) {
  7124. super.updateMatrixWorld(force);
  7125. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7126. }
  7127. updateWorldMatrix(updateParents, updateChildren) {
  7128. super.updateWorldMatrix(updateParents, updateChildren);
  7129. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7130. }
  7131. clone() {
  7132. return new this.constructor().copy(this);
  7133. }
  7134. }
  7135. Camera.prototype.isCamera = true;
  7136. class PerspectiveCamera extends Camera {
  7137. constructor(fov = 50, aspect = 1, near = 0.1, far = 2000) {
  7138. super();
  7139. this.type = 'PerspectiveCamera';
  7140. this.fov = fov;
  7141. this.zoom = 1;
  7142. this.near = near;
  7143. this.far = far;
  7144. this.focus = 10;
  7145. this.aspect = aspect;
  7146. this.view = null;
  7147. this.filmGauge = 35; // width of the film (default in millimeters)
  7148. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7149. this.updateProjectionMatrix();
  7150. }
  7151. copy(source, recursive) {
  7152. super.copy(source, recursive);
  7153. this.fov = source.fov;
  7154. this.zoom = source.zoom;
  7155. this.near = source.near;
  7156. this.far = source.far;
  7157. this.focus = source.focus;
  7158. this.aspect = source.aspect;
  7159. this.view = source.view === null ? null : Object.assign({}, source.view);
  7160. this.filmGauge = source.filmGauge;
  7161. this.filmOffset = source.filmOffset;
  7162. return this;
  7163. }
  7164. /**
  7165. * Sets the FOV by focal length in respect to the current .filmGauge.
  7166. *
  7167. * The default film gauge is 35, so that the focal length can be specified for
  7168. * a 35mm (full frame) camera.
  7169. *
  7170. * Values for focal length and film gauge must have the same unit.
  7171. */
  7172. setFocalLength(focalLength) {
  7173. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7174. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7175. this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope);
  7176. this.updateProjectionMatrix();
  7177. }
  7178. /**
  7179. * Calculates the focal length from the current .fov and .filmGauge.
  7180. */
  7181. getFocalLength() {
  7182. const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov);
  7183. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7184. }
  7185. getEffectiveFOV() {
  7186. return RAD2DEG * 2 * Math.atan(Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom);
  7187. }
  7188. getFilmWidth() {
  7189. // film not completely covered in portrait format (aspect < 1)
  7190. return this.filmGauge * Math.min(this.aspect, 1);
  7191. }
  7192. getFilmHeight() {
  7193. // film not completely covered in landscape format (aspect > 1)
  7194. return this.filmGauge / Math.max(this.aspect, 1);
  7195. }
  7196. /**
  7197. * Sets an offset in a larger frustum. This is useful for multi-window or
  7198. * multi-monitor/multi-machine setups.
  7199. *
  7200. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7201. * the monitors are in grid like this
  7202. *
  7203. * +---+---+---+
  7204. * | A | B | C |
  7205. * +---+---+---+
  7206. * | D | E | F |
  7207. * +---+---+---+
  7208. *
  7209. * then for each monitor you would call it like this
  7210. *
  7211. * const w = 1920;
  7212. * const h = 1080;
  7213. * const fullWidth = w * 3;
  7214. * const fullHeight = h * 2;
  7215. *
  7216. * --A--
  7217. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7218. * --B--
  7219. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7220. * --C--
  7221. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7222. * --D--
  7223. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7224. * --E--
  7225. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7226. * --F--
  7227. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7228. *
  7229. * Note there is no reason monitors have to be the same size or in a grid.
  7230. */
  7231. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  7232. this.aspect = fullWidth / fullHeight;
  7233. if (this.view === null) {
  7234. this.view = {
  7235. enabled: true,
  7236. fullWidth: 1,
  7237. fullHeight: 1,
  7238. offsetX: 0,
  7239. offsetY: 0,
  7240. width: 1,
  7241. height: 1
  7242. };
  7243. }
  7244. this.view.enabled = true;
  7245. this.view.fullWidth = fullWidth;
  7246. this.view.fullHeight = fullHeight;
  7247. this.view.offsetX = x;
  7248. this.view.offsetY = y;
  7249. this.view.width = width;
  7250. this.view.height = height;
  7251. this.updateProjectionMatrix();
  7252. }
  7253. clearViewOffset() {
  7254. if (this.view !== null) {
  7255. this.view.enabled = false;
  7256. }
  7257. this.updateProjectionMatrix();
  7258. }
  7259. updateProjectionMatrix() {
  7260. const near = this.near;
  7261. let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom;
  7262. let height = 2 * top;
  7263. let width = this.aspect * height;
  7264. let left = -0.5 * width;
  7265. const view = this.view;
  7266. if (this.view !== null && this.view.enabled) {
  7267. const fullWidth = view.fullWidth,
  7268. fullHeight = view.fullHeight;
  7269. left += view.offsetX * width / fullWidth;
  7270. top -= view.offsetY * height / fullHeight;
  7271. width *= view.width / fullWidth;
  7272. height *= view.height / fullHeight;
  7273. }
  7274. const skew = this.filmOffset;
  7275. if (skew !== 0) left += near * skew / this.getFilmWidth();
  7276. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  7277. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  7278. }
  7279. toJSON(meta) {
  7280. const data = super.toJSON(meta);
  7281. data.object.fov = this.fov;
  7282. data.object.zoom = this.zoom;
  7283. data.object.near = this.near;
  7284. data.object.far = this.far;
  7285. data.object.focus = this.focus;
  7286. data.object.aspect = this.aspect;
  7287. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  7288. data.object.filmGauge = this.filmGauge;
  7289. data.object.filmOffset = this.filmOffset;
  7290. return data;
  7291. }
  7292. }
  7293. PerspectiveCamera.prototype.isPerspectiveCamera = true;
  7294. const fov = 90,
  7295. aspect = 1;
  7296. class CubeCamera extends Object3D {
  7297. constructor(near, far, renderTarget) {
  7298. super();
  7299. this.type = 'CubeCamera';
  7300. if (renderTarget.isWebGLCubeRenderTarget !== true) {
  7301. console.error('THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.');
  7302. return;
  7303. }
  7304. this.renderTarget = renderTarget;
  7305. const cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  7306. cameraPX.layers = this.layers;
  7307. cameraPX.up.set(0, -1, 0);
  7308. cameraPX.lookAt(new Vector3(1, 0, 0));
  7309. this.add(cameraPX);
  7310. const cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  7311. cameraNX.layers = this.layers;
  7312. cameraNX.up.set(0, -1, 0);
  7313. cameraNX.lookAt(new Vector3(-1, 0, 0));
  7314. this.add(cameraNX);
  7315. const cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  7316. cameraPY.layers = this.layers;
  7317. cameraPY.up.set(0, 0, 1);
  7318. cameraPY.lookAt(new Vector3(0, 1, 0));
  7319. this.add(cameraPY);
  7320. const cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  7321. cameraNY.layers = this.layers;
  7322. cameraNY.up.set(0, 0, -1);
  7323. cameraNY.lookAt(new Vector3(0, -1, 0));
  7324. this.add(cameraNY);
  7325. const cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  7326. cameraPZ.layers = this.layers;
  7327. cameraPZ.up.set(0, -1, 0);
  7328. cameraPZ.lookAt(new Vector3(0, 0, 1));
  7329. this.add(cameraPZ);
  7330. const cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  7331. cameraNZ.layers = this.layers;
  7332. cameraNZ.up.set(0, -1, 0);
  7333. cameraNZ.lookAt(new Vector3(0, 0, -1));
  7334. this.add(cameraNZ);
  7335. }
  7336. update(renderer, scene) {
  7337. if (this.parent === null) this.updateMatrixWorld();
  7338. const renderTarget = this.renderTarget;
  7339. const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children;
  7340. const currentXrEnabled = renderer.xr.enabled;
  7341. const currentRenderTarget = renderer.getRenderTarget();
  7342. renderer.xr.enabled = false;
  7343. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7344. renderTarget.texture.generateMipmaps = false;
  7345. renderer.setRenderTarget(renderTarget, 0);
  7346. renderer.render(scene, cameraPX);
  7347. renderer.setRenderTarget(renderTarget, 1);
  7348. renderer.render(scene, cameraNX);
  7349. renderer.setRenderTarget(renderTarget, 2);
  7350. renderer.render(scene, cameraPY);
  7351. renderer.setRenderTarget(renderTarget, 3);
  7352. renderer.render(scene, cameraNY);
  7353. renderer.setRenderTarget(renderTarget, 4);
  7354. renderer.render(scene, cameraPZ);
  7355. renderTarget.texture.generateMipmaps = generateMipmaps;
  7356. renderer.setRenderTarget(renderTarget, 5);
  7357. renderer.render(scene, cameraNZ);
  7358. renderer.setRenderTarget(currentRenderTarget);
  7359. renderer.xr.enabled = currentXrEnabled;
  7360. }
  7361. }
  7362. class CubeTexture extends Texture {
  7363. constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  7364. images = images !== undefined ? images : [];
  7365. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7366. super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  7367. this.flipY = false;
  7368. }
  7369. get images() {
  7370. return this.image;
  7371. }
  7372. set images(value) {
  7373. this.image = value;
  7374. }
  7375. }
  7376. CubeTexture.prototype.isCubeTexture = true;
  7377. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7378. constructor(size, options, dummy) {
  7379. if (Number.isInteger(options)) {
  7380. console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');
  7381. options = dummy;
  7382. }
  7383. super(size, size, options);
  7384. options = options || {}; // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7385. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7386. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7387. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7388. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7389. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7390. this.texture = new CubeTexture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  7391. this.texture.isRenderTargetTexture = true;
  7392. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7393. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7394. this.texture._needsFlipEnvMap = false;
  7395. }
  7396. fromEquirectangularTexture(renderer, texture) {
  7397. this.texture.type = texture.type;
  7398. this.texture.format = RGBAFormat; // see #18859
  7399. this.texture.encoding = texture.encoding;
  7400. this.texture.generateMipmaps = texture.generateMipmaps;
  7401. this.texture.minFilter = texture.minFilter;
  7402. this.texture.magFilter = texture.magFilter;
  7403. const shader = {
  7404. uniforms: {
  7405. tEquirect: {
  7406. value: null
  7407. }
  7408. },
  7409. vertexShader:
  7410. /* glsl */
  7411. `
  7412. varying vec3 vWorldDirection;
  7413. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7414. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7415. }
  7416. void main() {
  7417. vWorldDirection = transformDirection( position, modelMatrix );
  7418. #include <begin_vertex>
  7419. #include <project_vertex>
  7420. }
  7421. `,
  7422. fragmentShader:
  7423. /* glsl */
  7424. `
  7425. uniform sampler2D tEquirect;
  7426. varying vec3 vWorldDirection;
  7427. #include <common>
  7428. void main() {
  7429. vec3 direction = normalize( vWorldDirection );
  7430. vec2 sampleUV = equirectUv( direction );
  7431. gl_FragColor = texture2D( tEquirect, sampleUV );
  7432. }
  7433. `
  7434. };
  7435. const geometry = new BoxGeometry(5, 5, 5);
  7436. const material = new ShaderMaterial({
  7437. name: 'CubemapFromEquirect',
  7438. uniforms: cloneUniforms(shader.uniforms),
  7439. vertexShader: shader.vertexShader,
  7440. fragmentShader: shader.fragmentShader,
  7441. side: BackSide,
  7442. blending: NoBlending
  7443. });
  7444. material.uniforms.tEquirect.value = texture;
  7445. const mesh = new Mesh(geometry, material);
  7446. const currentMinFilter = texture.minFilter; // Avoid blurred poles
  7447. if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
  7448. const camera = new CubeCamera(1, 10, this);
  7449. camera.update(renderer, mesh);
  7450. texture.minFilter = currentMinFilter;
  7451. mesh.geometry.dispose();
  7452. mesh.material.dispose();
  7453. return this;
  7454. }
  7455. clear(renderer, color, depth, stencil) {
  7456. const currentRenderTarget = renderer.getRenderTarget();
  7457. for (let i = 0; i < 6; i++) {
  7458. renderer.setRenderTarget(this, i);
  7459. renderer.clear(color, depth, stencil);
  7460. }
  7461. renderer.setRenderTarget(currentRenderTarget);
  7462. }
  7463. }
  7464. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  7465. const _vector1 = /*@__PURE__*/new Vector3();
  7466. const _vector2 = /*@__PURE__*/new Vector3();
  7467. const _normalMatrix = /*@__PURE__*/new Matrix3();
  7468. class Plane {
  7469. constructor(normal = new Vector3(1, 0, 0), constant = 0) {
  7470. // normal is assumed to be normalized
  7471. this.normal = normal;
  7472. this.constant = constant;
  7473. }
  7474. set(normal, constant) {
  7475. this.normal.copy(normal);
  7476. this.constant = constant;
  7477. return this;
  7478. }
  7479. setComponents(x, y, z, w) {
  7480. this.normal.set(x, y, z);
  7481. this.constant = w;
  7482. return this;
  7483. }
  7484. setFromNormalAndCoplanarPoint(normal, point) {
  7485. this.normal.copy(normal);
  7486. this.constant = -point.dot(this.normal);
  7487. return this;
  7488. }
  7489. setFromCoplanarPoints(a, b, c) {
  7490. const normal = _vector1.subVectors(c, b).cross(_vector2.subVectors(a, b)).normalize(); // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7491. this.setFromNormalAndCoplanarPoint(normal, a);
  7492. return this;
  7493. }
  7494. copy(plane) {
  7495. this.normal.copy(plane.normal);
  7496. this.constant = plane.constant;
  7497. return this;
  7498. }
  7499. normalize() {
  7500. // Note: will lead to a divide by zero if the plane is invalid.
  7501. const inverseNormalLength = 1.0 / this.normal.length();
  7502. this.normal.multiplyScalar(inverseNormalLength);
  7503. this.constant *= inverseNormalLength;
  7504. return this;
  7505. }
  7506. negate() {
  7507. this.constant *= -1;
  7508. this.normal.negate();
  7509. return this;
  7510. }
  7511. distanceToPoint(point) {
  7512. return this.normal.dot(point) + this.constant;
  7513. }
  7514. distanceToSphere(sphere) {
  7515. return this.distanceToPoint(sphere.center) - sphere.radius;
  7516. }
  7517. projectPoint(point, target) {
  7518. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  7519. }
  7520. intersectLine(line, target) {
  7521. const direction = line.delta(_vector1);
  7522. const denominator = this.normal.dot(direction);
  7523. if (denominator === 0) {
  7524. // line is coplanar, return origin
  7525. if (this.distanceToPoint(line.start) === 0) {
  7526. return target.copy(line.start);
  7527. } // Unsure if this is the correct method to handle this case.
  7528. return null;
  7529. }
  7530. const t = -(line.start.dot(this.normal) + this.constant) / denominator;
  7531. if (t < 0 || t > 1) {
  7532. return null;
  7533. }
  7534. return target.copy(direction).multiplyScalar(t).add(line.start);
  7535. }
  7536. intersectsLine(line) {
  7537. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7538. const startSign = this.distanceToPoint(line.start);
  7539. const endSign = this.distanceToPoint(line.end);
  7540. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  7541. }
  7542. intersectsBox(box) {
  7543. return box.intersectsPlane(this);
  7544. }
  7545. intersectsSphere(sphere) {
  7546. return sphere.intersectsPlane(this);
  7547. }
  7548. coplanarPoint(target) {
  7549. return target.copy(this.normal).multiplyScalar(-this.constant);
  7550. }
  7551. applyMatrix4(matrix, optionalNormalMatrix) {
  7552. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  7553. const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  7554. const normal = this.normal.applyMatrix3(normalMatrix).normalize();
  7555. this.constant = -referencePoint.dot(normal);
  7556. return this;
  7557. }
  7558. translate(offset) {
  7559. this.constant -= offset.dot(this.normal);
  7560. return this;
  7561. }
  7562. equals(plane) {
  7563. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  7564. }
  7565. clone() {
  7566. return new this.constructor().copy(this);
  7567. }
  7568. }
  7569. Plane.prototype.isPlane = true;
  7570. const _sphere$2 = /*@__PURE__*/new Sphere();
  7571. const _vector$7 = /*@__PURE__*/new Vector3();
  7572. class Frustum {
  7573. constructor(p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane()) {
  7574. this.planes = [p0, p1, p2, p3, p4, p5];
  7575. }
  7576. set(p0, p1, p2, p3, p4, p5) {
  7577. const planes = this.planes;
  7578. planes[0].copy(p0);
  7579. planes[1].copy(p1);
  7580. planes[2].copy(p2);
  7581. planes[3].copy(p3);
  7582. planes[4].copy(p4);
  7583. planes[5].copy(p5);
  7584. return this;
  7585. }
  7586. copy(frustum) {
  7587. const planes = this.planes;
  7588. for (let i = 0; i < 6; i++) {
  7589. planes[i].copy(frustum.planes[i]);
  7590. }
  7591. return this;
  7592. }
  7593. setFromProjectionMatrix(m) {
  7594. const planes = this.planes;
  7595. const me = m.elements;
  7596. const me0 = me[0],
  7597. me1 = me[1],
  7598. me2 = me[2],
  7599. me3 = me[3];
  7600. const me4 = me[4],
  7601. me5 = me[5],
  7602. me6 = me[6],
  7603. me7 = me[7];
  7604. const me8 = me[8],
  7605. me9 = me[9],
  7606. me10 = me[10],
  7607. me11 = me[11];
  7608. const me12 = me[12],
  7609. me13 = me[13],
  7610. me14 = me[14],
  7611. me15 = me[15];
  7612. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  7613. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  7614. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  7615. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  7616. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  7617. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  7618. return this;
  7619. }
  7620. intersectsObject(object) {
  7621. const geometry = object.geometry;
  7622. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  7623. _sphere$2.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  7624. return this.intersectsSphere(_sphere$2);
  7625. }
  7626. intersectsSprite(sprite) {
  7627. _sphere$2.center.set(0, 0, 0);
  7628. _sphere$2.radius = 0.7071067811865476;
  7629. _sphere$2.applyMatrix4(sprite.matrixWorld);
  7630. return this.intersectsSphere(_sphere$2);
  7631. }
  7632. intersectsSphere(sphere) {
  7633. const planes = this.planes;
  7634. const center = sphere.center;
  7635. const negRadius = -sphere.radius;
  7636. for (let i = 0; i < 6; i++) {
  7637. const distance = planes[i].distanceToPoint(center);
  7638. if (distance < negRadius) {
  7639. return false;
  7640. }
  7641. }
  7642. return true;
  7643. }
  7644. intersectsBox(box) {
  7645. const planes = this.planes;
  7646. for (let i = 0; i < 6; i++) {
  7647. const plane = planes[i]; // corner at max distance
  7648. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7649. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7650. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7651. if (plane.distanceToPoint(_vector$7) < 0) {
  7652. return false;
  7653. }
  7654. }
  7655. return true;
  7656. }
  7657. containsPoint(point) {
  7658. const planes = this.planes;
  7659. for (let i = 0; i < 6; i++) {
  7660. if (planes[i].distanceToPoint(point) < 0) {
  7661. return false;
  7662. }
  7663. }
  7664. return true;
  7665. }
  7666. clone() {
  7667. return new this.constructor().copy(this);
  7668. }
  7669. }
  7670. function WebGLAnimation() {
  7671. let context = null;
  7672. let isAnimating = false;
  7673. let animationLoop = null;
  7674. let requestId = null;
  7675. function onAnimationFrame(time, frame) {
  7676. animationLoop(time, frame);
  7677. requestId = context.requestAnimationFrame(onAnimationFrame);
  7678. }
  7679. return {
  7680. start: function () {
  7681. if (isAnimating === true) return;
  7682. if (animationLoop === null) return;
  7683. requestId = context.requestAnimationFrame(onAnimationFrame);
  7684. isAnimating = true;
  7685. },
  7686. stop: function () {
  7687. context.cancelAnimationFrame(requestId);
  7688. isAnimating = false;
  7689. },
  7690. setAnimationLoop: function (callback) {
  7691. animationLoop = callback;
  7692. },
  7693. setContext: function (value) {
  7694. context = value;
  7695. }
  7696. };
  7697. }
  7698. function WebGLAttributes(gl, capabilities) {
  7699. const isWebGL2 = capabilities.isWebGL2;
  7700. const buffers = new WeakMap();
  7701. function createBuffer(attribute, bufferType) {
  7702. const array = attribute.array;
  7703. const usage = attribute.usage;
  7704. const buffer = gl.createBuffer();
  7705. gl.bindBuffer(bufferType, buffer);
  7706. gl.bufferData(bufferType, array, usage);
  7707. attribute.onUploadCallback();
  7708. let type = gl.FLOAT;
  7709. if (array instanceof Float32Array) {
  7710. type = gl.FLOAT;
  7711. } else if (array instanceof Float64Array) {
  7712. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  7713. } else if (array instanceof Uint16Array) {
  7714. if (attribute.isFloat16BufferAttribute) {
  7715. if (isWebGL2) {
  7716. type = gl.HALF_FLOAT;
  7717. } else {
  7718. console.warn('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
  7719. }
  7720. } else {
  7721. type = gl.UNSIGNED_SHORT;
  7722. }
  7723. } else if (array instanceof Int16Array) {
  7724. type = gl.SHORT;
  7725. } else if (array instanceof Uint32Array) {
  7726. type = gl.UNSIGNED_INT;
  7727. } else if (array instanceof Int32Array) {
  7728. type = gl.INT;
  7729. } else if (array instanceof Int8Array) {
  7730. type = gl.BYTE;
  7731. } else if (array instanceof Uint8Array) {
  7732. type = gl.UNSIGNED_BYTE;
  7733. } else if (array instanceof Uint8ClampedArray) {
  7734. type = gl.UNSIGNED_BYTE;
  7735. }
  7736. return {
  7737. buffer: buffer,
  7738. type: type,
  7739. bytesPerElement: array.BYTES_PER_ELEMENT,
  7740. version: attribute.version
  7741. };
  7742. }
  7743. function updateBuffer(buffer, attribute, bufferType) {
  7744. const array = attribute.array;
  7745. const updateRange = attribute.updateRange;
  7746. gl.bindBuffer(bufferType, buffer);
  7747. if (updateRange.count === -1) {
  7748. // Not using update ranges
  7749. gl.bufferSubData(bufferType, 0, array);
  7750. } else {
  7751. if (isWebGL2) {
  7752. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  7753. } else {
  7754. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  7755. }
  7756. updateRange.count = -1; // reset range
  7757. }
  7758. } //
  7759. function get(attribute) {
  7760. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7761. return buffers.get(attribute);
  7762. }
  7763. function remove(attribute) {
  7764. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7765. const data = buffers.get(attribute);
  7766. if (data) {
  7767. gl.deleteBuffer(data.buffer);
  7768. buffers.delete(attribute);
  7769. }
  7770. }
  7771. function update(attribute, bufferType) {
  7772. if (attribute.isGLBufferAttribute) {
  7773. const cached = buffers.get(attribute);
  7774. if (!cached || cached.version < attribute.version) {
  7775. buffers.set(attribute, {
  7776. buffer: attribute.buffer,
  7777. type: attribute.type,
  7778. bytesPerElement: attribute.elementSize,
  7779. version: attribute.version
  7780. });
  7781. }
  7782. return;
  7783. }
  7784. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7785. const data = buffers.get(attribute);
  7786. if (data === undefined) {
  7787. buffers.set(attribute, createBuffer(attribute, bufferType));
  7788. } else if (data.version < attribute.version) {
  7789. updateBuffer(data.buffer, attribute, bufferType);
  7790. data.version = attribute.version;
  7791. }
  7792. }
  7793. return {
  7794. get: get,
  7795. remove: remove,
  7796. update: update
  7797. };
  7798. }
  7799. class PlaneGeometry extends BufferGeometry {
  7800. constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) {
  7801. super();
  7802. this.type = 'PlaneGeometry';
  7803. this.parameters = {
  7804. width: width,
  7805. height: height,
  7806. widthSegments: widthSegments,
  7807. heightSegments: heightSegments
  7808. };
  7809. const width_half = width / 2;
  7810. const height_half = height / 2;
  7811. const gridX = Math.floor(widthSegments);
  7812. const gridY = Math.floor(heightSegments);
  7813. const gridX1 = gridX + 1;
  7814. const gridY1 = gridY + 1;
  7815. const segment_width = width / gridX;
  7816. const segment_height = height / gridY; //
  7817. const indices = [];
  7818. const vertices = [];
  7819. const normals = [];
  7820. const uvs = [];
  7821. for (let iy = 0; iy < gridY1; iy++) {
  7822. const y = iy * segment_height - height_half;
  7823. for (let ix = 0; ix < gridX1; ix++) {
  7824. const x = ix * segment_width - width_half;
  7825. vertices.push(x, -y, 0);
  7826. normals.push(0, 0, 1);
  7827. uvs.push(ix / gridX);
  7828. uvs.push(1 - iy / gridY);
  7829. }
  7830. }
  7831. for (let iy = 0; iy < gridY; iy++) {
  7832. for (let ix = 0; ix < gridX; ix++) {
  7833. const a = ix + gridX1 * iy;
  7834. const b = ix + gridX1 * (iy + 1);
  7835. const c = ix + 1 + gridX1 * (iy + 1);
  7836. const d = ix + 1 + gridX1 * iy;
  7837. indices.push(a, b, d);
  7838. indices.push(b, c, d);
  7839. }
  7840. }
  7841. this.setIndex(indices);
  7842. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  7843. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  7844. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  7845. }
  7846. static fromJSON(data) {
  7847. return new PlaneGeometry(data.width, data.height, data.widthSegments, data.heightSegments);
  7848. }
  7849. }
  7850. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7851. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7852. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  7853. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  7854. 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";
  7855. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7856. var begin_vertex = "vec3 transformed = vec3( position );";
  7857. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7858. 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 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}\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";
  7859. 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 = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\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";
  7860. 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";
  7861. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7862. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7863. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7864. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7865. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7866. 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";
  7867. 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";
  7868. 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; }\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 color ) { return dot( color, vec3( 0.3333 ) ); }\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 linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.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}";
  7869. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_maxMipLevel 8.0\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_maxTileSize 256.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\tfloat texelSize = 1.0 / ( 3.0 * cubeUV_maxTileSize );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 1.0 ) + 0.5;\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\tif ( mipInt < cubeUV_maxMipLevel ) {\n\t\t\tuv.y += 2.0 * cubeUV_maxTileSize;\n\t\t}\n\t\tuv.y += filterInt * 2.0 * cubeUV_minTileSize;\n\t\tuv.x += 3.0 * max( 0.0, cubeUV_maxTileSize - 2.0 * faceSize );\n\t\tuv *= texelSize;\n\t\treturn texture2D( envMap, uv ).rgb;\n\t}\n\t#define r0 1.0\n\t#define v0 0.339\n\t#define m0 - 2.0\n\t#define r1 0.8\n\t#define v1 0.276\n\t#define m1 - 1.0\n\t#define r4 0.4\n\t#define v4 0.046\n\t#define m4 2.0\n\t#define r5 0.305\n\t#define v5 0.016\n\t#define m5 3.0\n\t#define r6 0.21\n\t#define v6 0.0038\n\t#define m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= r1 ) {\n\t\t\tmip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0;\n\t\t} else if ( roughness >= r4 ) {\n\t\t\tmip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1;\n\t\t} else if ( roughness >= r5 ) {\n\t\t\tmip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4;\n\t\t} else if ( roughness >= r6 ) {\n\t\t\tmip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + 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 ), m0, cubeUV_maxMipLevel );\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";
  7870. 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";
  7871. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7872. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7873. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7874. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7875. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7876. var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\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}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = clamp( floor( D ) / 255.0, 0.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}";
  7877. 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\tenvColor = envMapTexelToLinear( envColor );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\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";
  7878. 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";
  7879. var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\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";
  7880. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\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";
  7881. 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";
  7882. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  7883. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  7884. 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";
  7885. 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";
  7886. 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\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";
  7887. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tlightMapIrradiance *= PI;\n\t#endif\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  7888. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7889. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry.normal );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry.normal );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointLightInfo( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotLightInfo( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalLightInfo( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry.normal );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";
  7890. 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";
  7891. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\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;\n\t\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\t\treflectVec = reflect( - viewDir, normal );\n\t\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\t#else\n\t\t\t\treflectVec = refract( - viewDir, normal, refractionRatio );\n\t\t\t#endif\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";
  7892. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7893. 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\n#define Material_LightProbeLOD( material )\t(0)";
  7894. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7895. 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\n#define Material_LightProbeLOD( material )\t(0)";
  7896. 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\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 *= specularColorMapTexelToLinear( 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( ( ior - 1.0 ) / ( 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_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= sheenColorMapTexelToLinear( 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";
  7897. 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_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\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}\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\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\tvec3 FssEss = specularColor * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 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\treflectedLight.directSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\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\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\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}";
  7898. 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\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 *= all( bvec2( 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\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 defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ 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 *= all( bvec2( 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";
  7899. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\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";
  7900. 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";
  7901. 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";
  7902. 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";
  7903. 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";
  7904. 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";
  7905. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  7906. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7907. 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\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
  7908. 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";
  7909. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7910. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7911. 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, 2 ) * 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";
  7912. 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 vec2 morphTargetsTextureSize;\n\t\tvec3 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset, const in int stride ) {\n\t\t\tfloat texelIndex = float( vertexIndex * stride + offset );\n\t\t\tfloat y = floor( texelIndex / morphTargetsTextureSize.x );\n\t\t\tfloat x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tvec3 morphUV = vec3( ( x + 0.5 ) / morphTargetsTextureSize.x, y / morphTargetsTextureSize.y, morphTargetIndex );\n\t\t\treturn texture( morphTargetsTexture, morphUV ).xyz;\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";
  7913. 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\t#ifndef USE_MORPHNORMALS\n\t\t\t\tif ( morphTargetInfluences[ i ] > 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 1 ) * morphTargetInfluences[ i ];\n\t\t\t#else\n\t\t\t\tif ( morphTargetInfluences[ i ] > 0.0 ) transformed += getMorph( gl_VertexID, i, 0, 2 ) * morphTargetInfluences[ i ];\n\t\t\t#endif\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";
  7914. var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\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;";
  7915. 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";
  7916. 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";
  7917. 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";
  7918. 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";
  7919. 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 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\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";
  7920. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7921. 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";
  7922. 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";
  7923. var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  7924. 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}\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}";
  7925. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7926. 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;";
  7927. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7928. 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";
  7929. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7930. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7931. var shadowmap_pars_fragment = "#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\tvarying vec4 vSpotShadowCoord[ 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\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\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";
  7932. var shadowmap_pars_vertex = "#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\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ 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 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";
  7933. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif";
  7934. 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, vSpotShadowCoord[ 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}";
  7935. 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";
  7936. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif";
  7937. 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";
  7938. 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";
  7939. 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";
  7940. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7941. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7942. 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; }";
  7943. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tfloat transmissionAlpha = 1.0;\n\tfloat transmissionFactor = transmission;\n\tfloat thicknessFactor = thickness;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\ttransmissionFactor *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tthicknessFactor *= 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, roughnessFactor, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, ior, thicknessFactor,\n\t\tattenuationColor, attenuationDistance );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, transmissionFactor );\n\ttransmissionAlpha = mix( transmissionAlpha, transmission.a, transmissionFactor );\n#endif";
  7944. 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( vec3 n, vec3 v, float thickness, float ior, 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( float roughness, float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( vec2 fragCoord, float roughness, float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef TEXTURE_LOD_EXT\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( vec3 radiance, float transmissionDistance, vec3 attenuationColor, float attenuationDistance ) {\n\t\tif ( attenuationDistance == 0.0 ) {\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( vec3 n, vec3 v, float roughness, vec3 diffuseColor, vec3 specularColor, float specularF90,\n\t\tvec3 position, mat4 modelMatrix, mat4 viewMatrix, mat4 projMatrix, float ior, float thickness,\n\t\tvec3 attenuationColor, 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";
  7945. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7946. 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";
  7947. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7948. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7949. 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";
  7950. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7951. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION )\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";
  7952. const vertex$g = "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}";
  7953. const fragment$g = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7954. 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}";
  7955. const fragment$f = "#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7956. 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}";
  7957. 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}";
  7958. 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}";
  7959. 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}";
  7960. 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}";
  7961. 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\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7962. 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 <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}";
  7963. 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}";
  7964. 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#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}";
  7965. 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 <cube_uv_reflection_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 += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\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}";
  7966. const vertex$9 = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <color_pars_vertex>\n#include <fog_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 <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 <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7967. const fragment$9 = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\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 <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_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 <emissivemap_fragment>\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Lambert( diffuseColor.rgb ) * getShadowMask();\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}";
  7968. 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 <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}";
  7969. 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\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 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}";
  7970. 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}";
  7971. 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}";
  7972. 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 <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}";
  7973. 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 <cube_uv_reflection_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}";
  7974. 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 <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}";
  7975. 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_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 <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 <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_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}";
  7976. 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 <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}";
  7977. 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}";
  7978. 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 <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}";
  7979. 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}";
  7980. 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}";
  7981. 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}";
  7982. 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}";
  7983. 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}";
  7984. const ShaderChunk = {
  7985. alphamap_fragment: alphamap_fragment,
  7986. alphamap_pars_fragment: alphamap_pars_fragment,
  7987. alphatest_fragment: alphatest_fragment,
  7988. alphatest_pars_fragment: alphatest_pars_fragment,
  7989. aomap_fragment: aomap_fragment,
  7990. aomap_pars_fragment: aomap_pars_fragment,
  7991. begin_vertex: begin_vertex,
  7992. beginnormal_vertex: beginnormal_vertex,
  7993. bsdfs: bsdfs,
  7994. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7995. clipping_planes_fragment: clipping_planes_fragment,
  7996. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7997. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7998. clipping_planes_vertex: clipping_planes_vertex,
  7999. color_fragment: color_fragment,
  8000. color_pars_fragment: color_pars_fragment,
  8001. color_pars_vertex: color_pars_vertex,
  8002. color_vertex: color_vertex,
  8003. common: common,
  8004. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8005. defaultnormal_vertex: defaultnormal_vertex,
  8006. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8007. displacementmap_vertex: displacementmap_vertex,
  8008. emissivemap_fragment: emissivemap_fragment,
  8009. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8010. encodings_fragment: encodings_fragment,
  8011. encodings_pars_fragment: encodings_pars_fragment,
  8012. envmap_fragment: envmap_fragment,
  8013. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8014. envmap_pars_fragment: envmap_pars_fragment,
  8015. envmap_pars_vertex: envmap_pars_vertex,
  8016. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8017. envmap_vertex: envmap_vertex,
  8018. fog_vertex: fog_vertex,
  8019. fog_pars_vertex: fog_pars_vertex,
  8020. fog_fragment: fog_fragment,
  8021. fog_pars_fragment: fog_pars_fragment,
  8022. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8023. lightmap_fragment: lightmap_fragment,
  8024. lightmap_pars_fragment: lightmap_pars_fragment,
  8025. lights_lambert_vertex: lights_lambert_vertex,
  8026. lights_pars_begin: lights_pars_begin,
  8027. lights_toon_fragment: lights_toon_fragment,
  8028. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8029. lights_phong_fragment: lights_phong_fragment,
  8030. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8031. lights_physical_fragment: lights_physical_fragment,
  8032. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8033. lights_fragment_begin: lights_fragment_begin,
  8034. lights_fragment_maps: lights_fragment_maps,
  8035. lights_fragment_end: lights_fragment_end,
  8036. logdepthbuf_fragment: logdepthbuf_fragment,
  8037. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8038. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8039. logdepthbuf_vertex: logdepthbuf_vertex,
  8040. map_fragment: map_fragment,
  8041. map_pars_fragment: map_pars_fragment,
  8042. map_particle_fragment: map_particle_fragment,
  8043. map_particle_pars_fragment: map_particle_pars_fragment,
  8044. metalnessmap_fragment: metalnessmap_fragment,
  8045. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8046. morphnormal_vertex: morphnormal_vertex,
  8047. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8048. morphtarget_vertex: morphtarget_vertex,
  8049. normal_fragment_begin: normal_fragment_begin,
  8050. normal_fragment_maps: normal_fragment_maps,
  8051. normal_pars_fragment: normal_pars_fragment,
  8052. normal_pars_vertex: normal_pars_vertex,
  8053. normal_vertex: normal_vertex,
  8054. normalmap_pars_fragment: normalmap_pars_fragment,
  8055. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8056. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8057. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8058. output_fragment: output_fragment,
  8059. packing: packing,
  8060. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8061. project_vertex: project_vertex,
  8062. dithering_fragment: dithering_fragment,
  8063. dithering_pars_fragment: dithering_pars_fragment,
  8064. roughnessmap_fragment: roughnessmap_fragment,
  8065. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8066. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8067. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8068. shadowmap_vertex: shadowmap_vertex,
  8069. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8070. skinbase_vertex: skinbase_vertex,
  8071. skinning_pars_vertex: skinning_pars_vertex,
  8072. skinning_vertex: skinning_vertex,
  8073. skinnormal_vertex: skinnormal_vertex,
  8074. specularmap_fragment: specularmap_fragment,
  8075. specularmap_pars_fragment: specularmap_pars_fragment,
  8076. tonemapping_fragment: tonemapping_fragment,
  8077. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8078. transmission_fragment: transmission_fragment,
  8079. transmission_pars_fragment: transmission_pars_fragment,
  8080. uv_pars_fragment: uv_pars_fragment,
  8081. uv_pars_vertex: uv_pars_vertex,
  8082. uv_vertex: uv_vertex,
  8083. uv2_pars_fragment: uv2_pars_fragment,
  8084. uv2_pars_vertex: uv2_pars_vertex,
  8085. uv2_vertex: uv2_vertex,
  8086. worldpos_vertex: worldpos_vertex,
  8087. background_vert: vertex$g,
  8088. background_frag: fragment$g,
  8089. cube_vert: vertex$f,
  8090. cube_frag: fragment$f,
  8091. depth_vert: vertex$e,
  8092. depth_frag: fragment$e,
  8093. distanceRGBA_vert: vertex$d,
  8094. distanceRGBA_frag: fragment$d,
  8095. equirect_vert: vertex$c,
  8096. equirect_frag: fragment$c,
  8097. linedashed_vert: vertex$b,
  8098. linedashed_frag: fragment$b,
  8099. meshbasic_vert: vertex$a,
  8100. meshbasic_frag: fragment$a,
  8101. meshlambert_vert: vertex$9,
  8102. meshlambert_frag: fragment$9,
  8103. meshmatcap_vert: vertex$8,
  8104. meshmatcap_frag: fragment$8,
  8105. meshnormal_vert: vertex$7,
  8106. meshnormal_frag: fragment$7,
  8107. meshphong_vert: vertex$6,
  8108. meshphong_frag: fragment$6,
  8109. meshphysical_vert: vertex$5,
  8110. meshphysical_frag: fragment$5,
  8111. meshtoon_vert: vertex$4,
  8112. meshtoon_frag: fragment$4,
  8113. points_vert: vertex$3,
  8114. points_frag: fragment$3,
  8115. shadow_vert: vertex$2,
  8116. shadow_frag: fragment$2,
  8117. sprite_vert: vertex$1,
  8118. sprite_frag: fragment$1
  8119. };
  8120. /**
  8121. * Uniforms library for shared webgl shaders
  8122. */
  8123. const UniformsLib = {
  8124. common: {
  8125. diffuse: {
  8126. value: new Color(0xffffff)
  8127. },
  8128. opacity: {
  8129. value: 1.0
  8130. },
  8131. map: {
  8132. value: null
  8133. },
  8134. uvTransform: {
  8135. value: new Matrix3()
  8136. },
  8137. uv2Transform: {
  8138. value: new Matrix3()
  8139. },
  8140. alphaMap: {
  8141. value: null
  8142. },
  8143. alphaTest: {
  8144. value: 0
  8145. }
  8146. },
  8147. specularmap: {
  8148. specularMap: {
  8149. value: null
  8150. }
  8151. },
  8152. envmap: {
  8153. envMap: {
  8154. value: null
  8155. },
  8156. flipEnvMap: {
  8157. value: -1
  8158. },
  8159. reflectivity: {
  8160. value: 1.0
  8161. },
  8162. // basic, lambert, phong
  8163. ior: {
  8164. value: 1.5
  8165. },
  8166. // standard, physical
  8167. refractionRatio: {
  8168. value: 0.98
  8169. }
  8170. },
  8171. aomap: {
  8172. aoMap: {
  8173. value: null
  8174. },
  8175. aoMapIntensity: {
  8176. value: 1
  8177. }
  8178. },
  8179. lightmap: {
  8180. lightMap: {
  8181. value: null
  8182. },
  8183. lightMapIntensity: {
  8184. value: 1
  8185. }
  8186. },
  8187. emissivemap: {
  8188. emissiveMap: {
  8189. value: null
  8190. }
  8191. },
  8192. bumpmap: {
  8193. bumpMap: {
  8194. value: null
  8195. },
  8196. bumpScale: {
  8197. value: 1
  8198. }
  8199. },
  8200. normalmap: {
  8201. normalMap: {
  8202. value: null
  8203. },
  8204. normalScale: {
  8205. value: new Vector2(1, 1)
  8206. }
  8207. },
  8208. displacementmap: {
  8209. displacementMap: {
  8210. value: null
  8211. },
  8212. displacementScale: {
  8213. value: 1
  8214. },
  8215. displacementBias: {
  8216. value: 0
  8217. }
  8218. },
  8219. roughnessmap: {
  8220. roughnessMap: {
  8221. value: null
  8222. }
  8223. },
  8224. metalnessmap: {
  8225. metalnessMap: {
  8226. value: null
  8227. }
  8228. },
  8229. gradientmap: {
  8230. gradientMap: {
  8231. value: null
  8232. }
  8233. },
  8234. fog: {
  8235. fogDensity: {
  8236. value: 0.00025
  8237. },
  8238. fogNear: {
  8239. value: 1
  8240. },
  8241. fogFar: {
  8242. value: 2000
  8243. },
  8244. fogColor: {
  8245. value: new Color(0xffffff)
  8246. }
  8247. },
  8248. lights: {
  8249. ambientLightColor: {
  8250. value: []
  8251. },
  8252. lightProbe: {
  8253. value: []
  8254. },
  8255. directionalLights: {
  8256. value: [],
  8257. properties: {
  8258. direction: {},
  8259. color: {}
  8260. }
  8261. },
  8262. directionalLightShadows: {
  8263. value: [],
  8264. properties: {
  8265. shadowBias: {},
  8266. shadowNormalBias: {},
  8267. shadowRadius: {},
  8268. shadowMapSize: {}
  8269. }
  8270. },
  8271. directionalShadowMap: {
  8272. value: []
  8273. },
  8274. directionalShadowMatrix: {
  8275. value: []
  8276. },
  8277. spotLights: {
  8278. value: [],
  8279. properties: {
  8280. color: {},
  8281. position: {},
  8282. direction: {},
  8283. distance: {},
  8284. coneCos: {},
  8285. penumbraCos: {},
  8286. decay: {}
  8287. }
  8288. },
  8289. spotLightShadows: {
  8290. value: [],
  8291. properties: {
  8292. shadowBias: {},
  8293. shadowNormalBias: {},
  8294. shadowRadius: {},
  8295. shadowMapSize: {}
  8296. }
  8297. },
  8298. spotShadowMap: {
  8299. value: []
  8300. },
  8301. spotShadowMatrix: {
  8302. value: []
  8303. },
  8304. pointLights: {
  8305. value: [],
  8306. properties: {
  8307. color: {},
  8308. position: {},
  8309. decay: {},
  8310. distance: {}
  8311. }
  8312. },
  8313. pointLightShadows: {
  8314. value: [],
  8315. properties: {
  8316. shadowBias: {},
  8317. shadowNormalBias: {},
  8318. shadowRadius: {},
  8319. shadowMapSize: {},
  8320. shadowCameraNear: {},
  8321. shadowCameraFar: {}
  8322. }
  8323. },
  8324. pointShadowMap: {
  8325. value: []
  8326. },
  8327. pointShadowMatrix: {
  8328. value: []
  8329. },
  8330. hemisphereLights: {
  8331. value: [],
  8332. properties: {
  8333. direction: {},
  8334. skyColor: {},
  8335. groundColor: {}
  8336. }
  8337. },
  8338. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8339. rectAreaLights: {
  8340. value: [],
  8341. properties: {
  8342. color: {},
  8343. position: {},
  8344. width: {},
  8345. height: {}
  8346. }
  8347. },
  8348. ltc_1: {
  8349. value: null
  8350. },
  8351. ltc_2: {
  8352. value: null
  8353. }
  8354. },
  8355. points: {
  8356. diffuse: {
  8357. value: new Color(0xffffff)
  8358. },
  8359. opacity: {
  8360. value: 1.0
  8361. },
  8362. size: {
  8363. value: 1.0
  8364. },
  8365. scale: {
  8366. value: 1.0
  8367. },
  8368. map: {
  8369. value: null
  8370. },
  8371. alphaMap: {
  8372. value: null
  8373. },
  8374. alphaTest: {
  8375. value: 0
  8376. },
  8377. uvTransform: {
  8378. value: new Matrix3()
  8379. }
  8380. },
  8381. sprite: {
  8382. diffuse: {
  8383. value: new Color(0xffffff)
  8384. },
  8385. opacity: {
  8386. value: 1.0
  8387. },
  8388. center: {
  8389. value: new Vector2(0.5, 0.5)
  8390. },
  8391. rotation: {
  8392. value: 0.0
  8393. },
  8394. map: {
  8395. value: null
  8396. },
  8397. alphaMap: {
  8398. value: null
  8399. },
  8400. alphaTest: {
  8401. value: 0
  8402. },
  8403. uvTransform: {
  8404. value: new Matrix3()
  8405. }
  8406. }
  8407. };
  8408. const ShaderLib = {
  8409. basic: {
  8410. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  8411. vertexShader: ShaderChunk.meshbasic_vert,
  8412. fragmentShader: ShaderChunk.meshbasic_frag
  8413. },
  8414. lambert: {
  8415. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  8416. emissive: {
  8417. value: new Color(0x000000)
  8418. }
  8419. }]),
  8420. vertexShader: ShaderChunk.meshlambert_vert,
  8421. fragmentShader: ShaderChunk.meshlambert_frag
  8422. },
  8423. phong: {
  8424. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  8425. emissive: {
  8426. value: new Color(0x000000)
  8427. },
  8428. specular: {
  8429. value: new Color(0x111111)
  8430. },
  8431. shininess: {
  8432. value: 30
  8433. }
  8434. }]),
  8435. vertexShader: ShaderChunk.meshphong_vert,
  8436. fragmentShader: ShaderChunk.meshphong_frag
  8437. },
  8438. standard: {
  8439. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.roughnessmap, UniformsLib.metalnessmap, UniformsLib.fog, UniformsLib.lights, {
  8440. emissive: {
  8441. value: new Color(0x000000)
  8442. },
  8443. roughness: {
  8444. value: 1.0
  8445. },
  8446. metalness: {
  8447. value: 0.0
  8448. },
  8449. envMapIntensity: {
  8450. value: 1
  8451. } // temporary
  8452. }]),
  8453. vertexShader: ShaderChunk.meshphysical_vert,
  8454. fragmentShader: ShaderChunk.meshphysical_frag
  8455. },
  8456. toon: {
  8457. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  8458. emissive: {
  8459. value: new Color(0x000000)
  8460. }
  8461. }]),
  8462. vertexShader: ShaderChunk.meshtoon_vert,
  8463. fragmentShader: ShaderChunk.meshtoon_frag
  8464. },
  8465. matcap: {
  8466. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  8467. matcap: {
  8468. value: null
  8469. }
  8470. }]),
  8471. vertexShader: ShaderChunk.meshmatcap_vert,
  8472. fragmentShader: ShaderChunk.meshmatcap_frag
  8473. },
  8474. points: {
  8475. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  8476. vertexShader: ShaderChunk.points_vert,
  8477. fragmentShader: ShaderChunk.points_frag
  8478. },
  8479. dashed: {
  8480. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  8481. scale: {
  8482. value: 1
  8483. },
  8484. dashSize: {
  8485. value: 1
  8486. },
  8487. totalSize: {
  8488. value: 2
  8489. }
  8490. }]),
  8491. vertexShader: ShaderChunk.linedashed_vert,
  8492. fragmentShader: ShaderChunk.linedashed_frag
  8493. },
  8494. depth: {
  8495. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  8496. vertexShader: ShaderChunk.depth_vert,
  8497. fragmentShader: ShaderChunk.depth_frag
  8498. },
  8499. normal: {
  8500. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  8501. opacity: {
  8502. value: 1.0
  8503. }
  8504. }]),
  8505. vertexShader: ShaderChunk.meshnormal_vert,
  8506. fragmentShader: ShaderChunk.meshnormal_frag
  8507. },
  8508. sprite: {
  8509. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  8510. vertexShader: ShaderChunk.sprite_vert,
  8511. fragmentShader: ShaderChunk.sprite_frag
  8512. },
  8513. background: {
  8514. uniforms: {
  8515. uvTransform: {
  8516. value: new Matrix3()
  8517. },
  8518. t2D: {
  8519. value: null
  8520. }
  8521. },
  8522. vertexShader: ShaderChunk.background_vert,
  8523. fragmentShader: ShaderChunk.background_frag
  8524. },
  8525. /* -------------------------------------------------------------------------
  8526. // Cube map shader
  8527. ------------------------------------------------------------------------- */
  8528. cube: {
  8529. uniforms: mergeUniforms([UniformsLib.envmap, {
  8530. opacity: {
  8531. value: 1.0
  8532. }
  8533. }]),
  8534. vertexShader: ShaderChunk.cube_vert,
  8535. fragmentShader: ShaderChunk.cube_frag
  8536. },
  8537. equirect: {
  8538. uniforms: {
  8539. tEquirect: {
  8540. value: null
  8541. }
  8542. },
  8543. vertexShader: ShaderChunk.equirect_vert,
  8544. fragmentShader: ShaderChunk.equirect_frag
  8545. },
  8546. distanceRGBA: {
  8547. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  8548. referencePosition: {
  8549. value: new Vector3()
  8550. },
  8551. nearDistance: {
  8552. value: 1
  8553. },
  8554. farDistance: {
  8555. value: 1000
  8556. }
  8557. }]),
  8558. vertexShader: ShaderChunk.distanceRGBA_vert,
  8559. fragmentShader: ShaderChunk.distanceRGBA_frag
  8560. },
  8561. shadow: {
  8562. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  8563. color: {
  8564. value: new Color(0x00000)
  8565. },
  8566. opacity: {
  8567. value: 1.0
  8568. }
  8569. }]),
  8570. vertexShader: ShaderChunk.shadow_vert,
  8571. fragmentShader: ShaderChunk.shadow_frag
  8572. }
  8573. };
  8574. ShaderLib.physical = {
  8575. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  8576. clearcoat: {
  8577. value: 0
  8578. },
  8579. clearcoatMap: {
  8580. value: null
  8581. },
  8582. clearcoatRoughness: {
  8583. value: 0
  8584. },
  8585. clearcoatRoughnessMap: {
  8586. value: null
  8587. },
  8588. clearcoatNormalScale: {
  8589. value: new Vector2(1, 1)
  8590. },
  8591. clearcoatNormalMap: {
  8592. value: null
  8593. },
  8594. sheen: {
  8595. value: 0
  8596. },
  8597. sheenColor: {
  8598. value: new Color(0x000000)
  8599. },
  8600. sheenColorMap: {
  8601. value: null
  8602. },
  8603. sheenRoughness: {
  8604. value: 0
  8605. },
  8606. sheenRoughnessMap: {
  8607. value: null
  8608. },
  8609. transmission: {
  8610. value: 0
  8611. },
  8612. transmissionMap: {
  8613. value: null
  8614. },
  8615. transmissionSamplerSize: {
  8616. value: new Vector2()
  8617. },
  8618. transmissionSamplerMap: {
  8619. value: null
  8620. },
  8621. thickness: {
  8622. value: 0
  8623. },
  8624. thicknessMap: {
  8625. value: null
  8626. },
  8627. attenuationDistance: {
  8628. value: 0
  8629. },
  8630. attenuationColor: {
  8631. value: new Color(0x000000)
  8632. },
  8633. specularIntensity: {
  8634. value: 0
  8635. },
  8636. specularIntensityMap: {
  8637. value: null
  8638. },
  8639. specularColor: {
  8640. value: new Color(1, 1, 1)
  8641. },
  8642. specularColorMap: {
  8643. value: null
  8644. }
  8645. }]),
  8646. vertexShader: ShaderChunk.meshphysical_vert,
  8647. fragmentShader: ShaderChunk.meshphysical_frag
  8648. };
  8649. function WebGLBackground(renderer, cubemaps, state, objects, premultipliedAlpha) {
  8650. const clearColor = new Color(0x000000);
  8651. let clearAlpha = 0;
  8652. let planeMesh;
  8653. let boxMesh;
  8654. let currentBackground = null;
  8655. let currentBackgroundVersion = 0;
  8656. let currentTonemapping = null;
  8657. function render(renderList, scene) {
  8658. let forceClear = false;
  8659. let background = scene.isScene === true ? scene.background : null;
  8660. if (background && background.isTexture) {
  8661. background = cubemaps.get(background);
  8662. } // Ignore background in AR
  8663. // TODO: Reconsider this.
  8664. const xr = renderer.xr;
  8665. const session = xr.getSession && xr.getSession();
  8666. if (session && session.environmentBlendMode === 'additive') {
  8667. background = null;
  8668. }
  8669. if (background === null) {
  8670. setClear(clearColor, clearAlpha);
  8671. } else if (background && background.isColor) {
  8672. setClear(background, 1);
  8673. forceClear = true;
  8674. }
  8675. if (renderer.autoClear || forceClear) {
  8676. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  8677. }
  8678. if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) {
  8679. if (boxMesh === undefined) {
  8680. boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({
  8681. name: 'BackgroundCubeMaterial',
  8682. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  8683. vertexShader: ShaderLib.cube.vertexShader,
  8684. fragmentShader: ShaderLib.cube.fragmentShader,
  8685. side: BackSide,
  8686. depthTest: false,
  8687. depthWrite: false,
  8688. fog: false
  8689. }));
  8690. boxMesh.geometry.deleteAttribute('normal');
  8691. boxMesh.geometry.deleteAttribute('uv');
  8692. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  8693. this.matrixWorld.copyPosition(camera.matrixWorld);
  8694. }; // enable code injection for non-built-in material
  8695. Object.defineProperty(boxMesh.material, 'envMap', {
  8696. get: function () {
  8697. return this.uniforms.envMap.value;
  8698. }
  8699. });
  8700. objects.update(boxMesh);
  8701. }
  8702. boxMesh.material.uniforms.envMap.value = background;
  8703. boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background.isRenderTargetTexture === false ? -1 : 1;
  8704. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8705. boxMesh.material.needsUpdate = true;
  8706. currentBackground = background;
  8707. currentBackgroundVersion = background.version;
  8708. currentTonemapping = renderer.toneMapping;
  8709. } // push to the pre-sorted opaque render list
  8710. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  8711. } else if (background && background.isTexture) {
  8712. if (planeMesh === undefined) {
  8713. planeMesh = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({
  8714. name: 'BackgroundMaterial',
  8715. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  8716. vertexShader: ShaderLib.background.vertexShader,
  8717. fragmentShader: ShaderLib.background.fragmentShader,
  8718. side: FrontSide,
  8719. depthTest: false,
  8720. depthWrite: false,
  8721. fog: false
  8722. }));
  8723. planeMesh.geometry.deleteAttribute('normal'); // enable code injection for non-built-in material
  8724. Object.defineProperty(planeMesh.material, 'map', {
  8725. get: function () {
  8726. return this.uniforms.t2D.value;
  8727. }
  8728. });
  8729. objects.update(planeMesh);
  8730. }
  8731. planeMesh.material.uniforms.t2D.value = background;
  8732. if (background.matrixAutoUpdate === true) {
  8733. background.updateMatrix();
  8734. }
  8735. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  8736. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8737. planeMesh.material.needsUpdate = true;
  8738. currentBackground = background;
  8739. currentBackgroundVersion = background.version;
  8740. currentTonemapping = renderer.toneMapping;
  8741. } // push to the pre-sorted opaque render list
  8742. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  8743. }
  8744. }
  8745. function setClear(color, alpha) {
  8746. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  8747. }
  8748. return {
  8749. getClearColor: function () {
  8750. return clearColor;
  8751. },
  8752. setClearColor: function (color, alpha = 1) {
  8753. clearColor.set(color);
  8754. clearAlpha = alpha;
  8755. setClear(clearColor, clearAlpha);
  8756. },
  8757. getClearAlpha: function () {
  8758. return clearAlpha;
  8759. },
  8760. setClearAlpha: function (alpha) {
  8761. clearAlpha = alpha;
  8762. setClear(clearColor, clearAlpha);
  8763. },
  8764. render: render
  8765. };
  8766. }
  8767. function WebGLBindingStates(gl, extensions, attributes, capabilities) {
  8768. const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  8769. const extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
  8770. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8771. const bindingStates = {};
  8772. const defaultState = createBindingState(null);
  8773. let currentState = defaultState;
  8774. function setup(object, material, program, geometry, index) {
  8775. let updateBuffers = false;
  8776. if (vaoAvailable) {
  8777. const state = getBindingState(geometry, program, material);
  8778. if (currentState !== state) {
  8779. currentState = state;
  8780. bindVertexArrayObject(currentState.object);
  8781. }
  8782. updateBuffers = needsUpdate(geometry, index);
  8783. if (updateBuffers) saveCache(geometry, index);
  8784. } else {
  8785. const wireframe = material.wireframe === true;
  8786. if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
  8787. currentState.geometry = geometry.id;
  8788. currentState.program = program.id;
  8789. currentState.wireframe = wireframe;
  8790. updateBuffers = true;
  8791. }
  8792. }
  8793. if (object.isInstancedMesh === true) {
  8794. updateBuffers = true;
  8795. }
  8796. if (index !== null) {
  8797. attributes.update(index, gl.ELEMENT_ARRAY_BUFFER);
  8798. }
  8799. if (updateBuffers) {
  8800. setupVertexAttributes(object, material, program, geometry);
  8801. if (index !== null) {
  8802. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index).buffer);
  8803. }
  8804. }
  8805. }
  8806. function createVertexArrayObject() {
  8807. if (capabilities.isWebGL2) return gl.createVertexArray();
  8808. return extension.createVertexArrayOES();
  8809. }
  8810. function bindVertexArrayObject(vao) {
  8811. if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
  8812. return extension.bindVertexArrayOES(vao);
  8813. }
  8814. function deleteVertexArrayObject(vao) {
  8815. if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
  8816. return extension.deleteVertexArrayOES(vao);
  8817. }
  8818. function getBindingState(geometry, program, material) {
  8819. const wireframe = material.wireframe === true;
  8820. let programMap = bindingStates[geometry.id];
  8821. if (programMap === undefined) {
  8822. programMap = {};
  8823. bindingStates[geometry.id] = programMap;
  8824. }
  8825. let stateMap = programMap[program.id];
  8826. if (stateMap === undefined) {
  8827. stateMap = {};
  8828. programMap[program.id] = stateMap;
  8829. }
  8830. let state = stateMap[wireframe];
  8831. if (state === undefined) {
  8832. state = createBindingState(createVertexArrayObject());
  8833. stateMap[wireframe] = state;
  8834. }
  8835. return state;
  8836. }
  8837. function createBindingState(vao) {
  8838. const newAttributes = [];
  8839. const enabledAttributes = [];
  8840. const attributeDivisors = [];
  8841. for (let i = 0; i < maxVertexAttributes; i++) {
  8842. newAttributes[i] = 0;
  8843. enabledAttributes[i] = 0;
  8844. attributeDivisors[i] = 0;
  8845. }
  8846. return {
  8847. // for backward compatibility on non-VAO support browser
  8848. geometry: null,
  8849. program: null,
  8850. wireframe: false,
  8851. newAttributes: newAttributes,
  8852. enabledAttributes: enabledAttributes,
  8853. attributeDivisors: attributeDivisors,
  8854. object: vao,
  8855. attributes: {},
  8856. index: null
  8857. };
  8858. }
  8859. function needsUpdate(geometry, index) {
  8860. const cachedAttributes = currentState.attributes;
  8861. const geometryAttributes = geometry.attributes;
  8862. let attributesNum = 0;
  8863. for (const key in geometryAttributes) {
  8864. const cachedAttribute = cachedAttributes[key];
  8865. const geometryAttribute = geometryAttributes[key];
  8866. if (cachedAttribute === undefined) return true;
  8867. if (cachedAttribute.attribute !== geometryAttribute) return true;
  8868. if (cachedAttribute.data !== geometryAttribute.data) return true;
  8869. attributesNum++;
  8870. }
  8871. if (currentState.attributesNum !== attributesNum) return true;
  8872. if (currentState.index !== index) return true;
  8873. return false;
  8874. }
  8875. function saveCache(geometry, index) {
  8876. const cache = {};
  8877. const attributes = geometry.attributes;
  8878. let attributesNum = 0;
  8879. for (const key in attributes) {
  8880. const attribute = attributes[key];
  8881. const data = {};
  8882. data.attribute = attribute;
  8883. if (attribute.data) {
  8884. data.data = attribute.data;
  8885. }
  8886. cache[key] = data;
  8887. attributesNum++;
  8888. }
  8889. currentState.attributes = cache;
  8890. currentState.attributesNum = attributesNum;
  8891. currentState.index = index;
  8892. }
  8893. function initAttributes() {
  8894. const newAttributes = currentState.newAttributes;
  8895. for (let i = 0, il = newAttributes.length; i < il; i++) {
  8896. newAttributes[i] = 0;
  8897. }
  8898. }
  8899. function enableAttribute(attribute) {
  8900. enableAttributeAndDivisor(attribute, 0);
  8901. }
  8902. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  8903. const newAttributes = currentState.newAttributes;
  8904. const enabledAttributes = currentState.enabledAttributes;
  8905. const attributeDivisors = currentState.attributeDivisors;
  8906. newAttributes[attribute] = 1;
  8907. if (enabledAttributes[attribute] === 0) {
  8908. gl.enableVertexAttribArray(attribute);
  8909. enabledAttributes[attribute] = 1;
  8910. }
  8911. if (attributeDivisors[attribute] !== meshPerAttribute) {
  8912. const extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  8913. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  8914. attributeDivisors[attribute] = meshPerAttribute;
  8915. }
  8916. }
  8917. function disableUnusedAttributes() {
  8918. const newAttributes = currentState.newAttributes;
  8919. const enabledAttributes = currentState.enabledAttributes;
  8920. for (let i = 0, il = enabledAttributes.length; i < il; i++) {
  8921. if (enabledAttributes[i] !== newAttributes[i]) {
  8922. gl.disableVertexAttribArray(i);
  8923. enabledAttributes[i] = 0;
  8924. }
  8925. }
  8926. }
  8927. function vertexAttribPointer(index, size, type, normalized, stride, offset) {
  8928. if (capabilities.isWebGL2 === true && (type === gl.INT || type === gl.UNSIGNED_INT)) {
  8929. gl.vertexAttribIPointer(index, size, type, stride, offset);
  8930. } else {
  8931. gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
  8932. }
  8933. }
  8934. function setupVertexAttributes(object, material, program, geometry) {
  8935. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  8936. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  8937. }
  8938. initAttributes();
  8939. const geometryAttributes = geometry.attributes;
  8940. const programAttributes = program.getAttributes();
  8941. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8942. for (const name in programAttributes) {
  8943. const programAttribute = programAttributes[name];
  8944. if (programAttribute.location >= 0) {
  8945. let geometryAttribute = geometryAttributes[name];
  8946. if (geometryAttribute === undefined) {
  8947. if (name === 'instanceMatrix' && object.instanceMatrix) geometryAttribute = object.instanceMatrix;
  8948. if (name === 'instanceColor' && object.instanceColor) geometryAttribute = object.instanceColor;
  8949. }
  8950. if (geometryAttribute !== undefined) {
  8951. const normalized = geometryAttribute.normalized;
  8952. const size = geometryAttribute.itemSize;
  8953. const attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  8954. if (attribute === undefined) continue;
  8955. const buffer = attribute.buffer;
  8956. const type = attribute.type;
  8957. const bytesPerElement = attribute.bytesPerElement;
  8958. if (geometryAttribute.isInterleavedBufferAttribute) {
  8959. const data = geometryAttribute.data;
  8960. const stride = data.stride;
  8961. const offset = geometryAttribute.offset;
  8962. if (data && data.isInstancedInterleavedBuffer) {
  8963. for (let i = 0; i < programAttribute.locationSize; i++) {
  8964. enableAttributeAndDivisor(programAttribute.location + i, data.meshPerAttribute);
  8965. }
  8966. if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
  8967. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8968. }
  8969. } else {
  8970. for (let i = 0; i < programAttribute.locationSize; i++) {
  8971. enableAttribute(programAttribute.location + i);
  8972. }
  8973. }
  8974. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8975. for (let i = 0; i < programAttribute.locationSize; i++) {
  8976. vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, stride * bytesPerElement, (offset + size / programAttribute.locationSize * i) * bytesPerElement);
  8977. }
  8978. } else {
  8979. if (geometryAttribute.isInstancedBufferAttribute) {
  8980. for (let i = 0; i < programAttribute.locationSize; i++) {
  8981. enableAttributeAndDivisor(programAttribute.location + i, geometryAttribute.meshPerAttribute);
  8982. }
  8983. if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
  8984. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8985. }
  8986. } else {
  8987. for (let i = 0; i < programAttribute.locationSize; i++) {
  8988. enableAttribute(programAttribute.location + i);
  8989. }
  8990. }
  8991. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8992. for (let i = 0; i < programAttribute.locationSize; i++) {
  8993. vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, size * bytesPerElement, size / programAttribute.locationSize * i * bytesPerElement);
  8994. }
  8995. }
  8996. } else if (materialDefaultAttributeValues !== undefined) {
  8997. const value = materialDefaultAttributeValues[name];
  8998. if (value !== undefined) {
  8999. switch (value.length) {
  9000. case 2:
  9001. gl.vertexAttrib2fv(programAttribute.location, value);
  9002. break;
  9003. case 3:
  9004. gl.vertexAttrib3fv(programAttribute.location, value);
  9005. break;
  9006. case 4:
  9007. gl.vertexAttrib4fv(programAttribute.location, value);
  9008. break;
  9009. default:
  9010. gl.vertexAttrib1fv(programAttribute.location, value);
  9011. }
  9012. }
  9013. }
  9014. }
  9015. }
  9016. disableUnusedAttributes();
  9017. }
  9018. function dispose() {
  9019. reset();
  9020. for (const geometryId in bindingStates) {
  9021. const programMap = bindingStates[geometryId];
  9022. for (const programId in programMap) {
  9023. const stateMap = programMap[programId];
  9024. for (const wireframe in stateMap) {
  9025. deleteVertexArrayObject(stateMap[wireframe].object);
  9026. delete stateMap[wireframe];
  9027. }
  9028. delete programMap[programId];
  9029. }
  9030. delete bindingStates[geometryId];
  9031. }
  9032. }
  9033. function releaseStatesOfGeometry(geometry) {
  9034. if (bindingStates[geometry.id] === undefined) return;
  9035. const programMap = bindingStates[geometry.id];
  9036. for (const programId in programMap) {
  9037. const stateMap = programMap[programId];
  9038. for (const wireframe in stateMap) {
  9039. deleteVertexArrayObject(stateMap[wireframe].object);
  9040. delete stateMap[wireframe];
  9041. }
  9042. delete programMap[programId];
  9043. }
  9044. delete bindingStates[geometry.id];
  9045. }
  9046. function releaseStatesOfProgram(program) {
  9047. for (const geometryId in bindingStates) {
  9048. const programMap = bindingStates[geometryId];
  9049. if (programMap[program.id] === undefined) continue;
  9050. const stateMap = programMap[program.id];
  9051. for (const wireframe in stateMap) {
  9052. deleteVertexArrayObject(stateMap[wireframe].object);
  9053. delete stateMap[wireframe];
  9054. }
  9055. delete programMap[program.id];
  9056. }
  9057. }
  9058. function reset() {
  9059. resetDefaultState();
  9060. if (currentState === defaultState) return;
  9061. currentState = defaultState;
  9062. bindVertexArrayObject(currentState.object);
  9063. } // for backward-compatilibity
  9064. function resetDefaultState() {
  9065. defaultState.geometry = null;
  9066. defaultState.program = null;
  9067. defaultState.wireframe = false;
  9068. }
  9069. return {
  9070. setup: setup,
  9071. reset: reset,
  9072. resetDefaultState: resetDefaultState,
  9073. dispose: dispose,
  9074. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9075. releaseStatesOfProgram: releaseStatesOfProgram,
  9076. initAttributes: initAttributes,
  9077. enableAttribute: enableAttribute,
  9078. disableUnusedAttributes: disableUnusedAttributes
  9079. };
  9080. }
  9081. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  9082. const isWebGL2 = capabilities.isWebGL2;
  9083. let mode;
  9084. function setMode(value) {
  9085. mode = value;
  9086. }
  9087. function render(start, count) {
  9088. gl.drawArrays(mode, start, count);
  9089. info.update(count, mode, 1);
  9090. }
  9091. function renderInstances(start, count, primcount) {
  9092. if (primcount === 0) return;
  9093. let extension, methodName;
  9094. if (isWebGL2) {
  9095. extension = gl;
  9096. methodName = 'drawArraysInstanced';
  9097. } else {
  9098. extension = extensions.get('ANGLE_instanced_arrays');
  9099. methodName = 'drawArraysInstancedANGLE';
  9100. if (extension === null) {
  9101. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9102. return;
  9103. }
  9104. }
  9105. extension[methodName](mode, start, count, primcount);
  9106. info.update(count, mode, primcount);
  9107. } //
  9108. this.setMode = setMode;
  9109. this.render = render;
  9110. this.renderInstances = renderInstances;
  9111. }
  9112. function WebGLCapabilities(gl, extensions, parameters) {
  9113. let maxAnisotropy;
  9114. function getMaxAnisotropy() {
  9115. if (maxAnisotropy !== undefined) return maxAnisotropy;
  9116. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  9117. const extension = extensions.get('EXT_texture_filter_anisotropic');
  9118. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  9119. } else {
  9120. maxAnisotropy = 0;
  9121. }
  9122. return maxAnisotropy;
  9123. }
  9124. function getMaxPrecision(precision) {
  9125. if (precision === 'highp') {
  9126. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) {
  9127. return 'highp';
  9128. }
  9129. precision = 'mediump';
  9130. }
  9131. if (precision === 'mediump') {
  9132. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) {
  9133. return 'mediump';
  9134. }
  9135. }
  9136. return 'lowp';
  9137. }
  9138. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  9139. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9140. const maxPrecision = getMaxPrecision(precision);
  9141. if (maxPrecision !== precision) {
  9142. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  9143. precision = maxPrecision;
  9144. }
  9145. const drawBuffers = isWebGL2 || extensions.has('WEBGL_draw_buffers');
  9146. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9147. const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
  9148. const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9149. const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
  9150. const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9151. const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  9152. const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
  9153. const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS);
  9154. const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9155. const vertexTextures = maxVertexTextures > 0;
  9156. const floatFragmentTextures = isWebGL2 || extensions.has('OES_texture_float');
  9157. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9158. const maxSamples = isWebGL2 ? gl.getParameter(gl.MAX_SAMPLES) : 0;
  9159. return {
  9160. isWebGL2: isWebGL2,
  9161. drawBuffers: drawBuffers,
  9162. getMaxAnisotropy: getMaxAnisotropy,
  9163. getMaxPrecision: getMaxPrecision,
  9164. precision: precision,
  9165. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9166. maxTextures: maxTextures,
  9167. maxVertexTextures: maxVertexTextures,
  9168. maxTextureSize: maxTextureSize,
  9169. maxCubemapSize: maxCubemapSize,
  9170. maxAttributes: maxAttributes,
  9171. maxVertexUniforms: maxVertexUniforms,
  9172. maxVaryings: maxVaryings,
  9173. maxFragmentUniforms: maxFragmentUniforms,
  9174. vertexTextures: vertexTextures,
  9175. floatFragmentTextures: floatFragmentTextures,
  9176. floatVertexTextures: floatVertexTextures,
  9177. maxSamples: maxSamples
  9178. };
  9179. }
  9180. function WebGLClipping(properties) {
  9181. const scope = this;
  9182. let globalState = null,
  9183. numGlobalPlanes = 0,
  9184. localClippingEnabled = false,
  9185. renderingShadows = false;
  9186. const plane = new Plane(),
  9187. viewNormalMatrix = new Matrix3(),
  9188. uniform = {
  9189. value: null,
  9190. needsUpdate: false
  9191. };
  9192. this.uniform = uniform;
  9193. this.numPlanes = 0;
  9194. this.numIntersection = 0;
  9195. this.init = function (planes, enableLocalClipping, camera) {
  9196. const enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  9197. // run another frame in order to reset the state:
  9198. numGlobalPlanes !== 0 || localClippingEnabled;
  9199. localClippingEnabled = enableLocalClipping;
  9200. globalState = projectPlanes(planes, camera, 0);
  9201. numGlobalPlanes = planes.length;
  9202. return enabled;
  9203. };
  9204. this.beginShadows = function () {
  9205. renderingShadows = true;
  9206. projectPlanes(null);
  9207. };
  9208. this.endShadows = function () {
  9209. renderingShadows = false;
  9210. resetGlobalState();
  9211. };
  9212. this.setState = function (material, camera, useCache) {
  9213. const planes = material.clippingPlanes,
  9214. clipIntersection = material.clipIntersection,
  9215. clipShadows = material.clipShadows;
  9216. const materialProperties = properties.get(material);
  9217. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  9218. // there's no local clipping
  9219. if (renderingShadows) {
  9220. // there's no global clipping
  9221. projectPlanes(null);
  9222. } else {
  9223. resetGlobalState();
  9224. }
  9225. } else {
  9226. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9227. lGlobal = nGlobal * 4;
  9228. let dstArray = materialProperties.clippingState || null;
  9229. uniform.value = dstArray; // ensure unique state
  9230. dstArray = projectPlanes(planes, camera, lGlobal, useCache);
  9231. for (let i = 0; i !== lGlobal; ++i) {
  9232. dstArray[i] = globalState[i];
  9233. }
  9234. materialProperties.clippingState = dstArray;
  9235. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9236. this.numPlanes += nGlobal;
  9237. }
  9238. };
  9239. function resetGlobalState() {
  9240. if (uniform.value !== globalState) {
  9241. uniform.value = globalState;
  9242. uniform.needsUpdate = numGlobalPlanes > 0;
  9243. }
  9244. scope.numPlanes = numGlobalPlanes;
  9245. scope.numIntersection = 0;
  9246. }
  9247. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  9248. const nPlanes = planes !== null ? planes.length : 0;
  9249. let dstArray = null;
  9250. if (nPlanes !== 0) {
  9251. dstArray = uniform.value;
  9252. if (skipTransform !== true || dstArray === null) {
  9253. const flatSize = dstOffset + nPlanes * 4,
  9254. viewMatrix = camera.matrixWorldInverse;
  9255. viewNormalMatrix.getNormalMatrix(viewMatrix);
  9256. if (dstArray === null || dstArray.length < flatSize) {
  9257. dstArray = new Float32Array(flatSize);
  9258. }
  9259. for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  9260. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  9261. plane.normal.toArray(dstArray, i4);
  9262. dstArray[i4 + 3] = plane.constant;
  9263. }
  9264. }
  9265. uniform.value = dstArray;
  9266. uniform.needsUpdate = true;
  9267. }
  9268. scope.numPlanes = nPlanes;
  9269. scope.numIntersection = 0;
  9270. return dstArray;
  9271. }
  9272. }
  9273. function WebGLCubeMaps(renderer) {
  9274. let cubemaps = new WeakMap();
  9275. function mapTextureMapping(texture, mapping) {
  9276. if (mapping === EquirectangularReflectionMapping) {
  9277. texture.mapping = CubeReflectionMapping;
  9278. } else if (mapping === EquirectangularRefractionMapping) {
  9279. texture.mapping = CubeRefractionMapping;
  9280. }
  9281. return texture;
  9282. }
  9283. function get(texture) {
  9284. if (texture && texture.isTexture && texture.isRenderTargetTexture === false) {
  9285. const mapping = texture.mapping;
  9286. if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
  9287. if (cubemaps.has(texture)) {
  9288. const cubemap = cubemaps.get(texture).texture;
  9289. return mapTextureMapping(cubemap, texture.mapping);
  9290. } else {
  9291. const image = texture.image;
  9292. if (image && image.height > 0) {
  9293. const currentRenderTarget = renderer.getRenderTarget();
  9294. const renderTarget = new WebGLCubeRenderTarget(image.height / 2);
  9295. renderTarget.fromEquirectangularTexture(renderer, texture);
  9296. cubemaps.set(texture, renderTarget);
  9297. renderer.setRenderTarget(currentRenderTarget);
  9298. texture.addEventListener('dispose', onTextureDispose);
  9299. return mapTextureMapping(renderTarget.texture, texture.mapping);
  9300. } else {
  9301. // image not yet ready. try the conversion next frame
  9302. return null;
  9303. }
  9304. }
  9305. }
  9306. }
  9307. return texture;
  9308. }
  9309. function onTextureDispose(event) {
  9310. const texture = event.target;
  9311. texture.removeEventListener('dispose', onTextureDispose);
  9312. const cubemap = cubemaps.get(texture);
  9313. if (cubemap !== undefined) {
  9314. cubemaps.delete(texture);
  9315. cubemap.dispose();
  9316. }
  9317. }
  9318. function dispose() {
  9319. cubemaps = new WeakMap();
  9320. }
  9321. return {
  9322. get: get,
  9323. dispose: dispose
  9324. };
  9325. }
  9326. class OrthographicCamera extends Camera {
  9327. constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) {
  9328. super();
  9329. this.type = 'OrthographicCamera';
  9330. this.zoom = 1;
  9331. this.view = null;
  9332. this.left = left;
  9333. this.right = right;
  9334. this.top = top;
  9335. this.bottom = bottom;
  9336. this.near = near;
  9337. this.far = far;
  9338. this.updateProjectionMatrix();
  9339. }
  9340. copy(source, recursive) {
  9341. super.copy(source, recursive);
  9342. this.left = source.left;
  9343. this.right = source.right;
  9344. this.top = source.top;
  9345. this.bottom = source.bottom;
  9346. this.near = source.near;
  9347. this.far = source.far;
  9348. this.zoom = source.zoom;
  9349. this.view = source.view === null ? null : Object.assign({}, source.view);
  9350. return this;
  9351. }
  9352. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  9353. if (this.view === null) {
  9354. this.view = {
  9355. enabled: true,
  9356. fullWidth: 1,
  9357. fullHeight: 1,
  9358. offsetX: 0,
  9359. offsetY: 0,
  9360. width: 1,
  9361. height: 1
  9362. };
  9363. }
  9364. this.view.enabled = true;
  9365. this.view.fullWidth = fullWidth;
  9366. this.view.fullHeight = fullHeight;
  9367. this.view.offsetX = x;
  9368. this.view.offsetY = y;
  9369. this.view.width = width;
  9370. this.view.height = height;
  9371. this.updateProjectionMatrix();
  9372. }
  9373. clearViewOffset() {
  9374. if (this.view !== null) {
  9375. this.view.enabled = false;
  9376. }
  9377. this.updateProjectionMatrix();
  9378. }
  9379. updateProjectionMatrix() {
  9380. const dx = (this.right - this.left) / (2 * this.zoom);
  9381. const dy = (this.top - this.bottom) / (2 * this.zoom);
  9382. const cx = (this.right + this.left) / 2;
  9383. const cy = (this.top + this.bottom) / 2;
  9384. let left = cx - dx;
  9385. let right = cx + dx;
  9386. let top = cy + dy;
  9387. let bottom = cy - dy;
  9388. if (this.view !== null && this.view.enabled) {
  9389. const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  9390. const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  9391. left += scaleW * this.view.offsetX;
  9392. right = left + scaleW * this.view.width;
  9393. top -= scaleH * this.view.offsetY;
  9394. bottom = top - scaleH * this.view.height;
  9395. }
  9396. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  9397. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  9398. }
  9399. toJSON(meta) {
  9400. const data = super.toJSON(meta);
  9401. data.object.zoom = this.zoom;
  9402. data.object.left = this.left;
  9403. data.object.right = this.right;
  9404. data.object.top = this.top;
  9405. data.object.bottom = this.bottom;
  9406. data.object.near = this.near;
  9407. data.object.far = this.far;
  9408. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  9409. return data;
  9410. }
  9411. }
  9412. OrthographicCamera.prototype.isOrthographicCamera = true;
  9413. class RawShaderMaterial extends ShaderMaterial {
  9414. constructor(parameters) {
  9415. super(parameters);
  9416. this.type = 'RawShaderMaterial';
  9417. }
  9418. }
  9419. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  9420. const LOD_MIN = 4;
  9421. const LOD_MAX = 8;
  9422. const SIZE_MAX = Math.pow(2, LOD_MAX); // The standard deviations (radians) associated with the extra mips. These are
  9423. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9424. // geometric shadowing function. These sigma values squared must match the
  9425. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9426. const EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
  9427. const TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9428. // samples and exit early, but not recompile the shader.
  9429. const MAX_SAMPLES = 20;
  9430. const ENCODINGS = {
  9431. [LinearEncoding]: 0,
  9432. [sRGBEncoding]: 1,
  9433. [RGBEEncoding]: 2,
  9434. [RGBM7Encoding]: 3,
  9435. [RGBM16Encoding]: 4,
  9436. [RGBDEncoding]: 5,
  9437. [GammaEncoding]: 6
  9438. };
  9439. const _flatCamera = /*@__PURE__*/new OrthographicCamera();
  9440. const {
  9441. _lodPlanes,
  9442. _sizeLods,
  9443. _sigmas
  9444. } = /*@__PURE__*/_createPlanes();
  9445. const _clearColor = /*@__PURE__*/new Color();
  9446. let _oldTarget = null; // Golden Ratio
  9447. const PHI = (1 + Math.sqrt(5)) / 2;
  9448. const INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
  9449. // same axis), used as axis directions evenly spread on a sphere.
  9450. const _axisDirections = [/*@__PURE__*/new Vector3(1, 1, 1), /*@__PURE__*/new Vector3(-1, 1, 1), /*@__PURE__*/new Vector3(1, 1, -1), /*@__PURE__*/new Vector3(-1, 1, -1), /*@__PURE__*/new Vector3(0, PHI, INV_PHI), /*@__PURE__*/new Vector3(0, PHI, -INV_PHI), /*@__PURE__*/new Vector3(INV_PHI, 0, PHI), /*@__PURE__*/new Vector3(-INV_PHI, 0, PHI), /*@__PURE__*/new Vector3(PHI, INV_PHI, 0), /*@__PURE__*/new Vector3(-PHI, INV_PHI, 0)];
  9451. /**
  9452. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9453. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9454. * blur to be quickly accessed based on material roughness. It is packed into a
  9455. * special CubeUV format that allows us to perform custom interpolation so that
  9456. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9457. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9458. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9459. * higher roughness levels. In this way we maintain resolution to smoothly
  9460. * interpolate diffuse lighting while limiting sampling computation.
  9461. *
  9462. * Paper: Fast, Accurate Image-Based Lighting
  9463. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9464. */
  9465. class PMREMGenerator {
  9466. constructor(renderer) {
  9467. this._renderer = renderer;
  9468. this._pingPongRenderTarget = null;
  9469. this._blurMaterial = _getBlurShader(MAX_SAMPLES);
  9470. this._equirectShader = null;
  9471. this._cubemapShader = null;
  9472. this._compileMaterial(this._blurMaterial);
  9473. }
  9474. /**
  9475. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9476. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9477. * in radians to be applied to the scene before PMREM generation. Optional near
  9478. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9479. * is placed at the origin).
  9480. */
  9481. fromScene(scene, sigma = 0, near = 0.1, far = 100) {
  9482. _oldTarget = this._renderer.getRenderTarget();
  9483. const cubeUVRenderTarget = this._allocateTargets();
  9484. this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  9485. if (sigma > 0) {
  9486. this._blur(cubeUVRenderTarget, 0, 0, sigma);
  9487. }
  9488. this._applyPMREM(cubeUVRenderTarget);
  9489. this._cleanup(cubeUVRenderTarget);
  9490. return cubeUVRenderTarget;
  9491. }
  9492. /**
  9493. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9494. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  9495. * as this matches best with the 256 x 256 cubemap output.
  9496. */
  9497. fromEquirectangular(equirectangular) {
  9498. return this._fromTexture(equirectangular);
  9499. }
  9500. /**
  9501. * Generates a PMREM from an cubemap texture, which can be either LDR
  9502. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  9503. * as this matches best with the 256 x 256 cubemap output.
  9504. */
  9505. fromCubemap(cubemap) {
  9506. return this._fromTexture(cubemap);
  9507. }
  9508. /**
  9509. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9510. * your texture's network fetch for increased concurrency.
  9511. */
  9512. compileCubemapShader() {
  9513. if (this._cubemapShader === null) {
  9514. this._cubemapShader = _getCubemapShader();
  9515. this._compileMaterial(this._cubemapShader);
  9516. }
  9517. }
  9518. /**
  9519. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9520. * your texture's network fetch for increased concurrency.
  9521. */
  9522. compileEquirectangularShader() {
  9523. if (this._equirectShader === null) {
  9524. this._equirectShader = _getEquirectShader();
  9525. this._compileMaterial(this._equirectShader);
  9526. }
  9527. }
  9528. /**
  9529. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9530. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9531. * one of them will cause any others to also become unusable.
  9532. */
  9533. dispose() {
  9534. this._blurMaterial.dispose();
  9535. if (this._cubemapShader !== null) this._cubemapShader.dispose();
  9536. if (this._equirectShader !== null) this._equirectShader.dispose();
  9537. for (let i = 0; i < _lodPlanes.length; i++) {
  9538. _lodPlanes[i].dispose();
  9539. }
  9540. } // private interface
  9541. _cleanup(outputTarget) {
  9542. this._pingPongRenderTarget.dispose();
  9543. this._renderer.setRenderTarget(_oldTarget);
  9544. outputTarget.scissorTest = false;
  9545. _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
  9546. }
  9547. _fromTexture(texture) {
  9548. _oldTarget = this._renderer.getRenderTarget();
  9549. const cubeUVRenderTarget = this._allocateTargets(texture);
  9550. this._textureToCubeUV(texture, cubeUVRenderTarget);
  9551. this._applyPMREM(cubeUVRenderTarget);
  9552. this._cleanup(cubeUVRenderTarget);
  9553. return cubeUVRenderTarget;
  9554. }
  9555. _allocateTargets(texture) {
  9556. // warning: null texture is valid
  9557. const params = {
  9558. magFilter: LinearFilter,
  9559. minFilter: LinearFilter,
  9560. generateMipmaps: false,
  9561. type: HalfFloatType,
  9562. format: RGBAFormat,
  9563. encoding: LinearEncoding,
  9564. depthBuffer: false
  9565. };
  9566. const cubeUVRenderTarget = _createRenderTarget(params);
  9567. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  9568. this._pingPongRenderTarget = _createRenderTarget(params);
  9569. return cubeUVRenderTarget;
  9570. }
  9571. _compileMaterial(material) {
  9572. const tmpMesh = new Mesh(_lodPlanes[0], material);
  9573. this._renderer.compile(tmpMesh, _flatCamera);
  9574. }
  9575. _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  9576. const fov = 90;
  9577. const aspect = 1;
  9578. const cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  9579. const upSign = [1, -1, 1, 1, 1, 1];
  9580. const forwardSign = [1, 1, 1, -1, -1, -1];
  9581. const renderer = this._renderer;
  9582. const originalAutoClear = renderer.autoClear;
  9583. const toneMapping = renderer.toneMapping;
  9584. renderer.getClearColor(_clearColor);
  9585. renderer.toneMapping = NoToneMapping;
  9586. renderer.autoClear = false;
  9587. const backgroundMaterial = new MeshBasicMaterial({
  9588. name: 'PMREM.Background',
  9589. side: BackSide,
  9590. depthWrite: false,
  9591. depthTest: false
  9592. });
  9593. const backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial);
  9594. let useSolidColor = false;
  9595. const background = scene.background;
  9596. if (background) {
  9597. if (background.isColor) {
  9598. backgroundMaterial.color.copy(background);
  9599. scene.background = null;
  9600. useSolidColor = true;
  9601. }
  9602. } else {
  9603. backgroundMaterial.color.copy(_clearColor);
  9604. useSolidColor = true;
  9605. }
  9606. for (let i = 0; i < 6; i++) {
  9607. const col = i % 3;
  9608. if (col == 0) {
  9609. cubeCamera.up.set(0, upSign[i], 0);
  9610. cubeCamera.lookAt(forwardSign[i], 0, 0);
  9611. } else if (col == 1) {
  9612. cubeCamera.up.set(0, 0, upSign[i]);
  9613. cubeCamera.lookAt(0, forwardSign[i], 0);
  9614. } else {
  9615. cubeCamera.up.set(0, upSign[i], 0);
  9616. cubeCamera.lookAt(0, 0, forwardSign[i]);
  9617. }
  9618. _setViewport(cubeUVRenderTarget, col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX);
  9619. renderer.setRenderTarget(cubeUVRenderTarget);
  9620. if (useSolidColor) {
  9621. renderer.render(backgroundBox, cubeCamera);
  9622. }
  9623. renderer.render(scene, cubeCamera);
  9624. }
  9625. backgroundBox.geometry.dispose();
  9626. backgroundBox.material.dispose();
  9627. renderer.toneMapping = toneMapping;
  9628. renderer.autoClear = originalAutoClear;
  9629. scene.background = background;
  9630. }
  9631. _setEncoding(uniform, texture) {
  9632. if (this._renderer.capabilities.isWebGL2 === true && texture.format === RGBAFormat && texture.type === UnsignedByteType && texture.encoding === sRGBEncoding) {
  9633. uniform.value = ENCODINGS[LinearEncoding];
  9634. } else {
  9635. uniform.value = ENCODINGS[texture.encoding];
  9636. }
  9637. }
  9638. _textureToCubeUV(texture, cubeUVRenderTarget) {
  9639. const renderer = this._renderer;
  9640. const isCubeTexture = texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping;
  9641. if (isCubeTexture) {
  9642. if (this._cubemapShader == null) {
  9643. this._cubemapShader = _getCubemapShader();
  9644. }
  9645. } else {
  9646. if (this._equirectShader == null) {
  9647. this._equirectShader = _getEquirectShader();
  9648. }
  9649. }
  9650. const material = isCubeTexture ? this._cubemapShader : this._equirectShader;
  9651. const mesh = new Mesh(_lodPlanes[0], material);
  9652. const uniforms = material.uniforms;
  9653. uniforms['envMap'].value = texture;
  9654. if (!isCubeTexture) {
  9655. uniforms['texelSize'].value.set(1.0 / texture.image.width, 1.0 / texture.image.height);
  9656. }
  9657. this._setEncoding(uniforms['inputEncoding'], texture);
  9658. _setViewport(cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX);
  9659. renderer.setRenderTarget(cubeUVRenderTarget);
  9660. renderer.render(mesh, _flatCamera);
  9661. }
  9662. _applyPMREM(cubeUVRenderTarget) {
  9663. const renderer = this._renderer;
  9664. const autoClear = renderer.autoClear;
  9665. renderer.autoClear = false;
  9666. for (let i = 1; i < TOTAL_LODS; i++) {
  9667. const sigma = Math.sqrt(_sigmas[i] * _sigmas[i] - _sigmas[i - 1] * _sigmas[i - 1]);
  9668. const poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  9669. this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  9670. }
  9671. renderer.autoClear = autoClear;
  9672. }
  9673. /**
  9674. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9675. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9676. * the blur latitudinally (around the poles), and then longitudinally (towards
  9677. * the poles) to approximate the orthogonally-separable blur. It is least
  9678. * accurate at the poles, but still does a decent job.
  9679. */
  9680. _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  9681. const pingPongRenderTarget = this._pingPongRenderTarget;
  9682. this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  9683. this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  9684. }
  9685. _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  9686. const renderer = this._renderer;
  9687. const blurMaterial = this._blurMaterial;
  9688. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  9689. console.error('blur direction must be either latitudinal or longitudinal!');
  9690. } // Number of standard deviations at which to cut off the discrete approximation.
  9691. const STANDARD_DEVIATIONS = 3;
  9692. const blurMesh = new Mesh(_lodPlanes[lodOut], blurMaterial);
  9693. const blurUniforms = blurMaterial.uniforms;
  9694. const pixels = _sizeLods[lodIn] - 1;
  9695. const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  9696. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9697. const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  9698. if (samples > MAX_SAMPLES) {
  9699. console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
  9700. }
  9701. const weights = [];
  9702. let sum = 0;
  9703. for (let i = 0; i < MAX_SAMPLES; ++i) {
  9704. const x = i / sigmaPixels;
  9705. const weight = Math.exp(-x * x / 2);
  9706. weights.push(weight);
  9707. if (i == 0) {
  9708. sum += weight;
  9709. } else if (i < samples) {
  9710. sum += 2 * weight;
  9711. }
  9712. }
  9713. for (let i = 0; i < weights.length; i++) {
  9714. weights[i] = weights[i] / sum;
  9715. }
  9716. blurUniforms['envMap'].value = targetIn.texture;
  9717. blurUniforms['samples'].value = samples;
  9718. blurUniforms['weights'].value = weights;
  9719. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  9720. if (poleAxis) {
  9721. blurUniforms['poleAxis'].value = poleAxis;
  9722. }
  9723. blurUniforms['dTheta'].value = radiansPerPixel;
  9724. blurUniforms['mipInt'].value = LOD_MAX - lodIn;
  9725. const outputSize = _sizeLods[lodOut];
  9726. const x = 3 * Math.max(0, SIZE_MAX - 2 * outputSize);
  9727. const y = (lodOut === 0 ? 0 : 2 * SIZE_MAX) + 2 * outputSize * (lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0);
  9728. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  9729. renderer.setRenderTarget(targetOut);
  9730. renderer.render(blurMesh, _flatCamera);
  9731. }
  9732. }
  9733. function _createPlanes() {
  9734. const _lodPlanes = [];
  9735. const _sizeLods = [];
  9736. const _sigmas = [];
  9737. let lod = LOD_MAX;
  9738. for (let i = 0; i < TOTAL_LODS; i++) {
  9739. const sizeLod = Math.pow(2, lod);
  9740. _sizeLods.push(sizeLod);
  9741. let sigma = 1.0 / sizeLod;
  9742. if (i > LOD_MAX - LOD_MIN) {
  9743. sigma = EXTRA_LOD_SIGMA[i - LOD_MAX + LOD_MIN - 1];
  9744. } else if (i == 0) {
  9745. sigma = 0;
  9746. }
  9747. _sigmas.push(sigma);
  9748. const texelSize = 1.0 / (sizeLod - 1);
  9749. const min = -texelSize / 2;
  9750. const max = 1 + texelSize / 2;
  9751. const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  9752. const cubeFaces = 6;
  9753. const vertices = 6;
  9754. const positionSize = 3;
  9755. const uvSize = 2;
  9756. const faceIndexSize = 1;
  9757. const position = new Float32Array(positionSize * vertices * cubeFaces);
  9758. const uv = new Float32Array(uvSize * vertices * cubeFaces);
  9759. const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  9760. for (let face = 0; face < cubeFaces; face++) {
  9761. const x = face % 3 * 2 / 3 - 1;
  9762. const y = face > 2 ? 0 : -1;
  9763. const coordinates = [x, y, 0, x + 2 / 3, y, 0, x + 2 / 3, y + 1, 0, x, y, 0, x + 2 / 3, y + 1, 0, x, y + 1, 0];
  9764. position.set(coordinates, positionSize * vertices * face);
  9765. uv.set(uv1, uvSize * vertices * face);
  9766. const fill = [face, face, face, face, face, face];
  9767. faceIndex.set(fill, faceIndexSize * vertices * face);
  9768. }
  9769. const planes = new BufferGeometry();
  9770. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  9771. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  9772. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  9773. _lodPlanes.push(planes);
  9774. if (lod > LOD_MIN) {
  9775. lod--;
  9776. }
  9777. }
  9778. return {
  9779. _lodPlanes,
  9780. _sizeLods,
  9781. _sigmas
  9782. };
  9783. }
  9784. function _createRenderTarget(params) {
  9785. const cubeUVRenderTarget = new WebGLRenderTarget(3 * SIZE_MAX, 3 * SIZE_MAX, params);
  9786. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9787. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9788. cubeUVRenderTarget.scissorTest = true;
  9789. return cubeUVRenderTarget;
  9790. }
  9791. function _setViewport(target, x, y, width, height) {
  9792. target.viewport.set(x, y, width, height);
  9793. target.scissor.set(x, y, width, height);
  9794. }
  9795. function _getBlurShader(maxSamples) {
  9796. const weights = new Float32Array(maxSamples);
  9797. const poleAxis = new Vector3(0, 1, 0);
  9798. const shaderMaterial = new RawShaderMaterial({
  9799. name: 'SphericalGaussianBlur',
  9800. defines: {
  9801. 'n': maxSamples
  9802. },
  9803. uniforms: {
  9804. 'envMap': {
  9805. value: null
  9806. },
  9807. 'samples': {
  9808. value: 1
  9809. },
  9810. 'weights': {
  9811. value: weights
  9812. },
  9813. 'latitudinal': {
  9814. value: false
  9815. },
  9816. 'dTheta': {
  9817. value: 0
  9818. },
  9819. 'mipInt': {
  9820. value: 0
  9821. },
  9822. 'poleAxis': {
  9823. value: poleAxis
  9824. }
  9825. },
  9826. vertexShader: _getCommonVertexShader(),
  9827. fragmentShader:
  9828. /* glsl */
  9829. `
  9830. precision mediump float;
  9831. precision mediump int;
  9832. varying vec3 vOutputDirection;
  9833. uniform sampler2D envMap;
  9834. uniform int samples;
  9835. uniform float weights[ n ];
  9836. uniform bool latitudinal;
  9837. uniform float dTheta;
  9838. uniform float mipInt;
  9839. uniform vec3 poleAxis;
  9840. ${_getEncodings()}
  9841. #define ENVMAP_TYPE_CUBE_UV
  9842. #include <cube_uv_reflection_fragment>
  9843. vec3 getSample( float theta, vec3 axis ) {
  9844. float cosTheta = cos( theta );
  9845. // Rodrigues' axis-angle rotation
  9846. vec3 sampleDirection = vOutputDirection * cosTheta
  9847. + cross( axis, vOutputDirection ) * sin( theta )
  9848. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9849. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  9850. }
  9851. void main() {
  9852. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  9853. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  9854. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  9855. }
  9856. axis = normalize( axis );
  9857. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9858. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  9859. for ( int i = 1; i < n; i++ ) {
  9860. if ( i >= samples ) {
  9861. break;
  9862. }
  9863. float theta = dTheta * float( i );
  9864. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  9865. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  9866. }
  9867. }
  9868. `,
  9869. blending: NoBlending,
  9870. depthTest: false,
  9871. depthWrite: false
  9872. });
  9873. return shaderMaterial;
  9874. }
  9875. function _getEquirectShader() {
  9876. const texelSize = new Vector2(1, 1);
  9877. const shaderMaterial = new RawShaderMaterial({
  9878. name: 'EquirectangularToCubeUV',
  9879. uniforms: {
  9880. 'envMap': {
  9881. value: null
  9882. },
  9883. 'texelSize': {
  9884. value: texelSize
  9885. },
  9886. 'inputEncoding': {
  9887. value: ENCODINGS[LinearEncoding]
  9888. }
  9889. },
  9890. vertexShader: _getCommonVertexShader(),
  9891. fragmentShader:
  9892. /* glsl */
  9893. `
  9894. precision mediump float;
  9895. precision mediump int;
  9896. varying vec3 vOutputDirection;
  9897. uniform sampler2D envMap;
  9898. uniform vec2 texelSize;
  9899. ${_getEncodings()}
  9900. #include <common>
  9901. void main() {
  9902. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9903. vec3 outputDirection = normalize( vOutputDirection );
  9904. vec2 uv = equirectUv( outputDirection );
  9905. vec2 f = fract( uv / texelSize - 0.5 );
  9906. uv -= f * texelSize;
  9907. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9908. uv.x += texelSize.x;
  9909. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9910. uv.y += texelSize.y;
  9911. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9912. uv.x -= texelSize.x;
  9913. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9914. vec3 tm = mix( tl, tr, f.x );
  9915. vec3 bm = mix( bl, br, f.x );
  9916. gl_FragColor.rgb = mix( tm, bm, f.y );
  9917. }
  9918. `,
  9919. blending: NoBlending,
  9920. depthTest: false,
  9921. depthWrite: false
  9922. });
  9923. return shaderMaterial;
  9924. }
  9925. function _getCubemapShader() {
  9926. const shaderMaterial = new RawShaderMaterial({
  9927. name: 'CubemapToCubeUV',
  9928. uniforms: {
  9929. 'envMap': {
  9930. value: null
  9931. },
  9932. 'inputEncoding': {
  9933. value: ENCODINGS[LinearEncoding]
  9934. }
  9935. },
  9936. vertexShader: _getCommonVertexShader(),
  9937. fragmentShader:
  9938. /* glsl */
  9939. `
  9940. precision mediump float;
  9941. precision mediump int;
  9942. varying vec3 vOutputDirection;
  9943. uniform samplerCube envMap;
  9944. ${_getEncodings()}
  9945. void main() {
  9946. gl_FragColor = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) );
  9947. }
  9948. `,
  9949. blending: NoBlending,
  9950. depthTest: false,
  9951. depthWrite: false
  9952. });
  9953. return shaderMaterial;
  9954. }
  9955. function _getCommonVertexShader() {
  9956. return (
  9957. /* glsl */
  9958. `
  9959. precision mediump float;
  9960. precision mediump int;
  9961. attribute vec3 position;
  9962. attribute vec2 uv;
  9963. attribute float faceIndex;
  9964. varying vec3 vOutputDirection;
  9965. // RH coordinate system; PMREM face-indexing convention
  9966. vec3 getDirection( vec2 uv, float face ) {
  9967. uv = 2.0 * uv - 1.0;
  9968. vec3 direction = vec3( uv, 1.0 );
  9969. if ( face == 0.0 ) {
  9970. direction = direction.zyx; // ( 1, v, u ) pos x
  9971. } else if ( face == 1.0 ) {
  9972. direction = direction.xzy;
  9973. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  9974. } else if ( face == 2.0 ) {
  9975. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  9976. } else if ( face == 3.0 ) {
  9977. direction = direction.zyx;
  9978. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  9979. } else if ( face == 4.0 ) {
  9980. direction = direction.xzy;
  9981. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  9982. } else if ( face == 5.0 ) {
  9983. direction.z *= -1.0; // ( u, v, -1 ) neg z
  9984. }
  9985. return direction;
  9986. }
  9987. void main() {
  9988. vOutputDirection = getDirection( uv, faceIndex );
  9989. gl_Position = vec4( position, 1.0 );
  9990. }
  9991. `
  9992. );
  9993. }
  9994. function _getEncodings() {
  9995. return (
  9996. /* glsl */
  9997. `
  9998. uniform int inputEncoding;
  9999. #include <encodings_pars_fragment>
  10000. vec4 inputTexelToLinear( vec4 value ) {
  10001. if ( inputEncoding == 0 ) {
  10002. return value;
  10003. } else if ( inputEncoding == 1 ) {
  10004. return sRGBToLinear( value );
  10005. } else if ( inputEncoding == 2 ) {
  10006. return RGBEToLinear( value );
  10007. } else if ( inputEncoding == 3 ) {
  10008. return RGBMToLinear( value, 7.0 );
  10009. } else if ( inputEncoding == 4 ) {
  10010. return RGBMToLinear( value, 16.0 );
  10011. } else if ( inputEncoding == 5 ) {
  10012. return RGBDToLinear( value, 256.0 );
  10013. } else {
  10014. return GammaToLinear( value, 2.2 );
  10015. }
  10016. }
  10017. vec4 envMapTexelToLinear( vec4 color ) {
  10018. return inputTexelToLinear( color );
  10019. }
  10020. `
  10021. );
  10022. }
  10023. function WebGLCubeUVMaps(renderer) {
  10024. let cubeUVmaps = new WeakMap();
  10025. let pmremGenerator = null;
  10026. function get(texture) {
  10027. if (texture && texture.isTexture && texture.isRenderTargetTexture === false) {
  10028. const mapping = texture.mapping;
  10029. const isEquirectMap = mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping;
  10030. const isCubeMap = mapping === CubeReflectionMapping || mapping === CubeRefractionMapping;
  10031. if (isEquirectMap || isCubeMap) {
  10032. // equirect/cube map to cubeUV conversion
  10033. if (cubeUVmaps.has(texture)) {
  10034. return cubeUVmaps.get(texture).texture;
  10035. } else {
  10036. const image = texture.image;
  10037. if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) {
  10038. const currentRenderTarget = renderer.getRenderTarget();
  10039. if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer);
  10040. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture);
  10041. cubeUVmaps.set(texture, renderTarget);
  10042. renderer.setRenderTarget(currentRenderTarget);
  10043. texture.addEventListener('dispose', onTextureDispose);
  10044. return renderTarget.texture;
  10045. } else {
  10046. // image not yet ready. try the conversion next frame
  10047. return null;
  10048. }
  10049. }
  10050. }
  10051. }
  10052. return texture;
  10053. }
  10054. function isCubeTextureComplete(image) {
  10055. let count = 0;
  10056. const length = 6;
  10057. for (let i = 0; i < length; i++) {
  10058. if (image[i] !== undefined) count++;
  10059. }
  10060. return count === length;
  10061. }
  10062. function onTextureDispose(event) {
  10063. const texture = event.target;
  10064. texture.removeEventListener('dispose', onTextureDispose);
  10065. const cubemapUV = cubeUVmaps.get(texture);
  10066. if (cubemapUV !== undefined) {
  10067. cubeUVmaps.delete(texture);
  10068. cubemapUV.dispose();
  10069. }
  10070. }
  10071. function dispose() {
  10072. cubeUVmaps = new WeakMap();
  10073. if (pmremGenerator !== null) {
  10074. pmremGenerator.dispose();
  10075. pmremGenerator = null;
  10076. }
  10077. }
  10078. return {
  10079. get: get,
  10080. dispose: dispose
  10081. };
  10082. }
  10083. function WebGLExtensions(gl) {
  10084. const extensions = {};
  10085. function getExtension(name) {
  10086. if (extensions[name] !== undefined) {
  10087. return extensions[name];
  10088. }
  10089. let extension;
  10090. switch (name) {
  10091. case 'WEBGL_depth_texture':
  10092. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  10093. break;
  10094. case 'EXT_texture_filter_anisotropic':
  10095. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  10096. break;
  10097. case 'WEBGL_compressed_texture_s3tc':
  10098. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10099. break;
  10100. case 'WEBGL_compressed_texture_pvrtc':
  10101. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10102. break;
  10103. default:
  10104. extension = gl.getExtension(name);
  10105. }
  10106. extensions[name] = extension;
  10107. return extension;
  10108. }
  10109. return {
  10110. has: function (name) {
  10111. return getExtension(name) !== null;
  10112. },
  10113. init: function (capabilities) {
  10114. if (capabilities.isWebGL2) {
  10115. getExtension('EXT_color_buffer_float');
  10116. } else {
  10117. getExtension('WEBGL_depth_texture');
  10118. getExtension('OES_texture_float');
  10119. getExtension('OES_texture_half_float');
  10120. getExtension('OES_texture_half_float_linear');
  10121. getExtension('OES_standard_derivatives');
  10122. getExtension('OES_element_index_uint');
  10123. getExtension('OES_vertex_array_object');
  10124. getExtension('ANGLE_instanced_arrays');
  10125. }
  10126. getExtension('OES_texture_float_linear');
  10127. getExtension('EXT_color_buffer_half_float');
  10128. getExtension('WEBGL_multisampled_render_to_texture');
  10129. },
  10130. get: function (name) {
  10131. const extension = getExtension(name);
  10132. if (extension === null) {
  10133. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  10134. }
  10135. return extension;
  10136. }
  10137. };
  10138. }
  10139. function WebGLGeometries(gl, attributes, info, bindingStates) {
  10140. const geometries = {};
  10141. const wireframeAttributes = new WeakMap();
  10142. function onGeometryDispose(event) {
  10143. const geometry = event.target;
  10144. if (geometry.index !== null) {
  10145. attributes.remove(geometry.index);
  10146. }
  10147. for (const name in geometry.attributes) {
  10148. attributes.remove(geometry.attributes[name]);
  10149. }
  10150. geometry.removeEventListener('dispose', onGeometryDispose);
  10151. delete geometries[geometry.id];
  10152. const attribute = wireframeAttributes.get(geometry);
  10153. if (attribute) {
  10154. attributes.remove(attribute);
  10155. wireframeAttributes.delete(geometry);
  10156. }
  10157. bindingStates.releaseStatesOfGeometry(geometry);
  10158. if (geometry.isInstancedBufferGeometry === true) {
  10159. delete geometry._maxInstanceCount;
  10160. } //
  10161. info.memory.geometries--;
  10162. }
  10163. function get(object, geometry) {
  10164. if (geometries[geometry.id] === true) return geometry;
  10165. geometry.addEventListener('dispose', onGeometryDispose);
  10166. geometries[geometry.id] = true;
  10167. info.memory.geometries++;
  10168. return geometry;
  10169. }
  10170. function update(geometry) {
  10171. const geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates.
  10172. for (const name in geometryAttributes) {
  10173. attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER);
  10174. } // morph targets
  10175. const morphAttributes = geometry.morphAttributes;
  10176. for (const name in morphAttributes) {
  10177. const array = morphAttributes[name];
  10178. for (let i = 0, l = array.length; i < l; i++) {
  10179. attributes.update(array[i], gl.ARRAY_BUFFER);
  10180. }
  10181. }
  10182. }
  10183. function updateWireframeAttribute(geometry) {
  10184. const indices = [];
  10185. const geometryIndex = geometry.index;
  10186. const geometryPosition = geometry.attributes.position;
  10187. let version = 0;
  10188. if (geometryIndex !== null) {
  10189. const array = geometryIndex.array;
  10190. version = geometryIndex.version;
  10191. for (let i = 0, l = array.length; i < l; i += 3) {
  10192. const a = array[i + 0];
  10193. const b = array[i + 1];
  10194. const c = array[i + 2];
  10195. indices.push(a, b, b, c, c, a);
  10196. }
  10197. } else {
  10198. const array = geometryPosition.array;
  10199. version = geometryPosition.version;
  10200. for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  10201. const a = i + 0;
  10202. const b = i + 1;
  10203. const c = i + 2;
  10204. indices.push(a, b, b, c, c, a);
  10205. }
  10206. }
  10207. const attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  10208. attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
  10209. //
  10210. const previousAttribute = wireframeAttributes.get(geometry);
  10211. if (previousAttribute) attributes.remove(previousAttribute); //
  10212. wireframeAttributes.set(geometry, attribute);
  10213. }
  10214. function getWireframeAttribute(geometry) {
  10215. const currentAttribute = wireframeAttributes.get(geometry);
  10216. if (currentAttribute) {
  10217. const geometryIndex = geometry.index;
  10218. if (geometryIndex !== null) {
  10219. // if the attribute is obsolete, create a new one
  10220. if (currentAttribute.version < geometryIndex.version) {
  10221. updateWireframeAttribute(geometry);
  10222. }
  10223. }
  10224. } else {
  10225. updateWireframeAttribute(geometry);
  10226. }
  10227. return wireframeAttributes.get(geometry);
  10228. }
  10229. return {
  10230. get: get,
  10231. update: update,
  10232. getWireframeAttribute: getWireframeAttribute
  10233. };
  10234. }
  10235. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  10236. const isWebGL2 = capabilities.isWebGL2;
  10237. let mode;
  10238. function setMode(value) {
  10239. mode = value;
  10240. }
  10241. let type, bytesPerElement;
  10242. function setIndex(value) {
  10243. type = value.type;
  10244. bytesPerElement = value.bytesPerElement;
  10245. }
  10246. function render(start, count) {
  10247. gl.drawElements(mode, count, type, start * bytesPerElement);
  10248. info.update(count, mode, 1);
  10249. }
  10250. function renderInstances(start, count, primcount) {
  10251. if (primcount === 0) return;
  10252. let extension, methodName;
  10253. if (isWebGL2) {
  10254. extension = gl;
  10255. methodName = 'drawElementsInstanced';
  10256. } else {
  10257. extension = extensions.get('ANGLE_instanced_arrays');
  10258. methodName = 'drawElementsInstancedANGLE';
  10259. if (extension === null) {
  10260. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  10261. return;
  10262. }
  10263. }
  10264. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  10265. info.update(count, mode, primcount);
  10266. } //
  10267. this.setMode = setMode;
  10268. this.setIndex = setIndex;
  10269. this.render = render;
  10270. this.renderInstances = renderInstances;
  10271. }
  10272. function WebGLInfo(gl) {
  10273. const memory = {
  10274. geometries: 0,
  10275. textures: 0
  10276. };
  10277. const render = {
  10278. frame: 0,
  10279. calls: 0,
  10280. triangles: 0,
  10281. points: 0,
  10282. lines: 0
  10283. };
  10284. function update(count, mode, instanceCount) {
  10285. render.calls++;
  10286. switch (mode) {
  10287. case gl.TRIANGLES:
  10288. render.triangles += instanceCount * (count / 3);
  10289. break;
  10290. case gl.LINES:
  10291. render.lines += instanceCount * (count / 2);
  10292. break;
  10293. case gl.LINE_STRIP:
  10294. render.lines += instanceCount * (count - 1);
  10295. break;
  10296. case gl.LINE_LOOP:
  10297. render.lines += instanceCount * count;
  10298. break;
  10299. case gl.POINTS:
  10300. render.points += instanceCount * count;
  10301. break;
  10302. default:
  10303. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  10304. break;
  10305. }
  10306. }
  10307. function reset() {
  10308. render.frame++;
  10309. render.calls = 0;
  10310. render.triangles = 0;
  10311. render.points = 0;
  10312. render.lines = 0;
  10313. }
  10314. return {
  10315. memory: memory,
  10316. render: render,
  10317. programs: null,
  10318. autoReset: true,
  10319. reset: reset,
  10320. update: update
  10321. };
  10322. }
  10323. class DataTexture2DArray extends Texture {
  10324. constructor(data = null, width = 1, height = 1, depth = 1) {
  10325. super(null);
  10326. this.image = {
  10327. data,
  10328. width,
  10329. height,
  10330. depth
  10331. };
  10332. this.magFilter = NearestFilter;
  10333. this.minFilter = NearestFilter;
  10334. this.wrapR = ClampToEdgeWrapping;
  10335. this.generateMipmaps = false;
  10336. this.flipY = false;
  10337. this.unpackAlignment = 1;
  10338. }
  10339. }
  10340. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  10341. function numericalSort(a, b) {
  10342. return a[0] - b[0];
  10343. }
  10344. function absNumericalSort(a, b) {
  10345. return Math.abs(b[1]) - Math.abs(a[1]);
  10346. }
  10347. function denormalize(morph, attribute) {
  10348. let denominator = 1;
  10349. const array = attribute.isInterleavedBufferAttribute ? attribute.data.array : attribute.array;
  10350. if (array instanceof Int8Array) denominator = 127;else if (array instanceof Int16Array) denominator = 32767;else if (array instanceof Int32Array) denominator = 2147483647;else console.error('THREE.WebGLMorphtargets: Unsupported morph attribute data type: ', array);
  10351. morph.divideScalar(denominator);
  10352. }
  10353. function WebGLMorphtargets(gl, capabilities, textures) {
  10354. const influencesList = {};
  10355. const morphInfluences = new Float32Array(8);
  10356. const morphTextures = new WeakMap();
  10357. const morph = new Vector3();
  10358. const workInfluences = [];
  10359. for (let i = 0; i < 8; i++) {
  10360. workInfluences[i] = [i, 0];
  10361. }
  10362. function update(object, geometry, material, program) {
  10363. const objectInfluences = object.morphTargetInfluences;
  10364. if (capabilities.isWebGL2 === true) {
  10365. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10366. // into an array of data textures. Each layer represents a single morph target.
  10367. const numberOfMorphTargets = geometry.morphAttributes.position.length;
  10368. let entry = morphTextures.get(geometry);
  10369. if (entry === undefined || entry.count !== numberOfMorphTargets) {
  10370. if (entry !== undefined) entry.texture.dispose();
  10371. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10372. const morphTargets = geometry.morphAttributes.position;
  10373. const morphNormals = geometry.morphAttributes.normal || [];
  10374. const numberOfVertices = geometry.attributes.position.count;
  10375. const numberOfVertexData = hasMorphNormals === true ? 2 : 1; // (v,n) vs. (v)
  10376. let width = numberOfVertices * numberOfVertexData;
  10377. let height = 1;
  10378. if (width > capabilities.maxTextureSize) {
  10379. height = Math.ceil(width / capabilities.maxTextureSize);
  10380. width = capabilities.maxTextureSize;
  10381. }
  10382. const buffer = new Float32Array(width * height * 4 * numberOfMorphTargets);
  10383. const texture = new DataTexture2DArray(buffer, width, height, numberOfMorphTargets);
  10384. texture.format = RGBAFormat; // using RGBA since RGB might be emulated (and is thus slower)
  10385. texture.type = FloatType;
  10386. texture.needsUpdate = true; // fill buffer
  10387. const vertexDataStride = numberOfVertexData * 4;
  10388. for (let i = 0; i < numberOfMorphTargets; i++) {
  10389. const morphTarget = morphTargets[i];
  10390. const morphNormal = morphNormals[i];
  10391. const offset = width * height * 4 * i;
  10392. for (let j = 0; j < morphTarget.count; j++) {
  10393. morph.fromBufferAttribute(morphTarget, j);
  10394. if (morphTarget.normalized === true) denormalize(morph, morphTarget);
  10395. const stride = j * vertexDataStride;
  10396. buffer[offset + stride + 0] = morph.x;
  10397. buffer[offset + stride + 1] = morph.y;
  10398. buffer[offset + stride + 2] = morph.z;
  10399. buffer[offset + stride + 3] = 0;
  10400. if (hasMorphNormals === true) {
  10401. morph.fromBufferAttribute(morphNormal, j);
  10402. if (morphNormal.normalized === true) denormalize(morph, morphNormal);
  10403. buffer[offset + stride + 4] = morph.x;
  10404. buffer[offset + stride + 5] = morph.y;
  10405. buffer[offset + stride + 6] = morph.z;
  10406. buffer[offset + stride + 7] = 0;
  10407. }
  10408. }
  10409. }
  10410. entry = {
  10411. count: numberOfMorphTargets,
  10412. texture: texture,
  10413. size: new Vector2(width, height)
  10414. };
  10415. morphTextures.set(geometry, entry);
  10416. } //
  10417. let morphInfluencesSum = 0;
  10418. for (let i = 0; i < objectInfluences.length; i++) {
  10419. morphInfluencesSum += objectInfluences[i];
  10420. }
  10421. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10422. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10423. program.getUniforms().setValue(gl, 'morphTargetInfluences', objectInfluences);
  10424. program.getUniforms().setValue(gl, 'morphTargetsTexture', entry.texture, textures);
  10425. program.getUniforms().setValue(gl, 'morphTargetsTextureSize', entry.size);
  10426. } else {
  10427. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10428. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10429. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10430. let influences = influencesList[geometry.id];
  10431. if (influences === undefined || influences.length !== length) {
  10432. // initialise list
  10433. influences = [];
  10434. for (let i = 0; i < length; i++) {
  10435. influences[i] = [i, 0];
  10436. }
  10437. influencesList[geometry.id] = influences;
  10438. } // Collect influences
  10439. for (let i = 0; i < length; i++) {
  10440. const influence = influences[i];
  10441. influence[0] = i;
  10442. influence[1] = objectInfluences[i];
  10443. }
  10444. influences.sort(absNumericalSort);
  10445. for (let i = 0; i < 8; i++) {
  10446. if (i < length && influences[i][1]) {
  10447. workInfluences[i][0] = influences[i][0];
  10448. workInfluences[i][1] = influences[i][1];
  10449. } else {
  10450. workInfluences[i][0] = Number.MAX_SAFE_INTEGER;
  10451. workInfluences[i][1] = 0;
  10452. }
  10453. }
  10454. workInfluences.sort(numericalSort);
  10455. const morphTargets = geometry.morphAttributes.position;
  10456. const morphNormals = geometry.morphAttributes.normal;
  10457. let morphInfluencesSum = 0;
  10458. for (let i = 0; i < 8; i++) {
  10459. const influence = workInfluences[i];
  10460. const index = influence[0];
  10461. const value = influence[1];
  10462. if (index !== Number.MAX_SAFE_INTEGER && value) {
  10463. if (morphTargets && geometry.getAttribute('morphTarget' + i) !== morphTargets[index]) {
  10464. geometry.setAttribute('morphTarget' + i, morphTargets[index]);
  10465. }
  10466. if (morphNormals && geometry.getAttribute('morphNormal' + i) !== morphNormals[index]) {
  10467. geometry.setAttribute('morphNormal' + i, morphNormals[index]);
  10468. }
  10469. morphInfluences[i] = value;
  10470. morphInfluencesSum += value;
  10471. } else {
  10472. if (morphTargets && geometry.hasAttribute('morphTarget' + i) === true) {
  10473. geometry.deleteAttribute('morphTarget' + i);
  10474. }
  10475. if (morphNormals && geometry.hasAttribute('morphNormal' + i) === true) {
  10476. geometry.deleteAttribute('morphNormal' + i);
  10477. }
  10478. morphInfluences[i] = 0;
  10479. }
  10480. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10481. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10482. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10483. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10484. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10485. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  10486. }
  10487. }
  10488. return {
  10489. update: update
  10490. };
  10491. }
  10492. function WebGLObjects(gl, geometries, attributes, info) {
  10493. let updateMap = new WeakMap();
  10494. function update(object) {
  10495. const frame = info.render.frame;
  10496. const geometry = object.geometry;
  10497. const buffergeometry = geometries.get(object, geometry); // Update once per frame
  10498. if (updateMap.get(buffergeometry) !== frame) {
  10499. geometries.update(buffergeometry);
  10500. updateMap.set(buffergeometry, frame);
  10501. }
  10502. if (object.isInstancedMesh) {
  10503. if (object.hasEventListener('dispose', onInstancedMeshDispose) === false) {
  10504. object.addEventListener('dispose', onInstancedMeshDispose);
  10505. }
  10506. attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER);
  10507. if (object.instanceColor !== null) {
  10508. attributes.update(object.instanceColor, gl.ARRAY_BUFFER);
  10509. }
  10510. }
  10511. return buffergeometry;
  10512. }
  10513. function dispose() {
  10514. updateMap = new WeakMap();
  10515. }
  10516. function onInstancedMeshDispose(event) {
  10517. const instancedMesh = event.target;
  10518. instancedMesh.removeEventListener('dispose', onInstancedMeshDispose);
  10519. attributes.remove(instancedMesh.instanceMatrix);
  10520. if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor);
  10521. }
  10522. return {
  10523. update: update,
  10524. dispose: dispose
  10525. };
  10526. }
  10527. class DataTexture3D extends Texture {
  10528. constructor(data = null, width = 1, height = 1, depth = 1) {
  10529. // We're going to add .setXXX() methods for setting properties later.
  10530. // Users can still set in DataTexture3D directly.
  10531. //
  10532. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  10533. // texture.anisotropy = 16;
  10534. //
  10535. // See #14839
  10536. super(null);
  10537. this.image = {
  10538. data,
  10539. width,
  10540. height,
  10541. depth
  10542. };
  10543. this.magFilter = NearestFilter;
  10544. this.minFilter = NearestFilter;
  10545. this.wrapR = ClampToEdgeWrapping;
  10546. this.generateMipmaps = false;
  10547. this.flipY = false;
  10548. this.unpackAlignment = 1;
  10549. }
  10550. }
  10551. DataTexture3D.prototype.isDataTexture3D = true;
  10552. /**
  10553. * Uniforms of a program.
  10554. * Those form a tree structure with a special top-level container for the root,
  10555. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10556. *
  10557. *
  10558. * Properties of inner nodes including the top-level container:
  10559. *
  10560. * .seq - array of nested uniforms
  10561. * .map - nested uniforms by name
  10562. *
  10563. *
  10564. * Methods of all nodes except the top-level container:
  10565. *
  10566. * .setValue( gl, value, [textures] )
  10567. *
  10568. * uploads a uniform value(s)
  10569. * the 'textures' parameter is needed for sampler uniforms
  10570. *
  10571. *
  10572. * Static methods of the top-level container (textures factorizations):
  10573. *
  10574. * .upload( gl, seq, values, textures )
  10575. *
  10576. * sets uniforms in 'seq' to 'values[id].value'
  10577. *
  10578. * .seqWithValue( seq, values ) : filteredSeq
  10579. *
  10580. * filters 'seq' entries with corresponding entry in values
  10581. *
  10582. *
  10583. * Methods of the top-level container (textures factorizations):
  10584. *
  10585. * .setValue( gl, name, value, textures )
  10586. *
  10587. * sets uniform with name 'name' to 'value'
  10588. *
  10589. * .setOptional( gl, obj, prop )
  10590. *
  10591. * like .set for an optional property of the object
  10592. *
  10593. */
  10594. const emptyTexture = new Texture();
  10595. const emptyTexture2dArray = new DataTexture2DArray();
  10596. const emptyTexture3d = new DataTexture3D();
  10597. const emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  10598. // Array Caches (provide typed arrays for temporary by size)
  10599. const arrayCacheF32 = [];
  10600. const arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  10601. const mat4array = new Float32Array(16);
  10602. const mat3array = new Float32Array(9);
  10603. const mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  10604. function flatten(array, nBlocks, blockSize) {
  10605. const firstElem = array[0];
  10606. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  10607. // see http://jacksondunstan.com/articles/983
  10608. const n = nBlocks * blockSize;
  10609. let r = arrayCacheF32[n];
  10610. if (r === undefined) {
  10611. r = new Float32Array(n);
  10612. arrayCacheF32[n] = r;
  10613. }
  10614. if (nBlocks !== 0) {
  10615. firstElem.toArray(r, 0);
  10616. for (let i = 1, offset = 0; i !== nBlocks; ++i) {
  10617. offset += blockSize;
  10618. array[i].toArray(r, offset);
  10619. }
  10620. }
  10621. return r;
  10622. }
  10623. function arraysEqual(a, b) {
  10624. if (a.length !== b.length) return false;
  10625. for (let i = 0, l = a.length; i < l; i++) {
  10626. if (a[i] !== b[i]) return false;
  10627. }
  10628. return true;
  10629. }
  10630. function copyArray(a, b) {
  10631. for (let i = 0, l = b.length; i < l; i++) {
  10632. a[i] = b[i];
  10633. }
  10634. } // Texture unit allocation
  10635. function allocTexUnits(textures, n) {
  10636. let r = arrayCacheI32[n];
  10637. if (r === undefined) {
  10638. r = new Int32Array(n);
  10639. arrayCacheI32[n] = r;
  10640. }
  10641. for (let i = 0; i !== n; ++i) {
  10642. r[i] = textures.allocateTextureUnit();
  10643. }
  10644. return r;
  10645. } // --- Setters ---
  10646. // Note: Defining these methods externally, because they come in a bunch
  10647. // and this way their names minify.
  10648. // Single scalar
  10649. function setValueV1f(gl, v) {
  10650. const cache = this.cache;
  10651. if (cache[0] === v) return;
  10652. gl.uniform1f(this.addr, v);
  10653. cache[0] = v;
  10654. } // Single float vector (from flat array or THREE.VectorN)
  10655. function setValueV2f(gl, v) {
  10656. const cache = this.cache;
  10657. if (v.x !== undefined) {
  10658. if (cache[0] !== v.x || cache[1] !== v.y) {
  10659. gl.uniform2f(this.addr, v.x, v.y);
  10660. cache[0] = v.x;
  10661. cache[1] = v.y;
  10662. }
  10663. } else {
  10664. if (arraysEqual(cache, v)) return;
  10665. gl.uniform2fv(this.addr, v);
  10666. copyArray(cache, v);
  10667. }
  10668. }
  10669. function setValueV3f(gl, v) {
  10670. const cache = this.cache;
  10671. if (v.x !== undefined) {
  10672. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  10673. gl.uniform3f(this.addr, v.x, v.y, v.z);
  10674. cache[0] = v.x;
  10675. cache[1] = v.y;
  10676. cache[2] = v.z;
  10677. }
  10678. } else if (v.r !== undefined) {
  10679. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  10680. gl.uniform3f(this.addr, v.r, v.g, v.b);
  10681. cache[0] = v.r;
  10682. cache[1] = v.g;
  10683. cache[2] = v.b;
  10684. }
  10685. } else {
  10686. if (arraysEqual(cache, v)) return;
  10687. gl.uniform3fv(this.addr, v);
  10688. copyArray(cache, v);
  10689. }
  10690. }
  10691. function setValueV4f(gl, v) {
  10692. const cache = this.cache;
  10693. if (v.x !== undefined) {
  10694. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  10695. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  10696. cache[0] = v.x;
  10697. cache[1] = v.y;
  10698. cache[2] = v.z;
  10699. cache[3] = v.w;
  10700. }
  10701. } else {
  10702. if (arraysEqual(cache, v)) return;
  10703. gl.uniform4fv(this.addr, v);
  10704. copyArray(cache, v);
  10705. }
  10706. } // Single matrix (from flat array or THREE.MatrixN)
  10707. function setValueM2(gl, v) {
  10708. const cache = this.cache;
  10709. const elements = v.elements;
  10710. if (elements === undefined) {
  10711. if (arraysEqual(cache, v)) return;
  10712. gl.uniformMatrix2fv(this.addr, false, v);
  10713. copyArray(cache, v);
  10714. } else {
  10715. if (arraysEqual(cache, elements)) return;
  10716. mat2array.set(elements);
  10717. gl.uniformMatrix2fv(this.addr, false, mat2array);
  10718. copyArray(cache, elements);
  10719. }
  10720. }
  10721. function setValueM3(gl, v) {
  10722. const cache = this.cache;
  10723. const elements = v.elements;
  10724. if (elements === undefined) {
  10725. if (arraysEqual(cache, v)) return;
  10726. gl.uniformMatrix3fv(this.addr, false, v);
  10727. copyArray(cache, v);
  10728. } else {
  10729. if (arraysEqual(cache, elements)) return;
  10730. mat3array.set(elements);
  10731. gl.uniformMatrix3fv(this.addr, false, mat3array);
  10732. copyArray(cache, elements);
  10733. }
  10734. }
  10735. function setValueM4(gl, v) {
  10736. const cache = this.cache;
  10737. const elements = v.elements;
  10738. if (elements === undefined) {
  10739. if (arraysEqual(cache, v)) return;
  10740. gl.uniformMatrix4fv(this.addr, false, v);
  10741. copyArray(cache, v);
  10742. } else {
  10743. if (arraysEqual(cache, elements)) return;
  10744. mat4array.set(elements);
  10745. gl.uniformMatrix4fv(this.addr, false, mat4array);
  10746. copyArray(cache, elements);
  10747. }
  10748. } // Single integer / boolean
  10749. function setValueV1i(gl, v) {
  10750. const cache = this.cache;
  10751. if (cache[0] === v) return;
  10752. gl.uniform1i(this.addr, v);
  10753. cache[0] = v;
  10754. } // Single integer / boolean vector (from flat array)
  10755. function setValueV2i(gl, v) {
  10756. const cache = this.cache;
  10757. if (arraysEqual(cache, v)) return;
  10758. gl.uniform2iv(this.addr, v);
  10759. copyArray(cache, v);
  10760. }
  10761. function setValueV3i(gl, v) {
  10762. const cache = this.cache;
  10763. if (arraysEqual(cache, v)) return;
  10764. gl.uniform3iv(this.addr, v);
  10765. copyArray(cache, v);
  10766. }
  10767. function setValueV4i(gl, v) {
  10768. const cache = this.cache;
  10769. if (arraysEqual(cache, v)) return;
  10770. gl.uniform4iv(this.addr, v);
  10771. copyArray(cache, v);
  10772. } // Single unsigned integer
  10773. function setValueV1ui(gl, v) {
  10774. const cache = this.cache;
  10775. if (cache[0] === v) return;
  10776. gl.uniform1ui(this.addr, v);
  10777. cache[0] = v;
  10778. } // Single unsigned integer vector (from flat array)
  10779. function setValueV2ui(gl, v) {
  10780. const cache = this.cache;
  10781. if (arraysEqual(cache, v)) return;
  10782. gl.uniform2uiv(this.addr, v);
  10783. copyArray(cache, v);
  10784. }
  10785. function setValueV3ui(gl, v) {
  10786. const cache = this.cache;
  10787. if (arraysEqual(cache, v)) return;
  10788. gl.uniform3uiv(this.addr, v);
  10789. copyArray(cache, v);
  10790. }
  10791. function setValueV4ui(gl, v) {
  10792. const cache = this.cache;
  10793. if (arraysEqual(cache, v)) return;
  10794. gl.uniform4uiv(this.addr, v);
  10795. copyArray(cache, v);
  10796. } // Single texture (2D / Cube)
  10797. function setValueT1(gl, v, textures) {
  10798. const cache = this.cache;
  10799. const unit = textures.allocateTextureUnit();
  10800. if (cache[0] !== unit) {
  10801. gl.uniform1i(this.addr, unit);
  10802. cache[0] = unit;
  10803. }
  10804. textures.safeSetTexture2D(v || emptyTexture, unit);
  10805. }
  10806. function setValueT3D1(gl, v, textures) {
  10807. const cache = this.cache;
  10808. const unit = textures.allocateTextureUnit();
  10809. if (cache[0] !== unit) {
  10810. gl.uniform1i(this.addr, unit);
  10811. cache[0] = unit;
  10812. }
  10813. textures.setTexture3D(v || emptyTexture3d, unit);
  10814. }
  10815. function setValueT6(gl, v, textures) {
  10816. const cache = this.cache;
  10817. const unit = textures.allocateTextureUnit();
  10818. if (cache[0] !== unit) {
  10819. gl.uniform1i(this.addr, unit);
  10820. cache[0] = unit;
  10821. }
  10822. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  10823. }
  10824. function setValueT2DArray1(gl, v, textures) {
  10825. const cache = this.cache;
  10826. const unit = textures.allocateTextureUnit();
  10827. if (cache[0] !== unit) {
  10828. gl.uniform1i(this.addr, unit);
  10829. cache[0] = unit;
  10830. }
  10831. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  10832. } // Helper to pick the right setter for the singular case
  10833. function getSingularSetter(type) {
  10834. switch (type) {
  10835. case 0x1406:
  10836. return setValueV1f;
  10837. // FLOAT
  10838. case 0x8b50:
  10839. return setValueV2f;
  10840. // _VEC2
  10841. case 0x8b51:
  10842. return setValueV3f;
  10843. // _VEC3
  10844. case 0x8b52:
  10845. return setValueV4f;
  10846. // _VEC4
  10847. case 0x8b5a:
  10848. return setValueM2;
  10849. // _MAT2
  10850. case 0x8b5b:
  10851. return setValueM3;
  10852. // _MAT3
  10853. case 0x8b5c:
  10854. return setValueM4;
  10855. // _MAT4
  10856. case 0x1404:
  10857. case 0x8b56:
  10858. return setValueV1i;
  10859. // INT, BOOL
  10860. case 0x8b53:
  10861. case 0x8b57:
  10862. return setValueV2i;
  10863. // _VEC2
  10864. case 0x8b54:
  10865. case 0x8b58:
  10866. return setValueV3i;
  10867. // _VEC3
  10868. case 0x8b55:
  10869. case 0x8b59:
  10870. return setValueV4i;
  10871. // _VEC4
  10872. case 0x1405:
  10873. return setValueV1ui;
  10874. // UINT
  10875. case 0x8dc6:
  10876. return setValueV2ui;
  10877. // _VEC2
  10878. case 0x8dc7:
  10879. return setValueV3ui;
  10880. // _VEC3
  10881. case 0x8dc8:
  10882. return setValueV4ui;
  10883. // _VEC4
  10884. case 0x8b5e: // SAMPLER_2D
  10885. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10886. case 0x8dca: // INT_SAMPLER_2D
  10887. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10888. case 0x8b62:
  10889. // SAMPLER_2D_SHADOW
  10890. return setValueT1;
  10891. case 0x8b5f: // SAMPLER_3D
  10892. case 0x8dcb: // INT_SAMPLER_3D
  10893. case 0x8dd3:
  10894. // UNSIGNED_INT_SAMPLER_3D
  10895. return setValueT3D1;
  10896. case 0x8b60: // SAMPLER_CUBE
  10897. case 0x8dcc: // INT_SAMPLER_CUBE
  10898. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10899. case 0x8dc5:
  10900. // SAMPLER_CUBE_SHADOW
  10901. return setValueT6;
  10902. case 0x8dc1: // SAMPLER_2D_ARRAY
  10903. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10904. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10905. case 0x8dc4:
  10906. // SAMPLER_2D_ARRAY_SHADOW
  10907. return setValueT2DArray1;
  10908. }
  10909. } // Array of scalars
  10910. function setValueV1fArray(gl, v) {
  10911. gl.uniform1fv(this.addr, v);
  10912. } // Array of vectors (from flat array or array of THREE.VectorN)
  10913. function setValueV2fArray(gl, v) {
  10914. const data = flatten(v, this.size, 2);
  10915. gl.uniform2fv(this.addr, data);
  10916. }
  10917. function setValueV3fArray(gl, v) {
  10918. const data = flatten(v, this.size, 3);
  10919. gl.uniform3fv(this.addr, data);
  10920. }
  10921. function setValueV4fArray(gl, v) {
  10922. const data = flatten(v, this.size, 4);
  10923. gl.uniform4fv(this.addr, data);
  10924. } // Array of matrices (from flat array or array of THREE.MatrixN)
  10925. function setValueM2Array(gl, v) {
  10926. const data = flatten(v, this.size, 4);
  10927. gl.uniformMatrix2fv(this.addr, false, data);
  10928. }
  10929. function setValueM3Array(gl, v) {
  10930. const data = flatten(v, this.size, 9);
  10931. gl.uniformMatrix3fv(this.addr, false, data);
  10932. }
  10933. function setValueM4Array(gl, v) {
  10934. const data = flatten(v, this.size, 16);
  10935. gl.uniformMatrix4fv(this.addr, false, data);
  10936. } // Array of integer / boolean
  10937. function setValueV1iArray(gl, v) {
  10938. gl.uniform1iv(this.addr, v);
  10939. } // Array of integer / boolean vectors (from flat array)
  10940. function setValueV2iArray(gl, v) {
  10941. gl.uniform2iv(this.addr, v);
  10942. }
  10943. function setValueV3iArray(gl, v) {
  10944. gl.uniform3iv(this.addr, v);
  10945. }
  10946. function setValueV4iArray(gl, v) {
  10947. gl.uniform4iv(this.addr, v);
  10948. } // Array of unsigned integer
  10949. function setValueV1uiArray(gl, v) {
  10950. gl.uniform1uiv(this.addr, v);
  10951. } // Array of unsigned integer vectors (from flat array)
  10952. function setValueV2uiArray(gl, v) {
  10953. gl.uniform2uiv(this.addr, v);
  10954. }
  10955. function setValueV3uiArray(gl, v) {
  10956. gl.uniform3uiv(this.addr, v);
  10957. }
  10958. function setValueV4uiArray(gl, v) {
  10959. gl.uniform4uiv(this.addr, v);
  10960. } // Array of textures (2D / 3D / Cube / 2DArray)
  10961. function setValueT1Array(gl, v, textures) {
  10962. const n = v.length;
  10963. const units = allocTexUnits(textures, n);
  10964. gl.uniform1iv(this.addr, units);
  10965. for (let i = 0; i !== n; ++i) {
  10966. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  10967. }
  10968. }
  10969. function setValueT3DArray(gl, v, textures) {
  10970. const n = v.length;
  10971. const units = allocTexUnits(textures, n);
  10972. gl.uniform1iv(this.addr, units);
  10973. for (let i = 0; i !== n; ++i) {
  10974. textures.setTexture3D(v[i] || emptyTexture3d, units[i]);
  10975. }
  10976. }
  10977. function setValueT6Array(gl, v, textures) {
  10978. const n = v.length;
  10979. const units = allocTexUnits(textures, n);
  10980. gl.uniform1iv(this.addr, units);
  10981. for (let i = 0; i !== n; ++i) {
  10982. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  10983. }
  10984. }
  10985. function setValueT2DArrayArray(gl, v, textures) {
  10986. const n = v.length;
  10987. const units = allocTexUnits(textures, n);
  10988. gl.uniform1iv(this.addr, units);
  10989. for (let i = 0; i !== n; ++i) {
  10990. textures.setTexture2DArray(v[i] || emptyTexture2dArray, units[i]);
  10991. }
  10992. } // Helper to pick the right setter for a pure (bottom-level) array
  10993. function getPureArraySetter(type) {
  10994. switch (type) {
  10995. case 0x1406:
  10996. return setValueV1fArray;
  10997. // FLOAT
  10998. case 0x8b50:
  10999. return setValueV2fArray;
  11000. // _VEC2
  11001. case 0x8b51:
  11002. return setValueV3fArray;
  11003. // _VEC3
  11004. case 0x8b52:
  11005. return setValueV4fArray;
  11006. // _VEC4
  11007. case 0x8b5a:
  11008. return setValueM2Array;
  11009. // _MAT2
  11010. case 0x8b5b:
  11011. return setValueM3Array;
  11012. // _MAT3
  11013. case 0x8b5c:
  11014. return setValueM4Array;
  11015. // _MAT4
  11016. case 0x1404:
  11017. case 0x8b56:
  11018. return setValueV1iArray;
  11019. // INT, BOOL
  11020. case 0x8b53:
  11021. case 0x8b57:
  11022. return setValueV2iArray;
  11023. // _VEC2
  11024. case 0x8b54:
  11025. case 0x8b58:
  11026. return setValueV3iArray;
  11027. // _VEC3
  11028. case 0x8b55:
  11029. case 0x8b59:
  11030. return setValueV4iArray;
  11031. // _VEC4
  11032. case 0x1405:
  11033. return setValueV1uiArray;
  11034. // UINT
  11035. case 0x8dc6:
  11036. return setValueV2uiArray;
  11037. // _VEC2
  11038. case 0x8dc7:
  11039. return setValueV3uiArray;
  11040. // _VEC3
  11041. case 0x8dc8:
  11042. return setValueV4uiArray;
  11043. // _VEC4
  11044. case 0x8b5e: // SAMPLER_2D
  11045. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11046. case 0x8dca: // INT_SAMPLER_2D
  11047. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11048. case 0x8b62:
  11049. // SAMPLER_2D_SHADOW
  11050. return setValueT1Array;
  11051. case 0x8b5f: // SAMPLER_3D
  11052. case 0x8dcb: // INT_SAMPLER_3D
  11053. case 0x8dd3:
  11054. // UNSIGNED_INT_SAMPLER_3D
  11055. return setValueT3DArray;
  11056. case 0x8b60: // SAMPLER_CUBE
  11057. case 0x8dcc: // INT_SAMPLER_CUBE
  11058. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11059. case 0x8dc5:
  11060. // SAMPLER_CUBE_SHADOW
  11061. return setValueT6Array;
  11062. case 0x8dc1: // SAMPLER_2D_ARRAY
  11063. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11064. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11065. case 0x8dc4:
  11066. // SAMPLER_2D_ARRAY_SHADOW
  11067. return setValueT2DArrayArray;
  11068. }
  11069. } // --- Uniform Classes ---
  11070. function SingleUniform(id, activeInfo, addr) {
  11071. this.id = id;
  11072. this.addr = addr;
  11073. this.cache = [];
  11074. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  11075. }
  11076. function PureArrayUniform(id, activeInfo, addr) {
  11077. this.id = id;
  11078. this.addr = addr;
  11079. this.cache = [];
  11080. this.size = activeInfo.size;
  11081. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  11082. }
  11083. PureArrayUniform.prototype.updateCache = function (data) {
  11084. const cache = this.cache;
  11085. if (data instanceof Float32Array && cache.length !== data.length) {
  11086. this.cache = new Float32Array(data.length);
  11087. }
  11088. copyArray(cache, data);
  11089. };
  11090. function StructuredUniform(id) {
  11091. this.id = id;
  11092. this.seq = [];
  11093. this.map = {};
  11094. }
  11095. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  11096. const seq = this.seq;
  11097. for (let i = 0, n = seq.length; i !== n; ++i) {
  11098. const u = seq[i];
  11099. u.setValue(gl, value[u.id], textures);
  11100. }
  11101. }; // --- Top-level ---
  11102. // Parser - builds up the property tree from the path strings
  11103. const RePathPart = /(\w+)(\])?(\[|\.)?/g; // extracts
  11104. // - the identifier (member name or array index)
  11105. // - followed by an optional right bracket (found when array index)
  11106. // - followed by an optional left bracket or dot (type of subscript)
  11107. //
  11108. // Note: These portions can be read in a non-overlapping fashion and
  11109. // allow straightforward parsing of the hierarchy that WebGL encodes
  11110. // in the uniform names.
  11111. function addUniform(container, uniformObject) {
  11112. container.seq.push(uniformObject);
  11113. container.map[uniformObject.id] = uniformObject;
  11114. }
  11115. function parseUniform(activeInfo, addr, container) {
  11116. const path = activeInfo.name,
  11117. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  11118. RePathPart.lastIndex = 0;
  11119. while (true) {
  11120. const match = RePathPart.exec(path),
  11121. matchEnd = RePathPart.lastIndex;
  11122. let id = match[1];
  11123. const idIsIndex = match[2] === ']',
  11124. subscript = match[3];
  11125. if (idIsIndex) id = id | 0; // convert to integer
  11126. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  11127. // bare name or "pure" bottom-level array "[0]" suffix
  11128. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  11129. break;
  11130. } else {
  11131. // step into inner node / create it in case it doesn't exist
  11132. const map = container.map;
  11133. let next = map[id];
  11134. if (next === undefined) {
  11135. next = new StructuredUniform(id);
  11136. addUniform(container, next);
  11137. }
  11138. container = next;
  11139. }
  11140. }
  11141. } // Root Container
  11142. function WebGLUniforms(gl, program) {
  11143. this.seq = [];
  11144. this.map = {};
  11145. const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  11146. for (let i = 0; i < n; ++i) {
  11147. const info = gl.getActiveUniform(program, i),
  11148. addr = gl.getUniformLocation(program, info.name);
  11149. parseUniform(info, addr, this);
  11150. }
  11151. }
  11152. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  11153. const u = this.map[name];
  11154. if (u !== undefined) u.setValue(gl, value, textures);
  11155. };
  11156. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  11157. const v = object[name];
  11158. if (v !== undefined) this.setValue(gl, name, v);
  11159. }; // Static interface
  11160. WebGLUniforms.upload = function (gl, seq, values, textures) {
  11161. for (let i = 0, n = seq.length; i !== n; ++i) {
  11162. const u = seq[i],
  11163. v = values[u.id];
  11164. if (v.needsUpdate !== false) {
  11165. // note: always updating when .needsUpdate is undefined
  11166. u.setValue(gl, v.value, textures);
  11167. }
  11168. }
  11169. };
  11170. WebGLUniforms.seqWithValue = function (seq, values) {
  11171. const r = [];
  11172. for (let i = 0, n = seq.length; i !== n; ++i) {
  11173. const u = seq[i];
  11174. if (u.id in values) r.push(u);
  11175. }
  11176. return r;
  11177. };
  11178. function WebGLShader(gl, type, string) {
  11179. const shader = gl.createShader(type);
  11180. gl.shaderSource(shader, string);
  11181. gl.compileShader(shader);
  11182. return shader;
  11183. }
  11184. let programIdCount = 0;
  11185. function addLineNumbers(string) {
  11186. const lines = string.split('\n');
  11187. for (let i = 0; i < lines.length; i++) {
  11188. lines[i] = i + 1 + ': ' + lines[i];
  11189. }
  11190. return lines.join('\n');
  11191. }
  11192. function getEncodingComponents(encoding) {
  11193. switch (encoding) {
  11194. case LinearEncoding:
  11195. return ['Linear', '( value )'];
  11196. case sRGBEncoding:
  11197. return ['sRGB', '( value )'];
  11198. case RGBEEncoding:
  11199. return ['RGBE', '( value )'];
  11200. case RGBM7Encoding:
  11201. return ['RGBM', '( value, 7.0 )'];
  11202. case RGBM16Encoding:
  11203. return ['RGBM', '( value, 16.0 )'];
  11204. case RGBDEncoding:
  11205. return ['RGBD', '( value, 256.0 )'];
  11206. case GammaEncoding:
  11207. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  11208. default:
  11209. console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
  11210. return ['Linear', '( value )'];
  11211. }
  11212. }
  11213. function getShaderErrors(gl, shader, type) {
  11214. const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  11215. const errors = gl.getShaderInfoLog(shader).trim();
  11216. if (status && errors === '') return ''; // --enable-privileged-webgl-extension
  11217. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11218. return type.toUpperCase() + '\n\n' + errors + '\n\n' + addLineNumbers(gl.getShaderSource(shader));
  11219. }
  11220. function getTexelDecodingFunction(functionName, encoding) {
  11221. const components = getEncodingComponents(encoding);
  11222. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  11223. }
  11224. function getTexelEncodingFunction(functionName, encoding) {
  11225. const components = getEncodingComponents(encoding);
  11226. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  11227. }
  11228. function getToneMappingFunction(functionName, toneMapping) {
  11229. let toneMappingName;
  11230. switch (toneMapping) {
  11231. case LinearToneMapping:
  11232. toneMappingName = 'Linear';
  11233. break;
  11234. case ReinhardToneMapping:
  11235. toneMappingName = 'Reinhard';
  11236. break;
  11237. case CineonToneMapping:
  11238. toneMappingName = 'OptimizedCineon';
  11239. break;
  11240. case ACESFilmicToneMapping:
  11241. toneMappingName = 'ACESFilmic';
  11242. break;
  11243. case CustomToneMapping:
  11244. toneMappingName = 'Custom';
  11245. break;
  11246. default:
  11247. console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
  11248. toneMappingName = 'Linear';
  11249. }
  11250. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11251. }
  11252. function generateExtensions(parameters) {
  11253. const chunks = [parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ? '#extension GL_OES_standard_derivatives : enable' : '', (parameters.extensionFragDepth || parameters.logarithmicDepthBuffer) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ? '#extension GL_EXT_draw_buffers : require' : '', (parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''];
  11254. return chunks.filter(filterEmptyLine).join('\n');
  11255. }
  11256. function generateDefines(defines) {
  11257. const chunks = [];
  11258. for (const name in defines) {
  11259. const value = defines[name];
  11260. if (value === false) continue;
  11261. chunks.push('#define ' + name + ' ' + value);
  11262. }
  11263. return chunks.join('\n');
  11264. }
  11265. function fetchAttributeLocations(gl, program) {
  11266. const attributes = {};
  11267. const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  11268. for (let i = 0; i < n; i++) {
  11269. const info = gl.getActiveAttrib(program, i);
  11270. const name = info.name;
  11271. let locationSize = 1;
  11272. if (info.type === gl.FLOAT_MAT2) locationSize = 2;
  11273. if (info.type === gl.FLOAT_MAT3) locationSize = 3;
  11274. if (info.type === gl.FLOAT_MAT4) locationSize = 4; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11275. attributes[name] = {
  11276. type: info.type,
  11277. location: gl.getAttribLocation(program, name),
  11278. locationSize: locationSize
  11279. };
  11280. }
  11281. return attributes;
  11282. }
  11283. function filterEmptyLine(string) {
  11284. return string !== '';
  11285. }
  11286. function replaceLightNums(string, parameters) {
  11287. return string.replace(/NUM_DIR_LIGHTS/g, parameters.numDirLights).replace(/NUM_SPOT_LIGHTS/g, parameters.numSpotLights).replace(/NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, parameters.numPointLights).replace(/NUM_HEMI_LIGHTS/g, parameters.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows);
  11288. }
  11289. function replaceClippingPlaneNums(string, parameters) {
  11290. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  11291. } // Resolve Includes
  11292. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11293. function resolveIncludes(string) {
  11294. return string.replace(includePattern, includeReplacer);
  11295. }
  11296. function includeReplacer(match, include) {
  11297. const string = ShaderChunk[include];
  11298. if (string === undefined) {
  11299. throw new Error('Can not resolve #include <' + include + '>');
  11300. }
  11301. return resolveIncludes(string);
  11302. } // Unroll Loops
  11303. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  11304. 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;
  11305. function unrollLoops(string) {
  11306. return string.replace(unrollLoopPattern, loopReplacer).replace(deprecatedUnrollLoopPattern, deprecatedLoopReplacer);
  11307. }
  11308. function deprecatedLoopReplacer(match, start, end, snippet) {
  11309. console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');
  11310. return loopReplacer(match, start, end, snippet);
  11311. }
  11312. function loopReplacer(match, start, end, snippet) {
  11313. let string = '';
  11314. for (let i = parseInt(start); i < parseInt(end); i++) {
  11315. string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  11316. }
  11317. return string;
  11318. } //
  11319. function generatePrecision(parameters) {
  11320. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11321. if (parameters.precision === 'highp') {
  11322. precisionstring += '\n#define HIGH_PRECISION';
  11323. } else if (parameters.precision === 'mediump') {
  11324. precisionstring += '\n#define MEDIUM_PRECISION';
  11325. } else if (parameters.precision === 'lowp') {
  11326. precisionstring += '\n#define LOW_PRECISION';
  11327. }
  11328. return precisionstring;
  11329. }
  11330. function generateShadowMapTypeDefine(parameters) {
  11331. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11332. if (parameters.shadowMapType === PCFShadowMap) {
  11333. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11334. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  11335. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11336. } else if (parameters.shadowMapType === VSMShadowMap) {
  11337. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11338. }
  11339. return shadowMapTypeDefine;
  11340. }
  11341. function generateEnvMapTypeDefine(parameters) {
  11342. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11343. if (parameters.envMap) {
  11344. switch (parameters.envMapMode) {
  11345. case CubeReflectionMapping:
  11346. case CubeRefractionMapping:
  11347. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11348. break;
  11349. case CubeUVReflectionMapping:
  11350. case CubeUVRefractionMapping:
  11351. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11352. break;
  11353. }
  11354. }
  11355. return envMapTypeDefine;
  11356. }
  11357. function generateEnvMapModeDefine(parameters) {
  11358. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11359. if (parameters.envMap) {
  11360. switch (parameters.envMapMode) {
  11361. case CubeRefractionMapping:
  11362. case CubeUVRefractionMapping:
  11363. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11364. break;
  11365. }
  11366. }
  11367. return envMapModeDefine;
  11368. }
  11369. function generateEnvMapBlendingDefine(parameters) {
  11370. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11371. if (parameters.envMap) {
  11372. switch (parameters.combine) {
  11373. case MultiplyOperation:
  11374. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11375. break;
  11376. case MixOperation:
  11377. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11378. break;
  11379. case AddOperation:
  11380. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11381. break;
  11382. }
  11383. }
  11384. return envMapBlendingDefine;
  11385. }
  11386. function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
  11387. // TODO Send this event to Three.js DevTools
  11388. // console.log( 'WebGLProgram', cacheKey );
  11389. const gl = renderer.getContext();
  11390. const defines = parameters.defines;
  11391. let vertexShader = parameters.vertexShader;
  11392. let fragmentShader = parameters.fragmentShader;
  11393. const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  11394. const envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  11395. const envMapModeDefine = generateEnvMapModeDefine(parameters);
  11396. const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  11397. const gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  11398. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  11399. const customDefines = generateDefines(defines);
  11400. const program = gl.createProgram();
  11401. let prefixVertex, prefixFragment;
  11402. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11403. if (parameters.isRawShaderMaterial) {
  11404. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  11405. if (prefixVertex.length > 0) {
  11406. prefixVertex += '\n';
  11407. }
  11408. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  11409. if (prefixFragment.length > 0) {
  11410. prefixFragment += '\n';
  11411. }
  11412. } else {
  11413. prefixVertex = [generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.instancing ? '#define USE_INSTANCING' : '', parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', '#define GAMMA_FACTOR ' + gammaFactorDefine, '#define MAX_BONES ' + parameters.maxBones, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.transmission ? '#define USE_TRANSMISSION' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.skinning ? '#define USE_SKINNING' : '', parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', parameters.morphTargets && parameters.isWebGL2 ? '#define MORPHTARGETS_TEXTURE' : '', parameters.morphTargets && parameters.isWebGL2 ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', 'uniform mat4 modelMatrix;', 'uniform mat4 modelViewMatrix;', 'uniform mat4 projectionMatrix;', 'uniform mat4 viewMatrix;', 'uniform mat3 normalMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', '#ifdef USE_INSTANCING', ' attribute mat4 instanceMatrix;', '#endif', '#ifdef USE_INSTANCING_COLOR', ' attribute vec3 instanceColor;', '#endif', 'attribute vec3 position;', 'attribute vec3 normal;', 'attribute vec2 uv;', '#ifdef USE_TANGENT', ' attribute vec4 tangent;', '#endif', '#if defined( USE_COLOR_ALPHA )', ' attribute vec4 color;', '#elif defined( USE_COLOR )', ' attribute vec3 color;', '#endif', '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )', ' attribute vec3 morphTarget0;', ' attribute vec3 morphTarget1;', ' attribute vec3 morphTarget2;', ' attribute vec3 morphTarget3;', ' #ifdef USE_MORPHNORMALS', ' attribute vec3 morphNormal0;', ' attribute vec3 morphNormal1;', ' attribute vec3 morphNormal2;', ' attribute vec3 morphNormal3;', ' #else', ' attribute vec3 morphTarget4;', ' attribute vec3 morphTarget5;', ' attribute vec3 morphTarget6;', ' attribute vec3 morphTarget7;', ' #endif', '#endif', '#ifdef USE_SKINNING', ' attribute vec4 skinIndex;', ' attribute vec4 skinWeight;', '#endif', '\n'].filter(filterEmptyLine).join('\n');
  11414. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, '#define GAMMA_FACTOR ' + gammaFactorDefine, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.matcap ? '#define USE_MATCAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapTypeDefine : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.envMap ? '#define ' + envMapBlendingDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoat ? '#define USE_CLEARCOAT' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.alphaTest ? '#define USE_ALPHATEST' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', parameters.transmission ? '#define USE_TRANSMISSION' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '', parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', (parameters.extensionShaderTextureLOD || parameters.envMap) && parameters.rendererExtensionShaderTextureLod ? '#define TEXTURE_LOD_EXT' : '', 'uniform mat4 viewMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', parameters.toneMapping !== NoToneMapping ? '#define TONE_MAPPING' : '', parameters.toneMapping !== NoToneMapping ? ShaderChunk['tonemapping_pars_fragment'] : '', // this code is required here because it is used by the toneMapping() function defined below
  11415. parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', parameters.format === RGBFormat ? '#define OPAQUE' : '', ShaderChunk['encodings_pars_fragment'], // this code is required here because it is used by the various encoding/decoding function defined below
  11416. parameters.map ? getTexelDecodingFunction('mapTexelToLinear', parameters.mapEncoding) : '', parameters.matcap ? getTexelDecodingFunction('matcapTexelToLinear', parameters.matcapEncoding) : '', parameters.envMap ? getTexelDecodingFunction('envMapTexelToLinear', parameters.envMapEncoding) : '', parameters.emissiveMap ? getTexelDecodingFunction('emissiveMapTexelToLinear', parameters.emissiveMapEncoding) : '', parameters.specularColorMap ? getTexelDecodingFunction('specularColorMapTexelToLinear', parameters.specularColorMapEncoding) : '', parameters.sheenColorMap ? getTexelDecodingFunction('sheenColorMapTexelToLinear', parameters.sheenColorMapEncoding) : '', parameters.lightMap ? getTexelDecodingFunction('lightMapTexelToLinear', parameters.lightMapEncoding) : '', getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  11417. }
  11418. vertexShader = resolveIncludes(vertexShader);
  11419. vertexShader = replaceLightNums(vertexShader, parameters);
  11420. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  11421. fragmentShader = resolveIncludes(fragmentShader);
  11422. fragmentShader = replaceLightNums(fragmentShader, parameters);
  11423. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  11424. vertexShader = unrollLoops(vertexShader);
  11425. fragmentShader = unrollLoops(fragmentShader);
  11426. if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
  11427. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11428. versionString = '#version 300 es\n';
  11429. prefixVertex = ['precision mediump sampler2DArray;', '#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  11430. prefixFragment = ['#define varying in', parameters.glslVersion === GLSL3 ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;', parameters.glslVersion === GLSL3 ? '' : '#define gl_FragColor pc_fragColor', '#define gl_FragDepthEXT gl_FragDepth', '#define texture2D texture', '#define textureCube texture', '#define texture2DProj textureProj', '#define texture2DLodEXT textureLod', '#define texture2DProjLodEXT textureProjLod', '#define textureCubeLodEXT textureLod', '#define texture2DGradEXT textureGrad', '#define texture2DProjGradEXT textureProjGrad', '#define textureCubeGradEXT textureGrad'].join('\n') + '\n' + prefixFragment;
  11431. }
  11432. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11433. const fragmentGlsl = versionString + prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  11434. // console.log( '*FRAGMENT*', fragmentGlsl );
  11435. const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl);
  11436. const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl);
  11437. gl.attachShader(program, glVertexShader);
  11438. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  11439. if (parameters.index0AttributeName !== undefined) {
  11440. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  11441. } else if (parameters.morphTargets === true) {
  11442. // programs with morphTargets displace position out of attribute 0
  11443. gl.bindAttribLocation(program, 0, 'position');
  11444. }
  11445. gl.linkProgram(program); // check for link errors
  11446. if (renderer.debug.checkShaderErrors) {
  11447. const programLog = gl.getProgramInfoLog(program).trim();
  11448. const vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  11449. const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  11450. let runnable = true;
  11451. let haveDiagnostics = true;
  11452. if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {
  11453. runnable = false;
  11454. const vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  11455. const fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  11456. console.error('THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' + 'VALIDATE_STATUS ' + gl.getProgramParameter(program, gl.VALIDATE_STATUS) + '\n\n' + 'Program Info Log: ' + programLog + '\n' + vertexErrors + '\n' + fragmentErrors);
  11457. } else if (programLog !== '') {
  11458. console.warn('THREE.WebGLProgram: Program Info Log:', programLog);
  11459. } else if (vertexLog === '' || fragmentLog === '') {
  11460. haveDiagnostics = false;
  11461. }
  11462. if (haveDiagnostics) {
  11463. this.diagnostics = {
  11464. runnable: runnable,
  11465. programLog: programLog,
  11466. vertexShader: {
  11467. log: vertexLog,
  11468. prefix: prefixVertex
  11469. },
  11470. fragmentShader: {
  11471. log: fragmentLog,
  11472. prefix: prefixFragment
  11473. }
  11474. };
  11475. }
  11476. } // Clean up
  11477. // Crashes in iOS9 and iOS10. #18402
  11478. // gl.detachShader( program, glVertexShader );
  11479. // gl.detachShader( program, glFragmentShader );
  11480. gl.deleteShader(glVertexShader);
  11481. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  11482. let cachedUniforms;
  11483. this.getUniforms = function () {
  11484. if (cachedUniforms === undefined) {
  11485. cachedUniforms = new WebGLUniforms(gl, program);
  11486. }
  11487. return cachedUniforms;
  11488. }; // set up caching for attribute locations
  11489. let cachedAttributes;
  11490. this.getAttributes = function () {
  11491. if (cachedAttributes === undefined) {
  11492. cachedAttributes = fetchAttributeLocations(gl, program);
  11493. }
  11494. return cachedAttributes;
  11495. }; // free resource
  11496. this.destroy = function () {
  11497. bindingStates.releaseStatesOfProgram(this);
  11498. gl.deleteProgram(program);
  11499. this.program = undefined;
  11500. }; //
  11501. this.name = parameters.shaderName;
  11502. this.id = programIdCount++;
  11503. this.cacheKey = cacheKey;
  11504. this.usedTimes = 1;
  11505. this.program = program;
  11506. this.vertexShader = glVertexShader;
  11507. this.fragmentShader = glFragmentShader;
  11508. return this;
  11509. }
  11510. let _id = 0;
  11511. class WebGLShaderCache {
  11512. constructor() {
  11513. this.shaderCache = new Map();
  11514. this.materialCache = new Map();
  11515. }
  11516. update(material) {
  11517. const vertexShader = material.vertexShader;
  11518. const fragmentShader = material.fragmentShader;
  11519. const vertexShaderStage = this._getShaderStage(vertexShader);
  11520. const fragmentShaderStage = this._getShaderStage(fragmentShader);
  11521. const materialShaders = this._getShaderCacheForMaterial(material);
  11522. if (materialShaders.has(vertexShaderStage) === false) {
  11523. materialShaders.add(vertexShaderStage);
  11524. vertexShaderStage.usedTimes++;
  11525. }
  11526. if (materialShaders.has(fragmentShaderStage) === false) {
  11527. materialShaders.add(fragmentShaderStage);
  11528. fragmentShaderStage.usedTimes++;
  11529. }
  11530. return this;
  11531. }
  11532. remove(material) {
  11533. const materialShaders = this.materialCache.get(material);
  11534. for (const shaderStage of materialShaders) {
  11535. shaderStage.usedTimes--;
  11536. if (shaderStage.usedTimes === 0) this.shaderCache.delete(shaderStage);
  11537. }
  11538. this.materialCache.delete(material);
  11539. return this;
  11540. }
  11541. getVertexShaderID(material) {
  11542. return this._getShaderStage(material.vertexShader).id;
  11543. }
  11544. getFragmentShaderID(material) {
  11545. return this._getShaderStage(material.fragmentShader).id;
  11546. }
  11547. dispose() {
  11548. this.shaderCache.clear();
  11549. this.materialCache.clear();
  11550. }
  11551. _getShaderCacheForMaterial(material) {
  11552. const cache = this.materialCache;
  11553. if (cache.has(material) === false) {
  11554. cache.set(material, new Set());
  11555. }
  11556. return cache.get(material);
  11557. }
  11558. _getShaderStage(code) {
  11559. const cache = this.shaderCache;
  11560. if (cache.has(code) === false) {
  11561. const stage = new WebGLShaderStage();
  11562. cache.set(code, stage);
  11563. }
  11564. return cache.get(code);
  11565. }
  11566. }
  11567. class WebGLShaderStage {
  11568. constructor() {
  11569. this.id = _id++;
  11570. this.usedTimes = 0;
  11571. }
  11572. }
  11573. function WebGLPrograms(renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping) {
  11574. const _programLayers = new Layers();
  11575. const _customShaders = new WebGLShaderCache();
  11576. const programs = [];
  11577. const isWebGL2 = capabilities.isWebGL2;
  11578. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11579. const floatVertexTextures = capabilities.floatVertexTextures;
  11580. const maxVertexUniforms = capabilities.maxVertexUniforms;
  11581. const vertexTextures = capabilities.vertexTextures;
  11582. let precision = capabilities.precision;
  11583. const shaderIDs = {
  11584. MeshDepthMaterial: 'depth',
  11585. MeshDistanceMaterial: 'distanceRGBA',
  11586. MeshNormalMaterial: 'normal',
  11587. MeshBasicMaterial: 'basic',
  11588. MeshLambertMaterial: 'lambert',
  11589. MeshPhongMaterial: 'phong',
  11590. MeshToonMaterial: 'toon',
  11591. MeshStandardMaterial: 'physical',
  11592. MeshPhysicalMaterial: 'physical',
  11593. MeshMatcapMaterial: 'matcap',
  11594. LineBasicMaterial: 'basic',
  11595. LineDashedMaterial: 'dashed',
  11596. PointsMaterial: 'points',
  11597. ShadowMaterial: 'shadow',
  11598. SpriteMaterial: 'sprite'
  11599. };
  11600. function getMaxBones(object) {
  11601. const skeleton = object.skeleton;
  11602. const bones = skeleton.bones;
  11603. if (floatVertexTextures) {
  11604. return 1024;
  11605. } else {
  11606. // default for when object is not specified
  11607. // ( for example when prebuilding shader to be used with multiple objects )
  11608. //
  11609. // - leave some extra space for other uniforms
  11610. // - limit here is ANGLE's 254 max uniform vectors
  11611. // (up to 54 should be safe)
  11612. const nVertexUniforms = maxVertexUniforms;
  11613. const nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  11614. const maxBones = Math.min(nVertexMatrices, bones.length);
  11615. if (maxBones < bones.length) {
  11616. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  11617. return 0;
  11618. }
  11619. return maxBones;
  11620. }
  11621. }
  11622. function getTextureEncodingFromMap(map) {
  11623. let encoding;
  11624. if (map && map.isTexture) {
  11625. encoding = map.encoding;
  11626. } else if (map && map.isWebGLRenderTarget) {
  11627. console.warn('THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.');
  11628. encoding = map.texture.encoding;
  11629. } else {
  11630. encoding = LinearEncoding;
  11631. }
  11632. if (isWebGL2 && map && map.isTexture && map.format === RGBAFormat && map.type === UnsignedByteType && map.encoding === sRGBEncoding) {
  11633. encoding = LinearEncoding; // disable inline decode for sRGB textures in WebGL 2
  11634. }
  11635. return encoding;
  11636. }
  11637. function getParameters(material, lights, shadows, scene, object) {
  11638. const fog = scene.fog;
  11639. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11640. const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
  11641. const shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  11642. // (not to blow over maxLights budget)
  11643. const maxBones = object.isSkinnedMesh ? getMaxBones(object) : 0;
  11644. if (material.precision !== null) {
  11645. precision = capabilities.getMaxPrecision(material.precision);
  11646. if (precision !== material.precision) {
  11647. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  11648. }
  11649. }
  11650. let vertexShader, fragmentShader;
  11651. let customVertexShaderID, customFragmentShaderID;
  11652. if (shaderID) {
  11653. const shader = ShaderLib[shaderID];
  11654. vertexShader = shader.vertexShader;
  11655. fragmentShader = shader.fragmentShader;
  11656. } else {
  11657. vertexShader = material.vertexShader;
  11658. fragmentShader = material.fragmentShader;
  11659. _customShaders.update(material);
  11660. customVertexShaderID = _customShaders.getVertexShaderID(material);
  11661. customFragmentShaderID = _customShaders.getFragmentShaderID(material);
  11662. }
  11663. const currentRenderTarget = renderer.getRenderTarget();
  11664. const useAlphaTest = material.alphaTest > 0;
  11665. const useClearcoat = material.clearcoat > 0;
  11666. const parameters = {
  11667. isWebGL2: isWebGL2,
  11668. shaderID: shaderID,
  11669. shaderName: material.type,
  11670. vertexShader: vertexShader,
  11671. fragmentShader: fragmentShader,
  11672. defines: material.defines,
  11673. customVertexShaderID: customVertexShaderID,
  11674. customFragmentShaderID: customFragmentShaderID,
  11675. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11676. glslVersion: material.glslVersion,
  11677. precision: precision,
  11678. instancing: object.isInstancedMesh === true,
  11679. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11680. supportsVertexTextures: vertexTextures,
  11681. outputEncoding: currentRenderTarget !== null ? getTextureEncodingFromMap(currentRenderTarget.texture) : renderer.outputEncoding,
  11682. map: !!material.map,
  11683. mapEncoding: getTextureEncodingFromMap(material.map),
  11684. matcap: !!material.matcap,
  11685. matcapEncoding: getTextureEncodingFromMap(material.matcap),
  11686. envMap: !!envMap,
  11687. envMapMode: envMap && envMap.mapping,
  11688. envMapEncoding: getTextureEncodingFromMap(envMap),
  11689. envMapCubeUV: !!envMap && (envMap.mapping === CubeUVReflectionMapping || envMap.mapping === CubeUVRefractionMapping),
  11690. lightMap: !!material.lightMap,
  11691. lightMapEncoding: getTextureEncodingFromMap(material.lightMap),
  11692. aoMap: !!material.aoMap,
  11693. emissiveMap: !!material.emissiveMap,
  11694. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap),
  11695. bumpMap: !!material.bumpMap,
  11696. normalMap: !!material.normalMap,
  11697. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11698. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11699. clearcoat: useClearcoat,
  11700. clearcoatMap: useClearcoat && !!material.clearcoatMap,
  11701. clearcoatRoughnessMap: useClearcoat && !!material.clearcoatRoughnessMap,
  11702. clearcoatNormalMap: useClearcoat && !!material.clearcoatNormalMap,
  11703. displacementMap: !!material.displacementMap,
  11704. roughnessMap: !!material.roughnessMap,
  11705. metalnessMap: !!material.metalnessMap,
  11706. specularMap: !!material.specularMap,
  11707. specularIntensityMap: !!material.specularIntensityMap,
  11708. specularColorMap: !!material.specularColorMap,
  11709. specularColorMapEncoding: getTextureEncodingFromMap(material.specularColorMap),
  11710. alphaMap: !!material.alphaMap,
  11711. alphaTest: useAlphaTest,
  11712. gradientMap: !!material.gradientMap,
  11713. sheen: material.sheen > 0,
  11714. sheenColorMap: !!material.sheenColorMap,
  11715. sheenColorMapEncoding: getTextureEncodingFromMap(material.sheenColorMap),
  11716. sheenRoughnessMap: !!material.sheenRoughnessMap,
  11717. transmission: material.transmission > 0,
  11718. transmissionMap: !!material.transmissionMap,
  11719. thicknessMap: !!material.thicknessMap,
  11720. combine: material.combine,
  11721. vertexTangents: !!material.normalMap && !!object.geometry && !!object.geometry.attributes.tangent,
  11722. vertexColors: material.vertexColors,
  11723. vertexAlphas: material.vertexColors === true && !!object.geometry && !!object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4,
  11724. vertexUvs: !!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatMap || !!material.clearcoatRoughnessMap || !!material.clearcoatNormalMap || !!material.displacementMap || !!material.transmissionMap || !!material.thicknessMap || !!material.specularIntensityMap || !!material.specularColorMap || !!material.sheenColorMap || !!material.sheenRoughnessMap,
  11725. uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap || material.transmission > 0 || !!material.transmissionMap || !!material.thicknessMap || !!material.specularIntensityMap || !!material.specularColorMap || material.sheen > 0 || !!material.sheenColorMap || !!material.sheenRoughnessMap) && !!material.displacementMap,
  11726. fog: !!fog,
  11727. useFog: material.fog,
  11728. fogExp2: fog && fog.isFogExp2,
  11729. flatShading: !!material.flatShading,
  11730. sizeAttenuation: material.sizeAttenuation,
  11731. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11732. skinning: object.isSkinnedMesh === true && maxBones > 0,
  11733. maxBones: maxBones,
  11734. useVertexTexture: floatVertexTextures,
  11735. morphTargets: !!object.geometry && !!object.geometry.morphAttributes.position,
  11736. morphNormals: !!object.geometry && !!object.geometry.morphAttributes.normal,
  11737. morphTargetsCount: !!object.geometry && !!object.geometry.morphAttributes.position ? object.geometry.morphAttributes.position.length : 0,
  11738. numDirLights: lights.directional.length,
  11739. numPointLights: lights.point.length,
  11740. numSpotLights: lights.spot.length,
  11741. numRectAreaLights: lights.rectArea.length,
  11742. numHemiLights: lights.hemi.length,
  11743. numDirLightShadows: lights.directionalShadowMap.length,
  11744. numPointLightShadows: lights.pointShadowMap.length,
  11745. numSpotLightShadows: lights.spotShadowMap.length,
  11746. numClippingPlanes: clipping.numPlanes,
  11747. numClipIntersection: clipping.numIntersection,
  11748. format: material.format,
  11749. dithering: material.dithering,
  11750. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11751. shadowMapType: renderer.shadowMap.type,
  11752. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11753. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11754. premultipliedAlpha: material.premultipliedAlpha,
  11755. doubleSided: material.side === DoubleSide,
  11756. flipSided: material.side === BackSide,
  11757. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false,
  11758. index0AttributeName: material.index0AttributeName,
  11759. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11760. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11761. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11762. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11763. rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
  11764. rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
  11765. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
  11766. customProgramCacheKey: material.customProgramCacheKey()
  11767. };
  11768. return parameters;
  11769. }
  11770. function getProgramCacheKey(parameters) {
  11771. const array = [];
  11772. if (parameters.shaderID) {
  11773. array.push(parameters.shaderID);
  11774. } else {
  11775. array.push(parameters.customVertexShaderID);
  11776. array.push(parameters.customFragmentShaderID);
  11777. }
  11778. if (parameters.defines !== undefined) {
  11779. for (const name in parameters.defines) {
  11780. array.push(name);
  11781. array.push(parameters.defines[name]);
  11782. }
  11783. }
  11784. if (parameters.isRawShaderMaterial === false) {
  11785. getProgramCacheKeyParameters(array, parameters);
  11786. getProgramCacheKeyBooleans(array, parameters);
  11787. array.push(renderer.outputEncoding);
  11788. array.push(renderer.gammaFactor);
  11789. }
  11790. array.push(parameters.customProgramCacheKey);
  11791. return array.join();
  11792. }
  11793. function getProgramCacheKeyParameters(array, parameters) {
  11794. array.push(parameters.precision);
  11795. array.push(parameters.outputEncoding);
  11796. array.push(parameters.mapEncoding);
  11797. array.push(parameters.matcapEncoding);
  11798. array.push(parameters.envMapMode);
  11799. array.push(parameters.envMapEncoding);
  11800. array.push(parameters.lightMapEncoding);
  11801. array.push(parameters.emissiveMapEncoding);
  11802. array.push(parameters.combine);
  11803. array.push(parameters.vertexUvs);
  11804. array.push(parameters.fogExp2);
  11805. array.push(parameters.sizeAttenuation);
  11806. array.push(parameters.maxBones);
  11807. array.push(parameters.morphTargetsCount);
  11808. array.push(parameters.numDirLights);
  11809. array.push(parameters.numPointLights);
  11810. array.push(parameters.numSpotLights);
  11811. array.push(parameters.numHemiLights);
  11812. array.push(parameters.numRectAreaLights);
  11813. array.push(parameters.numDirLightShadows);
  11814. array.push(parameters.numPointLightShadows);
  11815. array.push(parameters.numSpotLightShadows);
  11816. array.push(parameters.shadowMapType);
  11817. array.push(parameters.toneMapping);
  11818. array.push(parameters.numClippingPlanes);
  11819. array.push(parameters.numClipIntersection);
  11820. array.push(parameters.format);
  11821. array.push(parameters.specularColorMapEncoding);
  11822. array.push(parameters.sheenColorMapEncoding);
  11823. }
  11824. function getProgramCacheKeyBooleans(array, parameters) {
  11825. _programLayers.disableAll();
  11826. if (parameters.isWebGL2) _programLayers.enable(0);
  11827. if (parameters.supportsVertexTextures) _programLayers.enable(1);
  11828. if (parameters.instancing) _programLayers.enable(2);
  11829. if (parameters.instancingColor) _programLayers.enable(3);
  11830. if (parameters.map) _programLayers.enable(4);
  11831. if (parameters.matcap) _programLayers.enable(5);
  11832. if (parameters.envMap) _programLayers.enable(6);
  11833. if (parameters.envMapCubeUV) _programLayers.enable(7);
  11834. if (parameters.lightMap) _programLayers.enable(8);
  11835. if (parameters.aoMap) _programLayers.enable(9);
  11836. if (parameters.emissiveMap) _programLayers.enable(10);
  11837. if (parameters.bumpMap) _programLayers.enable(11);
  11838. if (parameters.normalMap) _programLayers.enable(12);
  11839. if (parameters.objectSpaceNormalMap) _programLayers.enable(13);
  11840. if (parameters.tangentSpaceNormalMap) _programLayers.enable(14);
  11841. if (parameters.clearcoat) _programLayers.enable(15);
  11842. if (parameters.clearcoatMap) _programLayers.enable(16);
  11843. if (parameters.clearcoatRoughnessMap) _programLayers.enable(17);
  11844. if (parameters.clearcoatNormalMap) _programLayers.enable(18);
  11845. if (parameters.displacementMap) _programLayers.enable(19);
  11846. if (parameters.specularMap) _programLayers.enable(20);
  11847. if (parameters.roughnessMap) _programLayers.enable(21);
  11848. if (parameters.metalnessMap) _programLayers.enable(22);
  11849. if (parameters.gradientMap) _programLayers.enable(23);
  11850. if (parameters.alphaMap) _programLayers.enable(24);
  11851. if (parameters.alphaTest) _programLayers.enable(25);
  11852. if (parameters.vertexColors) _programLayers.enable(26);
  11853. if (parameters.vertexAlphas) _programLayers.enable(27);
  11854. if (parameters.vertexUvs) _programLayers.enable(28);
  11855. if (parameters.vertexTangents) _programLayers.enable(29);
  11856. if (parameters.uvsVertexOnly) _programLayers.enable(30);
  11857. if (parameters.fog) _programLayers.enable(31);
  11858. array.push(_programLayers.mask);
  11859. _programLayers.disableAll();
  11860. if (parameters.useFog) _programLayers.enable(0);
  11861. if (parameters.flatShading) _programLayers.enable(1);
  11862. if (parameters.logarithmicDepthBuffer) _programLayers.enable(2);
  11863. if (parameters.skinning) _programLayers.enable(3);
  11864. if (parameters.useVertexTexture) _programLayers.enable(4);
  11865. if (parameters.morphTargets) _programLayers.enable(5);
  11866. if (parameters.morphNormals) _programLayers.enable(6);
  11867. if (parameters.premultipliedAlpha) _programLayers.enable(7);
  11868. if (parameters.shadowMapEnabled) _programLayers.enable(8);
  11869. if (parameters.physicallyCorrectLights) _programLayers.enable(9);
  11870. if (parameters.doubleSided) _programLayers.enable(10);
  11871. if (parameters.flipSided) _programLayers.enable(11);
  11872. if (parameters.depthPacking) _programLayers.enable(12);
  11873. if (parameters.dithering) _programLayers.enable(13);
  11874. if (parameters.specularIntensityMap) _programLayers.enable(14);
  11875. if (parameters.specularColorMap) _programLayers.enable(15);
  11876. if (parameters.transmission) _programLayers.enable(16);
  11877. if (parameters.transmissionMap) _programLayers.enable(17);
  11878. if (parameters.thicknessMap) _programLayers.enable(18);
  11879. if (parameters.sheen) _programLayers.enable(19);
  11880. if (parameters.sheenColorMap) _programLayers.enable(20);
  11881. if (parameters.sheenRoughnessMap) _programLayers.enable(21);
  11882. array.push(_programLayers.mask);
  11883. }
  11884. function getUniforms(material) {
  11885. const shaderID = shaderIDs[material.type];
  11886. let uniforms;
  11887. if (shaderID) {
  11888. const shader = ShaderLib[shaderID];
  11889. uniforms = UniformsUtils.clone(shader.uniforms);
  11890. } else {
  11891. uniforms = material.uniforms;
  11892. }
  11893. return uniforms;
  11894. }
  11895. function acquireProgram(parameters, cacheKey) {
  11896. let program; // Check if code has been already compiled
  11897. for (let p = 0, pl = programs.length; p < pl; p++) {
  11898. const preexistingProgram = programs[p];
  11899. if (preexistingProgram.cacheKey === cacheKey) {
  11900. program = preexistingProgram;
  11901. ++program.usedTimes;
  11902. break;
  11903. }
  11904. }
  11905. if (program === undefined) {
  11906. program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
  11907. programs.push(program);
  11908. }
  11909. return program;
  11910. }
  11911. function releaseProgram(program) {
  11912. if (--program.usedTimes === 0) {
  11913. // Remove from unordered set
  11914. const i = programs.indexOf(program);
  11915. programs[i] = programs[programs.length - 1];
  11916. programs.pop(); // Free WebGL resources
  11917. program.destroy();
  11918. }
  11919. }
  11920. function releaseShaderCache(material) {
  11921. _customShaders.remove(material);
  11922. }
  11923. function dispose() {
  11924. _customShaders.dispose();
  11925. }
  11926. return {
  11927. getParameters: getParameters,
  11928. getProgramCacheKey: getProgramCacheKey,
  11929. getUniforms: getUniforms,
  11930. acquireProgram: acquireProgram,
  11931. releaseProgram: releaseProgram,
  11932. releaseShaderCache: releaseShaderCache,
  11933. // Exposed for resource monitoring & error feedback via renderer.info:
  11934. programs: programs,
  11935. dispose: dispose
  11936. };
  11937. }
  11938. function WebGLProperties() {
  11939. let properties = new WeakMap();
  11940. function get(object) {
  11941. let map = properties.get(object);
  11942. if (map === undefined) {
  11943. map = {};
  11944. properties.set(object, map);
  11945. }
  11946. return map;
  11947. }
  11948. function remove(object) {
  11949. properties.delete(object);
  11950. }
  11951. function update(object, key, value) {
  11952. properties.get(object)[key] = value;
  11953. }
  11954. function dispose() {
  11955. properties = new WeakMap();
  11956. }
  11957. return {
  11958. get: get,
  11959. remove: remove,
  11960. update: update,
  11961. dispose: dispose
  11962. };
  11963. }
  11964. function painterSortStable(a, b) {
  11965. if (a.groupOrder !== b.groupOrder) {
  11966. return a.groupOrder - b.groupOrder;
  11967. } else if (a.renderOrder !== b.renderOrder) {
  11968. return a.renderOrder - b.renderOrder;
  11969. } else if (a.material.id !== b.material.id) {
  11970. return a.material.id - b.material.id;
  11971. } else if (a.z !== b.z) {
  11972. return a.z - b.z;
  11973. } else {
  11974. return a.id - b.id;
  11975. }
  11976. }
  11977. function reversePainterSortStable(a, b) {
  11978. if (a.groupOrder !== b.groupOrder) {
  11979. return a.groupOrder - b.groupOrder;
  11980. } else if (a.renderOrder !== b.renderOrder) {
  11981. return a.renderOrder - b.renderOrder;
  11982. } else if (a.z !== b.z) {
  11983. return b.z - a.z;
  11984. } else {
  11985. return a.id - b.id;
  11986. }
  11987. }
  11988. function WebGLRenderList() {
  11989. const renderItems = [];
  11990. let renderItemsIndex = 0;
  11991. const opaque = [];
  11992. const transmissive = [];
  11993. const transparent = [];
  11994. function init() {
  11995. renderItemsIndex = 0;
  11996. opaque.length = 0;
  11997. transmissive.length = 0;
  11998. transparent.length = 0;
  11999. }
  12000. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  12001. let renderItem = renderItems[renderItemsIndex];
  12002. if (renderItem === undefined) {
  12003. renderItem = {
  12004. id: object.id,
  12005. object: object,
  12006. geometry: geometry,
  12007. material: material,
  12008. groupOrder: groupOrder,
  12009. renderOrder: object.renderOrder,
  12010. z: z,
  12011. group: group
  12012. };
  12013. renderItems[renderItemsIndex] = renderItem;
  12014. } else {
  12015. renderItem.id = object.id;
  12016. renderItem.object = object;
  12017. renderItem.geometry = geometry;
  12018. renderItem.material = material;
  12019. renderItem.groupOrder = groupOrder;
  12020. renderItem.renderOrder = object.renderOrder;
  12021. renderItem.z = z;
  12022. renderItem.group = group;
  12023. }
  12024. renderItemsIndex++;
  12025. return renderItem;
  12026. }
  12027. function push(object, geometry, material, groupOrder, z, group) {
  12028. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12029. if (material.transmission > 0.0) {
  12030. transmissive.push(renderItem);
  12031. } else if (material.transparent === true) {
  12032. transparent.push(renderItem);
  12033. } else {
  12034. opaque.push(renderItem);
  12035. }
  12036. }
  12037. function unshift(object, geometry, material, groupOrder, z, group) {
  12038. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12039. if (material.transmission > 0.0) {
  12040. transmissive.unshift(renderItem);
  12041. } else if (material.transparent === true) {
  12042. transparent.unshift(renderItem);
  12043. } else {
  12044. opaque.unshift(renderItem);
  12045. }
  12046. }
  12047. function sort(customOpaqueSort, customTransparentSort) {
  12048. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  12049. if (transmissive.length > 1) transmissive.sort(customTransparentSort || reversePainterSortStable);
  12050. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  12051. }
  12052. function finish() {
  12053. // Clear references from inactive renderItems in the list
  12054. for (let i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  12055. const renderItem = renderItems[i];
  12056. if (renderItem.id === null) break;
  12057. renderItem.id = null;
  12058. renderItem.object = null;
  12059. renderItem.geometry = null;
  12060. renderItem.material = null;
  12061. renderItem.group = null;
  12062. }
  12063. }
  12064. return {
  12065. opaque: opaque,
  12066. transmissive: transmissive,
  12067. transparent: transparent,
  12068. init: init,
  12069. push: push,
  12070. unshift: unshift,
  12071. finish: finish,
  12072. sort: sort
  12073. };
  12074. }
  12075. function WebGLRenderLists() {
  12076. let lists = new WeakMap();
  12077. function get(scene, renderCallDepth) {
  12078. let list;
  12079. if (lists.has(scene) === false) {
  12080. list = new WebGLRenderList();
  12081. lists.set(scene, [list]);
  12082. } else {
  12083. if (renderCallDepth >= lists.get(scene).length) {
  12084. list = new WebGLRenderList();
  12085. lists.get(scene).push(list);
  12086. } else {
  12087. list = lists.get(scene)[renderCallDepth];
  12088. }
  12089. }
  12090. return list;
  12091. }
  12092. function dispose() {
  12093. lists = new WeakMap();
  12094. }
  12095. return {
  12096. get: get,
  12097. dispose: dispose
  12098. };
  12099. }
  12100. function UniformsCache() {
  12101. const lights = {};
  12102. return {
  12103. get: function (light) {
  12104. if (lights[light.id] !== undefined) {
  12105. return lights[light.id];
  12106. }
  12107. let uniforms;
  12108. switch (light.type) {
  12109. case 'DirectionalLight':
  12110. uniforms = {
  12111. direction: new Vector3(),
  12112. color: new Color()
  12113. };
  12114. break;
  12115. case 'SpotLight':
  12116. uniforms = {
  12117. position: new Vector3(),
  12118. direction: new Vector3(),
  12119. color: new Color(),
  12120. distance: 0,
  12121. coneCos: 0,
  12122. penumbraCos: 0,
  12123. decay: 0
  12124. };
  12125. break;
  12126. case 'PointLight':
  12127. uniforms = {
  12128. position: new Vector3(),
  12129. color: new Color(),
  12130. distance: 0,
  12131. decay: 0
  12132. };
  12133. break;
  12134. case 'HemisphereLight':
  12135. uniforms = {
  12136. direction: new Vector3(),
  12137. skyColor: new Color(),
  12138. groundColor: new Color()
  12139. };
  12140. break;
  12141. case 'RectAreaLight':
  12142. uniforms = {
  12143. color: new Color(),
  12144. position: new Vector3(),
  12145. halfWidth: new Vector3(),
  12146. halfHeight: new Vector3()
  12147. };
  12148. break;
  12149. }
  12150. lights[light.id] = uniforms;
  12151. return uniforms;
  12152. }
  12153. };
  12154. }
  12155. function ShadowUniformsCache() {
  12156. const lights = {};
  12157. return {
  12158. get: function (light) {
  12159. if (lights[light.id] !== undefined) {
  12160. return lights[light.id];
  12161. }
  12162. let uniforms;
  12163. switch (light.type) {
  12164. case 'DirectionalLight':
  12165. uniforms = {
  12166. shadowBias: 0,
  12167. shadowNormalBias: 0,
  12168. shadowRadius: 1,
  12169. shadowMapSize: new Vector2()
  12170. };
  12171. break;
  12172. case 'SpotLight':
  12173. uniforms = {
  12174. shadowBias: 0,
  12175. shadowNormalBias: 0,
  12176. shadowRadius: 1,
  12177. shadowMapSize: new Vector2()
  12178. };
  12179. break;
  12180. case 'PointLight':
  12181. uniforms = {
  12182. shadowBias: 0,
  12183. shadowNormalBias: 0,
  12184. shadowRadius: 1,
  12185. shadowMapSize: new Vector2(),
  12186. shadowCameraNear: 1,
  12187. shadowCameraFar: 1000
  12188. };
  12189. break;
  12190. // TODO (abelnation): set RectAreaLight shadow uniforms
  12191. }
  12192. lights[light.id] = uniforms;
  12193. return uniforms;
  12194. }
  12195. };
  12196. }
  12197. let nextVersion = 0;
  12198. function shadowCastingLightsFirst(lightA, lightB) {
  12199. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  12200. }
  12201. function WebGLLights(extensions, capabilities) {
  12202. const cache = new UniformsCache();
  12203. const shadowCache = ShadowUniformsCache();
  12204. const state = {
  12205. version: 0,
  12206. hash: {
  12207. directionalLength: -1,
  12208. pointLength: -1,
  12209. spotLength: -1,
  12210. rectAreaLength: -1,
  12211. hemiLength: -1,
  12212. numDirectionalShadows: -1,
  12213. numPointShadows: -1,
  12214. numSpotShadows: -1
  12215. },
  12216. ambient: [0, 0, 0],
  12217. probe: [],
  12218. directional: [],
  12219. directionalShadow: [],
  12220. directionalShadowMap: [],
  12221. directionalShadowMatrix: [],
  12222. spot: [],
  12223. spotShadow: [],
  12224. spotShadowMap: [],
  12225. spotShadowMatrix: [],
  12226. rectArea: [],
  12227. rectAreaLTC1: null,
  12228. rectAreaLTC2: null,
  12229. point: [],
  12230. pointShadow: [],
  12231. pointShadowMap: [],
  12232. pointShadowMatrix: [],
  12233. hemi: []
  12234. };
  12235. for (let i = 0; i < 9; i++) state.probe.push(new Vector3());
  12236. const vector3 = new Vector3();
  12237. const matrix4 = new Matrix4();
  12238. const matrix42 = new Matrix4();
  12239. function setup(lights, physicallyCorrectLights) {
  12240. let r = 0,
  12241. g = 0,
  12242. b = 0;
  12243. for (let i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  12244. let directionalLength = 0;
  12245. let pointLength = 0;
  12246. let spotLength = 0;
  12247. let rectAreaLength = 0;
  12248. let hemiLength = 0;
  12249. let numDirectionalShadows = 0;
  12250. let numPointShadows = 0;
  12251. let numSpotShadows = 0;
  12252. lights.sort(shadowCastingLightsFirst); // artist-friendly light intensity scaling factor
  12253. const scaleFactor = physicallyCorrectLights !== true ? Math.PI : 1;
  12254. for (let i = 0, l = lights.length; i < l; i++) {
  12255. const light = lights[i];
  12256. const color = light.color;
  12257. const intensity = light.intensity;
  12258. const distance = light.distance;
  12259. const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  12260. if (light.isAmbientLight) {
  12261. r += color.r * intensity * scaleFactor;
  12262. g += color.g * intensity * scaleFactor;
  12263. b += color.b * intensity * scaleFactor;
  12264. } else if (light.isLightProbe) {
  12265. for (let j = 0; j < 9; j++) {
  12266. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  12267. }
  12268. } else if (light.isDirectionalLight) {
  12269. const uniforms = cache.get(light);
  12270. uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
  12271. if (light.castShadow) {
  12272. const shadow = light.shadow;
  12273. const shadowUniforms = shadowCache.get(light);
  12274. shadowUniforms.shadowBias = shadow.bias;
  12275. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12276. shadowUniforms.shadowRadius = shadow.radius;
  12277. shadowUniforms.shadowMapSize = shadow.mapSize;
  12278. state.directionalShadow[directionalLength] = shadowUniforms;
  12279. state.directionalShadowMap[directionalLength] = shadowMap;
  12280. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  12281. numDirectionalShadows++;
  12282. }
  12283. state.directional[directionalLength] = uniforms;
  12284. directionalLength++;
  12285. } else if (light.isSpotLight) {
  12286. const uniforms = cache.get(light);
  12287. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12288. uniforms.color.copy(color).multiplyScalar(intensity * scaleFactor);
  12289. uniforms.distance = distance;
  12290. uniforms.coneCos = Math.cos(light.angle);
  12291. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  12292. uniforms.decay = light.decay;
  12293. if (light.castShadow) {
  12294. const shadow = light.shadow;
  12295. const shadowUniforms = shadowCache.get(light);
  12296. shadowUniforms.shadowBias = shadow.bias;
  12297. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12298. shadowUniforms.shadowRadius = shadow.radius;
  12299. shadowUniforms.shadowMapSize = shadow.mapSize;
  12300. state.spotShadow[spotLength] = shadowUniforms;
  12301. state.spotShadowMap[spotLength] = shadowMap;
  12302. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  12303. numSpotShadows++;
  12304. }
  12305. state.spot[spotLength] = uniforms;
  12306. spotLength++;
  12307. } else if (light.isRectAreaLight) {
  12308. const uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  12309. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  12310. // (b) intensity is the brightness of the light
  12311. uniforms.color.copy(color).multiplyScalar(intensity);
  12312. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12313. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12314. state.rectArea[rectAreaLength] = uniforms;
  12315. rectAreaLength++;
  12316. } else if (light.isPointLight) {
  12317. const uniforms = cache.get(light);
  12318. uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
  12319. uniforms.distance = light.distance;
  12320. uniforms.decay = light.decay;
  12321. if (light.castShadow) {
  12322. const shadow = light.shadow;
  12323. const shadowUniforms = shadowCache.get(light);
  12324. shadowUniforms.shadowBias = shadow.bias;
  12325. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12326. shadowUniforms.shadowRadius = shadow.radius;
  12327. shadowUniforms.shadowMapSize = shadow.mapSize;
  12328. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12329. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12330. state.pointShadow[pointLength] = shadowUniforms;
  12331. state.pointShadowMap[pointLength] = shadowMap;
  12332. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  12333. numPointShadows++;
  12334. }
  12335. state.point[pointLength] = uniforms;
  12336. pointLength++;
  12337. } else if (light.isHemisphereLight) {
  12338. const uniforms = cache.get(light);
  12339. uniforms.skyColor.copy(light.color).multiplyScalar(intensity * scaleFactor);
  12340. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity * scaleFactor);
  12341. state.hemi[hemiLength] = uniforms;
  12342. hemiLength++;
  12343. }
  12344. }
  12345. if (rectAreaLength > 0) {
  12346. if (capabilities.isWebGL2) {
  12347. // WebGL 2
  12348. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12349. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12350. } else {
  12351. // WebGL 1
  12352. if (extensions.has('OES_texture_float_linear') === true) {
  12353. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12354. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12355. } else if (extensions.has('OES_texture_half_float_linear') === true) {
  12356. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12357. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12358. } else {
  12359. console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
  12360. }
  12361. }
  12362. }
  12363. state.ambient[0] = r;
  12364. state.ambient[1] = g;
  12365. state.ambient[2] = b;
  12366. const hash = state.hash;
  12367. if (hash.directionalLength !== directionalLength || hash.pointLength !== pointLength || hash.spotLength !== spotLength || hash.rectAreaLength !== rectAreaLength || hash.hemiLength !== hemiLength || hash.numDirectionalShadows !== numDirectionalShadows || hash.numPointShadows !== numPointShadows || hash.numSpotShadows !== numSpotShadows) {
  12368. state.directional.length = directionalLength;
  12369. state.spot.length = spotLength;
  12370. state.rectArea.length = rectAreaLength;
  12371. state.point.length = pointLength;
  12372. state.hemi.length = hemiLength;
  12373. state.directionalShadow.length = numDirectionalShadows;
  12374. state.directionalShadowMap.length = numDirectionalShadows;
  12375. state.pointShadow.length = numPointShadows;
  12376. state.pointShadowMap.length = numPointShadows;
  12377. state.spotShadow.length = numSpotShadows;
  12378. state.spotShadowMap.length = numSpotShadows;
  12379. state.directionalShadowMatrix.length = numDirectionalShadows;
  12380. state.pointShadowMatrix.length = numPointShadows;
  12381. state.spotShadowMatrix.length = numSpotShadows;
  12382. hash.directionalLength = directionalLength;
  12383. hash.pointLength = pointLength;
  12384. hash.spotLength = spotLength;
  12385. hash.rectAreaLength = rectAreaLength;
  12386. hash.hemiLength = hemiLength;
  12387. hash.numDirectionalShadows = numDirectionalShadows;
  12388. hash.numPointShadows = numPointShadows;
  12389. hash.numSpotShadows = numSpotShadows;
  12390. state.version = nextVersion++;
  12391. }
  12392. }
  12393. function setupView(lights, camera) {
  12394. let directionalLength = 0;
  12395. let pointLength = 0;
  12396. let spotLength = 0;
  12397. let rectAreaLength = 0;
  12398. let hemiLength = 0;
  12399. const viewMatrix = camera.matrixWorldInverse;
  12400. for (let i = 0, l = lights.length; i < l; i++) {
  12401. const light = lights[i];
  12402. if (light.isDirectionalLight) {
  12403. const uniforms = state.directional[directionalLength];
  12404. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12405. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12406. uniforms.direction.sub(vector3);
  12407. uniforms.direction.transformDirection(viewMatrix);
  12408. directionalLength++;
  12409. } else if (light.isSpotLight) {
  12410. const uniforms = state.spot[spotLength];
  12411. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12412. uniforms.position.applyMatrix4(viewMatrix);
  12413. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12414. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12415. uniforms.direction.sub(vector3);
  12416. uniforms.direction.transformDirection(viewMatrix);
  12417. spotLength++;
  12418. } else if (light.isRectAreaLight) {
  12419. const uniforms = state.rectArea[rectAreaLength];
  12420. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12421. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  12422. matrix42.identity();
  12423. matrix4.copy(light.matrixWorld);
  12424. matrix4.premultiply(viewMatrix);
  12425. matrix42.extractRotation(matrix4);
  12426. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12427. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12428. uniforms.halfWidth.applyMatrix4(matrix42);
  12429. uniforms.halfHeight.applyMatrix4(matrix42);
  12430. rectAreaLength++;
  12431. } else if (light.isPointLight) {
  12432. const uniforms = state.point[pointLength];
  12433. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12434. uniforms.position.applyMatrix4(viewMatrix);
  12435. pointLength++;
  12436. } else if (light.isHemisphereLight) {
  12437. const uniforms = state.hemi[hemiLength];
  12438. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12439. uniforms.direction.transformDirection(viewMatrix);
  12440. uniforms.direction.normalize();
  12441. hemiLength++;
  12442. }
  12443. }
  12444. }
  12445. return {
  12446. setup: setup,
  12447. setupView: setupView,
  12448. state: state
  12449. };
  12450. }
  12451. function WebGLRenderState(extensions, capabilities) {
  12452. const lights = new WebGLLights(extensions, capabilities);
  12453. const lightsArray = [];
  12454. const shadowsArray = [];
  12455. function init() {
  12456. lightsArray.length = 0;
  12457. shadowsArray.length = 0;
  12458. }
  12459. function pushLight(light) {
  12460. lightsArray.push(light);
  12461. }
  12462. function pushShadow(shadowLight) {
  12463. shadowsArray.push(shadowLight);
  12464. }
  12465. function setupLights(physicallyCorrectLights) {
  12466. lights.setup(lightsArray, physicallyCorrectLights);
  12467. }
  12468. function setupLightsView(camera) {
  12469. lights.setupView(lightsArray, camera);
  12470. }
  12471. const state = {
  12472. lightsArray: lightsArray,
  12473. shadowsArray: shadowsArray,
  12474. lights: lights
  12475. };
  12476. return {
  12477. init: init,
  12478. state: state,
  12479. setupLights: setupLights,
  12480. setupLightsView: setupLightsView,
  12481. pushLight: pushLight,
  12482. pushShadow: pushShadow
  12483. };
  12484. }
  12485. function WebGLRenderStates(extensions, capabilities) {
  12486. let renderStates = new WeakMap();
  12487. function get(scene, renderCallDepth = 0) {
  12488. let renderState;
  12489. if (renderStates.has(scene) === false) {
  12490. renderState = new WebGLRenderState(extensions, capabilities);
  12491. renderStates.set(scene, [renderState]);
  12492. } else {
  12493. if (renderCallDepth >= renderStates.get(scene).length) {
  12494. renderState = new WebGLRenderState(extensions, capabilities);
  12495. renderStates.get(scene).push(renderState);
  12496. } else {
  12497. renderState = renderStates.get(scene)[renderCallDepth];
  12498. }
  12499. }
  12500. return renderState;
  12501. }
  12502. function dispose() {
  12503. renderStates = new WeakMap();
  12504. }
  12505. return {
  12506. get: get,
  12507. dispose: dispose
  12508. };
  12509. }
  12510. /**
  12511. * parameters = {
  12512. *
  12513. * opacity: <float>,
  12514. *
  12515. * map: new THREE.Texture( <Image> ),
  12516. *
  12517. * alphaMap: new THREE.Texture( <Image> ),
  12518. *
  12519. * displacementMap: new THREE.Texture( <Image> ),
  12520. * displacementScale: <float>,
  12521. * displacementBias: <float>,
  12522. *
  12523. * wireframe: <boolean>,
  12524. * wireframeLinewidth: <float>
  12525. * }
  12526. */
  12527. class MeshDepthMaterial extends Material {
  12528. constructor(parameters) {
  12529. super();
  12530. this.type = 'MeshDepthMaterial';
  12531. this.depthPacking = BasicDepthPacking;
  12532. this.map = null;
  12533. this.alphaMap = null;
  12534. this.displacementMap = null;
  12535. this.displacementScale = 1;
  12536. this.displacementBias = 0;
  12537. this.wireframe = false;
  12538. this.wireframeLinewidth = 1;
  12539. this.fog = false;
  12540. this.setValues(parameters);
  12541. }
  12542. copy(source) {
  12543. super.copy(source);
  12544. this.depthPacking = source.depthPacking;
  12545. this.map = source.map;
  12546. this.alphaMap = source.alphaMap;
  12547. this.displacementMap = source.displacementMap;
  12548. this.displacementScale = source.displacementScale;
  12549. this.displacementBias = source.displacementBias;
  12550. this.wireframe = source.wireframe;
  12551. this.wireframeLinewidth = source.wireframeLinewidth;
  12552. return this;
  12553. }
  12554. }
  12555. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  12556. /**
  12557. * parameters = {
  12558. *
  12559. * referencePosition: <float>,
  12560. * nearDistance: <float>,
  12561. * farDistance: <float>,
  12562. *
  12563. * map: new THREE.Texture( <Image> ),
  12564. *
  12565. * alphaMap: new THREE.Texture( <Image> ),
  12566. *
  12567. * displacementMap: new THREE.Texture( <Image> ),
  12568. * displacementScale: <float>,
  12569. * displacementBias: <float>
  12570. *
  12571. * }
  12572. */
  12573. class MeshDistanceMaterial extends Material {
  12574. constructor(parameters) {
  12575. super();
  12576. this.type = 'MeshDistanceMaterial';
  12577. this.referencePosition = new Vector3();
  12578. this.nearDistance = 1;
  12579. this.farDistance = 1000;
  12580. this.map = null;
  12581. this.alphaMap = null;
  12582. this.displacementMap = null;
  12583. this.displacementScale = 1;
  12584. this.displacementBias = 0;
  12585. this.fog = false;
  12586. this.setValues(parameters);
  12587. }
  12588. copy(source) {
  12589. super.copy(source);
  12590. this.referencePosition.copy(source.referencePosition);
  12591. this.nearDistance = source.nearDistance;
  12592. this.farDistance = source.farDistance;
  12593. this.map = source.map;
  12594. this.alphaMap = source.alphaMap;
  12595. this.displacementMap = source.displacementMap;
  12596. this.displacementScale = source.displacementScale;
  12597. this.displacementBias = source.displacementBias;
  12598. return this;
  12599. }
  12600. }
  12601. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  12602. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12603. 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}";
  12604. function WebGLShadowMap(_renderer, _objects, _capabilities) {
  12605. let _frustum = new Frustum();
  12606. const _shadowMapSize = new Vector2(),
  12607. _viewportSize = new Vector2(),
  12608. _viewport = new Vector4(),
  12609. _depthMaterial = new MeshDepthMaterial({
  12610. depthPacking: RGBADepthPacking
  12611. }),
  12612. _distanceMaterial = new MeshDistanceMaterial(),
  12613. _materialCache = {},
  12614. _maxTextureSize = _capabilities.maxTextureSize;
  12615. const shadowSide = {
  12616. 0: BackSide,
  12617. 1: FrontSide,
  12618. 2: DoubleSide
  12619. };
  12620. const shadowMaterialVertical = new ShaderMaterial({
  12621. defines: {
  12622. VSM_SAMPLES: 8
  12623. },
  12624. uniforms: {
  12625. shadow_pass: {
  12626. value: null
  12627. },
  12628. resolution: {
  12629. value: new Vector2()
  12630. },
  12631. radius: {
  12632. value: 4.0
  12633. }
  12634. },
  12635. vertexShader: vertex,
  12636. fragmentShader: fragment
  12637. });
  12638. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12639. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12640. const fullScreenTri = new BufferGeometry();
  12641. fullScreenTri.setAttribute('position', new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  12642. const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  12643. const scope = this;
  12644. this.enabled = false;
  12645. this.autoUpdate = true;
  12646. this.needsUpdate = false;
  12647. this.type = PCFShadowMap;
  12648. this.render = function (lights, scene, camera) {
  12649. if (scope.enabled === false) return;
  12650. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  12651. if (lights.length === 0) return;
  12652. const currentRenderTarget = _renderer.getRenderTarget();
  12653. const activeCubeFace = _renderer.getActiveCubeFace();
  12654. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12655. const _state = _renderer.state; // Set GL state for depth map.
  12656. _state.setBlending(NoBlending);
  12657. _state.buffers.color.setClear(1, 1, 1, 1);
  12658. _state.buffers.depth.setTest(true);
  12659. _state.setScissorTest(false); // render depth map
  12660. for (let i = 0, il = lights.length; i < il; i++) {
  12661. const light = lights[i];
  12662. const shadow = light.shadow;
  12663. if (shadow === undefined) {
  12664. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  12665. continue;
  12666. }
  12667. if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
  12668. _shadowMapSize.copy(shadow.mapSize);
  12669. const shadowFrameExtents = shadow.getFrameExtents();
  12670. _shadowMapSize.multiply(shadowFrameExtents);
  12671. _viewportSize.copy(shadow.mapSize);
  12672. if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) {
  12673. if (_shadowMapSize.x > _maxTextureSize) {
  12674. _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x);
  12675. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12676. shadow.mapSize.x = _viewportSize.x;
  12677. }
  12678. if (_shadowMapSize.y > _maxTextureSize) {
  12679. _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y);
  12680. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12681. shadow.mapSize.y = _viewportSize.y;
  12682. }
  12683. }
  12684. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12685. const pars = {
  12686. minFilter: LinearFilter,
  12687. magFilter: LinearFilter,
  12688. format: RGBAFormat
  12689. };
  12690. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12691. shadow.map.texture.name = light.name + '.shadowMap';
  12692. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12693. shadow.camera.updateProjectionMatrix();
  12694. }
  12695. if (shadow.map === null) {
  12696. const pars = {
  12697. minFilter: NearestFilter,
  12698. magFilter: NearestFilter,
  12699. format: RGBAFormat
  12700. };
  12701. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12702. shadow.map.texture.name = light.name + '.shadowMap';
  12703. shadow.camera.updateProjectionMatrix();
  12704. }
  12705. _renderer.setRenderTarget(shadow.map);
  12706. _renderer.clear();
  12707. const viewportCount = shadow.getViewportCount();
  12708. for (let vp = 0; vp < viewportCount; vp++) {
  12709. const viewport = shadow.getViewport(vp);
  12710. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  12711. _state.viewport(_viewport);
  12712. shadow.updateMatrices(light, vp);
  12713. _frustum = shadow.getFrustum();
  12714. renderObject(scene, camera, shadow.camera, light, this.type);
  12715. } // do blur pass for VSM
  12716. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12717. VSMPass(shadow, camera);
  12718. }
  12719. shadow.needsUpdate = false;
  12720. }
  12721. scope.needsUpdate = false;
  12722. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  12723. };
  12724. function VSMPass(shadow, camera) {
  12725. const geometry = _objects.update(fullScreenMesh);
  12726. if (shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples) {
  12727. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  12728. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  12729. shadowMaterialVertical.needsUpdate = true;
  12730. shadowMaterialHorizontal.needsUpdate = true;
  12731. } // vertical pass
  12732. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12733. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12734. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12735. _renderer.setRenderTarget(shadow.mapPass);
  12736. _renderer.clear();
  12737. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizontal pass
  12738. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12739. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12740. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12741. _renderer.setRenderTarget(shadow.map);
  12742. _renderer.clear();
  12743. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null);
  12744. }
  12745. function getDepthMaterial(object, geometry, material, light, shadowCameraNear, shadowCameraFar, type) {
  12746. let result = null;
  12747. const customMaterial = light.isPointLight === true ? object.customDistanceMaterial : object.customDepthMaterial;
  12748. if (customMaterial !== undefined) {
  12749. result = customMaterial;
  12750. } else {
  12751. result = light.isPointLight === true ? _distanceMaterial : _depthMaterial;
  12752. }
  12753. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0 || material.displacementMap && material.displacementScale !== 0 || material.alphaMap && material.alphaTest > 0) {
  12754. // in this case we need a unique material instance reflecting the
  12755. // appropriate state
  12756. const keyA = result.uuid,
  12757. keyB = material.uuid;
  12758. let materialsForVariant = _materialCache[keyA];
  12759. if (materialsForVariant === undefined) {
  12760. materialsForVariant = {};
  12761. _materialCache[keyA] = materialsForVariant;
  12762. }
  12763. let cachedMaterial = materialsForVariant[keyB];
  12764. if (cachedMaterial === undefined) {
  12765. cachedMaterial = result.clone();
  12766. materialsForVariant[keyB] = cachedMaterial;
  12767. }
  12768. result = cachedMaterial;
  12769. }
  12770. result.visible = material.visible;
  12771. result.wireframe = material.wireframe;
  12772. if (type === VSMShadowMap) {
  12773. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  12774. } else {
  12775. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  12776. }
  12777. result.alphaMap = material.alphaMap;
  12778. result.alphaTest = material.alphaTest;
  12779. result.clipShadows = material.clipShadows;
  12780. result.clippingPlanes = material.clippingPlanes;
  12781. result.clipIntersection = material.clipIntersection;
  12782. result.displacementMap = material.displacementMap;
  12783. result.displacementScale = material.displacementScale;
  12784. result.displacementBias = material.displacementBias;
  12785. result.wireframeLinewidth = material.wireframeLinewidth;
  12786. result.linewidth = material.linewidth;
  12787. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  12788. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  12789. result.nearDistance = shadowCameraNear;
  12790. result.farDistance = shadowCameraFar;
  12791. }
  12792. return result;
  12793. }
  12794. function renderObject(object, camera, shadowCamera, light, type) {
  12795. if (object.visible === false) return;
  12796. const visible = object.layers.test(camera.layers);
  12797. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  12798. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  12799. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  12800. const geometry = _objects.update(object);
  12801. const material = object.material;
  12802. if (Array.isArray(material)) {
  12803. const groups = geometry.groups;
  12804. for (let k = 0, kl = groups.length; k < kl; k++) {
  12805. const group = groups[k];
  12806. const groupMaterial = material[group.materialIndex];
  12807. if (groupMaterial && groupMaterial.visible) {
  12808. const depthMaterial = getDepthMaterial(object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  12809. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  12810. }
  12811. }
  12812. } else if (material.visible) {
  12813. const depthMaterial = getDepthMaterial(object, geometry, material, light, shadowCamera.near, shadowCamera.far, type);
  12814. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  12815. }
  12816. }
  12817. }
  12818. const children = object.children;
  12819. for (let i = 0, l = children.length; i < l; i++) {
  12820. renderObject(children[i], camera, shadowCamera, light, type);
  12821. }
  12822. }
  12823. }
  12824. function WebGLState(gl, extensions, capabilities) {
  12825. const isWebGL2 = capabilities.isWebGL2;
  12826. function ColorBuffer() {
  12827. let locked = false;
  12828. const color = new Vector4();
  12829. let currentColorMask = null;
  12830. const currentColorClear = new Vector4(0, 0, 0, 0);
  12831. return {
  12832. setMask: function (colorMask) {
  12833. if (currentColorMask !== colorMask && !locked) {
  12834. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  12835. currentColorMask = colorMask;
  12836. }
  12837. },
  12838. setLocked: function (lock) {
  12839. locked = lock;
  12840. },
  12841. setClear: function (r, g, b, a, premultipliedAlpha) {
  12842. if (premultipliedAlpha === true) {
  12843. r *= a;
  12844. g *= a;
  12845. b *= a;
  12846. }
  12847. color.set(r, g, b, a);
  12848. if (currentColorClear.equals(color) === false) {
  12849. gl.clearColor(r, g, b, a);
  12850. currentColorClear.copy(color);
  12851. }
  12852. },
  12853. reset: function () {
  12854. locked = false;
  12855. currentColorMask = null;
  12856. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  12857. }
  12858. };
  12859. }
  12860. function DepthBuffer() {
  12861. let locked = false;
  12862. let currentDepthMask = null;
  12863. let currentDepthFunc = null;
  12864. let currentDepthClear = null;
  12865. return {
  12866. setTest: function (depthTest) {
  12867. if (depthTest) {
  12868. enable(gl.DEPTH_TEST);
  12869. } else {
  12870. disable(gl.DEPTH_TEST);
  12871. }
  12872. },
  12873. setMask: function (depthMask) {
  12874. if (currentDepthMask !== depthMask && !locked) {
  12875. gl.depthMask(depthMask);
  12876. currentDepthMask = depthMask;
  12877. }
  12878. },
  12879. setFunc: function (depthFunc) {
  12880. if (currentDepthFunc !== depthFunc) {
  12881. if (depthFunc) {
  12882. switch (depthFunc) {
  12883. case NeverDepth:
  12884. gl.depthFunc(gl.NEVER);
  12885. break;
  12886. case AlwaysDepth:
  12887. gl.depthFunc(gl.ALWAYS);
  12888. break;
  12889. case LessDepth:
  12890. gl.depthFunc(gl.LESS);
  12891. break;
  12892. case LessEqualDepth:
  12893. gl.depthFunc(gl.LEQUAL);
  12894. break;
  12895. case EqualDepth:
  12896. gl.depthFunc(gl.EQUAL);
  12897. break;
  12898. case GreaterEqualDepth:
  12899. gl.depthFunc(gl.GEQUAL);
  12900. break;
  12901. case GreaterDepth:
  12902. gl.depthFunc(gl.GREATER);
  12903. break;
  12904. case NotEqualDepth:
  12905. gl.depthFunc(gl.NOTEQUAL);
  12906. break;
  12907. default:
  12908. gl.depthFunc(gl.LEQUAL);
  12909. }
  12910. } else {
  12911. gl.depthFunc(gl.LEQUAL);
  12912. }
  12913. currentDepthFunc = depthFunc;
  12914. }
  12915. },
  12916. setLocked: function (lock) {
  12917. locked = lock;
  12918. },
  12919. setClear: function (depth) {
  12920. if (currentDepthClear !== depth) {
  12921. gl.clearDepth(depth);
  12922. currentDepthClear = depth;
  12923. }
  12924. },
  12925. reset: function () {
  12926. locked = false;
  12927. currentDepthMask = null;
  12928. currentDepthFunc = null;
  12929. currentDepthClear = null;
  12930. }
  12931. };
  12932. }
  12933. function StencilBuffer() {
  12934. let locked = false;
  12935. let currentStencilMask = null;
  12936. let currentStencilFunc = null;
  12937. let currentStencilRef = null;
  12938. let currentStencilFuncMask = null;
  12939. let currentStencilFail = null;
  12940. let currentStencilZFail = null;
  12941. let currentStencilZPass = null;
  12942. let currentStencilClear = null;
  12943. return {
  12944. setTest: function (stencilTest) {
  12945. if (!locked) {
  12946. if (stencilTest) {
  12947. enable(gl.STENCIL_TEST);
  12948. } else {
  12949. disable(gl.STENCIL_TEST);
  12950. }
  12951. }
  12952. },
  12953. setMask: function (stencilMask) {
  12954. if (currentStencilMask !== stencilMask && !locked) {
  12955. gl.stencilMask(stencilMask);
  12956. currentStencilMask = stencilMask;
  12957. }
  12958. },
  12959. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  12960. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  12961. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  12962. currentStencilFunc = stencilFunc;
  12963. currentStencilRef = stencilRef;
  12964. currentStencilFuncMask = stencilMask;
  12965. }
  12966. },
  12967. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  12968. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  12969. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  12970. currentStencilFail = stencilFail;
  12971. currentStencilZFail = stencilZFail;
  12972. currentStencilZPass = stencilZPass;
  12973. }
  12974. },
  12975. setLocked: function (lock) {
  12976. locked = lock;
  12977. },
  12978. setClear: function (stencil) {
  12979. if (currentStencilClear !== stencil) {
  12980. gl.clearStencil(stencil);
  12981. currentStencilClear = stencil;
  12982. }
  12983. },
  12984. reset: function () {
  12985. locked = false;
  12986. currentStencilMask = null;
  12987. currentStencilFunc = null;
  12988. currentStencilRef = null;
  12989. currentStencilFuncMask = null;
  12990. currentStencilFail = null;
  12991. currentStencilZFail = null;
  12992. currentStencilZPass = null;
  12993. currentStencilClear = null;
  12994. }
  12995. };
  12996. } //
  12997. const colorBuffer = new ColorBuffer();
  12998. const depthBuffer = new DepthBuffer();
  12999. const stencilBuffer = new StencilBuffer();
  13000. let enabledCapabilities = {};
  13001. let currentBoundFramebuffers = {};
  13002. let currentProgram = null;
  13003. let currentBlendingEnabled = false;
  13004. let currentBlending = null;
  13005. let currentBlendEquation = null;
  13006. let currentBlendSrc = null;
  13007. let currentBlendDst = null;
  13008. let currentBlendEquationAlpha = null;
  13009. let currentBlendSrcAlpha = null;
  13010. let currentBlendDstAlpha = null;
  13011. let currentPremultipledAlpha = false;
  13012. let currentFlipSided = null;
  13013. let currentCullFace = null;
  13014. let currentLineWidth = null;
  13015. let currentPolygonOffsetFactor = null;
  13016. let currentPolygonOffsetUnits = null;
  13017. const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  13018. let lineWidthAvailable = false;
  13019. let version = 0;
  13020. const glVersion = gl.getParameter(gl.VERSION);
  13021. if (glVersion.indexOf('WebGL') !== -1) {
  13022. version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]);
  13023. lineWidthAvailable = version >= 1.0;
  13024. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  13025. version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);
  13026. lineWidthAvailable = version >= 2.0;
  13027. }
  13028. let currentTextureSlot = null;
  13029. let currentBoundTextures = {};
  13030. const scissorParam = gl.getParameter(gl.SCISSOR_BOX);
  13031. const viewportParam = gl.getParameter(gl.VIEWPORT);
  13032. const currentScissor = new Vector4().fromArray(scissorParam);
  13033. const currentViewport = new Vector4().fromArray(viewportParam);
  13034. function createTexture(type, target, count) {
  13035. const data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  13036. const texture = gl.createTexture();
  13037. gl.bindTexture(type, texture);
  13038. gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13039. gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13040. for (let i = 0; i < count; i++) {
  13041. gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
  13042. }
  13043. return texture;
  13044. }
  13045. const emptyTextures = {};
  13046. emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1);
  13047. emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); // init
  13048. colorBuffer.setClear(0, 0, 0, 1);
  13049. depthBuffer.setClear(1);
  13050. stencilBuffer.setClear(0);
  13051. enable(gl.DEPTH_TEST);
  13052. depthBuffer.setFunc(LessEqualDepth);
  13053. setFlipSided(false);
  13054. setCullFace(CullFaceBack);
  13055. enable(gl.CULL_FACE);
  13056. setBlending(NoBlending); //
  13057. function enable(id) {
  13058. if (enabledCapabilities[id] !== true) {
  13059. gl.enable(id);
  13060. enabledCapabilities[id] = true;
  13061. }
  13062. }
  13063. function disable(id) {
  13064. if (enabledCapabilities[id] !== false) {
  13065. gl.disable(id);
  13066. enabledCapabilities[id] = false;
  13067. }
  13068. }
  13069. function bindFramebuffer(target, framebuffer) {
  13070. if (currentBoundFramebuffers[target] !== framebuffer) {
  13071. gl.bindFramebuffer(target, framebuffer);
  13072. currentBoundFramebuffers[target] = framebuffer;
  13073. if (isWebGL2) {
  13074. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  13075. if (target === gl.DRAW_FRAMEBUFFER) {
  13076. currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer;
  13077. }
  13078. if (target === gl.FRAMEBUFFER) {
  13079. currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer;
  13080. }
  13081. }
  13082. return true;
  13083. }
  13084. return false;
  13085. }
  13086. function useProgram(program) {
  13087. if (currentProgram !== program) {
  13088. gl.useProgram(program);
  13089. currentProgram = program;
  13090. return true;
  13091. }
  13092. return false;
  13093. }
  13094. const equationToGL = {
  13095. [AddEquation]: gl.FUNC_ADD,
  13096. [SubtractEquation]: gl.FUNC_SUBTRACT,
  13097. [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT
  13098. };
  13099. if (isWebGL2) {
  13100. equationToGL[MinEquation] = gl.MIN;
  13101. equationToGL[MaxEquation] = gl.MAX;
  13102. } else {
  13103. const extension = extensions.get('EXT_blend_minmax');
  13104. if (extension !== null) {
  13105. equationToGL[MinEquation] = extension.MIN_EXT;
  13106. equationToGL[MaxEquation] = extension.MAX_EXT;
  13107. }
  13108. }
  13109. const factorToGL = {
  13110. [ZeroFactor]: gl.ZERO,
  13111. [OneFactor]: gl.ONE,
  13112. [SrcColorFactor]: gl.SRC_COLOR,
  13113. [SrcAlphaFactor]: gl.SRC_ALPHA,
  13114. [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE,
  13115. [DstColorFactor]: gl.DST_COLOR,
  13116. [DstAlphaFactor]: gl.DST_ALPHA,
  13117. [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR,
  13118. [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA,
  13119. [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR,
  13120. [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA
  13121. };
  13122. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  13123. if (blending === NoBlending) {
  13124. if (currentBlendingEnabled === true) {
  13125. disable(gl.BLEND);
  13126. currentBlendingEnabled = false;
  13127. }
  13128. return;
  13129. }
  13130. if (currentBlendingEnabled === false) {
  13131. enable(gl.BLEND);
  13132. currentBlendingEnabled = true;
  13133. }
  13134. if (blending !== CustomBlending) {
  13135. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  13136. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  13137. gl.blendEquation(gl.FUNC_ADD);
  13138. currentBlendEquation = AddEquation;
  13139. currentBlendEquationAlpha = AddEquation;
  13140. }
  13141. if (premultipliedAlpha) {
  13142. switch (blending) {
  13143. case NormalBlending:
  13144. gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  13145. break;
  13146. case AdditiveBlending:
  13147. gl.blendFunc(gl.ONE, gl.ONE);
  13148. break;
  13149. case SubtractiveBlending:
  13150. gl.blendFuncSeparate(gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA);
  13151. break;
  13152. case MultiplyBlending:
  13153. gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA);
  13154. break;
  13155. default:
  13156. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13157. break;
  13158. }
  13159. } else {
  13160. switch (blending) {
  13161. case NormalBlending:
  13162. gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  13163. break;
  13164. case AdditiveBlending:
  13165. gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  13166. break;
  13167. case SubtractiveBlending:
  13168. gl.blendFunc(gl.ZERO, gl.ONE_MINUS_SRC_COLOR);
  13169. break;
  13170. case MultiplyBlending:
  13171. gl.blendFunc(gl.ZERO, gl.SRC_COLOR);
  13172. break;
  13173. default:
  13174. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13175. break;
  13176. }
  13177. }
  13178. currentBlendSrc = null;
  13179. currentBlendDst = null;
  13180. currentBlendSrcAlpha = null;
  13181. currentBlendDstAlpha = null;
  13182. currentBlending = blending;
  13183. currentPremultipledAlpha = premultipliedAlpha;
  13184. }
  13185. return;
  13186. } // custom blending
  13187. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13188. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13189. blendDstAlpha = blendDstAlpha || blendDst;
  13190. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  13191. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  13192. currentBlendEquation = blendEquation;
  13193. currentBlendEquationAlpha = blendEquationAlpha;
  13194. }
  13195. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  13196. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  13197. currentBlendSrc = blendSrc;
  13198. currentBlendDst = blendDst;
  13199. currentBlendSrcAlpha = blendSrcAlpha;
  13200. currentBlendDstAlpha = blendDstAlpha;
  13201. }
  13202. currentBlending = blending;
  13203. currentPremultipledAlpha = null;
  13204. }
  13205. function setMaterial(material, frontFaceCW) {
  13206. material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE);
  13207. let flipSided = material.side === BackSide;
  13208. if (frontFaceCW) flipSided = !flipSided;
  13209. setFlipSided(flipSided);
  13210. material.blending === NormalBlending && material.transparent === false ? setBlending(NoBlending) : setBlending(material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha);
  13211. depthBuffer.setFunc(material.depthFunc);
  13212. depthBuffer.setTest(material.depthTest);
  13213. depthBuffer.setMask(material.depthWrite);
  13214. colorBuffer.setMask(material.colorWrite);
  13215. const stencilWrite = material.stencilWrite;
  13216. stencilBuffer.setTest(stencilWrite);
  13217. if (stencilWrite) {
  13218. stencilBuffer.setMask(material.stencilWriteMask);
  13219. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  13220. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  13221. }
  13222. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  13223. material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  13224. } //
  13225. function setFlipSided(flipSided) {
  13226. if (currentFlipSided !== flipSided) {
  13227. if (flipSided) {
  13228. gl.frontFace(gl.CW);
  13229. } else {
  13230. gl.frontFace(gl.CCW);
  13231. }
  13232. currentFlipSided = flipSided;
  13233. }
  13234. }
  13235. function setCullFace(cullFace) {
  13236. if (cullFace !== CullFaceNone) {
  13237. enable(gl.CULL_FACE);
  13238. if (cullFace !== currentCullFace) {
  13239. if (cullFace === CullFaceBack) {
  13240. gl.cullFace(gl.BACK);
  13241. } else if (cullFace === CullFaceFront) {
  13242. gl.cullFace(gl.FRONT);
  13243. } else {
  13244. gl.cullFace(gl.FRONT_AND_BACK);
  13245. }
  13246. }
  13247. } else {
  13248. disable(gl.CULL_FACE);
  13249. }
  13250. currentCullFace = cullFace;
  13251. }
  13252. function setLineWidth(width) {
  13253. if (width !== currentLineWidth) {
  13254. if (lineWidthAvailable) gl.lineWidth(width);
  13255. currentLineWidth = width;
  13256. }
  13257. }
  13258. function setPolygonOffset(polygonOffset, factor, units) {
  13259. if (polygonOffset) {
  13260. enable(gl.POLYGON_OFFSET_FILL);
  13261. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  13262. gl.polygonOffset(factor, units);
  13263. currentPolygonOffsetFactor = factor;
  13264. currentPolygonOffsetUnits = units;
  13265. }
  13266. } else {
  13267. disable(gl.POLYGON_OFFSET_FILL);
  13268. }
  13269. }
  13270. function setScissorTest(scissorTest) {
  13271. if (scissorTest) {
  13272. enable(gl.SCISSOR_TEST);
  13273. } else {
  13274. disable(gl.SCISSOR_TEST);
  13275. }
  13276. } // texture
  13277. function activeTexture(webglSlot) {
  13278. if (webglSlot === undefined) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13279. if (currentTextureSlot !== webglSlot) {
  13280. gl.activeTexture(webglSlot);
  13281. currentTextureSlot = webglSlot;
  13282. }
  13283. }
  13284. function bindTexture(webglType, webglTexture) {
  13285. if (currentTextureSlot === null) {
  13286. activeTexture();
  13287. }
  13288. let boundTexture = currentBoundTextures[currentTextureSlot];
  13289. if (boundTexture === undefined) {
  13290. boundTexture = {
  13291. type: undefined,
  13292. texture: undefined
  13293. };
  13294. currentBoundTextures[currentTextureSlot] = boundTexture;
  13295. }
  13296. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  13297. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  13298. boundTexture.type = webglType;
  13299. boundTexture.texture = webglTexture;
  13300. }
  13301. }
  13302. function unbindTexture() {
  13303. const boundTexture = currentBoundTextures[currentTextureSlot];
  13304. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  13305. gl.bindTexture(boundTexture.type, null);
  13306. boundTexture.type = undefined;
  13307. boundTexture.texture = undefined;
  13308. }
  13309. }
  13310. function compressedTexImage2D() {
  13311. try {
  13312. gl.compressedTexImage2D.apply(gl, arguments);
  13313. } catch (error) {
  13314. console.error('THREE.WebGLState:', error);
  13315. }
  13316. }
  13317. function texSubImage2D() {
  13318. try {
  13319. gl.texSubImage2D.apply(gl, arguments);
  13320. } catch (error) {
  13321. console.error('THREE.WebGLState:', error);
  13322. }
  13323. }
  13324. function texSubImage3D() {
  13325. try {
  13326. gl.texSubImage3D.apply(gl, arguments);
  13327. } catch (error) {
  13328. console.error('THREE.WebGLState:', error);
  13329. }
  13330. }
  13331. function compressedTexSubImage2D() {
  13332. try {
  13333. gl.compressedTexSubImage2D.apply(gl, arguments);
  13334. } catch (error) {
  13335. console.error('THREE.WebGLState:', error);
  13336. }
  13337. }
  13338. function texStorage2D() {
  13339. try {
  13340. gl.texStorage2D.apply(gl, arguments);
  13341. } catch (error) {
  13342. console.error('THREE.WebGLState:', error);
  13343. }
  13344. }
  13345. function texStorage3D() {
  13346. try {
  13347. gl.texStorage3D.apply(gl, arguments);
  13348. } catch (error) {
  13349. console.error('THREE.WebGLState:', error);
  13350. }
  13351. }
  13352. function texImage2D() {
  13353. try {
  13354. gl.texImage2D.apply(gl, arguments);
  13355. } catch (error) {
  13356. console.error('THREE.WebGLState:', error);
  13357. }
  13358. }
  13359. function texImage3D() {
  13360. try {
  13361. gl.texImage3D.apply(gl, arguments);
  13362. } catch (error) {
  13363. console.error('THREE.WebGLState:', error);
  13364. }
  13365. } //
  13366. function scissor(scissor) {
  13367. if (currentScissor.equals(scissor) === false) {
  13368. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  13369. currentScissor.copy(scissor);
  13370. }
  13371. }
  13372. function viewport(viewport) {
  13373. if (currentViewport.equals(viewport) === false) {
  13374. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  13375. currentViewport.copy(viewport);
  13376. }
  13377. } //
  13378. function reset() {
  13379. // reset state
  13380. gl.disable(gl.BLEND);
  13381. gl.disable(gl.CULL_FACE);
  13382. gl.disable(gl.DEPTH_TEST);
  13383. gl.disable(gl.POLYGON_OFFSET_FILL);
  13384. gl.disable(gl.SCISSOR_TEST);
  13385. gl.disable(gl.STENCIL_TEST);
  13386. gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  13387. gl.blendEquation(gl.FUNC_ADD);
  13388. gl.blendFunc(gl.ONE, gl.ZERO);
  13389. gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO);
  13390. gl.colorMask(true, true, true, true);
  13391. gl.clearColor(0, 0, 0, 0);
  13392. gl.depthMask(true);
  13393. gl.depthFunc(gl.LESS);
  13394. gl.clearDepth(1);
  13395. gl.stencilMask(0xffffffff);
  13396. gl.stencilFunc(gl.ALWAYS, 0, 0xffffffff);
  13397. gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
  13398. gl.clearStencil(0);
  13399. gl.cullFace(gl.BACK);
  13400. gl.frontFace(gl.CCW);
  13401. gl.polygonOffset(0, 0);
  13402. gl.activeTexture(gl.TEXTURE0);
  13403. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13404. if (isWebGL2 === true) {
  13405. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
  13406. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  13407. }
  13408. gl.useProgram(null);
  13409. gl.lineWidth(1);
  13410. gl.scissor(0, 0, gl.canvas.width, gl.canvas.height);
  13411. gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); // reset internals
  13412. enabledCapabilities = {};
  13413. currentTextureSlot = null;
  13414. currentBoundTextures = {};
  13415. currentBoundFramebuffers = {};
  13416. currentProgram = null;
  13417. currentBlendingEnabled = false;
  13418. currentBlending = null;
  13419. currentBlendEquation = null;
  13420. currentBlendSrc = null;
  13421. currentBlendDst = null;
  13422. currentBlendEquationAlpha = null;
  13423. currentBlendSrcAlpha = null;
  13424. currentBlendDstAlpha = null;
  13425. currentPremultipledAlpha = false;
  13426. currentFlipSided = null;
  13427. currentCullFace = null;
  13428. currentLineWidth = null;
  13429. currentPolygonOffsetFactor = null;
  13430. currentPolygonOffsetUnits = null;
  13431. currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height);
  13432. currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height);
  13433. colorBuffer.reset();
  13434. depthBuffer.reset();
  13435. stencilBuffer.reset();
  13436. }
  13437. return {
  13438. buffers: {
  13439. color: colorBuffer,
  13440. depth: depthBuffer,
  13441. stencil: stencilBuffer
  13442. },
  13443. enable: enable,
  13444. disable: disable,
  13445. bindFramebuffer: bindFramebuffer,
  13446. useProgram: useProgram,
  13447. setBlending: setBlending,
  13448. setMaterial: setMaterial,
  13449. setFlipSided: setFlipSided,
  13450. setCullFace: setCullFace,
  13451. setLineWidth: setLineWidth,
  13452. setPolygonOffset: setPolygonOffset,
  13453. setScissorTest: setScissorTest,
  13454. activeTexture: activeTexture,
  13455. bindTexture: bindTexture,
  13456. unbindTexture: unbindTexture,
  13457. compressedTexImage2D: compressedTexImage2D,
  13458. texImage2D: texImage2D,
  13459. texImage3D: texImage3D,
  13460. texStorage2D: texStorage2D,
  13461. texStorage3D: texStorage3D,
  13462. texSubImage2D: texSubImage2D,
  13463. texSubImage3D: texSubImage3D,
  13464. compressedTexSubImage2D: compressedTexSubImage2D,
  13465. scissor: scissor,
  13466. viewport: viewport,
  13467. reset: reset
  13468. };
  13469. }
  13470. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  13471. const isWebGL2 = capabilities.isWebGL2;
  13472. const maxTextures = capabilities.maxTextures;
  13473. const maxCubemapSize = capabilities.maxCubemapSize;
  13474. const maxTextureSize = capabilities.maxTextureSize;
  13475. const maxSamples = capabilities.maxSamples;
  13476. const hasMultisampledRenderToTexture = extensions.has('WEBGL_multisampled_render_to_texture');
  13477. const MultisampledRenderToTextureExtension = hasMultisampledRenderToTexture ? extensions.get('WEBGL_multisampled_render_to_texture') : undefined;
  13478. const _videoTextures = new WeakMap();
  13479. let _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13480. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13481. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13482. let useOffscreenCanvas = false;
  13483. try {
  13484. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext('2d') !== null;
  13485. } catch (err) {// Ignore any errors
  13486. }
  13487. function createCanvas(width, height) {
  13488. // Use OffscreenCanvas when available. Specially needed in web workers
  13489. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : createElementNS('canvas');
  13490. }
  13491. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  13492. let scale = 1; // handle case if texture exceeds max size
  13493. if (image.width > maxSize || image.height > maxSize) {
  13494. scale = maxSize / Math.max(image.width, image.height);
  13495. } // only perform resize if necessary
  13496. if (scale < 1 || needsPowerOfTwo === true) {
  13497. // only perform resize for certain image types
  13498. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  13499. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13500. const width = floor(scale * image.width);
  13501. const height = floor(scale * image.height);
  13502. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  13503. const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  13504. canvas.width = width;
  13505. canvas.height = height;
  13506. const context = canvas.getContext('2d');
  13507. context.drawImage(image, 0, 0, width, height);
  13508. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  13509. return canvas;
  13510. } else {
  13511. if ('data' in image) {
  13512. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  13513. }
  13514. return image;
  13515. }
  13516. }
  13517. return image;
  13518. }
  13519. function isPowerOfTwo$1(image) {
  13520. return isPowerOfTwo(image.width) && isPowerOfTwo(image.height);
  13521. }
  13522. function textureNeedsPowerOfTwo(texture) {
  13523. if (isWebGL2) return false;
  13524. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13525. }
  13526. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  13527. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13528. }
  13529. function generateMipmap(target) {
  13530. _gl.generateMipmap(target);
  13531. }
  13532. function getInternalFormat(internalFormatName, glFormat, glType, encoding) {
  13533. if (isWebGL2 === false) return glFormat;
  13534. if (internalFormatName !== null) {
  13535. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  13536. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  13537. }
  13538. let internalFormat = glFormat;
  13539. if (glFormat === _gl.RED) {
  13540. if (glType === _gl.FLOAT) internalFormat = _gl.R32F;
  13541. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.R16F;
  13542. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8;
  13543. }
  13544. if (glFormat === _gl.RGB) {
  13545. if (glType === _gl.FLOAT) internalFormat = _gl.RGB32F;
  13546. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGB16F;
  13547. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGB8;
  13548. }
  13549. if (glFormat === _gl.RGBA) {
  13550. if (glType === _gl.FLOAT) internalFormat = _gl.RGBA32F;
  13551. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGBA16F;
  13552. if (glType === _gl.UNSIGNED_BYTE) internalFormat = encoding === sRGBEncoding ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  13553. }
  13554. if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) {
  13555. extensions.get('EXT_color_buffer_float');
  13556. }
  13557. return internalFormat;
  13558. }
  13559. function getMipLevels(texture, image, supportsMips) {
  13560. if (textureNeedsGenerateMipmaps(texture, supportsMips) === true || texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13561. return Math.log2(Math.max(image.width, image.height)) + 1;
  13562. } else if (texture.mipmaps !== undefined && texture.mipmaps.length > 0) {
  13563. // user-defined mipmaps
  13564. return texture.mipmaps.length;
  13565. } else if (texture.isCompressedTexture && Array.isArray(texture.image)) {
  13566. return image.mipmaps.length;
  13567. } else {
  13568. // texture without mipmaps (only base level)
  13569. return 1;
  13570. }
  13571. } // Fallback filters for non-power-of-2 textures
  13572. function filterFallback(f) {
  13573. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  13574. return _gl.NEAREST;
  13575. }
  13576. return _gl.LINEAR;
  13577. } //
  13578. function onTextureDispose(event) {
  13579. const texture = event.target;
  13580. texture.removeEventListener('dispose', onTextureDispose);
  13581. deallocateTexture(texture);
  13582. if (texture.isVideoTexture) {
  13583. _videoTextures.delete(texture);
  13584. }
  13585. info.memory.textures--;
  13586. }
  13587. function onRenderTargetDispose(event) {
  13588. const renderTarget = event.target;
  13589. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  13590. deallocateRenderTarget(renderTarget);
  13591. } //
  13592. function deallocateTexture(texture) {
  13593. const textureProperties = properties.get(texture);
  13594. if (textureProperties.__webglInit === undefined) return;
  13595. _gl.deleteTexture(textureProperties.__webglTexture);
  13596. properties.remove(texture);
  13597. }
  13598. function deallocateRenderTarget(renderTarget) {
  13599. const texture = renderTarget.texture;
  13600. const renderTargetProperties = properties.get(renderTarget);
  13601. const textureProperties = properties.get(texture);
  13602. if (!renderTarget) return;
  13603. if (textureProperties.__webglTexture !== undefined) {
  13604. _gl.deleteTexture(textureProperties.__webglTexture);
  13605. info.memory.textures--;
  13606. }
  13607. if (renderTarget.depthTexture) {
  13608. renderTarget.depthTexture.dispose();
  13609. }
  13610. if (renderTarget.isWebGLCubeRenderTarget) {
  13611. for (let i = 0; i < 6; i++) {
  13612. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  13613. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  13614. }
  13615. } else {
  13616. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  13617. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  13618. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  13619. if (renderTargetProperties.__webglColorRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);
  13620. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  13621. }
  13622. if (renderTarget.isWebGLMultipleRenderTargets) {
  13623. for (let i = 0, il = texture.length; i < il; i++) {
  13624. const attachmentProperties = properties.get(texture[i]);
  13625. if (attachmentProperties.__webglTexture) {
  13626. _gl.deleteTexture(attachmentProperties.__webglTexture);
  13627. info.memory.textures--;
  13628. }
  13629. properties.remove(texture[i]);
  13630. }
  13631. }
  13632. properties.remove(texture);
  13633. properties.remove(renderTarget);
  13634. } //
  13635. let textureUnits = 0;
  13636. function resetTextureUnits() {
  13637. textureUnits = 0;
  13638. }
  13639. function allocateTextureUnit() {
  13640. const textureUnit = textureUnits;
  13641. if (textureUnit >= maxTextures) {
  13642. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  13643. }
  13644. textureUnits += 1;
  13645. return textureUnit;
  13646. } //
  13647. function setTexture2D(texture, slot) {
  13648. const textureProperties = properties.get(texture);
  13649. if (texture.isVideoTexture) updateVideoTexture(texture);
  13650. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13651. const image = texture.image;
  13652. if (image === undefined) {
  13653. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  13654. } else if (image.complete === false) {
  13655. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  13656. } else {
  13657. uploadTexture(textureProperties, texture, slot);
  13658. return;
  13659. }
  13660. }
  13661. state.activeTexture(_gl.TEXTURE0 + slot);
  13662. state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture);
  13663. }
  13664. function setTexture2DArray(texture, slot) {
  13665. const textureProperties = properties.get(texture);
  13666. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13667. uploadTexture(textureProperties, texture, slot);
  13668. return;
  13669. }
  13670. state.activeTexture(_gl.TEXTURE0 + slot);
  13671. state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture);
  13672. }
  13673. function setTexture3D(texture, slot) {
  13674. const textureProperties = properties.get(texture);
  13675. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13676. uploadTexture(textureProperties, texture, slot);
  13677. return;
  13678. }
  13679. state.activeTexture(_gl.TEXTURE0 + slot);
  13680. state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture);
  13681. }
  13682. function setTextureCube(texture, slot) {
  13683. const textureProperties = properties.get(texture);
  13684. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13685. uploadCubeTexture(textureProperties, texture, slot);
  13686. return;
  13687. }
  13688. state.activeTexture(_gl.TEXTURE0 + slot);
  13689. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  13690. }
  13691. const wrappingToGL = {
  13692. [RepeatWrapping]: _gl.REPEAT,
  13693. [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE,
  13694. [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT
  13695. };
  13696. const filterToGL = {
  13697. [NearestFilter]: _gl.NEAREST,
  13698. [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST,
  13699. [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR,
  13700. [LinearFilter]: _gl.LINEAR,
  13701. [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST,
  13702. [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR
  13703. };
  13704. function setTextureParameters(textureType, texture, supportsMips) {
  13705. if (supportsMips) {
  13706. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]);
  13707. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]);
  13708. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  13709. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]);
  13710. }
  13711. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]);
  13712. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]);
  13713. } else {
  13714. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE);
  13715. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE);
  13716. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  13717. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE);
  13718. }
  13719. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  13720. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  13721. }
  13722. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterFallback(texture.magFilter));
  13723. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterFallback(texture.minFilter));
  13724. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13725. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  13726. }
  13727. }
  13728. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  13729. const extension = extensions.get('EXT_texture_filter_anisotropic');
  13730. if (texture.type === FloatType && extensions.has('OES_texture_float_linear') === false) return; // verify extension for WebGL 1 and WebGL 2
  13731. if (isWebGL2 === false && texture.type === HalfFloatType && extensions.has('OES_texture_half_float_linear') === false) return; // verify extension for WebGL 1 only
  13732. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  13733. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  13734. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  13735. }
  13736. }
  13737. }
  13738. function initTexture(textureProperties, texture) {
  13739. if (textureProperties.__webglInit === undefined) {
  13740. textureProperties.__webglInit = true;
  13741. texture.addEventListener('dispose', onTextureDispose);
  13742. textureProperties.__webglTexture = _gl.createTexture();
  13743. info.memory.textures++;
  13744. }
  13745. }
  13746. function uploadTexture(textureProperties, texture, slot) {
  13747. let textureType = _gl.TEXTURE_2D;
  13748. if (texture.isDataTexture2DArray) textureType = _gl.TEXTURE_2D_ARRAY;
  13749. if (texture.isDataTexture3D) textureType = _gl.TEXTURE_3D;
  13750. initTexture(textureProperties, texture);
  13751. state.activeTexture(_gl.TEXTURE0 + slot);
  13752. state.bindTexture(textureType, textureProperties.__webglTexture);
  13753. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  13754. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  13755. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  13756. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  13757. const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo$1(texture.image) === false;
  13758. const image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  13759. const supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  13760. glFormat = utils.convert(texture.format);
  13761. let glType = utils.convert(texture.type),
  13762. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  13763. setTextureParameters(textureType, texture, supportsMips);
  13764. let mipmap;
  13765. const mipmaps = texture.mipmaps;
  13766. const useTexStorage = isWebGL2 && texture.isVideoTexture !== true;
  13767. const allocateMemory = textureProperties.__version === undefined;
  13768. const levels = getMipLevels(texture, image, supportsMips);
  13769. if (texture.isDepthTexture) {
  13770. // populate depth texture with dummy data
  13771. glInternalFormat = _gl.DEPTH_COMPONENT;
  13772. if (isWebGL2) {
  13773. if (texture.type === FloatType) {
  13774. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  13775. } else if (texture.type === UnsignedIntType) {
  13776. glInternalFormat = _gl.DEPTH_COMPONENT24;
  13777. } else if (texture.type === UnsignedInt248Type) {
  13778. glInternalFormat = _gl.DEPTH24_STENCIL8;
  13779. } else {
  13780. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  13781. }
  13782. } else {
  13783. if (texture.type === FloatType) {
  13784. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  13785. }
  13786. } // validation checks for WebGL 1
  13787. if (texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  13788. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13789. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13790. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13791. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  13792. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  13793. texture.type = UnsignedShortType;
  13794. glType = utils.convert(texture.type);
  13795. }
  13796. }
  13797. if (texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  13798. // Depth stencil textures need the DEPTH_STENCIL internal format
  13799. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13800. glInternalFormat = _gl.DEPTH_STENCIL; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13801. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13802. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13803. if (texture.type !== UnsignedInt248Type) {
  13804. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  13805. texture.type = UnsignedInt248Type;
  13806. glType = utils.convert(texture.type);
  13807. }
  13808. } //
  13809. if (useTexStorage && allocateMemory) {
  13810. state.texStorage2D(_gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height);
  13811. } else {
  13812. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  13813. }
  13814. } else if (texture.isDataTexture) {
  13815. // use manually created mipmaps if available
  13816. // if there are no manual mipmaps
  13817. // set 0 level mipmap and then use GL to generate other mipmap levels
  13818. if (mipmaps.length > 0 && supportsMips) {
  13819. if (useTexStorage && allocateMemory) {
  13820. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  13821. }
  13822. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13823. mipmap = mipmaps[i];
  13824. if (useTexStorage) {
  13825. state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  13826. } else {
  13827. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13828. }
  13829. }
  13830. texture.generateMipmaps = false;
  13831. } else {
  13832. if (useTexStorage) {
  13833. if (allocateMemory) {
  13834. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  13835. }
  13836. state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data);
  13837. } else {
  13838. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  13839. }
  13840. }
  13841. } else if (texture.isCompressedTexture) {
  13842. if (useTexStorage && allocateMemory) {
  13843. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  13844. }
  13845. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13846. mipmap = mipmaps[i];
  13847. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13848. if (glFormat !== null) {
  13849. if (useTexStorage) {
  13850. state.compressedTexSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data);
  13851. } else {
  13852. state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13853. }
  13854. } else {
  13855. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  13856. }
  13857. } else {
  13858. if (useTexStorage) {
  13859. state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  13860. } else {
  13861. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13862. }
  13863. }
  13864. }
  13865. } else if (texture.isDataTexture2DArray) {
  13866. if (useTexStorage) {
  13867. if (allocateMemory) {
  13868. state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth);
  13869. }
  13870. state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data);
  13871. } else {
  13872. state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13873. }
  13874. } else if (texture.isDataTexture3D) {
  13875. if (useTexStorage) {
  13876. if (allocateMemory) {
  13877. state.texStorage3D(_gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth);
  13878. }
  13879. state.texSubImage3D(_gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data);
  13880. } else {
  13881. state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13882. }
  13883. } else if (texture.isFramebufferTexture) {
  13884. if (useTexStorage && allocateMemory) {
  13885. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  13886. } else {
  13887. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  13888. }
  13889. } else {
  13890. // regular Texture (image, video, canvas)
  13891. // use manually created mipmaps if available
  13892. // if there are no manual mipmaps
  13893. // set 0 level mipmap and then use GL to generate other mipmap levels
  13894. if (mipmaps.length > 0 && supportsMips) {
  13895. if (useTexStorage && allocateMemory) {
  13896. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  13897. }
  13898. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13899. mipmap = mipmaps[i];
  13900. if (useTexStorage) {
  13901. state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap);
  13902. } else {
  13903. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap);
  13904. }
  13905. }
  13906. texture.generateMipmaps = false;
  13907. } else {
  13908. if (useTexStorage) {
  13909. if (allocateMemory) {
  13910. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  13911. }
  13912. state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image);
  13913. } else {
  13914. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image);
  13915. }
  13916. }
  13917. }
  13918. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13919. generateMipmap(textureType);
  13920. }
  13921. textureProperties.__version = texture.version;
  13922. if (texture.onUpdate) texture.onUpdate(texture);
  13923. }
  13924. function uploadCubeTexture(textureProperties, texture, slot) {
  13925. if (texture.image.length !== 6) return;
  13926. initTexture(textureProperties, texture);
  13927. state.activeTexture(_gl.TEXTURE0 + slot);
  13928. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  13929. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  13930. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  13931. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  13932. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  13933. const isCompressed = texture && (texture.isCompressedTexture || texture.image[0].isCompressedTexture);
  13934. const isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  13935. const cubeImage = [];
  13936. for (let i = 0; i < 6; i++) {
  13937. if (!isCompressed && !isDataTexture) {
  13938. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  13939. } else {
  13940. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  13941. }
  13942. }
  13943. const image = cubeImage[0],
  13944. supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  13945. glFormat = utils.convert(texture.format),
  13946. glType = utils.convert(texture.type),
  13947. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  13948. const useTexStorage = isWebGL2 && texture.isVideoTexture !== true;
  13949. const allocateMemory = textureProperties.__version === undefined;
  13950. let levels = getMipLevels(texture, image, supportsMips);
  13951. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  13952. let mipmaps;
  13953. if (isCompressed) {
  13954. if (useTexStorage && allocateMemory) {
  13955. state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height);
  13956. }
  13957. for (let i = 0; i < 6; i++) {
  13958. mipmaps = cubeImage[i].mipmaps;
  13959. for (let j = 0; j < mipmaps.length; j++) {
  13960. const mipmap = mipmaps[j];
  13961. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13962. if (glFormat !== null) {
  13963. if (useTexStorage) {
  13964. state.compressedTexSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data);
  13965. } else {
  13966. state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13967. }
  13968. } else {
  13969. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  13970. }
  13971. } else {
  13972. if (useTexStorage) {
  13973. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  13974. } else {
  13975. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13976. }
  13977. }
  13978. }
  13979. }
  13980. } else {
  13981. mipmaps = texture.mipmaps;
  13982. if (useTexStorage && allocateMemory) {
  13983. // TODO: Uniformly handle mipmap definitions
  13984. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  13985. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  13986. if (mipmaps.length > 0) levels++;
  13987. state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[0].width, cubeImage[0].height);
  13988. }
  13989. for (let i = 0; i < 6; i++) {
  13990. if (isDataTexture) {
  13991. if (useTexStorage) {
  13992. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[i].width, cubeImage[i].height, glFormat, glType, cubeImage[i].data);
  13993. } else {
  13994. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  13995. }
  13996. for (let j = 0; j < mipmaps.length; j++) {
  13997. const mipmap = mipmaps[j];
  13998. const mipmapImage = mipmap.image[i].image;
  13999. if (useTexStorage) {
  14000. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data);
  14001. } else {
  14002. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  14003. }
  14004. }
  14005. } else {
  14006. if (useTexStorage) {
  14007. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[i]);
  14008. } else {
  14009. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  14010. }
  14011. for (let j = 0; j < mipmaps.length; j++) {
  14012. const mipmap = mipmaps[j];
  14013. if (useTexStorage) {
  14014. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[i]);
  14015. } else {
  14016. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  14017. }
  14018. }
  14019. }
  14020. }
  14021. }
  14022. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14023. // We assume images for cube map have the same size.
  14024. generateMipmap(_gl.TEXTURE_CUBE_MAP);
  14025. }
  14026. textureProperties.__version = texture.version;
  14027. if (texture.onUpdate) texture.onUpdate(texture);
  14028. } // Render targets
  14029. // Setup storage for target texture and bind it to correct framebuffer
  14030. function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget) {
  14031. const glFormat = utils.convert(texture.format);
  14032. const glType = utils.convert(texture.type);
  14033. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14034. const renderTargetProperties = properties.get(renderTarget);
  14035. if (!renderTargetProperties.__hasExternalTextures) {
  14036. if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) {
  14037. state.texImage3D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null);
  14038. } else {
  14039. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  14040. }
  14041. }
  14042. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  14043. if (renderTarget.useRenderToTexture) {
  14044. MultisampledRenderToTextureExtension.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0, getRenderTargetSamples(renderTarget));
  14045. } else {
  14046. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0);
  14047. }
  14048. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  14049. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14050. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  14051. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer);
  14052. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  14053. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  14054. if (isMultisample || renderTarget.useRenderToTexture) {
  14055. const depthTexture = renderTarget.depthTexture;
  14056. if (depthTexture && depthTexture.isDepthTexture) {
  14057. if (depthTexture.type === FloatType) {
  14058. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14059. } else if (depthTexture.type === UnsignedIntType) {
  14060. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14061. }
  14062. }
  14063. const samples = getRenderTargetSamples(renderTarget);
  14064. if (renderTarget.useRenderToTexture) {
  14065. MultisampledRenderToTextureExtension.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14066. } else {
  14067. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14068. }
  14069. } else {
  14070. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  14071. }
  14072. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  14073. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  14074. const samples = getRenderTargetSamples(renderTarget);
  14075. if (isMultisample && renderTarget.useRenderbuffer) {
  14076. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  14077. } else if (renderTarget.useRenderToTexture) {
  14078. MultisampledRenderToTextureExtension.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  14079. } else {
  14080. _gl.renderbufferStorage(_gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height);
  14081. }
  14082. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  14083. } else {
  14084. // Use the first texture for MRT so far
  14085. const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[0] : renderTarget.texture;
  14086. const glFormat = utils.convert(texture.format);
  14087. const glType = utils.convert(texture.type);
  14088. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14089. const samples = getRenderTargetSamples(renderTarget);
  14090. if (isMultisample && renderTarget.useRenderbuffer) {
  14091. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14092. } else if (renderTarget.useRenderToTexture) {
  14093. MultisampledRenderToTextureExtension.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14094. } else {
  14095. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  14096. }
  14097. }
  14098. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  14099. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  14100. function setupDepthTexture(framebuffer, renderTarget) {
  14101. const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  14102. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  14103. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  14104. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  14105. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  14106. } // upload an empty depth texture with framebuffer size
  14107. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  14108. renderTarget.depthTexture.image.width = renderTarget.width;
  14109. renderTarget.depthTexture.image.height = renderTarget.height;
  14110. renderTarget.depthTexture.needsUpdate = true;
  14111. }
  14112. setTexture2D(renderTarget.depthTexture, 0);
  14113. const webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  14114. const samples = getRenderTargetSamples(renderTarget);
  14115. if (renderTarget.depthTexture.format === DepthFormat) {
  14116. if (renderTarget.useRenderToTexture) {
  14117. MultisampledRenderToTextureExtension.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples);
  14118. } else {
  14119. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  14120. }
  14121. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  14122. if (renderTarget.useRenderToTexture) {
  14123. MultisampledRenderToTextureExtension.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples);
  14124. } else {
  14125. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  14126. }
  14127. } else {
  14128. throw new Error('Unknown depthTexture format');
  14129. }
  14130. } // Setup GL resources for a non-texture depth buffer
  14131. function setupDepthRenderbuffer(renderTarget) {
  14132. const renderTargetProperties = properties.get(renderTarget);
  14133. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  14134. if (renderTarget.depthTexture && !renderTargetProperties.__autoAllocateDepthBuffer) {
  14135. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  14136. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  14137. } else {
  14138. if (isCube) {
  14139. renderTargetProperties.__webglDepthbuffer = [];
  14140. for (let i = 0; i < 6; i++) {
  14141. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]);
  14142. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  14143. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  14144. }
  14145. } else {
  14146. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14147. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14148. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  14149. }
  14150. }
  14151. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  14152. } // rebind framebuffer with external textures
  14153. function rebindTextures(renderTarget, colorTexture, depthTexture) {
  14154. const renderTargetProperties = properties.get(renderTarget);
  14155. if (colorTexture !== undefined) {
  14156. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D);
  14157. }
  14158. if (depthTexture !== undefined) {
  14159. setupDepthRenderbuffer(renderTarget);
  14160. }
  14161. } // Set up GL resources for the render target
  14162. function setupRenderTarget(renderTarget) {
  14163. const texture = renderTarget.texture;
  14164. const renderTargetProperties = properties.get(renderTarget);
  14165. const textureProperties = properties.get(texture);
  14166. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  14167. if (renderTarget.isWebGLMultipleRenderTargets !== true) {
  14168. if (textureProperties.__webglTexture === undefined) {
  14169. textureProperties.__webglTexture = _gl.createTexture();
  14170. }
  14171. textureProperties.__version = texture.version;
  14172. info.memory.textures++;
  14173. }
  14174. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  14175. const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true;
  14176. const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray;
  14177. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2; // Handles WebGL2 RGBFormat fallback - #18858
  14178. if (isWebGL2 && texture.format === RGBFormat && (texture.type === FloatType || texture.type === HalfFloatType)) {
  14179. texture.format = RGBAFormat;
  14180. console.warn('THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.');
  14181. } // Setup framebuffer
  14182. if (isCube) {
  14183. renderTargetProperties.__webglFramebuffer = [];
  14184. for (let i = 0; i < 6; i++) {
  14185. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  14186. }
  14187. } else {
  14188. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14189. if (isMultipleRenderTargets) {
  14190. if (capabilities.drawBuffers) {
  14191. const textures = renderTarget.texture;
  14192. for (let i = 0, il = textures.length; i < il; i++) {
  14193. const attachmentProperties = properties.get(textures[i]);
  14194. if (attachmentProperties.__webglTexture === undefined) {
  14195. attachmentProperties.__webglTexture = _gl.createTexture();
  14196. info.memory.textures++;
  14197. }
  14198. }
  14199. } else {
  14200. console.warn('THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.');
  14201. }
  14202. } else if (renderTarget.useRenderbuffer) {
  14203. if (isWebGL2) {
  14204. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14205. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  14206. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  14207. const glFormat = utils.convert(texture.format);
  14208. const glType = utils.convert(texture.type);
  14209. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14210. const samples = getRenderTargetSamples(renderTarget);
  14211. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14212. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14213. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  14214. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  14215. if (renderTarget.depthBuffer) {
  14216. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14217. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  14218. }
  14219. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  14220. } else {
  14221. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  14222. }
  14223. }
  14224. } // Setup color buffer
  14225. if (isCube) {
  14226. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  14227. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  14228. for (let i = 0; i < 6; i++) {
  14229. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i);
  14230. }
  14231. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14232. generateMipmap(_gl.TEXTURE_CUBE_MAP);
  14233. }
  14234. state.unbindTexture();
  14235. } else if (isMultipleRenderTargets) {
  14236. const textures = renderTarget.texture;
  14237. for (let i = 0, il = textures.length; i < il; i++) {
  14238. const attachment = textures[i];
  14239. const attachmentProperties = properties.get(attachment);
  14240. state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture);
  14241. setTextureParameters(_gl.TEXTURE_2D, attachment, supportsMips);
  14242. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D);
  14243. if (textureNeedsGenerateMipmaps(attachment, supportsMips)) {
  14244. generateMipmap(_gl.TEXTURE_2D);
  14245. }
  14246. }
  14247. state.unbindTexture();
  14248. } else {
  14249. let glTextureType = _gl.TEXTURE_2D;
  14250. if (isRenderTarget3D) {
  14251. // Render targets containing layers, i.e: Texture 3D and 2d arrays
  14252. if (isWebGL2) {
  14253. const isTexture3D = texture.isDataTexture3D;
  14254. glTextureType = isTexture3D ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  14255. } else {
  14256. console.warn('THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.');
  14257. }
  14258. }
  14259. state.bindTexture(glTextureType, textureProperties.__webglTexture);
  14260. setTextureParameters(glTextureType, texture, supportsMips);
  14261. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType);
  14262. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14263. generateMipmap(glTextureType);
  14264. }
  14265. state.unbindTexture();
  14266. } // Setup depth and stencil buffers
  14267. if (renderTarget.depthBuffer) {
  14268. setupDepthRenderbuffer(renderTarget);
  14269. }
  14270. }
  14271. function updateRenderTargetMipmap(renderTarget) {
  14272. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2;
  14273. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture];
  14274. for (let i = 0, il = textures.length; i < il; i++) {
  14275. const texture = textures[i];
  14276. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14277. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  14278. const webglTexture = properties.get(texture).__webglTexture;
  14279. state.bindTexture(target, webglTexture);
  14280. generateMipmap(target);
  14281. state.unbindTexture();
  14282. }
  14283. }
  14284. }
  14285. function updateMultisampleRenderTarget(renderTarget) {
  14286. if (renderTarget.useRenderbuffer) {
  14287. if (isWebGL2) {
  14288. const width = renderTarget.width;
  14289. const height = renderTarget.height;
  14290. let mask = _gl.COLOR_BUFFER_BIT;
  14291. const invalidationArray = [_gl.COLOR_ATTACHMENT0];
  14292. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  14293. if (renderTarget.depthBuffer) {
  14294. invalidationArray.push(depthStyle);
  14295. }
  14296. if (!renderTarget.ignoreDepthForMultisampleCopy) {
  14297. if (renderTarget.depthBuffer) mask |= _gl.DEPTH_BUFFER_BIT;
  14298. if (renderTarget.stencilBuffer) mask |= _gl.STENCIL_BUFFER_BIT;
  14299. }
  14300. const renderTargetProperties = properties.get(renderTarget);
  14301. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14302. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14303. if (renderTarget.ignoreDepthForMultisampleCopy) {
  14304. _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, [depthStyle]);
  14305. _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, [depthStyle]);
  14306. }
  14307. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST);
  14308. _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, invalidationArray);
  14309. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null);
  14310. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14311. } else {
  14312. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  14313. }
  14314. }
  14315. }
  14316. function getRenderTargetSamples(renderTarget) {
  14317. return isWebGL2 && (renderTarget.useRenderbuffer || renderTarget.useRenderToTexture) ? Math.min(maxSamples, renderTarget.samples) : 0;
  14318. }
  14319. function updateVideoTexture(texture) {
  14320. const frame = info.render.frame; // Check the last frame we updated the VideoTexture
  14321. if (_videoTextures.get(texture) !== frame) {
  14322. _videoTextures.set(texture, frame);
  14323. texture.update();
  14324. }
  14325. } // backwards compatibility
  14326. let warnedTexture2D = false;
  14327. let warnedTextureCube = false;
  14328. function safeSetTexture2D(texture, slot) {
  14329. if (texture && texture.isWebGLRenderTarget) {
  14330. if (warnedTexture2D === false) {
  14331. console.warn('THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.');
  14332. warnedTexture2D = true;
  14333. }
  14334. texture = texture.texture;
  14335. }
  14336. setTexture2D(texture, slot);
  14337. }
  14338. function safeSetTextureCube(texture, slot) {
  14339. if (texture && texture.isWebGLCubeRenderTarget) {
  14340. if (warnedTextureCube === false) {
  14341. console.warn('THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.');
  14342. warnedTextureCube = true;
  14343. }
  14344. texture = texture.texture;
  14345. }
  14346. setTextureCube(texture, slot);
  14347. } //
  14348. this.allocateTextureUnit = allocateTextureUnit;
  14349. this.resetTextureUnits = resetTextureUnits;
  14350. this.setTexture2D = setTexture2D;
  14351. this.setTexture2DArray = setTexture2DArray;
  14352. this.setTexture3D = setTexture3D;
  14353. this.setTextureCube = setTextureCube;
  14354. this.rebindTextures = rebindTextures;
  14355. this.setupRenderTarget = setupRenderTarget;
  14356. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14357. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14358. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  14359. this.setupFrameBufferTexture = setupFrameBufferTexture;
  14360. this.safeSetTexture2D = safeSetTexture2D;
  14361. this.safeSetTextureCube = safeSetTextureCube;
  14362. }
  14363. function WebGLUtils(gl, extensions, capabilities) {
  14364. const isWebGL2 = capabilities.isWebGL2;
  14365. function convert(p) {
  14366. let extension;
  14367. if (p === UnsignedByteType) return gl.UNSIGNED_BYTE;
  14368. if (p === UnsignedShort4444Type) return gl.UNSIGNED_SHORT_4_4_4_4;
  14369. if (p === UnsignedShort5551Type) return gl.UNSIGNED_SHORT_5_5_5_1;
  14370. if (p === UnsignedShort565Type) return gl.UNSIGNED_SHORT_5_6_5;
  14371. if (p === ByteType) return gl.BYTE;
  14372. if (p === ShortType) return gl.SHORT;
  14373. if (p === UnsignedShortType) return gl.UNSIGNED_SHORT;
  14374. if (p === IntType) return gl.INT;
  14375. if (p === UnsignedIntType) return gl.UNSIGNED_INT;
  14376. if (p === FloatType) return gl.FLOAT;
  14377. if (p === HalfFloatType) {
  14378. if (isWebGL2) return gl.HALF_FLOAT;
  14379. extension = extensions.get('OES_texture_half_float');
  14380. if (extension !== null) {
  14381. return extension.HALF_FLOAT_OES;
  14382. } else {
  14383. return null;
  14384. }
  14385. }
  14386. if (p === AlphaFormat) return gl.ALPHA;
  14387. if (p === RGBFormat) return gl.RGB;
  14388. if (p === RGBAFormat) return gl.RGBA;
  14389. if (p === LuminanceFormat) return gl.LUMINANCE;
  14390. if (p === LuminanceAlphaFormat) return gl.LUMINANCE_ALPHA;
  14391. if (p === DepthFormat) return gl.DEPTH_COMPONENT;
  14392. if (p === DepthStencilFormat) return gl.DEPTH_STENCIL;
  14393. if (p === RedFormat) return gl.RED; // WebGL2 formats.
  14394. if (p === RedIntegerFormat) return gl.RED_INTEGER;
  14395. if (p === RGFormat) return gl.RG;
  14396. if (p === RGIntegerFormat) return gl.RG_INTEGER;
  14397. if (p === RGBIntegerFormat) return gl.RGB_INTEGER;
  14398. if (p === RGBAIntegerFormat) return gl.RGBA_INTEGER;
  14399. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  14400. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  14401. if (extension !== null) {
  14402. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14403. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14404. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14405. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14406. } else {
  14407. return null;
  14408. }
  14409. }
  14410. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  14411. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  14412. if (extension !== null) {
  14413. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14414. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14415. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14416. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14417. } else {
  14418. return null;
  14419. }
  14420. }
  14421. if (p === RGB_ETC1_Format) {
  14422. extension = extensions.get('WEBGL_compressed_texture_etc1');
  14423. if (extension !== null) {
  14424. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14425. } else {
  14426. return null;
  14427. }
  14428. }
  14429. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  14430. extension = extensions.get('WEBGL_compressed_texture_etc');
  14431. if (extension !== null) {
  14432. if (p === RGB_ETC2_Format) return extension.COMPRESSED_RGB8_ETC2;
  14433. if (p === RGBA_ETC2_EAC_Format) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  14434. }
  14435. }
  14436. if (p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format || p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format || p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format || p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format || p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format || p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format) {
  14437. extension = extensions.get('WEBGL_compressed_texture_astc');
  14438. if (extension !== null) {
  14439. // TODO Complete?
  14440. return p;
  14441. } else {
  14442. return null;
  14443. }
  14444. }
  14445. if (p === RGBA_BPTC_Format) {
  14446. extension = extensions.get('EXT_texture_compression_bptc');
  14447. if (extension !== null) {
  14448. // TODO Complete?
  14449. return p;
  14450. } else {
  14451. return null;
  14452. }
  14453. }
  14454. if (p === UnsignedInt248Type) {
  14455. if (isWebGL2) return gl.UNSIGNED_INT_24_8;
  14456. extension = extensions.get('WEBGL_depth_texture');
  14457. if (extension !== null) {
  14458. return extension.UNSIGNED_INT_24_8_WEBGL;
  14459. } else {
  14460. return null;
  14461. }
  14462. }
  14463. }
  14464. return {
  14465. convert: convert
  14466. };
  14467. }
  14468. class ArrayCamera extends PerspectiveCamera {
  14469. constructor(array = []) {
  14470. super();
  14471. this.cameras = array;
  14472. }
  14473. }
  14474. ArrayCamera.prototype.isArrayCamera = true;
  14475. class Group extends Object3D {
  14476. constructor() {
  14477. super();
  14478. this.type = 'Group';
  14479. }
  14480. }
  14481. Group.prototype.isGroup = true;
  14482. const _moveEvent = {
  14483. type: 'move'
  14484. };
  14485. class WebXRController {
  14486. constructor() {
  14487. this._targetRay = null;
  14488. this._grip = null;
  14489. this._hand = null;
  14490. }
  14491. getHandSpace() {
  14492. if (this._hand === null) {
  14493. this._hand = new Group();
  14494. this._hand.matrixAutoUpdate = false;
  14495. this._hand.visible = false;
  14496. this._hand.joints = {};
  14497. this._hand.inputState = {
  14498. pinching: false
  14499. };
  14500. }
  14501. return this._hand;
  14502. }
  14503. getTargetRaySpace() {
  14504. if (this._targetRay === null) {
  14505. this._targetRay = new Group();
  14506. this._targetRay.matrixAutoUpdate = false;
  14507. this._targetRay.visible = false;
  14508. this._targetRay.hasLinearVelocity = false;
  14509. this._targetRay.linearVelocity = new Vector3();
  14510. this._targetRay.hasAngularVelocity = false;
  14511. this._targetRay.angularVelocity = new Vector3();
  14512. }
  14513. return this._targetRay;
  14514. }
  14515. getGripSpace() {
  14516. if (this._grip === null) {
  14517. this._grip = new Group();
  14518. this._grip.matrixAutoUpdate = false;
  14519. this._grip.visible = false;
  14520. this._grip.hasLinearVelocity = false;
  14521. this._grip.linearVelocity = new Vector3();
  14522. this._grip.hasAngularVelocity = false;
  14523. this._grip.angularVelocity = new Vector3();
  14524. }
  14525. return this._grip;
  14526. }
  14527. dispatchEvent(event) {
  14528. if (this._targetRay !== null) {
  14529. this._targetRay.dispatchEvent(event);
  14530. }
  14531. if (this._grip !== null) {
  14532. this._grip.dispatchEvent(event);
  14533. }
  14534. if (this._hand !== null) {
  14535. this._hand.dispatchEvent(event);
  14536. }
  14537. return this;
  14538. }
  14539. disconnect(inputSource) {
  14540. this.dispatchEvent({
  14541. type: 'disconnected',
  14542. data: inputSource
  14543. });
  14544. if (this._targetRay !== null) {
  14545. this._targetRay.visible = false;
  14546. }
  14547. if (this._grip !== null) {
  14548. this._grip.visible = false;
  14549. }
  14550. if (this._hand !== null) {
  14551. this._hand.visible = false;
  14552. }
  14553. return this;
  14554. }
  14555. update(inputSource, frame, referenceSpace) {
  14556. let inputPose = null;
  14557. let gripPose = null;
  14558. let handPose = null;
  14559. const targetRay = this._targetRay;
  14560. const grip = this._grip;
  14561. const hand = this._hand;
  14562. if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
  14563. if (targetRay !== null) {
  14564. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  14565. if (inputPose !== null) {
  14566. targetRay.matrix.fromArray(inputPose.transform.matrix);
  14567. targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
  14568. if (inputPose.linearVelocity) {
  14569. targetRay.hasLinearVelocity = true;
  14570. targetRay.linearVelocity.copy(inputPose.linearVelocity);
  14571. } else {
  14572. targetRay.hasLinearVelocity = false;
  14573. }
  14574. if (inputPose.angularVelocity) {
  14575. targetRay.hasAngularVelocity = true;
  14576. targetRay.angularVelocity.copy(inputPose.angularVelocity);
  14577. } else {
  14578. targetRay.hasAngularVelocity = false;
  14579. }
  14580. this.dispatchEvent(_moveEvent);
  14581. }
  14582. }
  14583. if (hand && inputSource.hand) {
  14584. handPose = true;
  14585. for (const inputjoint of inputSource.hand.values()) {
  14586. // Update the joints groups with the XRJoint poses
  14587. const jointPose = frame.getJointPose(inputjoint, referenceSpace);
  14588. if (hand.joints[inputjoint.jointName] === undefined) {
  14589. // The transform of this joint will be updated with the joint pose on each frame
  14590. const joint = new Group();
  14591. joint.matrixAutoUpdate = false;
  14592. joint.visible = false;
  14593. hand.joints[inputjoint.jointName] = joint; // ??
  14594. hand.add(joint);
  14595. }
  14596. const joint = hand.joints[inputjoint.jointName];
  14597. if (jointPose !== null) {
  14598. joint.matrix.fromArray(jointPose.transform.matrix);
  14599. joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
  14600. joint.jointRadius = jointPose.radius;
  14601. }
  14602. joint.visible = jointPose !== null;
  14603. } // Custom events
  14604. // Check pinchz
  14605. const indexTip = hand.joints['index-finger-tip'];
  14606. const thumbTip = hand.joints['thumb-tip'];
  14607. const distance = indexTip.position.distanceTo(thumbTip.position);
  14608. const distanceToPinch = 0.02;
  14609. const threshold = 0.005;
  14610. if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
  14611. hand.inputState.pinching = false;
  14612. this.dispatchEvent({
  14613. type: 'pinchend',
  14614. handedness: inputSource.handedness,
  14615. target: this
  14616. });
  14617. } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
  14618. hand.inputState.pinching = true;
  14619. this.dispatchEvent({
  14620. type: 'pinchstart',
  14621. handedness: inputSource.handedness,
  14622. target: this
  14623. });
  14624. }
  14625. } else {
  14626. if (grip !== null && inputSource.gripSpace) {
  14627. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  14628. if (gripPose !== null) {
  14629. grip.matrix.fromArray(gripPose.transform.matrix);
  14630. grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
  14631. if (gripPose.linearVelocity) {
  14632. grip.hasLinearVelocity = true;
  14633. grip.linearVelocity.copy(gripPose.linearVelocity);
  14634. } else {
  14635. grip.hasLinearVelocity = false;
  14636. }
  14637. if (gripPose.angularVelocity) {
  14638. grip.hasAngularVelocity = true;
  14639. grip.angularVelocity.copy(gripPose.angularVelocity);
  14640. } else {
  14641. grip.hasAngularVelocity = false;
  14642. }
  14643. }
  14644. }
  14645. }
  14646. }
  14647. if (targetRay !== null) {
  14648. targetRay.visible = inputPose !== null;
  14649. }
  14650. if (grip !== null) {
  14651. grip.visible = gripPose !== null;
  14652. }
  14653. if (hand !== null) {
  14654. hand.visible = handPose !== null;
  14655. }
  14656. return this;
  14657. }
  14658. }
  14659. class DepthTexture extends Texture {
  14660. constructor(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  14661. format = format !== undefined ? format : DepthFormat;
  14662. if (format !== DepthFormat && format !== DepthStencilFormat) {
  14663. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  14664. }
  14665. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  14666. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  14667. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  14668. this.image = {
  14669. width: width,
  14670. height: height
  14671. };
  14672. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  14673. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  14674. this.flipY = false;
  14675. this.generateMipmaps = false;
  14676. }
  14677. }
  14678. DepthTexture.prototype.isDepthTexture = true;
  14679. class WebXRManager extends EventDispatcher {
  14680. constructor(renderer, gl) {
  14681. super();
  14682. const scope = this;
  14683. let session = null;
  14684. let framebufferScaleFactor = 1.0;
  14685. let referenceSpace = null;
  14686. let referenceSpaceType = 'local-floor';
  14687. const hasMultisampledRenderToTexture = renderer.extensions.has('WEBGL_multisampled_render_to_texture');
  14688. let pose = null;
  14689. let glBinding = null;
  14690. let glProjLayer = null;
  14691. let glBaseLayer = null;
  14692. let isMultisample = false;
  14693. let xrFrame = null;
  14694. const attributes = gl.getContextAttributes();
  14695. let initialRenderTarget = null;
  14696. let newRenderTarget = null;
  14697. const controllers = [];
  14698. const inputSourcesMap = new Map(); //
  14699. const cameraL = new PerspectiveCamera();
  14700. cameraL.layers.enable(1);
  14701. cameraL.viewport = new Vector4();
  14702. const cameraR = new PerspectiveCamera();
  14703. cameraR.layers.enable(2);
  14704. cameraR.viewport = new Vector4();
  14705. const cameras = [cameraL, cameraR];
  14706. const cameraVR = new ArrayCamera();
  14707. cameraVR.layers.enable(1);
  14708. cameraVR.layers.enable(2);
  14709. let _currentDepthNear = null;
  14710. let _currentDepthFar = null; //
  14711. this.cameraAutoUpdate = true;
  14712. this.enabled = false;
  14713. this.isPresenting = false;
  14714. this.getController = function (index) {
  14715. let controller = controllers[index];
  14716. if (controller === undefined) {
  14717. controller = new WebXRController();
  14718. controllers[index] = controller;
  14719. }
  14720. return controller.getTargetRaySpace();
  14721. };
  14722. this.getControllerGrip = function (index) {
  14723. let controller = controllers[index];
  14724. if (controller === undefined) {
  14725. controller = new WebXRController();
  14726. controllers[index] = controller;
  14727. }
  14728. return controller.getGripSpace();
  14729. };
  14730. this.getHand = function (index) {
  14731. let controller = controllers[index];
  14732. if (controller === undefined) {
  14733. controller = new WebXRController();
  14734. controllers[index] = controller;
  14735. }
  14736. return controller.getHandSpace();
  14737. }; //
  14738. function onSessionEvent(event) {
  14739. const controller = inputSourcesMap.get(event.inputSource);
  14740. if (controller) {
  14741. controller.dispatchEvent({
  14742. type: event.type,
  14743. data: event.inputSource
  14744. });
  14745. }
  14746. }
  14747. function onSessionEnd() {
  14748. inputSourcesMap.forEach(function (controller, inputSource) {
  14749. controller.disconnect(inputSource);
  14750. });
  14751. inputSourcesMap.clear();
  14752. _currentDepthNear = null;
  14753. _currentDepthFar = null; // restore framebuffer/rendering state
  14754. renderer.setRenderTarget(initialRenderTarget);
  14755. glBaseLayer = null;
  14756. glProjLayer = null;
  14757. glBinding = null;
  14758. session = null;
  14759. newRenderTarget = null; //
  14760. animation.stop();
  14761. scope.isPresenting = false;
  14762. scope.dispatchEvent({
  14763. type: 'sessionend'
  14764. });
  14765. }
  14766. this.setFramebufferScaleFactor = function (value) {
  14767. framebufferScaleFactor = value;
  14768. if (scope.isPresenting === true) {
  14769. console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
  14770. }
  14771. };
  14772. this.setReferenceSpaceType = function (value) {
  14773. referenceSpaceType = value;
  14774. if (scope.isPresenting === true) {
  14775. console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
  14776. }
  14777. };
  14778. this.getReferenceSpace = function () {
  14779. return referenceSpace;
  14780. };
  14781. this.getBaseLayer = function () {
  14782. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  14783. };
  14784. this.getBinding = function () {
  14785. return glBinding;
  14786. };
  14787. this.getFrame = function () {
  14788. return xrFrame;
  14789. };
  14790. this.getSession = function () {
  14791. return session;
  14792. };
  14793. this.setSession = async function (value) {
  14794. session = value;
  14795. if (session !== null) {
  14796. initialRenderTarget = renderer.getRenderTarget();
  14797. session.addEventListener('select', onSessionEvent);
  14798. session.addEventListener('selectstart', onSessionEvent);
  14799. session.addEventListener('selectend', onSessionEvent);
  14800. session.addEventListener('squeeze', onSessionEvent);
  14801. session.addEventListener('squeezestart', onSessionEvent);
  14802. session.addEventListener('squeezeend', onSessionEvent);
  14803. session.addEventListener('end', onSessionEnd);
  14804. session.addEventListener('inputsourceschange', onInputSourcesChange);
  14805. if (attributes.xrCompatible !== true) {
  14806. await gl.makeXRCompatible();
  14807. }
  14808. if (session.renderState.layers === undefined || renderer.capabilities.isWebGL2 === false) {
  14809. const layerInit = {
  14810. antialias: session.renderState.layers === undefined ? attributes.antialias : true,
  14811. alpha: attributes.alpha,
  14812. depth: attributes.depth,
  14813. stencil: attributes.stencil,
  14814. framebufferScaleFactor: framebufferScaleFactor
  14815. };
  14816. glBaseLayer = new XRWebGLLayer(session, gl, layerInit);
  14817. session.updateRenderState({
  14818. baseLayer: glBaseLayer
  14819. });
  14820. newRenderTarget = new WebGLRenderTarget(glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, {
  14821. format: RGBAFormat,
  14822. type: UnsignedByteType,
  14823. encoding: renderer.outputEncoding
  14824. });
  14825. } else {
  14826. isMultisample = attributes.antialias;
  14827. let depthFormat = null;
  14828. let depthType = null;
  14829. let glDepthFormat = null;
  14830. if (attributes.depth) {
  14831. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  14832. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  14833. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedShortType;
  14834. }
  14835. const projectionlayerInit = {
  14836. colorFormat: attributes.alpha || isMultisample ? gl.RGBA8 : gl.RGB8,
  14837. depthFormat: glDepthFormat,
  14838. scaleFactor: framebufferScaleFactor
  14839. };
  14840. glBinding = new XRWebGLBinding(session, gl);
  14841. glProjLayer = glBinding.createProjectionLayer(projectionlayerInit);
  14842. session.updateRenderState({
  14843. layers: [glProjLayer]
  14844. });
  14845. if (isMultisample) {
  14846. newRenderTarget = new WebGLMultisampleRenderTarget(glProjLayer.textureWidth, glProjLayer.textureHeight, {
  14847. format: RGBAFormat,
  14848. type: UnsignedByteType,
  14849. depthTexture: new DepthTexture(glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat),
  14850. stencilBuffer: attributes.stencil,
  14851. ignoreDepth: glProjLayer.ignoreDepthValues,
  14852. useRenderToTexture: hasMultisampledRenderToTexture,
  14853. encoding: renderer.outputEncoding
  14854. });
  14855. } else {
  14856. newRenderTarget = new WebGLRenderTarget(glProjLayer.textureWidth, glProjLayer.textureHeight, {
  14857. format: attributes.alpha ? RGBAFormat : RGBFormat,
  14858. type: UnsignedByteType,
  14859. depthTexture: new DepthTexture(glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat),
  14860. stencilBuffer: attributes.stencil,
  14861. ignoreDepth: glProjLayer.ignoreDepthValues,
  14862. encoding: renderer.outputEncoding
  14863. });
  14864. }
  14865. } // Set foveation to maximum.
  14866. this.setFoveation(1.0);
  14867. referenceSpace = await session.requestReferenceSpace(referenceSpaceType);
  14868. animation.setContext(session);
  14869. animation.start();
  14870. scope.isPresenting = true;
  14871. scope.dispatchEvent({
  14872. type: 'sessionstart'
  14873. });
  14874. }
  14875. };
  14876. function onInputSourcesChange(event) {
  14877. const inputSources = session.inputSources; // Assign inputSources to available controllers
  14878. for (let i = 0; i < controllers.length; i++) {
  14879. inputSourcesMap.set(inputSources[i], controllers[i]);
  14880. } // Notify disconnected
  14881. for (let i = 0; i < event.removed.length; i++) {
  14882. const inputSource = event.removed[i];
  14883. const controller = inputSourcesMap.get(inputSource);
  14884. if (controller) {
  14885. controller.dispatchEvent({
  14886. type: 'disconnected',
  14887. data: inputSource
  14888. });
  14889. inputSourcesMap.delete(inputSource);
  14890. }
  14891. } // Notify connected
  14892. for (let i = 0; i < event.added.length; i++) {
  14893. const inputSource = event.added[i];
  14894. const controller = inputSourcesMap.get(inputSource);
  14895. if (controller) {
  14896. controller.dispatchEvent({
  14897. type: 'connected',
  14898. data: inputSource
  14899. });
  14900. }
  14901. }
  14902. } //
  14903. const cameraLPos = new Vector3();
  14904. const cameraRPos = new Vector3();
  14905. /**
  14906. * Assumes 2 cameras that are parallel and share an X-axis, and that
  14907. * the cameras' projection and world matrices have already been set.
  14908. * And that near and far planes are identical for both cameras.
  14909. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  14910. */
  14911. function setProjectionFromUnion(camera, cameraL, cameraR) {
  14912. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  14913. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  14914. const ipd = cameraLPos.distanceTo(cameraRPos);
  14915. const projL = cameraL.projectionMatrix.elements;
  14916. const projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  14917. // most likely identical top and bottom frustum extents.
  14918. // Use the left camera for these values.
  14919. const near = projL[14] / (projL[10] - 1);
  14920. const far = projL[14] / (projL[10] + 1);
  14921. const topFov = (projL[9] + 1) / projL[5];
  14922. const bottomFov = (projL[9] - 1) / projL[5];
  14923. const leftFov = (projL[8] - 1) / projL[0];
  14924. const rightFov = (projR[8] + 1) / projR[0];
  14925. const left = near * leftFov;
  14926. const right = near * rightFov; // Calculate the new camera's position offset from the
  14927. // left camera. xOffset should be roughly half `ipd`.
  14928. const zOffset = ipd / (-leftFov + rightFov);
  14929. const xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  14930. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  14931. camera.translateX(xOffset);
  14932. camera.translateZ(zOffset);
  14933. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  14934. camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); // Find the union of the frustum values of the cameras and scale
  14935. // the values so that the near plane's position does not change in world space,
  14936. // although must now be relative to the new union camera.
  14937. const near2 = near + zOffset;
  14938. const far2 = far + zOffset;
  14939. const left2 = left - xOffset;
  14940. const right2 = right + (ipd - xOffset);
  14941. const top2 = topFov * far / far2 * near2;
  14942. const bottom2 = bottomFov * far / far2 * near2;
  14943. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  14944. }
  14945. function updateCamera(camera, parent) {
  14946. if (parent === null) {
  14947. camera.matrixWorld.copy(camera.matrix);
  14948. } else {
  14949. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  14950. }
  14951. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  14952. }
  14953. this.updateCamera = function (camera) {
  14954. if (session === null) return;
  14955. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  14956. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  14957. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  14958. // Note that the new renderState won't apply until the next frame. See #18320
  14959. session.updateRenderState({
  14960. depthNear: cameraVR.near,
  14961. depthFar: cameraVR.far
  14962. });
  14963. _currentDepthNear = cameraVR.near;
  14964. _currentDepthFar = cameraVR.far;
  14965. }
  14966. const parent = camera.parent;
  14967. const cameras = cameraVR.cameras;
  14968. updateCamera(cameraVR, parent);
  14969. for (let i = 0; i < cameras.length; i++) {
  14970. updateCamera(cameras[i], parent);
  14971. }
  14972. cameraVR.matrixWorld.decompose(cameraVR.position, cameraVR.quaternion, cameraVR.scale); // update user camera and its children
  14973. camera.position.copy(cameraVR.position);
  14974. camera.quaternion.copy(cameraVR.quaternion);
  14975. camera.scale.copy(cameraVR.scale);
  14976. camera.matrix.copy(cameraVR.matrix);
  14977. camera.matrixWorld.copy(cameraVR.matrixWorld);
  14978. const children = camera.children;
  14979. for (let i = 0, l = children.length; i < l; i++) {
  14980. children[i].updateMatrixWorld(true);
  14981. } // update projection matrix for proper view frustum culling
  14982. if (cameras.length === 2) {
  14983. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  14984. } else {
  14985. // assume single camera setup (AR)
  14986. cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
  14987. }
  14988. };
  14989. this.getCamera = function () {
  14990. return cameraVR;
  14991. };
  14992. this.getFoveation = function () {
  14993. if (glProjLayer !== null) {
  14994. return glProjLayer.fixedFoveation;
  14995. }
  14996. if (glBaseLayer !== null) {
  14997. return glBaseLayer.fixedFoveation;
  14998. }
  14999. return undefined;
  15000. };
  15001. this.setFoveation = function (foveation) {
  15002. // 0 = no foveation = full resolution
  15003. // 1 = maximum foveation = the edges render at lower resolution
  15004. if (glProjLayer !== null) {
  15005. glProjLayer.fixedFoveation = foveation;
  15006. }
  15007. if (glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined) {
  15008. glBaseLayer.fixedFoveation = foveation;
  15009. }
  15010. }; // Animation Loop
  15011. let onAnimationFrameCallback = null;
  15012. function onAnimationFrame(time, frame) {
  15013. pose = frame.getViewerPose(referenceSpace);
  15014. xrFrame = frame;
  15015. if (pose !== null) {
  15016. const views = pose.views;
  15017. if (glBaseLayer !== null) {
  15018. renderer.setRenderTargetFramebuffer(newRenderTarget, glBaseLayer.framebuffer);
  15019. renderer.setRenderTarget(newRenderTarget);
  15020. }
  15021. let cameraVRNeedsUpdate = false; // check if it's necessary to rebuild cameraVR's camera list
  15022. if (views.length !== cameraVR.cameras.length) {
  15023. cameraVR.cameras.length = 0;
  15024. cameraVRNeedsUpdate = true;
  15025. }
  15026. for (let i = 0; i < views.length; i++) {
  15027. const view = views[i];
  15028. let viewport = null;
  15029. if (glBaseLayer !== null) {
  15030. viewport = glBaseLayer.getViewport(view);
  15031. } else {
  15032. const glSubImage = glBinding.getViewSubImage(glProjLayer, view);
  15033. viewport = glSubImage.viewport; // For side-by-side projection, we only produce a single texture for both eyes.
  15034. if (i === 0) {
  15035. renderer.setRenderTargetTextures(newRenderTarget, glSubImage.colorTexture, glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture);
  15036. renderer.setRenderTarget(newRenderTarget);
  15037. }
  15038. }
  15039. const camera = cameras[i];
  15040. camera.matrix.fromArray(view.transform.matrix);
  15041. camera.projectionMatrix.fromArray(view.projectionMatrix);
  15042. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  15043. if (i === 0) {
  15044. cameraVR.matrix.copy(camera.matrix);
  15045. }
  15046. if (cameraVRNeedsUpdate === true) {
  15047. cameraVR.cameras.push(camera);
  15048. }
  15049. }
  15050. } //
  15051. const inputSources = session.inputSources;
  15052. for (let i = 0; i < controllers.length; i++) {
  15053. const controller = controllers[i];
  15054. const inputSource = inputSources[i];
  15055. controller.update(inputSource, frame, referenceSpace);
  15056. }
  15057. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  15058. xrFrame = null;
  15059. }
  15060. const animation = new WebGLAnimation();
  15061. animation.setAnimationLoop(onAnimationFrame);
  15062. this.setAnimationLoop = function (callback) {
  15063. onAnimationFrameCallback = callback;
  15064. };
  15065. this.dispose = function () {};
  15066. }
  15067. }
  15068. function WebGLMaterials(properties) {
  15069. function refreshFogUniforms(uniforms, fog) {
  15070. uniforms.fogColor.value.copy(fog.color);
  15071. if (fog.isFog) {
  15072. uniforms.fogNear.value = fog.near;
  15073. uniforms.fogFar.value = fog.far;
  15074. } else if (fog.isFogExp2) {
  15075. uniforms.fogDensity.value = fog.density;
  15076. }
  15077. }
  15078. function refreshMaterialUniforms(uniforms, material, pixelRatio, height, transmissionRenderTarget) {
  15079. if (material.isMeshBasicMaterial) {
  15080. refreshUniformsCommon(uniforms, material);
  15081. } else if (material.isMeshLambertMaterial) {
  15082. refreshUniformsCommon(uniforms, material);
  15083. refreshUniformsLambert(uniforms, material);
  15084. } else if (material.isMeshToonMaterial) {
  15085. refreshUniformsCommon(uniforms, material);
  15086. refreshUniformsToon(uniforms, material);
  15087. } else if (material.isMeshPhongMaterial) {
  15088. refreshUniformsCommon(uniforms, material);
  15089. refreshUniformsPhong(uniforms, material);
  15090. } else if (material.isMeshStandardMaterial) {
  15091. refreshUniformsCommon(uniforms, material);
  15092. if (material.isMeshPhysicalMaterial) {
  15093. refreshUniformsPhysical(uniforms, material, transmissionRenderTarget);
  15094. } else {
  15095. refreshUniformsStandard(uniforms, material);
  15096. }
  15097. } else if (material.isMeshMatcapMaterial) {
  15098. refreshUniformsCommon(uniforms, material);
  15099. refreshUniformsMatcap(uniforms, material);
  15100. } else if (material.isMeshDepthMaterial) {
  15101. refreshUniformsCommon(uniforms, material);
  15102. refreshUniformsDepth(uniforms, material);
  15103. } else if (material.isMeshDistanceMaterial) {
  15104. refreshUniformsCommon(uniforms, material);
  15105. refreshUniformsDistance(uniforms, material);
  15106. } else if (material.isMeshNormalMaterial) {
  15107. refreshUniformsCommon(uniforms, material);
  15108. refreshUniformsNormal(uniforms, material);
  15109. } else if (material.isLineBasicMaterial) {
  15110. refreshUniformsLine(uniforms, material);
  15111. if (material.isLineDashedMaterial) {
  15112. refreshUniformsDash(uniforms, material);
  15113. }
  15114. } else if (material.isPointsMaterial) {
  15115. refreshUniformsPoints(uniforms, material, pixelRatio, height);
  15116. } else if (material.isSpriteMaterial) {
  15117. refreshUniformsSprites(uniforms, material);
  15118. } else if (material.isShadowMaterial) {
  15119. uniforms.color.value.copy(material.color);
  15120. uniforms.opacity.value = material.opacity;
  15121. } else if (material.isShaderMaterial) {
  15122. material.uniformsNeedUpdate = false; // #15581
  15123. }
  15124. }
  15125. function refreshUniformsCommon(uniforms, material) {
  15126. uniforms.opacity.value = material.opacity;
  15127. if (material.color) {
  15128. uniforms.diffuse.value.copy(material.color);
  15129. }
  15130. if (material.emissive) {
  15131. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  15132. }
  15133. if (material.map) {
  15134. uniforms.map.value = material.map;
  15135. }
  15136. if (material.alphaMap) {
  15137. uniforms.alphaMap.value = material.alphaMap;
  15138. }
  15139. if (material.specularMap) {
  15140. uniforms.specularMap.value = material.specularMap;
  15141. }
  15142. if (material.alphaTest > 0) {
  15143. uniforms.alphaTest.value = material.alphaTest;
  15144. }
  15145. const envMap = properties.get(material).envMap;
  15146. if (envMap) {
  15147. uniforms.envMap.value = envMap;
  15148. uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1;
  15149. uniforms.reflectivity.value = material.reflectivity;
  15150. uniforms.ior.value = material.ior;
  15151. uniforms.refractionRatio.value = material.refractionRatio;
  15152. }
  15153. if (material.lightMap) {
  15154. uniforms.lightMap.value = material.lightMap;
  15155. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  15156. }
  15157. if (material.aoMap) {
  15158. uniforms.aoMap.value = material.aoMap;
  15159. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15160. } // uv repeat and offset setting priorities
  15161. // 1. color map
  15162. // 2. specular map
  15163. // 3. displacementMap map
  15164. // 4. normal map
  15165. // 5. bump map
  15166. // 6. roughnessMap map
  15167. // 7. metalnessMap map
  15168. // 8. alphaMap map
  15169. // 9. emissiveMap map
  15170. // 10. clearcoat map
  15171. // 11. clearcoat normal map
  15172. // 12. clearcoat roughnessMap map
  15173. // 13. specular intensity map
  15174. // 14. specular tint map
  15175. // 15. transmission map
  15176. // 16. thickness map
  15177. let uvScaleMap;
  15178. if (material.map) {
  15179. uvScaleMap = material.map;
  15180. } else if (material.specularMap) {
  15181. uvScaleMap = material.specularMap;
  15182. } else if (material.displacementMap) {
  15183. uvScaleMap = material.displacementMap;
  15184. } else if (material.normalMap) {
  15185. uvScaleMap = material.normalMap;
  15186. } else if (material.bumpMap) {
  15187. uvScaleMap = material.bumpMap;
  15188. } else if (material.roughnessMap) {
  15189. uvScaleMap = material.roughnessMap;
  15190. } else if (material.metalnessMap) {
  15191. uvScaleMap = material.metalnessMap;
  15192. } else if (material.alphaMap) {
  15193. uvScaleMap = material.alphaMap;
  15194. } else if (material.emissiveMap) {
  15195. uvScaleMap = material.emissiveMap;
  15196. } else if (material.clearcoatMap) {
  15197. uvScaleMap = material.clearcoatMap;
  15198. } else if (material.clearcoatNormalMap) {
  15199. uvScaleMap = material.clearcoatNormalMap;
  15200. } else if (material.clearcoatRoughnessMap) {
  15201. uvScaleMap = material.clearcoatRoughnessMap;
  15202. } else if (material.specularIntensityMap) {
  15203. uvScaleMap = material.specularIntensityMap;
  15204. } else if (material.specularColorMap) {
  15205. uvScaleMap = material.specularColorMap;
  15206. } else if (material.transmissionMap) {
  15207. uvScaleMap = material.transmissionMap;
  15208. } else if (material.thicknessMap) {
  15209. uvScaleMap = material.thicknessMap;
  15210. } else if (material.sheenColorMap) {
  15211. uvScaleMap = material.sheenColorMap;
  15212. } else if (material.sheenRoughnessMap) {
  15213. uvScaleMap = material.sheenRoughnessMap;
  15214. }
  15215. if (uvScaleMap !== undefined) {
  15216. // backwards compatibility
  15217. if (uvScaleMap.isWebGLRenderTarget) {
  15218. uvScaleMap = uvScaleMap.texture;
  15219. }
  15220. if (uvScaleMap.matrixAutoUpdate === true) {
  15221. uvScaleMap.updateMatrix();
  15222. }
  15223. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15224. } // uv repeat and offset setting priorities for uv2
  15225. // 1. ao map
  15226. // 2. light map
  15227. let uv2ScaleMap;
  15228. if (material.aoMap) {
  15229. uv2ScaleMap = material.aoMap;
  15230. } else if (material.lightMap) {
  15231. uv2ScaleMap = material.lightMap;
  15232. }
  15233. if (uv2ScaleMap !== undefined) {
  15234. // backwards compatibility
  15235. if (uv2ScaleMap.isWebGLRenderTarget) {
  15236. uv2ScaleMap = uv2ScaleMap.texture;
  15237. }
  15238. if (uv2ScaleMap.matrixAutoUpdate === true) {
  15239. uv2ScaleMap.updateMatrix();
  15240. }
  15241. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  15242. }
  15243. }
  15244. function refreshUniformsLine(uniforms, material) {
  15245. uniforms.diffuse.value.copy(material.color);
  15246. uniforms.opacity.value = material.opacity;
  15247. }
  15248. function refreshUniformsDash(uniforms, material) {
  15249. uniforms.dashSize.value = material.dashSize;
  15250. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15251. uniforms.scale.value = material.scale;
  15252. }
  15253. function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
  15254. uniforms.diffuse.value.copy(material.color);
  15255. uniforms.opacity.value = material.opacity;
  15256. uniforms.size.value = material.size * pixelRatio;
  15257. uniforms.scale.value = height * 0.5;
  15258. if (material.map) {
  15259. uniforms.map.value = material.map;
  15260. }
  15261. if (material.alphaMap) {
  15262. uniforms.alphaMap.value = material.alphaMap;
  15263. }
  15264. if (material.alphaTest > 0) {
  15265. uniforms.alphaTest.value = material.alphaTest;
  15266. } // uv repeat and offset setting priorities
  15267. // 1. color map
  15268. // 2. alpha map
  15269. let uvScaleMap;
  15270. if (material.map) {
  15271. uvScaleMap = material.map;
  15272. } else if (material.alphaMap) {
  15273. uvScaleMap = material.alphaMap;
  15274. }
  15275. if (uvScaleMap !== undefined) {
  15276. if (uvScaleMap.matrixAutoUpdate === true) {
  15277. uvScaleMap.updateMatrix();
  15278. }
  15279. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15280. }
  15281. }
  15282. function refreshUniformsSprites(uniforms, material) {
  15283. uniforms.diffuse.value.copy(material.color);
  15284. uniforms.opacity.value = material.opacity;
  15285. uniforms.rotation.value = material.rotation;
  15286. if (material.map) {
  15287. uniforms.map.value = material.map;
  15288. }
  15289. if (material.alphaMap) {
  15290. uniforms.alphaMap.value = material.alphaMap;
  15291. }
  15292. if (material.alphaTest > 0) {
  15293. uniforms.alphaTest.value = material.alphaTest;
  15294. } // uv repeat and offset setting priorities
  15295. // 1. color map
  15296. // 2. alpha map
  15297. let uvScaleMap;
  15298. if (material.map) {
  15299. uvScaleMap = material.map;
  15300. } else if (material.alphaMap) {
  15301. uvScaleMap = material.alphaMap;
  15302. }
  15303. if (uvScaleMap !== undefined) {
  15304. if (uvScaleMap.matrixAutoUpdate === true) {
  15305. uvScaleMap.updateMatrix();
  15306. }
  15307. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15308. }
  15309. }
  15310. function refreshUniformsLambert(uniforms, material) {
  15311. if (material.emissiveMap) {
  15312. uniforms.emissiveMap.value = material.emissiveMap;
  15313. }
  15314. }
  15315. function refreshUniformsPhong(uniforms, material) {
  15316. uniforms.specular.value.copy(material.specular);
  15317. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  15318. if (material.emissiveMap) {
  15319. uniforms.emissiveMap.value = material.emissiveMap;
  15320. }
  15321. if (material.bumpMap) {
  15322. uniforms.bumpMap.value = material.bumpMap;
  15323. uniforms.bumpScale.value = material.bumpScale;
  15324. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15325. }
  15326. if (material.normalMap) {
  15327. uniforms.normalMap.value = material.normalMap;
  15328. uniforms.normalScale.value.copy(material.normalScale);
  15329. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15330. }
  15331. if (material.displacementMap) {
  15332. uniforms.displacementMap.value = material.displacementMap;
  15333. uniforms.displacementScale.value = material.displacementScale;
  15334. uniforms.displacementBias.value = material.displacementBias;
  15335. }
  15336. }
  15337. function refreshUniformsToon(uniforms, material) {
  15338. if (material.gradientMap) {
  15339. uniforms.gradientMap.value = material.gradientMap;
  15340. }
  15341. if (material.emissiveMap) {
  15342. uniforms.emissiveMap.value = material.emissiveMap;
  15343. }
  15344. if (material.bumpMap) {
  15345. uniforms.bumpMap.value = material.bumpMap;
  15346. uniforms.bumpScale.value = material.bumpScale;
  15347. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15348. }
  15349. if (material.normalMap) {
  15350. uniforms.normalMap.value = material.normalMap;
  15351. uniforms.normalScale.value.copy(material.normalScale);
  15352. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15353. }
  15354. if (material.displacementMap) {
  15355. uniforms.displacementMap.value = material.displacementMap;
  15356. uniforms.displacementScale.value = material.displacementScale;
  15357. uniforms.displacementBias.value = material.displacementBias;
  15358. }
  15359. }
  15360. function refreshUniformsStandard(uniforms, material) {
  15361. uniforms.roughness.value = material.roughness;
  15362. uniforms.metalness.value = material.metalness;
  15363. if (material.roughnessMap) {
  15364. uniforms.roughnessMap.value = material.roughnessMap;
  15365. }
  15366. if (material.metalnessMap) {
  15367. uniforms.metalnessMap.value = material.metalnessMap;
  15368. }
  15369. if (material.emissiveMap) {
  15370. uniforms.emissiveMap.value = material.emissiveMap;
  15371. }
  15372. if (material.bumpMap) {
  15373. uniforms.bumpMap.value = material.bumpMap;
  15374. uniforms.bumpScale.value = material.bumpScale;
  15375. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15376. }
  15377. if (material.normalMap) {
  15378. uniforms.normalMap.value = material.normalMap;
  15379. uniforms.normalScale.value.copy(material.normalScale);
  15380. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15381. }
  15382. if (material.displacementMap) {
  15383. uniforms.displacementMap.value = material.displacementMap;
  15384. uniforms.displacementScale.value = material.displacementScale;
  15385. uniforms.displacementBias.value = material.displacementBias;
  15386. }
  15387. const envMap = properties.get(material).envMap;
  15388. if (envMap) {
  15389. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15390. uniforms.envMapIntensity.value = material.envMapIntensity;
  15391. }
  15392. }
  15393. function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) {
  15394. refreshUniformsStandard(uniforms, material);
  15395. uniforms.ior.value = material.ior; // also part of uniforms common
  15396. if (material.sheen > 0) {
  15397. uniforms.sheenColor.value.copy(material.sheenColor).multiplyScalar(material.sheen);
  15398. uniforms.sheenRoughness.value = material.sheenRoughness;
  15399. if (material.sheenColorMap) {
  15400. uniforms.sheenColorMap.value = material.sheenColorMap;
  15401. }
  15402. if (material.sheenRoughnessMap) {
  15403. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  15404. }
  15405. }
  15406. if (material.clearcoat > 0) {
  15407. uniforms.clearcoat.value = material.clearcoat;
  15408. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  15409. if (material.clearcoatMap) {
  15410. uniforms.clearcoatMap.value = material.clearcoatMap;
  15411. }
  15412. if (material.clearcoatRoughnessMap) {
  15413. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  15414. }
  15415. if (material.clearcoatNormalMap) {
  15416. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  15417. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  15418. if (material.side === BackSide) {
  15419. uniforms.clearcoatNormalScale.value.negate();
  15420. }
  15421. }
  15422. }
  15423. if (material.transmission > 0) {
  15424. uniforms.transmission.value = material.transmission;
  15425. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  15426. uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height);
  15427. if (material.transmissionMap) {
  15428. uniforms.transmissionMap.value = material.transmissionMap;
  15429. }
  15430. uniforms.thickness.value = material.thickness;
  15431. if (material.thicknessMap) {
  15432. uniforms.thicknessMap.value = material.thicknessMap;
  15433. }
  15434. uniforms.attenuationDistance.value = material.attenuationDistance;
  15435. uniforms.attenuationColor.value.copy(material.attenuationColor);
  15436. }
  15437. uniforms.specularIntensity.value = material.specularIntensity;
  15438. uniforms.specularColor.value.copy(material.specularColor);
  15439. if (material.specularIntensityMap) {
  15440. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  15441. }
  15442. if (material.specularColorMap) {
  15443. uniforms.specularColorMap.value = material.specularColorMap;
  15444. }
  15445. }
  15446. function refreshUniformsMatcap(uniforms, material) {
  15447. if (material.matcap) {
  15448. uniforms.matcap.value = material.matcap;
  15449. }
  15450. if (material.bumpMap) {
  15451. uniforms.bumpMap.value = material.bumpMap;
  15452. uniforms.bumpScale.value = material.bumpScale;
  15453. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15454. }
  15455. if (material.normalMap) {
  15456. uniforms.normalMap.value = material.normalMap;
  15457. uniforms.normalScale.value.copy(material.normalScale);
  15458. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15459. }
  15460. if (material.displacementMap) {
  15461. uniforms.displacementMap.value = material.displacementMap;
  15462. uniforms.displacementScale.value = material.displacementScale;
  15463. uniforms.displacementBias.value = material.displacementBias;
  15464. }
  15465. }
  15466. function refreshUniformsDepth(uniforms, material) {
  15467. if (material.displacementMap) {
  15468. uniforms.displacementMap.value = material.displacementMap;
  15469. uniforms.displacementScale.value = material.displacementScale;
  15470. uniforms.displacementBias.value = material.displacementBias;
  15471. }
  15472. }
  15473. function refreshUniformsDistance(uniforms, material) {
  15474. if (material.displacementMap) {
  15475. uniforms.displacementMap.value = material.displacementMap;
  15476. uniforms.displacementScale.value = material.displacementScale;
  15477. uniforms.displacementBias.value = material.displacementBias;
  15478. }
  15479. uniforms.referencePosition.value.copy(material.referencePosition);
  15480. uniforms.nearDistance.value = material.nearDistance;
  15481. uniforms.farDistance.value = material.farDistance;
  15482. }
  15483. function refreshUniformsNormal(uniforms, material) {
  15484. if (material.bumpMap) {
  15485. uniforms.bumpMap.value = material.bumpMap;
  15486. uniforms.bumpScale.value = material.bumpScale;
  15487. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15488. }
  15489. if (material.normalMap) {
  15490. uniforms.normalMap.value = material.normalMap;
  15491. uniforms.normalScale.value.copy(material.normalScale);
  15492. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15493. }
  15494. if (material.displacementMap) {
  15495. uniforms.displacementMap.value = material.displacementMap;
  15496. uniforms.displacementScale.value = material.displacementScale;
  15497. uniforms.displacementBias.value = material.displacementBias;
  15498. }
  15499. }
  15500. return {
  15501. refreshFogUniforms: refreshFogUniforms,
  15502. refreshMaterialUniforms: refreshMaterialUniforms
  15503. };
  15504. }
  15505. function createCanvasElement() {
  15506. const canvas = createElementNS('canvas');
  15507. canvas.style.display = 'block';
  15508. return canvas;
  15509. }
  15510. function WebGLRenderer(parameters = {}) {
  15511. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  15512. _context = parameters.context !== undefined ? parameters.context : null,
  15513. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  15514. _depth = parameters.depth !== undefined ? parameters.depth : true,
  15515. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  15516. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  15517. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  15518. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  15519. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  15520. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  15521. let currentRenderList = null;
  15522. let currentRenderState = null; // render() can be called from within a callback triggered by another render.
  15523. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  15524. const renderListStack = [];
  15525. const renderStateStack = []; // public properties
  15526. this.domElement = _canvas; // Debug configuration container
  15527. this.debug = {
  15528. /**
  15529. * Enables error checking and reporting when shader programs are being compiled
  15530. * @type {boolean}
  15531. */
  15532. checkShaderErrors: true
  15533. }; // clearing
  15534. this.autoClear = true;
  15535. this.autoClearColor = true;
  15536. this.autoClearDepth = true;
  15537. this.autoClearStencil = true; // scene graph
  15538. this.sortObjects = true; // user-defined clipping
  15539. this.clippingPlanes = [];
  15540. this.localClippingEnabled = false; // physically based shading
  15541. this.gammaFactor = 2.0; // for backwards compatibility
  15542. this.outputEncoding = LinearEncoding; // physical lights
  15543. this.physicallyCorrectLights = false; // tone mapping
  15544. this.toneMapping = NoToneMapping;
  15545. this.toneMappingExposure = 1.0; // internal properties
  15546. const _this = this;
  15547. let _isContextLost = false; // internal state cache
  15548. let _currentActiveCubeFace = 0;
  15549. let _currentActiveMipmapLevel = 0;
  15550. let _currentRenderTarget = null;
  15551. let _currentMaterialId = -1;
  15552. let _currentCamera = null;
  15553. const _currentViewport = new Vector4();
  15554. const _currentScissor = new Vector4();
  15555. let _currentScissorTest = null; //
  15556. let _width = _canvas.width;
  15557. let _height = _canvas.height;
  15558. let _pixelRatio = 1;
  15559. let _opaqueSort = null;
  15560. let _transparentSort = null;
  15561. const _viewport = new Vector4(0, 0, _width, _height);
  15562. const _scissor = new Vector4(0, 0, _width, _height);
  15563. let _scissorTest = false; //
  15564. const _currentDrawBuffers = []; // frustum
  15565. const _frustum = new Frustum(); // clipping
  15566. let _clippingEnabled = false;
  15567. let _localClippingEnabled = false; // transmission
  15568. let _transmissionRenderTarget = null; // camera matrices cache
  15569. const _projScreenMatrix = new Matrix4();
  15570. const _vector3 = new Vector3();
  15571. const _emptyScene = {
  15572. background: null,
  15573. fog: null,
  15574. environment: null,
  15575. overrideMaterial: null,
  15576. isScene: true
  15577. };
  15578. function getTargetPixelRatio() {
  15579. return _currentRenderTarget === null ? _pixelRatio : 1;
  15580. } // initialize
  15581. let _gl = _context;
  15582. function getContext(contextNames, contextAttributes) {
  15583. for (let i = 0; i < contextNames.length; i++) {
  15584. const contextName = contextNames[i];
  15585. const context = _canvas.getContext(contextName, contextAttributes);
  15586. if (context !== null) return context;
  15587. }
  15588. return null;
  15589. }
  15590. try {
  15591. const contextAttributes = {
  15592. alpha: _alpha,
  15593. depth: _depth,
  15594. stencil: _stencil,
  15595. antialias: _antialias,
  15596. premultipliedAlpha: _premultipliedAlpha,
  15597. preserveDrawingBuffer: _preserveDrawingBuffer,
  15598. powerPreference: _powerPreference,
  15599. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  15600. }; // OffscreenCanvas does not have setAttribute, see #22811
  15601. if ('setAttribute' in _canvas) _canvas.setAttribute('data-engine', `three.js r${REVISION}`); // event listeners must be registered before WebGL context is created, see #12753
  15602. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  15603. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  15604. if (_gl === null) {
  15605. const contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
  15606. if (_this.isWebGL1Renderer === true) {
  15607. contextNames.shift();
  15608. }
  15609. _gl = getContext(contextNames, contextAttributes);
  15610. if (_gl === null) {
  15611. if (getContext(contextNames)) {
  15612. throw new Error('Error creating WebGL context with your selected attributes.');
  15613. } else {
  15614. throw new Error('Error creating WebGL context.');
  15615. }
  15616. }
  15617. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  15618. if (_gl.getShaderPrecisionFormat === undefined) {
  15619. _gl.getShaderPrecisionFormat = function () {
  15620. return {
  15621. 'rangeMin': 1,
  15622. 'rangeMax': 1,
  15623. 'precision': 1
  15624. };
  15625. };
  15626. }
  15627. } catch (error) {
  15628. console.error('THREE.WebGLRenderer: ' + error.message);
  15629. throw error;
  15630. }
  15631. let extensions, capabilities, state, info;
  15632. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  15633. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  15634. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  15635. let utils, bindingStates;
  15636. function initGLContext() {
  15637. extensions = new WebGLExtensions(_gl);
  15638. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  15639. extensions.init(capabilities);
  15640. utils = new WebGLUtils(_gl, extensions, capabilities);
  15641. state = new WebGLState(_gl, extensions, capabilities);
  15642. _currentDrawBuffers[0] = _gl.BACK;
  15643. info = new WebGLInfo(_gl);
  15644. properties = new WebGLProperties();
  15645. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  15646. cubemaps = new WebGLCubeMaps(_this);
  15647. cubeuvmaps = new WebGLCubeUVMaps(_this);
  15648. attributes = new WebGLAttributes(_gl, capabilities);
  15649. bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
  15650. geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
  15651. objects = new WebGLObjects(_gl, geometries, attributes, info);
  15652. morphtargets = new WebGLMorphtargets(_gl, capabilities, textures);
  15653. clipping = new WebGLClipping(properties);
  15654. programCache = new WebGLPrograms(_this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping);
  15655. materials = new WebGLMaterials(properties);
  15656. renderLists = new WebGLRenderLists();
  15657. renderStates = new WebGLRenderStates(extensions, capabilities);
  15658. background = new WebGLBackground(_this, cubemaps, state, objects, _premultipliedAlpha);
  15659. shadowMap = new WebGLShadowMap(_this, objects, capabilities);
  15660. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  15661. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  15662. info.programs = programCache.programs;
  15663. _this.capabilities = capabilities;
  15664. _this.extensions = extensions;
  15665. _this.properties = properties;
  15666. _this.renderLists = renderLists;
  15667. _this.shadowMap = shadowMap;
  15668. _this.state = state;
  15669. _this.info = info;
  15670. }
  15671. initGLContext(); // xr
  15672. const xr = new WebXRManager(_this, _gl);
  15673. this.xr = xr; // API
  15674. this.getContext = function () {
  15675. return _gl;
  15676. };
  15677. this.getContextAttributes = function () {
  15678. return _gl.getContextAttributes();
  15679. };
  15680. this.forceContextLoss = function () {
  15681. const extension = extensions.get('WEBGL_lose_context');
  15682. if (extension) extension.loseContext();
  15683. };
  15684. this.forceContextRestore = function () {
  15685. const extension = extensions.get('WEBGL_lose_context');
  15686. if (extension) extension.restoreContext();
  15687. };
  15688. this.getPixelRatio = function () {
  15689. return _pixelRatio;
  15690. };
  15691. this.setPixelRatio = function (value) {
  15692. if (value === undefined) return;
  15693. _pixelRatio = value;
  15694. this.setSize(_width, _height, false);
  15695. };
  15696. this.getSize = function (target) {
  15697. return target.set(_width, _height);
  15698. };
  15699. this.setSize = function (width, height, updateStyle) {
  15700. if (xr.isPresenting) {
  15701. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  15702. return;
  15703. }
  15704. _width = width;
  15705. _height = height;
  15706. _canvas.width = Math.floor(width * _pixelRatio);
  15707. _canvas.height = Math.floor(height * _pixelRatio);
  15708. if (updateStyle !== false) {
  15709. _canvas.style.width = width + 'px';
  15710. _canvas.style.height = height + 'px';
  15711. }
  15712. this.setViewport(0, 0, width, height);
  15713. };
  15714. this.getDrawingBufferSize = function (target) {
  15715. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  15716. };
  15717. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  15718. _width = width;
  15719. _height = height;
  15720. _pixelRatio = pixelRatio;
  15721. _canvas.width = Math.floor(width * pixelRatio);
  15722. _canvas.height = Math.floor(height * pixelRatio);
  15723. this.setViewport(0, 0, width, height);
  15724. };
  15725. this.getCurrentViewport = function (target) {
  15726. return target.copy(_currentViewport);
  15727. };
  15728. this.getViewport = function (target) {
  15729. return target.copy(_viewport);
  15730. };
  15731. this.setViewport = function (x, y, width, height) {
  15732. if (x.isVector4) {
  15733. _viewport.set(x.x, x.y, x.z, x.w);
  15734. } else {
  15735. _viewport.set(x, y, width, height);
  15736. }
  15737. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  15738. };
  15739. this.getScissor = function (target) {
  15740. return target.copy(_scissor);
  15741. };
  15742. this.setScissor = function (x, y, width, height) {
  15743. if (x.isVector4) {
  15744. _scissor.set(x.x, x.y, x.z, x.w);
  15745. } else {
  15746. _scissor.set(x, y, width, height);
  15747. }
  15748. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  15749. };
  15750. this.getScissorTest = function () {
  15751. return _scissorTest;
  15752. };
  15753. this.setScissorTest = function (boolean) {
  15754. state.setScissorTest(_scissorTest = boolean);
  15755. };
  15756. this.setOpaqueSort = function (method) {
  15757. _opaqueSort = method;
  15758. };
  15759. this.setTransparentSort = function (method) {
  15760. _transparentSort = method;
  15761. }; // Clearing
  15762. this.getClearColor = function (target) {
  15763. return target.copy(background.getClearColor());
  15764. };
  15765. this.setClearColor = function () {
  15766. background.setClearColor.apply(background, arguments);
  15767. };
  15768. this.getClearAlpha = function () {
  15769. return background.getClearAlpha();
  15770. };
  15771. this.setClearAlpha = function () {
  15772. background.setClearAlpha.apply(background, arguments);
  15773. };
  15774. this.clear = function (color, depth, stencil) {
  15775. let bits = 0;
  15776. if (color === undefined || color) bits |= _gl.COLOR_BUFFER_BIT;
  15777. if (depth === undefined || depth) bits |= _gl.DEPTH_BUFFER_BIT;
  15778. if (stencil === undefined || stencil) bits |= _gl.STENCIL_BUFFER_BIT;
  15779. _gl.clear(bits);
  15780. };
  15781. this.clearColor = function () {
  15782. this.clear(true, false, false);
  15783. };
  15784. this.clearDepth = function () {
  15785. this.clear(false, true, false);
  15786. };
  15787. this.clearStencil = function () {
  15788. this.clear(false, false, true);
  15789. }; //
  15790. this.dispose = function () {
  15791. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  15792. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  15793. renderLists.dispose();
  15794. renderStates.dispose();
  15795. properties.dispose();
  15796. cubemaps.dispose();
  15797. cubeuvmaps.dispose();
  15798. objects.dispose();
  15799. bindingStates.dispose();
  15800. programCache.dispose();
  15801. xr.dispose();
  15802. xr.removeEventListener('sessionstart', onXRSessionStart);
  15803. xr.removeEventListener('sessionend', onXRSessionEnd);
  15804. if (_transmissionRenderTarget) {
  15805. _transmissionRenderTarget.dispose();
  15806. _transmissionRenderTarget = null;
  15807. }
  15808. animation.stop();
  15809. }; // Events
  15810. function onContextLost(event) {
  15811. event.preventDefault();
  15812. console.log('THREE.WebGLRenderer: Context Lost.');
  15813. _isContextLost = true;
  15814. }
  15815. function onContextRestore() {
  15816. console.log('THREE.WebGLRenderer: Context Restored.');
  15817. _isContextLost = false;
  15818. const infoAutoReset = info.autoReset;
  15819. const shadowMapEnabled = shadowMap.enabled;
  15820. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  15821. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  15822. const shadowMapType = shadowMap.type;
  15823. initGLContext();
  15824. info.autoReset = infoAutoReset;
  15825. shadowMap.enabled = shadowMapEnabled;
  15826. shadowMap.autoUpdate = shadowMapAutoUpdate;
  15827. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  15828. shadowMap.type = shadowMapType;
  15829. }
  15830. function onMaterialDispose(event) {
  15831. const material = event.target;
  15832. material.removeEventListener('dispose', onMaterialDispose);
  15833. deallocateMaterial(material);
  15834. } // Buffer deallocation
  15835. function deallocateMaterial(material) {
  15836. releaseMaterialProgramReferences(material);
  15837. properties.remove(material);
  15838. }
  15839. function releaseMaterialProgramReferences(material) {
  15840. const programs = properties.get(material).programs;
  15841. if (programs !== undefined) {
  15842. programs.forEach(function (program) {
  15843. programCache.releaseProgram(program);
  15844. });
  15845. if (material.isShaderMaterial) {
  15846. programCache.releaseShaderCache(material);
  15847. }
  15848. }
  15849. } // Buffer rendering
  15850. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  15851. if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  15852. const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  15853. const program = setProgram(camera, scene, geometry, material, object);
  15854. state.setMaterial(material, frontFaceCW); //
  15855. let index = geometry.index;
  15856. const position = geometry.attributes.position; //
  15857. if (index === null) {
  15858. if (position === undefined || position.count === 0) return;
  15859. } else if (index.count === 0) {
  15860. return;
  15861. } //
  15862. let rangeFactor = 1;
  15863. if (material.wireframe === true) {
  15864. index = geometries.getWireframeAttribute(geometry);
  15865. rangeFactor = 2;
  15866. }
  15867. bindingStates.setup(object, material, program, geometry, index);
  15868. let attribute;
  15869. let renderer = bufferRenderer;
  15870. if (index !== null) {
  15871. attribute = attributes.get(index);
  15872. renderer = indexedBufferRenderer;
  15873. renderer.setIndex(attribute);
  15874. } //
  15875. const dataCount = index !== null ? index.count : position.count;
  15876. const rangeStart = geometry.drawRange.start * rangeFactor;
  15877. const rangeCount = geometry.drawRange.count * rangeFactor;
  15878. const groupStart = group !== null ? group.start * rangeFactor : 0;
  15879. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  15880. const drawStart = Math.max(rangeStart, groupStart);
  15881. const drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  15882. const drawCount = Math.max(0, drawEnd - drawStart + 1);
  15883. if (drawCount === 0) return; //
  15884. if (object.isMesh) {
  15885. if (material.wireframe === true) {
  15886. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  15887. renderer.setMode(_gl.LINES);
  15888. } else {
  15889. renderer.setMode(_gl.TRIANGLES);
  15890. }
  15891. } else if (object.isLine) {
  15892. let lineWidth = material.linewidth;
  15893. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  15894. state.setLineWidth(lineWidth * getTargetPixelRatio());
  15895. if (object.isLineSegments) {
  15896. renderer.setMode(_gl.LINES);
  15897. } else if (object.isLineLoop) {
  15898. renderer.setMode(_gl.LINE_LOOP);
  15899. } else {
  15900. renderer.setMode(_gl.LINE_STRIP);
  15901. }
  15902. } else if (object.isPoints) {
  15903. renderer.setMode(_gl.POINTS);
  15904. } else if (object.isSprite) {
  15905. renderer.setMode(_gl.TRIANGLES);
  15906. }
  15907. if (object.isInstancedMesh) {
  15908. renderer.renderInstances(drawStart, drawCount, object.count);
  15909. } else if (geometry.isInstancedBufferGeometry) {
  15910. const instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount);
  15911. renderer.renderInstances(drawStart, drawCount, instanceCount);
  15912. } else {
  15913. renderer.render(drawStart, drawCount);
  15914. }
  15915. }; // Compile
  15916. this.compile = function (scene, camera) {
  15917. currentRenderState = renderStates.get(scene);
  15918. currentRenderState.init();
  15919. renderStateStack.push(currentRenderState);
  15920. scene.traverseVisible(function (object) {
  15921. if (object.isLight && object.layers.test(camera.layers)) {
  15922. currentRenderState.pushLight(object);
  15923. if (object.castShadow) {
  15924. currentRenderState.pushShadow(object);
  15925. }
  15926. }
  15927. });
  15928. currentRenderState.setupLights(_this.physicallyCorrectLights);
  15929. scene.traverse(function (object) {
  15930. const material = object.material;
  15931. if (material) {
  15932. if (Array.isArray(material)) {
  15933. for (let i = 0; i < material.length; i++) {
  15934. const material2 = material[i];
  15935. getProgram(material2, scene, object);
  15936. }
  15937. } else {
  15938. getProgram(material, scene, object);
  15939. }
  15940. }
  15941. });
  15942. renderStateStack.pop();
  15943. currentRenderState = null;
  15944. }; // Animation Loop
  15945. let onAnimationFrameCallback = null;
  15946. function onAnimationFrame(time) {
  15947. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  15948. }
  15949. function onXRSessionStart() {
  15950. animation.stop();
  15951. }
  15952. function onXRSessionEnd() {
  15953. animation.start();
  15954. }
  15955. const animation = new WebGLAnimation();
  15956. animation.setAnimationLoop(onAnimationFrame);
  15957. if (typeof window !== 'undefined') animation.setContext(window);
  15958. this.setAnimationLoop = function (callback) {
  15959. onAnimationFrameCallback = callback;
  15960. xr.setAnimationLoop(callback);
  15961. callback === null ? animation.stop() : animation.start();
  15962. };
  15963. xr.addEventListener('sessionstart', onXRSessionStart);
  15964. xr.addEventListener('sessionend', onXRSessionEnd); // Rendering
  15965. this.render = function (scene, camera) {
  15966. if (camera !== undefined && camera.isCamera !== true) {
  15967. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  15968. return;
  15969. }
  15970. if (_isContextLost === true) return; // update scene graph
  15971. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  15972. if (camera.parent === null) camera.updateMatrixWorld();
  15973. if (xr.enabled === true && xr.isPresenting === true) {
  15974. if (xr.cameraAutoUpdate === true) xr.updateCamera(camera);
  15975. camera = xr.getCamera(); // use XR camera for rendering
  15976. } //
  15977. if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, _currentRenderTarget);
  15978. currentRenderState = renderStates.get(scene, renderStateStack.length);
  15979. currentRenderState.init();
  15980. renderStateStack.push(currentRenderState);
  15981. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  15982. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  15983. _localClippingEnabled = this.localClippingEnabled;
  15984. _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  15985. currentRenderList = renderLists.get(scene, renderListStack.length);
  15986. currentRenderList.init();
  15987. renderListStack.push(currentRenderList);
  15988. projectObject(scene, camera, 0, _this.sortObjects);
  15989. currentRenderList.finish();
  15990. if (_this.sortObjects === true) {
  15991. currentRenderList.sort(_opaqueSort, _transparentSort);
  15992. } //
  15993. if (_clippingEnabled === true) clipping.beginShadows();
  15994. const shadowsArray = currentRenderState.state.shadowsArray;
  15995. shadowMap.render(shadowsArray, scene, camera);
  15996. if (_clippingEnabled === true) clipping.endShadows(); //
  15997. if (this.info.autoReset === true) this.info.reset(); //
  15998. background.render(currentRenderList, scene); // render scene
  15999. currentRenderState.setupLights(_this.physicallyCorrectLights);
  16000. if (camera.isArrayCamera) {
  16001. const cameras = camera.cameras;
  16002. for (let i = 0, l = cameras.length; i < l; i++) {
  16003. const camera2 = cameras[i];
  16004. renderScene(currentRenderList, scene, camera2, camera2.viewport);
  16005. }
  16006. } else {
  16007. renderScene(currentRenderList, scene, camera);
  16008. } //
  16009. if (_currentRenderTarget !== null) {
  16010. // resolve multisample renderbuffers to a single-sample texture if necessary
  16011. textures.updateMultisampleRenderTarget(_currentRenderTarget); // Generate mipmap if we're using any kind of mipmap filtering
  16012. textures.updateRenderTargetMipmap(_currentRenderTarget);
  16013. } //
  16014. if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); // Ensure depth buffer writing is enabled so it can be cleared on next render
  16015. state.buffers.depth.setTest(true);
  16016. state.buffers.depth.setMask(true);
  16017. state.buffers.color.setMask(true);
  16018. state.setPolygonOffset(false); // _gl.finish();
  16019. bindingStates.resetDefaultState();
  16020. _currentMaterialId = -1;
  16021. _currentCamera = null;
  16022. renderStateStack.pop();
  16023. if (renderStateStack.length > 0) {
  16024. currentRenderState = renderStateStack[renderStateStack.length - 1];
  16025. } else {
  16026. currentRenderState = null;
  16027. }
  16028. renderListStack.pop();
  16029. if (renderListStack.length > 0) {
  16030. currentRenderList = renderListStack[renderListStack.length - 1];
  16031. } else {
  16032. currentRenderList = null;
  16033. }
  16034. };
  16035. function projectObject(object, camera, groupOrder, sortObjects) {
  16036. if (object.visible === false) return;
  16037. const visible = object.layers.test(camera.layers);
  16038. if (visible) {
  16039. if (object.isGroup) {
  16040. groupOrder = object.renderOrder;
  16041. } else if (object.isLOD) {
  16042. if (object.autoUpdate === true) object.update(camera);
  16043. } else if (object.isLight) {
  16044. currentRenderState.pushLight(object);
  16045. if (object.castShadow) {
  16046. currentRenderState.pushShadow(object);
  16047. }
  16048. } else if (object.isSprite) {
  16049. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  16050. if (sortObjects) {
  16051. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16052. }
  16053. const geometry = objects.update(object);
  16054. const material = object.material;
  16055. if (material.visible) {
  16056. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  16057. }
  16058. }
  16059. } else if (object.isMesh || object.isLine || object.isPoints) {
  16060. if (object.isSkinnedMesh) {
  16061. // update skeleton only once in a frame
  16062. if (object.skeleton.frame !== info.render.frame) {
  16063. object.skeleton.update();
  16064. object.skeleton.frame = info.render.frame;
  16065. }
  16066. }
  16067. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  16068. if (sortObjects) {
  16069. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16070. }
  16071. const geometry = objects.update(object);
  16072. const material = object.material;
  16073. if (Array.isArray(material)) {
  16074. const groups = geometry.groups;
  16075. for (let i = 0, l = groups.length; i < l; i++) {
  16076. const group = groups[i];
  16077. const groupMaterial = material[group.materialIndex];
  16078. if (groupMaterial && groupMaterial.visible) {
  16079. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  16080. }
  16081. }
  16082. } else if (material.visible) {
  16083. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  16084. }
  16085. }
  16086. }
  16087. }
  16088. const children = object.children;
  16089. for (let i = 0, l = children.length; i < l; i++) {
  16090. projectObject(children[i], camera, groupOrder, sortObjects);
  16091. }
  16092. }
  16093. function renderScene(currentRenderList, scene, camera, viewport) {
  16094. const opaqueObjects = currentRenderList.opaque;
  16095. const transmissiveObjects = currentRenderList.transmissive;
  16096. const transparentObjects = currentRenderList.transparent;
  16097. currentRenderState.setupLightsView(camera);
  16098. if (transmissiveObjects.length > 0) renderTransmissionPass(opaqueObjects, scene, camera);
  16099. if (viewport) state.viewport(_currentViewport.copy(viewport));
  16100. if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
  16101. if (transmissiveObjects.length > 0) renderObjects(transmissiveObjects, scene, camera);
  16102. if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera);
  16103. }
  16104. function renderTransmissionPass(opaqueObjects, scene, camera) {
  16105. if (_transmissionRenderTarget === null) {
  16106. const needsAntialias = _antialias === true && capabilities.isWebGL2 === true;
  16107. const renderTargetType = needsAntialias ? WebGLMultisampleRenderTarget : WebGLRenderTarget;
  16108. _transmissionRenderTarget = new renderTargetType(1024, 1024, {
  16109. generateMipmaps: true,
  16110. type: utils.convert(HalfFloatType) !== null ? HalfFloatType : UnsignedByteType,
  16111. minFilter: LinearMipmapLinearFilter,
  16112. magFilter: NearestFilter,
  16113. wrapS: ClampToEdgeWrapping,
  16114. wrapT: ClampToEdgeWrapping,
  16115. useRenderToTexture: extensions.has('WEBGL_multisampled_render_to_texture')
  16116. });
  16117. }
  16118. const currentRenderTarget = _this.getRenderTarget();
  16119. _this.setRenderTarget(_transmissionRenderTarget);
  16120. _this.clear(); // Turn off the features which can affect the frag color for opaque objects pass.
  16121. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  16122. const currentToneMapping = _this.toneMapping;
  16123. _this.toneMapping = NoToneMapping;
  16124. renderObjects(opaqueObjects, scene, camera);
  16125. _this.toneMapping = currentToneMapping;
  16126. textures.updateMultisampleRenderTarget(_transmissionRenderTarget);
  16127. textures.updateRenderTargetMipmap(_transmissionRenderTarget);
  16128. _this.setRenderTarget(currentRenderTarget);
  16129. }
  16130. function renderObjects(renderList, scene, camera) {
  16131. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  16132. for (let i = 0, l = renderList.length; i < l; i++) {
  16133. const renderItem = renderList[i];
  16134. const object = renderItem.object;
  16135. const geometry = renderItem.geometry;
  16136. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  16137. const group = renderItem.group;
  16138. if (object.layers.test(camera.layers)) {
  16139. renderObject(object, scene, camera, geometry, material, group);
  16140. }
  16141. }
  16142. }
  16143. function renderObject(object, scene, camera, geometry, material, group) {
  16144. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  16145. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  16146. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  16147. material.onBeforeRender(_this, scene, camera, geometry, object, group);
  16148. if (material.transparent === true && material.side === DoubleSide) {
  16149. material.side = BackSide;
  16150. material.needsUpdate = true;
  16151. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  16152. material.side = FrontSide;
  16153. material.needsUpdate = true;
  16154. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  16155. material.side = DoubleSide;
  16156. } else {
  16157. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  16158. }
  16159. object.onAfterRender(_this, scene, camera, geometry, material, group);
  16160. }
  16161. function getProgram(material, scene, object) {
  16162. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16163. const materialProperties = properties.get(material);
  16164. const lights = currentRenderState.state.lights;
  16165. const shadowsArray = currentRenderState.state.shadowsArray;
  16166. const lightsStateVersion = lights.state.version;
  16167. const parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
  16168. const programCacheKey = programCache.getProgramCacheKey(parameters);
  16169. let programs = materialProperties.programs; // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  16170. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  16171. materialProperties.fog = scene.fog;
  16172. materialProperties.envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || materialProperties.environment);
  16173. if (programs === undefined) {
  16174. // new material
  16175. material.addEventListener('dispose', onMaterialDispose);
  16176. programs = new Map();
  16177. materialProperties.programs = programs;
  16178. }
  16179. let program = programs.get(programCacheKey);
  16180. if (program !== undefined) {
  16181. // early out if program and light state is identical
  16182. if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) {
  16183. updateCommonMaterialProperties(material, parameters);
  16184. return program;
  16185. }
  16186. } else {
  16187. parameters.uniforms = programCache.getUniforms(material);
  16188. material.onBuild(object, parameters, _this);
  16189. material.onBeforeCompile(parameters, _this);
  16190. program = programCache.acquireProgram(parameters, programCacheKey);
  16191. programs.set(programCacheKey, program);
  16192. materialProperties.uniforms = parameters.uniforms;
  16193. }
  16194. const uniforms = materialProperties.uniforms;
  16195. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  16196. uniforms.clippingPlanes = clipping.uniform;
  16197. }
  16198. updateCommonMaterialProperties(material, parameters); // store the light setup it was created for
  16199. materialProperties.needsLights = materialNeedsLights(material);
  16200. materialProperties.lightsStateVersion = lightsStateVersion;
  16201. if (materialProperties.needsLights) {
  16202. // wire up the material to this renderer's lighting state
  16203. uniforms.ambientLightColor.value = lights.state.ambient;
  16204. uniforms.lightProbe.value = lights.state.probe;
  16205. uniforms.directionalLights.value = lights.state.directional;
  16206. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  16207. uniforms.spotLights.value = lights.state.spot;
  16208. uniforms.spotLightShadows.value = lights.state.spotShadow;
  16209. uniforms.rectAreaLights.value = lights.state.rectArea;
  16210. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  16211. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  16212. uniforms.pointLights.value = lights.state.point;
  16213. uniforms.pointLightShadows.value = lights.state.pointShadow;
  16214. uniforms.hemisphereLights.value = lights.state.hemi;
  16215. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  16216. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  16217. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  16218. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  16219. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  16220. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  16221. }
  16222. const progUniforms = program.getUniforms();
  16223. const uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  16224. materialProperties.currentProgram = program;
  16225. materialProperties.uniformsList = uniformsList;
  16226. return program;
  16227. }
  16228. function updateCommonMaterialProperties(material, parameters) {
  16229. const materialProperties = properties.get(material);
  16230. materialProperties.outputEncoding = parameters.outputEncoding;
  16231. materialProperties.instancing = parameters.instancing;
  16232. materialProperties.skinning = parameters.skinning;
  16233. materialProperties.morphTargets = parameters.morphTargets;
  16234. materialProperties.morphNormals = parameters.morphNormals;
  16235. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  16236. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  16237. materialProperties.numIntersection = parameters.numClipIntersection;
  16238. materialProperties.vertexAlphas = parameters.vertexAlphas;
  16239. materialProperties.vertexTangents = parameters.vertexTangents;
  16240. materialProperties.toneMapping = parameters.toneMapping;
  16241. }
  16242. function setProgram(camera, scene, geometry, material, object) {
  16243. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16244. textures.resetTextureUnits();
  16245. const fog = scene.fog;
  16246. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  16247. const encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  16248. const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
  16249. const vertexAlphas = material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  16250. const vertexTangents = !!material.normalMap && !!geometry.attributes.tangent;
  16251. const morphTargets = !!geometry.morphAttributes.position;
  16252. const morphNormals = !!geometry.morphAttributes.normal;
  16253. const morphTargetsCount = !!geometry.morphAttributes.position ? geometry.morphAttributes.position.length : 0;
  16254. const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping;
  16255. const materialProperties = properties.get(material);
  16256. const lights = currentRenderState.state.lights;
  16257. if (_clippingEnabled === true) {
  16258. if (_localClippingEnabled === true || camera !== _currentCamera) {
  16259. const useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  16260. // object instead of the material, once it becomes feasible
  16261. // (#8465, #8379)
  16262. clipping.setState(material, camera, useCache);
  16263. }
  16264. } //
  16265. let needsProgramChange = false;
  16266. if (material.version === materialProperties.__version) {
  16267. if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  16268. needsProgramChange = true;
  16269. } else if (materialProperties.outputEncoding !== encoding) {
  16270. needsProgramChange = true;
  16271. } else if (object.isInstancedMesh && materialProperties.instancing === false) {
  16272. needsProgramChange = true;
  16273. } else if (!object.isInstancedMesh && materialProperties.instancing === true) {
  16274. needsProgramChange = true;
  16275. } else if (object.isSkinnedMesh && materialProperties.skinning === false) {
  16276. needsProgramChange = true;
  16277. } else if (!object.isSkinnedMesh && materialProperties.skinning === true) {
  16278. needsProgramChange = true;
  16279. } else if (materialProperties.envMap !== envMap) {
  16280. needsProgramChange = true;
  16281. } else if (material.fog && materialProperties.fog !== fog) {
  16282. needsProgramChange = true;
  16283. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
  16284. needsProgramChange = true;
  16285. } else if (materialProperties.vertexAlphas !== vertexAlphas) {
  16286. needsProgramChange = true;
  16287. } else if (materialProperties.vertexTangents !== vertexTangents) {
  16288. needsProgramChange = true;
  16289. } else if (materialProperties.morphTargets !== morphTargets) {
  16290. needsProgramChange = true;
  16291. } else if (materialProperties.morphNormals !== morphNormals) {
  16292. needsProgramChange = true;
  16293. } else if (materialProperties.toneMapping !== toneMapping) {
  16294. needsProgramChange = true;
  16295. } else if (capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount) {
  16296. needsProgramChange = true;
  16297. }
  16298. } else {
  16299. needsProgramChange = true;
  16300. materialProperties.__version = material.version;
  16301. } //
  16302. let program = materialProperties.currentProgram;
  16303. if (needsProgramChange === true) {
  16304. program = getProgram(material, scene, object);
  16305. }
  16306. let refreshProgram = false;
  16307. let refreshMaterial = false;
  16308. let refreshLights = false;
  16309. const p_uniforms = program.getUniforms(),
  16310. m_uniforms = materialProperties.uniforms;
  16311. if (state.useProgram(program.program)) {
  16312. refreshProgram = true;
  16313. refreshMaterial = true;
  16314. refreshLights = true;
  16315. }
  16316. if (material.id !== _currentMaterialId) {
  16317. _currentMaterialId = material.id;
  16318. refreshMaterial = true;
  16319. }
  16320. if (refreshProgram || _currentCamera !== camera) {
  16321. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  16322. if (capabilities.logarithmicDepthBuffer) {
  16323. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  16324. }
  16325. if (_currentCamera !== camera) {
  16326. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  16327. // now, in case this material supports lights - or later, when
  16328. // the next material that does gets activated:
  16329. refreshMaterial = true; // set to true on material change
  16330. refreshLights = true; // remains set until update done
  16331. } // load material specific uniforms
  16332. // (shader material also gets them for the sake of genericity)
  16333. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  16334. const uCamPos = p_uniforms.map.cameraPosition;
  16335. if (uCamPos !== undefined) {
  16336. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  16337. }
  16338. }
  16339. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  16340. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  16341. }
  16342. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || object.isSkinnedMesh) {
  16343. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  16344. }
  16345. } // skinning and morph target uniforms must be set even if material didn't change
  16346. // auto-setting of texture unit for bone and morph texture must go before other textures
  16347. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  16348. if (object.isSkinnedMesh) {
  16349. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  16350. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  16351. const skeleton = object.skeleton;
  16352. if (skeleton) {
  16353. if (capabilities.floatVertexTextures) {
  16354. if (skeleton.boneTexture === null) skeleton.computeBoneTexture();
  16355. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  16356. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  16357. } else {
  16358. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  16359. }
  16360. }
  16361. }
  16362. if (!!geometry && (geometry.morphAttributes.position !== undefined || geometry.morphAttributes.normal !== undefined)) {
  16363. morphtargets.update(object, geometry, material, program);
  16364. }
  16365. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  16366. materialProperties.receiveShadow = object.receiveShadow;
  16367. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  16368. }
  16369. if (refreshMaterial) {
  16370. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  16371. if (materialProperties.needsLights) {
  16372. // the current material requires lighting info
  16373. // note: all lighting uniforms are always set correctly
  16374. // they simply reference the renderer's state for their
  16375. // values
  16376. //
  16377. // use the current material's .needsUpdate flags to set
  16378. // the GL state when required
  16379. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  16380. } // refresh uniforms common to several materials
  16381. if (fog && material.fog) {
  16382. materials.refreshFogUniforms(m_uniforms, fog);
  16383. }
  16384. materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget);
  16385. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16386. }
  16387. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  16388. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16389. material.uniformsNeedUpdate = false;
  16390. }
  16391. if (material.isSpriteMaterial) {
  16392. p_uniforms.setValue(_gl, 'center', object.center);
  16393. } // common matrices
  16394. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  16395. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  16396. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  16397. return program;
  16398. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  16399. function markUniformsLightsNeedsUpdate(uniforms, value) {
  16400. uniforms.ambientLightColor.needsUpdate = value;
  16401. uniforms.lightProbe.needsUpdate = value;
  16402. uniforms.directionalLights.needsUpdate = value;
  16403. uniforms.directionalLightShadows.needsUpdate = value;
  16404. uniforms.pointLights.needsUpdate = value;
  16405. uniforms.pointLightShadows.needsUpdate = value;
  16406. uniforms.spotLights.needsUpdate = value;
  16407. uniforms.spotLightShadows.needsUpdate = value;
  16408. uniforms.rectAreaLights.needsUpdate = value;
  16409. uniforms.hemisphereLights.needsUpdate = value;
  16410. }
  16411. function materialNeedsLights(material) {
  16412. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  16413. }
  16414. this.getActiveCubeFace = function () {
  16415. return _currentActiveCubeFace;
  16416. };
  16417. this.getActiveMipmapLevel = function () {
  16418. return _currentActiveMipmapLevel;
  16419. };
  16420. this.getRenderTarget = function () {
  16421. return _currentRenderTarget;
  16422. };
  16423. this.setRenderTargetTextures = function (renderTarget, colorTexture, depthTexture) {
  16424. properties.get(renderTarget.texture).__webglTexture = colorTexture;
  16425. properties.get(renderTarget.depthTexture).__webglTexture = depthTexture;
  16426. const renderTargetProperties = properties.get(renderTarget);
  16427. renderTargetProperties.__hasExternalTextures = true;
  16428. if (renderTargetProperties.__hasExternalTextures) {
  16429. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  16430. if (!renderTargetProperties.__autoAllocateDepthBuffer) {
  16431. // The multisample_render_to_texture extension doesn't work properly if there
  16432. // are midframe flushes and an external depth buffer. Disable use of the extension.
  16433. if (renderTarget.useRenderToTexture) {
  16434. console.warn('render-to-texture extension was disabled because an external texture was provided');
  16435. renderTarget.useRenderToTexture = false;
  16436. renderTarget.useRenderbuffer = true;
  16437. }
  16438. }
  16439. }
  16440. };
  16441. this.setRenderTargetFramebuffer = function (renderTarget, defaultFramebuffer) {
  16442. const renderTargetProperties = properties.get(renderTarget);
  16443. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  16444. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  16445. };
  16446. this.setRenderTarget = function (renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) {
  16447. _currentRenderTarget = renderTarget;
  16448. _currentActiveCubeFace = activeCubeFace;
  16449. _currentActiveMipmapLevel = activeMipmapLevel;
  16450. let useDefaultFramebuffer = true;
  16451. if (renderTarget) {
  16452. const renderTargetProperties = properties.get(renderTarget);
  16453. if (renderTargetProperties.__useDefaultFramebuffer !== undefined) {
  16454. // We need to make sure to rebind the framebuffer.
  16455. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  16456. useDefaultFramebuffer = false;
  16457. } else if (renderTargetProperties.__webglFramebuffer === undefined) {
  16458. textures.setupRenderTarget(renderTarget);
  16459. } else if (renderTargetProperties.__hasExternalTextures) {
  16460. // Color and depth texture must be rebound in order for the swapchain to update.
  16461. textures.rebindTextures(renderTarget, properties.get(renderTarget.texture).__webglTexture, properties.get(renderTarget.depthTexture).__webglTexture);
  16462. }
  16463. }
  16464. let framebuffer = null;
  16465. let isCube = false;
  16466. let isRenderTarget3D = false;
  16467. if (renderTarget) {
  16468. const texture = renderTarget.texture;
  16469. if (texture.isDataTexture3D || texture.isDataTexture2DArray) {
  16470. isRenderTarget3D = true;
  16471. }
  16472. const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  16473. if (renderTarget.isWebGLCubeRenderTarget) {
  16474. framebuffer = __webglFramebuffer[activeCubeFace];
  16475. isCube = true;
  16476. } else if (renderTarget.useRenderbuffer) {
  16477. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  16478. } else {
  16479. framebuffer = __webglFramebuffer;
  16480. }
  16481. _currentViewport.copy(renderTarget.viewport);
  16482. _currentScissor.copy(renderTarget.scissor);
  16483. _currentScissorTest = renderTarget.scissorTest;
  16484. } else {
  16485. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  16486. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  16487. _currentScissorTest = _scissorTest;
  16488. }
  16489. const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16490. if (framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer) {
  16491. let needsUpdate = false;
  16492. if (renderTarget) {
  16493. if (renderTarget.isWebGLMultipleRenderTargets) {
  16494. const textures = renderTarget.texture;
  16495. if (_currentDrawBuffers.length !== textures.length || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
  16496. for (let i = 0, il = textures.length; i < il; i++) {
  16497. _currentDrawBuffers[i] = _gl.COLOR_ATTACHMENT0 + i;
  16498. }
  16499. _currentDrawBuffers.length = textures.length;
  16500. needsUpdate = true;
  16501. }
  16502. } else {
  16503. if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
  16504. _currentDrawBuffers[0] = _gl.COLOR_ATTACHMENT0;
  16505. _currentDrawBuffers.length = 1;
  16506. needsUpdate = true;
  16507. }
  16508. }
  16509. } else {
  16510. if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.BACK) {
  16511. _currentDrawBuffers[0] = _gl.BACK;
  16512. _currentDrawBuffers.length = 1;
  16513. needsUpdate = true;
  16514. }
  16515. }
  16516. if (needsUpdate) {
  16517. if (capabilities.isWebGL2) {
  16518. _gl.drawBuffers(_currentDrawBuffers);
  16519. } else {
  16520. extensions.get('WEBGL_draw_buffers').drawBuffersWEBGL(_currentDrawBuffers);
  16521. }
  16522. }
  16523. }
  16524. state.viewport(_currentViewport);
  16525. state.scissor(_currentScissor);
  16526. state.setScissorTest(_currentScissorTest);
  16527. if (isCube) {
  16528. const textureProperties = properties.get(renderTarget.texture);
  16529. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
  16530. } else if (isRenderTarget3D) {
  16531. const textureProperties = properties.get(renderTarget.texture);
  16532. const layer = activeCubeFace || 0;
  16533. _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer);
  16534. }
  16535. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  16536. };
  16537. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  16538. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  16539. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  16540. return;
  16541. }
  16542. let framebuffer = properties.get(renderTarget).__webglFramebuffer;
  16543. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  16544. framebuffer = framebuffer[activeCubeFaceIndex];
  16545. }
  16546. if (framebuffer) {
  16547. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16548. try {
  16549. const texture = renderTarget.texture;
  16550. const textureFormat = texture.format;
  16551. const textureType = texture.type;
  16552. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_FORMAT)) {
  16553. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  16554. return;
  16555. }
  16556. const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has('EXT_color_buffer_half_float') || capabilities.isWebGL2 && extensions.has('EXT_color_buffer_float'));
  16557. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513)
  16558. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.has('OES_texture_float') || extensions.has('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  16559. !halfFloatSupportedByExt) {
  16560. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  16561. return;
  16562. }
  16563. if (_gl.checkFramebufferStatus(_gl.FRAMEBUFFER) === _gl.FRAMEBUFFER_COMPLETE) {
  16564. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  16565. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  16566. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  16567. }
  16568. } else {
  16569. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  16570. }
  16571. } finally {
  16572. // restore framebuffer of current render target if necessary
  16573. const framebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null;
  16574. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16575. }
  16576. }
  16577. };
  16578. this.copyFramebufferToTexture = function (position, texture, level = 0) {
  16579. if (texture.isFramebufferTexture !== true) {
  16580. console.error('THREE.WebGLRenderer: copyFramebufferToTexture() can only be used with FramebufferTexture.');
  16581. return;
  16582. }
  16583. const levelScale = Math.pow(2, -level);
  16584. const width = Math.floor(texture.image.width * levelScale);
  16585. const height = Math.floor(texture.image.height * levelScale);
  16586. textures.setTexture2D(texture, 0);
  16587. _gl.copyTexSubImage2D(_gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height);
  16588. state.unbindTexture();
  16589. };
  16590. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level = 0) {
  16591. const width = srcTexture.image.width;
  16592. const height = srcTexture.image.height;
  16593. const glFormat = utils.convert(dstTexture.format);
  16594. const glType = utils.convert(dstTexture.type);
  16595. textures.setTexture2D(dstTexture, 0); // As another texture upload may have changed pixelStorei
  16596. // parameters, make sure they are correct for the dstTexture
  16597. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  16598. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  16599. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  16600. if (srcTexture.isDataTexture) {
  16601. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  16602. } else {
  16603. if (srcTexture.isCompressedTexture) {
  16604. _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
  16605. } else {
  16606. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image);
  16607. }
  16608. } // Generate mipmaps only when copying level 0
  16609. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(_gl.TEXTURE_2D);
  16610. state.unbindTexture();
  16611. };
  16612. this.copyTextureToTexture3D = function (sourceBox, position, srcTexture, dstTexture, level = 0) {
  16613. if (_this.isWebGL1Renderer) {
  16614. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.');
  16615. return;
  16616. }
  16617. const width = sourceBox.max.x - sourceBox.min.x + 1;
  16618. const height = sourceBox.max.y - sourceBox.min.y + 1;
  16619. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  16620. const glFormat = utils.convert(dstTexture.format);
  16621. const glType = utils.convert(dstTexture.type);
  16622. let glTarget;
  16623. if (dstTexture.isDataTexture3D) {
  16624. textures.setTexture3D(dstTexture, 0);
  16625. glTarget = _gl.TEXTURE_3D;
  16626. } else if (dstTexture.isDataTexture2DArray) {
  16627. textures.setTexture2DArray(dstTexture, 0);
  16628. glTarget = _gl.TEXTURE_2D_ARRAY;
  16629. } else {
  16630. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.');
  16631. return;
  16632. }
  16633. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  16634. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  16635. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  16636. const unpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH);
  16637. const unpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT);
  16638. const unpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS);
  16639. const unpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS);
  16640. const unpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES);
  16641. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[0] : srcTexture.image;
  16642. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width);
  16643. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, image.height);
  16644. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, sourceBox.min.x);
  16645. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, sourceBox.min.y);
  16646. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, sourceBox.min.z);
  16647. if (srcTexture.isDataTexture || srcTexture.isDataTexture3D) {
  16648. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data);
  16649. } else {
  16650. if (srcTexture.isCompressedTexture) {
  16651. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.');
  16652. _gl.compressedTexSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data);
  16653. } else {
  16654. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image);
  16655. }
  16656. }
  16657. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, unpackRowLen);
  16658. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight);
  16659. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, unpackSkipPixels);
  16660. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, unpackSkipRows);
  16661. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, unpackSkipImages); // Generate mipmaps only when copying level 0
  16662. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(glTarget);
  16663. state.unbindTexture();
  16664. };
  16665. this.initTexture = function (texture) {
  16666. textures.setTexture2D(texture, 0);
  16667. state.unbindTexture();
  16668. };
  16669. this.resetState = function () {
  16670. _currentActiveCubeFace = 0;
  16671. _currentActiveMipmapLevel = 0;
  16672. _currentRenderTarget = null;
  16673. state.reset();
  16674. bindingStates.reset();
  16675. };
  16676. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  16677. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  16678. detail: this
  16679. }));
  16680. }
  16681. }
  16682. WebGLRenderer.prototype.isWebGLRenderer = true;
  16683. class WebGL1Renderer extends WebGLRenderer {}
  16684. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  16685. class FogExp2 {
  16686. constructor(color, density = 0.00025) {
  16687. this.name = '';
  16688. this.color = new Color(color);
  16689. this.density = density;
  16690. }
  16691. clone() {
  16692. return new FogExp2(this.color, this.density);
  16693. }
  16694. toJSON() {
  16695. return {
  16696. type: 'FogExp2',
  16697. color: this.color.getHex(),
  16698. density: this.density
  16699. };
  16700. }
  16701. }
  16702. FogExp2.prototype.isFogExp2 = true;
  16703. class Fog {
  16704. constructor(color, near = 1, far = 1000) {
  16705. this.name = '';
  16706. this.color = new Color(color);
  16707. this.near = near;
  16708. this.far = far;
  16709. }
  16710. clone() {
  16711. return new Fog(this.color, this.near, this.far);
  16712. }
  16713. toJSON() {
  16714. return {
  16715. type: 'Fog',
  16716. color: this.color.getHex(),
  16717. near: this.near,
  16718. far: this.far
  16719. };
  16720. }
  16721. }
  16722. Fog.prototype.isFog = true;
  16723. class Scene extends Object3D {
  16724. constructor() {
  16725. super();
  16726. this.type = 'Scene';
  16727. this.background = null;
  16728. this.environment = null;
  16729. this.fog = null;
  16730. this.overrideMaterial = null;
  16731. this.autoUpdate = true; // checked by the renderer
  16732. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  16733. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  16734. detail: this
  16735. }));
  16736. }
  16737. }
  16738. copy(source, recursive) {
  16739. super.copy(source, recursive);
  16740. if (source.background !== null) this.background = source.background.clone();
  16741. if (source.environment !== null) this.environment = source.environment.clone();
  16742. if (source.fog !== null) this.fog = source.fog.clone();
  16743. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  16744. this.autoUpdate = source.autoUpdate;
  16745. this.matrixAutoUpdate = source.matrixAutoUpdate;
  16746. return this;
  16747. }
  16748. toJSON(meta) {
  16749. const data = super.toJSON(meta);
  16750. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  16751. return data;
  16752. }
  16753. }
  16754. Scene.prototype.isScene = true;
  16755. class InterleavedBuffer {
  16756. constructor(array, stride) {
  16757. this.array = array;
  16758. this.stride = stride;
  16759. this.count = array !== undefined ? array.length / stride : 0;
  16760. this.usage = StaticDrawUsage;
  16761. this.updateRange = {
  16762. offset: 0,
  16763. count: -1
  16764. };
  16765. this.version = 0;
  16766. this.uuid = generateUUID();
  16767. }
  16768. onUploadCallback() {}
  16769. set needsUpdate(value) {
  16770. if (value === true) this.version++;
  16771. }
  16772. setUsage(value) {
  16773. this.usage = value;
  16774. return this;
  16775. }
  16776. copy(source) {
  16777. this.array = new source.array.constructor(source.array);
  16778. this.count = source.count;
  16779. this.stride = source.stride;
  16780. this.usage = source.usage;
  16781. return this;
  16782. }
  16783. copyAt(index1, attribute, index2) {
  16784. index1 *= this.stride;
  16785. index2 *= attribute.stride;
  16786. for (let i = 0, l = this.stride; i < l; i++) {
  16787. this.array[index1 + i] = attribute.array[index2 + i];
  16788. }
  16789. return this;
  16790. }
  16791. set(value, offset = 0) {
  16792. this.array.set(value, offset);
  16793. return this;
  16794. }
  16795. clone(data) {
  16796. if (data.arrayBuffers === undefined) {
  16797. data.arrayBuffers = {};
  16798. }
  16799. if (this.array.buffer._uuid === undefined) {
  16800. this.array.buffer._uuid = generateUUID();
  16801. }
  16802. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  16803. data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
  16804. }
  16805. const array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
  16806. const ib = new this.constructor(array, this.stride);
  16807. ib.setUsage(this.usage);
  16808. return ib;
  16809. }
  16810. onUpload(callback) {
  16811. this.onUploadCallback = callback;
  16812. return this;
  16813. }
  16814. toJSON(data) {
  16815. if (data.arrayBuffers === undefined) {
  16816. data.arrayBuffers = {};
  16817. } // generate UUID for array buffer if necessary
  16818. if (this.array.buffer._uuid === undefined) {
  16819. this.array.buffer._uuid = generateUUID();
  16820. }
  16821. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  16822. data.arrayBuffers[this.array.buffer._uuid] = Array.prototype.slice.call(new Uint32Array(this.array.buffer));
  16823. } //
  16824. return {
  16825. uuid: this.uuid,
  16826. buffer: this.array.buffer._uuid,
  16827. type: this.array.constructor.name,
  16828. stride: this.stride
  16829. };
  16830. }
  16831. }
  16832. InterleavedBuffer.prototype.isInterleavedBuffer = true;
  16833. const _vector$6 = /*@__PURE__*/new Vector3();
  16834. class InterleavedBufferAttribute {
  16835. constructor(interleavedBuffer, itemSize, offset, normalized = false) {
  16836. this.name = '';
  16837. this.data = interleavedBuffer;
  16838. this.itemSize = itemSize;
  16839. this.offset = offset;
  16840. this.normalized = normalized === true;
  16841. }
  16842. get count() {
  16843. return this.data.count;
  16844. }
  16845. get array() {
  16846. return this.data.array;
  16847. }
  16848. set needsUpdate(value) {
  16849. this.data.needsUpdate = value;
  16850. }
  16851. applyMatrix4(m) {
  16852. for (let i = 0, l = this.data.count; i < l; i++) {
  16853. _vector$6.x = this.getX(i);
  16854. _vector$6.y = this.getY(i);
  16855. _vector$6.z = this.getZ(i);
  16856. _vector$6.applyMatrix4(m);
  16857. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  16858. }
  16859. return this;
  16860. }
  16861. applyNormalMatrix(m) {
  16862. for (let i = 0, l = this.count; i < l; i++) {
  16863. _vector$6.x = this.getX(i);
  16864. _vector$6.y = this.getY(i);
  16865. _vector$6.z = this.getZ(i);
  16866. _vector$6.applyNormalMatrix(m);
  16867. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  16868. }
  16869. return this;
  16870. }
  16871. transformDirection(m) {
  16872. for (let i = 0, l = this.count; i < l; i++) {
  16873. _vector$6.x = this.getX(i);
  16874. _vector$6.y = this.getY(i);
  16875. _vector$6.z = this.getZ(i);
  16876. _vector$6.transformDirection(m);
  16877. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  16878. }
  16879. return this;
  16880. }
  16881. setX(index, x) {
  16882. this.data.array[index * this.data.stride + this.offset] = x;
  16883. return this;
  16884. }
  16885. setY(index, y) {
  16886. this.data.array[index * this.data.stride + this.offset + 1] = y;
  16887. return this;
  16888. }
  16889. setZ(index, z) {
  16890. this.data.array[index * this.data.stride + this.offset + 2] = z;
  16891. return this;
  16892. }
  16893. setW(index, w) {
  16894. this.data.array[index * this.data.stride + this.offset + 3] = w;
  16895. return this;
  16896. }
  16897. getX(index) {
  16898. return this.data.array[index * this.data.stride + this.offset];
  16899. }
  16900. getY(index) {
  16901. return this.data.array[index * this.data.stride + this.offset + 1];
  16902. }
  16903. getZ(index) {
  16904. return this.data.array[index * this.data.stride + this.offset + 2];
  16905. }
  16906. getW(index) {
  16907. return this.data.array[index * this.data.stride + this.offset + 3];
  16908. }
  16909. setXY(index, x, y) {
  16910. index = index * this.data.stride + this.offset;
  16911. this.data.array[index + 0] = x;
  16912. this.data.array[index + 1] = y;
  16913. return this;
  16914. }
  16915. setXYZ(index, x, y, z) {
  16916. index = index * this.data.stride + this.offset;
  16917. this.data.array[index + 0] = x;
  16918. this.data.array[index + 1] = y;
  16919. this.data.array[index + 2] = z;
  16920. return this;
  16921. }
  16922. setXYZW(index, x, y, z, w) {
  16923. index = index * this.data.stride + this.offset;
  16924. this.data.array[index + 0] = x;
  16925. this.data.array[index + 1] = y;
  16926. this.data.array[index + 2] = z;
  16927. this.data.array[index + 3] = w;
  16928. return this;
  16929. }
  16930. clone(data) {
  16931. if (data === undefined) {
  16932. console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.');
  16933. const array = [];
  16934. for (let i = 0; i < this.count; i++) {
  16935. const index = i * this.data.stride + this.offset;
  16936. for (let j = 0; j < this.itemSize; j++) {
  16937. array.push(this.data.array[index + j]);
  16938. }
  16939. }
  16940. return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
  16941. } else {
  16942. if (data.interleavedBuffers === undefined) {
  16943. data.interleavedBuffers = {};
  16944. }
  16945. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  16946. data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
  16947. }
  16948. return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  16949. }
  16950. }
  16951. toJSON(data) {
  16952. if (data === undefined) {
  16953. console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.');
  16954. const array = [];
  16955. for (let i = 0; i < this.count; i++) {
  16956. const index = i * this.data.stride + this.offset;
  16957. for (let j = 0; j < this.itemSize; j++) {
  16958. array.push(this.data.array[index + j]);
  16959. }
  16960. } // deinterleave data and save it as an ordinary buffer attribute for now
  16961. return {
  16962. itemSize: this.itemSize,
  16963. type: this.array.constructor.name,
  16964. array: array,
  16965. normalized: this.normalized
  16966. };
  16967. } else {
  16968. // save as true interlaved attribtue
  16969. if (data.interleavedBuffers === undefined) {
  16970. data.interleavedBuffers = {};
  16971. }
  16972. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  16973. data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
  16974. }
  16975. return {
  16976. isInterleavedBufferAttribute: true,
  16977. itemSize: this.itemSize,
  16978. data: this.data.uuid,
  16979. offset: this.offset,
  16980. normalized: this.normalized
  16981. };
  16982. }
  16983. }
  16984. }
  16985. InterleavedBufferAttribute.prototype.isInterleavedBufferAttribute = true;
  16986. /**
  16987. * parameters = {
  16988. * color: <hex>,
  16989. * map: new THREE.Texture( <Image> ),
  16990. * alphaMap: new THREE.Texture( <Image> ),
  16991. * rotation: <float>,
  16992. * sizeAttenuation: <bool>
  16993. * }
  16994. */
  16995. class SpriteMaterial extends Material {
  16996. constructor(parameters) {
  16997. super();
  16998. this.type = 'SpriteMaterial';
  16999. this.color = new Color(0xffffff);
  17000. this.map = null;
  17001. this.alphaMap = null;
  17002. this.rotation = 0;
  17003. this.sizeAttenuation = true;
  17004. this.transparent = true;
  17005. this.setValues(parameters);
  17006. }
  17007. copy(source) {
  17008. super.copy(source);
  17009. this.color.copy(source.color);
  17010. this.map = source.map;
  17011. this.alphaMap = source.alphaMap;
  17012. this.rotation = source.rotation;
  17013. this.sizeAttenuation = source.sizeAttenuation;
  17014. return this;
  17015. }
  17016. }
  17017. SpriteMaterial.prototype.isSpriteMaterial = true;
  17018. let _geometry;
  17019. const _intersectPoint = /*@__PURE__*/new Vector3();
  17020. const _worldScale = /*@__PURE__*/new Vector3();
  17021. const _mvPosition = /*@__PURE__*/new Vector3();
  17022. const _alignedPosition = /*@__PURE__*/new Vector2();
  17023. const _rotatedPosition = /*@__PURE__*/new Vector2();
  17024. const _viewWorldMatrix = /*@__PURE__*/new Matrix4();
  17025. const _vA = /*@__PURE__*/new Vector3();
  17026. const _vB = /*@__PURE__*/new Vector3();
  17027. const _vC = /*@__PURE__*/new Vector3();
  17028. const _uvA = /*@__PURE__*/new Vector2();
  17029. const _uvB = /*@__PURE__*/new Vector2();
  17030. const _uvC = /*@__PURE__*/new Vector2();
  17031. class Sprite extends Object3D {
  17032. constructor(material) {
  17033. super();
  17034. this.type = 'Sprite';
  17035. if (_geometry === undefined) {
  17036. _geometry = new BufferGeometry();
  17037. const float32Array = new Float32Array([-0.5, -0.5, 0, 0, 0, 0.5, -0.5, 0, 1, 0, 0.5, 0.5, 0, 1, 1, -0.5, 0.5, 0, 0, 1]);
  17038. const interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  17039. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  17040. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  17041. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  17042. }
  17043. this.geometry = _geometry;
  17044. this.material = material !== undefined ? material : new SpriteMaterial();
  17045. this.center = new Vector2(0.5, 0.5);
  17046. }
  17047. raycast(raycaster, intersects) {
  17048. if (raycaster.camera === null) {
  17049. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  17050. }
  17051. _worldScale.setFromMatrixScale(this.matrixWorld);
  17052. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  17053. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  17054. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  17055. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  17056. _worldScale.multiplyScalar(-_mvPosition.z);
  17057. }
  17058. const rotation = this.material.rotation;
  17059. let sin, cos;
  17060. if (rotation !== 0) {
  17061. cos = Math.cos(rotation);
  17062. sin = Math.sin(rotation);
  17063. }
  17064. const center = this.center;
  17065. transformVertex(_vA.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17066. transformVertex(_vB.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17067. transformVertex(_vC.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17068. _uvA.set(0, 0);
  17069. _uvB.set(1, 0);
  17070. _uvC.set(1, 1); // check first triangle
  17071. let intersect = raycaster.ray.intersectTriangle(_vA, _vB, _vC, false, _intersectPoint);
  17072. if (intersect === null) {
  17073. // check second triangle
  17074. transformVertex(_vB.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17075. _uvB.set(0, 1);
  17076. intersect = raycaster.ray.intersectTriangle(_vA, _vC, _vB, false, _intersectPoint);
  17077. if (intersect === null) {
  17078. return;
  17079. }
  17080. }
  17081. const distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  17082. if (distance < raycaster.near || distance > raycaster.far) return;
  17083. intersects.push({
  17084. distance: distance,
  17085. point: _intersectPoint.clone(),
  17086. uv: Triangle.getUV(_intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2()),
  17087. face: null,
  17088. object: this
  17089. });
  17090. }
  17091. copy(source) {
  17092. super.copy(source);
  17093. if (source.center !== undefined) this.center.copy(source.center);
  17094. this.material = source.material;
  17095. return this;
  17096. }
  17097. }
  17098. Sprite.prototype.isSprite = true;
  17099. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  17100. // compute position in camera space
  17101. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  17102. if (sin !== undefined) {
  17103. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  17104. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  17105. } else {
  17106. _rotatedPosition.copy(_alignedPosition);
  17107. }
  17108. vertexPosition.copy(mvPosition);
  17109. vertexPosition.x += _rotatedPosition.x;
  17110. vertexPosition.y += _rotatedPosition.y; // transform to world space
  17111. vertexPosition.applyMatrix4(_viewWorldMatrix);
  17112. }
  17113. const _v1$2 = /*@__PURE__*/new Vector3();
  17114. const _v2$1 = /*@__PURE__*/new Vector3();
  17115. class LOD extends Object3D {
  17116. constructor() {
  17117. super();
  17118. this._currentLevel = 0;
  17119. this.type = 'LOD';
  17120. Object.defineProperties(this, {
  17121. levels: {
  17122. enumerable: true,
  17123. value: []
  17124. },
  17125. isLOD: {
  17126. value: true
  17127. }
  17128. });
  17129. this.autoUpdate = true;
  17130. }
  17131. copy(source) {
  17132. super.copy(source, false);
  17133. const levels = source.levels;
  17134. for (let i = 0, l = levels.length; i < l; i++) {
  17135. const level = levels[i];
  17136. this.addLevel(level.object.clone(), level.distance);
  17137. }
  17138. this.autoUpdate = source.autoUpdate;
  17139. return this;
  17140. }
  17141. addLevel(object, distance = 0) {
  17142. distance = Math.abs(distance);
  17143. const levels = this.levels;
  17144. let l;
  17145. for (l = 0; l < levels.length; l++) {
  17146. if (distance < levels[l].distance) {
  17147. break;
  17148. }
  17149. }
  17150. levels.splice(l, 0, {
  17151. distance: distance,
  17152. object: object
  17153. });
  17154. this.add(object);
  17155. return this;
  17156. }
  17157. getCurrentLevel() {
  17158. return this._currentLevel;
  17159. }
  17160. getObjectForDistance(distance) {
  17161. const levels = this.levels;
  17162. if (levels.length > 0) {
  17163. let i, l;
  17164. for (i = 1, l = levels.length; i < l; i++) {
  17165. if (distance < levels[i].distance) {
  17166. break;
  17167. }
  17168. }
  17169. return levels[i - 1].object;
  17170. }
  17171. return null;
  17172. }
  17173. raycast(raycaster, intersects) {
  17174. const levels = this.levels;
  17175. if (levels.length > 0) {
  17176. _v1$2.setFromMatrixPosition(this.matrixWorld);
  17177. const distance = raycaster.ray.origin.distanceTo(_v1$2);
  17178. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  17179. }
  17180. }
  17181. update(camera) {
  17182. const levels = this.levels;
  17183. if (levels.length > 1) {
  17184. _v1$2.setFromMatrixPosition(camera.matrixWorld);
  17185. _v2$1.setFromMatrixPosition(this.matrixWorld);
  17186. const distance = _v1$2.distanceTo(_v2$1) / camera.zoom;
  17187. levels[0].object.visible = true;
  17188. let i, l;
  17189. for (i = 1, l = levels.length; i < l; i++) {
  17190. if (distance >= levels[i].distance) {
  17191. levels[i - 1].object.visible = false;
  17192. levels[i].object.visible = true;
  17193. } else {
  17194. break;
  17195. }
  17196. }
  17197. this._currentLevel = i - 1;
  17198. for (; i < l; i++) {
  17199. levels[i].object.visible = false;
  17200. }
  17201. }
  17202. }
  17203. toJSON(meta) {
  17204. const data = super.toJSON(meta);
  17205. if (this.autoUpdate === false) data.object.autoUpdate = false;
  17206. data.object.levels = [];
  17207. const levels = this.levels;
  17208. for (let i = 0, l = levels.length; i < l; i++) {
  17209. const level = levels[i];
  17210. data.object.levels.push({
  17211. object: level.object.uuid,
  17212. distance: level.distance
  17213. });
  17214. }
  17215. return data;
  17216. }
  17217. }
  17218. const _basePosition = /*@__PURE__*/new Vector3();
  17219. const _skinIndex = /*@__PURE__*/new Vector4();
  17220. const _skinWeight = /*@__PURE__*/new Vector4();
  17221. const _vector$5 = /*@__PURE__*/new Vector3();
  17222. const _matrix = /*@__PURE__*/new Matrix4();
  17223. class SkinnedMesh extends Mesh {
  17224. constructor(geometry, material) {
  17225. super(geometry, material);
  17226. this.type = 'SkinnedMesh';
  17227. this.bindMode = 'attached';
  17228. this.bindMatrix = new Matrix4();
  17229. this.bindMatrixInverse = new Matrix4();
  17230. }
  17231. copy(source) {
  17232. super.copy(source);
  17233. this.bindMode = source.bindMode;
  17234. this.bindMatrix.copy(source.bindMatrix);
  17235. this.bindMatrixInverse.copy(source.bindMatrixInverse);
  17236. this.skeleton = source.skeleton;
  17237. return this;
  17238. }
  17239. bind(skeleton, bindMatrix) {
  17240. this.skeleton = skeleton;
  17241. if (bindMatrix === undefined) {
  17242. this.updateMatrixWorld(true);
  17243. this.skeleton.calculateInverses();
  17244. bindMatrix = this.matrixWorld;
  17245. }
  17246. this.bindMatrix.copy(bindMatrix);
  17247. this.bindMatrixInverse.copy(bindMatrix).invert();
  17248. }
  17249. pose() {
  17250. this.skeleton.pose();
  17251. }
  17252. normalizeSkinWeights() {
  17253. const vector = new Vector4();
  17254. const skinWeight = this.geometry.attributes.skinWeight;
  17255. for (let i = 0, l = skinWeight.count; i < l; i++) {
  17256. vector.x = skinWeight.getX(i);
  17257. vector.y = skinWeight.getY(i);
  17258. vector.z = skinWeight.getZ(i);
  17259. vector.w = skinWeight.getW(i);
  17260. const scale = 1.0 / vector.manhattanLength();
  17261. if (scale !== Infinity) {
  17262. vector.multiplyScalar(scale);
  17263. } else {
  17264. vector.set(1, 0, 0, 0); // do something reasonable
  17265. }
  17266. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  17267. }
  17268. }
  17269. updateMatrixWorld(force) {
  17270. super.updateMatrixWorld(force);
  17271. if (this.bindMode === 'attached') {
  17272. this.bindMatrixInverse.copy(this.matrixWorld).invert();
  17273. } else if (this.bindMode === 'detached') {
  17274. this.bindMatrixInverse.copy(this.bindMatrix).invert();
  17275. } else {
  17276. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  17277. }
  17278. }
  17279. boneTransform(index, target) {
  17280. const skeleton = this.skeleton;
  17281. const geometry = this.geometry;
  17282. _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
  17283. _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
  17284. _basePosition.copy(target).applyMatrix4(this.bindMatrix);
  17285. target.set(0, 0, 0);
  17286. for (let i = 0; i < 4; i++) {
  17287. const weight = _skinWeight.getComponent(i);
  17288. if (weight !== 0) {
  17289. const boneIndex = _skinIndex.getComponent(i);
  17290. _matrix.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
  17291. target.addScaledVector(_vector$5.copy(_basePosition).applyMatrix4(_matrix), weight);
  17292. }
  17293. }
  17294. return target.applyMatrix4(this.bindMatrixInverse);
  17295. }
  17296. }
  17297. SkinnedMesh.prototype.isSkinnedMesh = true;
  17298. class Bone extends Object3D {
  17299. constructor() {
  17300. super();
  17301. this.type = 'Bone';
  17302. }
  17303. }
  17304. Bone.prototype.isBone = true;
  17305. class DataTexture extends Texture {
  17306. constructor(data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding) {
  17307. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  17308. this.image = {
  17309. data: data,
  17310. width: width,
  17311. height: height
  17312. };
  17313. this.magFilter = magFilter;
  17314. this.minFilter = minFilter;
  17315. this.generateMipmaps = false;
  17316. this.flipY = false;
  17317. this.unpackAlignment = 1;
  17318. }
  17319. }
  17320. DataTexture.prototype.isDataTexture = true;
  17321. const _offsetMatrix = /*@__PURE__*/new Matrix4();
  17322. const _identityMatrix = /*@__PURE__*/new Matrix4();
  17323. class Skeleton {
  17324. constructor(bones = [], boneInverses = []) {
  17325. this.uuid = generateUUID();
  17326. this.bones = bones.slice(0);
  17327. this.boneInverses = boneInverses;
  17328. this.boneMatrices = null;
  17329. this.boneTexture = null;
  17330. this.boneTextureSize = 0;
  17331. this.frame = -1;
  17332. this.init();
  17333. }
  17334. init() {
  17335. const bones = this.bones;
  17336. const boneInverses = this.boneInverses;
  17337. this.boneMatrices = new Float32Array(bones.length * 16); // calculate inverse bone matrices if necessary
  17338. if (boneInverses.length === 0) {
  17339. this.calculateInverses();
  17340. } else {
  17341. // handle special case
  17342. if (bones.length !== boneInverses.length) {
  17343. console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
  17344. this.boneInverses = [];
  17345. for (let i = 0, il = this.bones.length; i < il; i++) {
  17346. this.boneInverses.push(new Matrix4());
  17347. }
  17348. }
  17349. }
  17350. }
  17351. calculateInverses() {
  17352. this.boneInverses.length = 0;
  17353. for (let i = 0, il = this.bones.length; i < il; i++) {
  17354. const inverse = new Matrix4();
  17355. if (this.bones[i]) {
  17356. inverse.copy(this.bones[i].matrixWorld).invert();
  17357. }
  17358. this.boneInverses.push(inverse);
  17359. }
  17360. }
  17361. pose() {
  17362. // recover the bind-time world matrices
  17363. for (let i = 0, il = this.bones.length; i < il; i++) {
  17364. const bone = this.bones[i];
  17365. if (bone) {
  17366. bone.matrixWorld.copy(this.boneInverses[i]).invert();
  17367. }
  17368. } // compute the local matrices, positions, rotations and scales
  17369. for (let i = 0, il = this.bones.length; i < il; i++) {
  17370. const bone = this.bones[i];
  17371. if (bone) {
  17372. if (bone.parent && bone.parent.isBone) {
  17373. bone.matrix.copy(bone.parent.matrixWorld).invert();
  17374. bone.matrix.multiply(bone.matrixWorld);
  17375. } else {
  17376. bone.matrix.copy(bone.matrixWorld);
  17377. }
  17378. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  17379. }
  17380. }
  17381. }
  17382. update() {
  17383. const bones = this.bones;
  17384. const boneInverses = this.boneInverses;
  17385. const boneMatrices = this.boneMatrices;
  17386. const boneTexture = this.boneTexture; // flatten bone matrices to array
  17387. for (let i = 0, il = bones.length; i < il; i++) {
  17388. // compute the offset between the current and the original transform
  17389. const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  17390. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  17391. _offsetMatrix.toArray(boneMatrices, i * 16);
  17392. }
  17393. if (boneTexture !== null) {
  17394. boneTexture.needsUpdate = true;
  17395. }
  17396. }
  17397. clone() {
  17398. return new Skeleton(this.bones, this.boneInverses);
  17399. }
  17400. computeBoneTexture() {
  17401. // layout (1 matrix = 4 pixels)
  17402. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  17403. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  17404. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  17405. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  17406. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  17407. let size = Math.sqrt(this.bones.length * 4); // 4 pixels needed for 1 matrix
  17408. size = ceilPowerOfTwo(size);
  17409. size = Math.max(size, 4);
  17410. const boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  17411. boneMatrices.set(this.boneMatrices); // copy current values
  17412. const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  17413. boneTexture.needsUpdate = true;
  17414. this.boneMatrices = boneMatrices;
  17415. this.boneTexture = boneTexture;
  17416. this.boneTextureSize = size;
  17417. return this;
  17418. }
  17419. getBoneByName(name) {
  17420. for (let i = 0, il = this.bones.length; i < il; i++) {
  17421. const bone = this.bones[i];
  17422. if (bone.name === name) {
  17423. return bone;
  17424. }
  17425. }
  17426. return undefined;
  17427. }
  17428. dispose() {
  17429. if (this.boneTexture !== null) {
  17430. this.boneTexture.dispose();
  17431. this.boneTexture = null;
  17432. }
  17433. }
  17434. fromJSON(json, bones) {
  17435. this.uuid = json.uuid;
  17436. for (let i = 0, l = json.bones.length; i < l; i++) {
  17437. const uuid = json.bones[i];
  17438. let bone = bones[uuid];
  17439. if (bone === undefined) {
  17440. console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
  17441. bone = new Bone();
  17442. }
  17443. this.bones.push(bone);
  17444. this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
  17445. }
  17446. this.init();
  17447. return this;
  17448. }
  17449. toJSON() {
  17450. const data = {
  17451. metadata: {
  17452. version: 4.5,
  17453. type: 'Skeleton',
  17454. generator: 'Skeleton.toJSON'
  17455. },
  17456. bones: [],
  17457. boneInverses: []
  17458. };
  17459. data.uuid = this.uuid;
  17460. const bones = this.bones;
  17461. const boneInverses = this.boneInverses;
  17462. for (let i = 0, l = bones.length; i < l; i++) {
  17463. const bone = bones[i];
  17464. data.bones.push(bone.uuid);
  17465. const boneInverse = boneInverses[i];
  17466. data.boneInverses.push(boneInverse.toArray());
  17467. }
  17468. return data;
  17469. }
  17470. }
  17471. class InstancedBufferAttribute extends BufferAttribute {
  17472. constructor(array, itemSize, normalized, meshPerAttribute = 1) {
  17473. if (typeof normalized === 'number') {
  17474. meshPerAttribute = normalized;
  17475. normalized = false;
  17476. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  17477. }
  17478. super(array, itemSize, normalized);
  17479. this.meshPerAttribute = meshPerAttribute;
  17480. }
  17481. copy(source) {
  17482. super.copy(source);
  17483. this.meshPerAttribute = source.meshPerAttribute;
  17484. return this;
  17485. }
  17486. toJSON() {
  17487. const data = super.toJSON();
  17488. data.meshPerAttribute = this.meshPerAttribute;
  17489. data.isInstancedBufferAttribute = true;
  17490. return data;
  17491. }
  17492. }
  17493. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  17494. const _instanceLocalMatrix = /*@__PURE__*/new Matrix4();
  17495. const _instanceWorldMatrix = /*@__PURE__*/new Matrix4();
  17496. const _instanceIntersects = [];
  17497. const _mesh = /*@__PURE__*/new Mesh();
  17498. class InstancedMesh extends Mesh {
  17499. constructor(geometry, material, count) {
  17500. super(geometry, material);
  17501. this.instanceMatrix = new InstancedBufferAttribute(new Float32Array(count * 16), 16);
  17502. this.instanceColor = null;
  17503. this.count = count;
  17504. this.frustumCulled = false;
  17505. }
  17506. copy(source) {
  17507. super.copy(source);
  17508. this.instanceMatrix.copy(source.instanceMatrix);
  17509. if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone();
  17510. this.count = source.count;
  17511. return this;
  17512. }
  17513. getColorAt(index, color) {
  17514. color.fromArray(this.instanceColor.array, index * 3);
  17515. }
  17516. getMatrixAt(index, matrix) {
  17517. matrix.fromArray(this.instanceMatrix.array, index * 16);
  17518. }
  17519. raycast(raycaster, intersects) {
  17520. const matrixWorld = this.matrixWorld;
  17521. const raycastTimes = this.count;
  17522. _mesh.geometry = this.geometry;
  17523. _mesh.material = this.material;
  17524. if (_mesh.material === undefined) return;
  17525. for (let instanceId = 0; instanceId < raycastTimes; instanceId++) {
  17526. // calculate the world matrix for each instance
  17527. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  17528. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
  17529. _mesh.matrixWorld = _instanceWorldMatrix;
  17530. _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
  17531. for (let i = 0, l = _instanceIntersects.length; i < l; i++) {
  17532. const intersect = _instanceIntersects[i];
  17533. intersect.instanceId = instanceId;
  17534. intersect.object = this;
  17535. intersects.push(intersect);
  17536. }
  17537. _instanceIntersects.length = 0;
  17538. }
  17539. }
  17540. setColorAt(index, color) {
  17541. if (this.instanceColor === null) {
  17542. this.instanceColor = new InstancedBufferAttribute(new Float32Array(this.instanceMatrix.count * 3), 3);
  17543. }
  17544. color.toArray(this.instanceColor.array, index * 3);
  17545. }
  17546. setMatrixAt(index, matrix) {
  17547. matrix.toArray(this.instanceMatrix.array, index * 16);
  17548. }
  17549. updateMorphTargets() {}
  17550. dispose() {
  17551. this.dispatchEvent({
  17552. type: 'dispose'
  17553. });
  17554. }
  17555. }
  17556. InstancedMesh.prototype.isInstancedMesh = true;
  17557. /**
  17558. * parameters = {
  17559. * color: <hex>,
  17560. * opacity: <float>,
  17561. *
  17562. * linewidth: <float>,
  17563. * linecap: "round",
  17564. * linejoin: "round"
  17565. * }
  17566. */
  17567. class LineBasicMaterial extends Material {
  17568. constructor(parameters) {
  17569. super();
  17570. this.type = 'LineBasicMaterial';
  17571. this.color = new Color(0xffffff);
  17572. this.linewidth = 1;
  17573. this.linecap = 'round';
  17574. this.linejoin = 'round';
  17575. this.setValues(parameters);
  17576. }
  17577. copy(source) {
  17578. super.copy(source);
  17579. this.color.copy(source.color);
  17580. this.linewidth = source.linewidth;
  17581. this.linecap = source.linecap;
  17582. this.linejoin = source.linejoin;
  17583. return this;
  17584. }
  17585. }
  17586. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  17587. const _start$1 = /*@__PURE__*/new Vector3();
  17588. const _end$1 = /*@__PURE__*/new Vector3();
  17589. const _inverseMatrix$1 = /*@__PURE__*/new Matrix4();
  17590. const _ray$1 = /*@__PURE__*/new Ray();
  17591. const _sphere$1 = /*@__PURE__*/new Sphere();
  17592. class Line extends Object3D {
  17593. constructor(geometry = new BufferGeometry(), material = new LineBasicMaterial()) {
  17594. super();
  17595. this.type = 'Line';
  17596. this.geometry = geometry;
  17597. this.material = material;
  17598. this.updateMorphTargets();
  17599. }
  17600. copy(source) {
  17601. super.copy(source);
  17602. this.material = source.material;
  17603. this.geometry = source.geometry;
  17604. return this;
  17605. }
  17606. computeLineDistances() {
  17607. const geometry = this.geometry;
  17608. if (geometry.isBufferGeometry) {
  17609. // we assume non-indexed geometry
  17610. if (geometry.index === null) {
  17611. const positionAttribute = geometry.attributes.position;
  17612. const lineDistances = [0];
  17613. for (let i = 1, l = positionAttribute.count; i < l; i++) {
  17614. _start$1.fromBufferAttribute(positionAttribute, i - 1);
  17615. _end$1.fromBufferAttribute(positionAttribute, i);
  17616. lineDistances[i] = lineDistances[i - 1];
  17617. lineDistances[i] += _start$1.distanceTo(_end$1);
  17618. }
  17619. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  17620. } else {
  17621. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  17622. }
  17623. } else if (geometry.isGeometry) {
  17624. console.error('THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17625. }
  17626. return this;
  17627. }
  17628. raycast(raycaster, intersects) {
  17629. const geometry = this.geometry;
  17630. const matrixWorld = this.matrixWorld;
  17631. const threshold = raycaster.params.Line.threshold;
  17632. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  17633. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  17634. _sphere$1.copy(geometry.boundingSphere);
  17635. _sphere$1.applyMatrix4(matrixWorld);
  17636. _sphere$1.radius += threshold;
  17637. if (raycaster.ray.intersectsSphere(_sphere$1) === false) return; //
  17638. _inverseMatrix$1.copy(matrixWorld).invert();
  17639. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  17640. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  17641. const localThresholdSq = localThreshold * localThreshold;
  17642. const vStart = new Vector3();
  17643. const vEnd = new Vector3();
  17644. const interSegment = new Vector3();
  17645. const interRay = new Vector3();
  17646. const step = this.isLineSegments ? 2 : 1;
  17647. if (geometry.isBufferGeometry) {
  17648. const index = geometry.index;
  17649. const attributes = geometry.attributes;
  17650. const positionAttribute = attributes.position;
  17651. if (index !== null) {
  17652. const start = Math.max(0, drawRange.start);
  17653. const end = Math.min(index.count, drawRange.start + drawRange.count);
  17654. for (let i = start, l = end - 1; i < l; i += step) {
  17655. const a = index.getX(i);
  17656. const b = index.getX(i + 1);
  17657. vStart.fromBufferAttribute(positionAttribute, a);
  17658. vEnd.fromBufferAttribute(positionAttribute, b);
  17659. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  17660. if (distSq > localThresholdSq) continue;
  17661. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17662. const distance = raycaster.ray.origin.distanceTo(interRay);
  17663. if (distance < raycaster.near || distance > raycaster.far) continue;
  17664. intersects.push({
  17665. distance: distance,
  17666. // What do we want? intersection point on the ray or on the segment??
  17667. // point: raycaster.ray.at( distance ),
  17668. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17669. index: i,
  17670. face: null,
  17671. faceIndex: null,
  17672. object: this
  17673. });
  17674. }
  17675. } else {
  17676. const start = Math.max(0, drawRange.start);
  17677. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  17678. for (let i = start, l = end - 1; i < l; i += step) {
  17679. vStart.fromBufferAttribute(positionAttribute, i);
  17680. vEnd.fromBufferAttribute(positionAttribute, i + 1);
  17681. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  17682. if (distSq > localThresholdSq) continue;
  17683. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17684. const distance = raycaster.ray.origin.distanceTo(interRay);
  17685. if (distance < raycaster.near || distance > raycaster.far) continue;
  17686. intersects.push({
  17687. distance: distance,
  17688. // What do we want? intersection point on the ray or on the segment??
  17689. // point: raycaster.ray.at( distance ),
  17690. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17691. index: i,
  17692. face: null,
  17693. faceIndex: null,
  17694. object: this
  17695. });
  17696. }
  17697. }
  17698. } else if (geometry.isGeometry) {
  17699. console.error('THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17700. }
  17701. }
  17702. updateMorphTargets() {
  17703. const geometry = this.geometry;
  17704. if (geometry.isBufferGeometry) {
  17705. const morphAttributes = geometry.morphAttributes;
  17706. const keys = Object.keys(morphAttributes);
  17707. if (keys.length > 0) {
  17708. const morphAttribute = morphAttributes[keys[0]];
  17709. if (morphAttribute !== undefined) {
  17710. this.morphTargetInfluences = [];
  17711. this.morphTargetDictionary = {};
  17712. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  17713. const name = morphAttribute[m].name || String(m);
  17714. this.morphTargetInfluences.push(0);
  17715. this.morphTargetDictionary[name] = m;
  17716. }
  17717. }
  17718. }
  17719. } else {
  17720. const morphTargets = geometry.morphTargets;
  17721. if (morphTargets !== undefined && morphTargets.length > 0) {
  17722. console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  17723. }
  17724. }
  17725. }
  17726. }
  17727. Line.prototype.isLine = true;
  17728. const _start = /*@__PURE__*/new Vector3();
  17729. const _end = /*@__PURE__*/new Vector3();
  17730. class LineSegments extends Line {
  17731. constructor(geometry, material) {
  17732. super(geometry, material);
  17733. this.type = 'LineSegments';
  17734. }
  17735. computeLineDistances() {
  17736. const geometry = this.geometry;
  17737. if (geometry.isBufferGeometry) {
  17738. // we assume non-indexed geometry
  17739. if (geometry.index === null) {
  17740. const positionAttribute = geometry.attributes.position;
  17741. const lineDistances = [];
  17742. for (let i = 0, l = positionAttribute.count; i < l; i += 2) {
  17743. _start.fromBufferAttribute(positionAttribute, i);
  17744. _end.fromBufferAttribute(positionAttribute, i + 1);
  17745. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  17746. lineDistances[i + 1] = lineDistances[i] + _start.distanceTo(_end);
  17747. }
  17748. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  17749. } else {
  17750. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  17751. }
  17752. } else if (geometry.isGeometry) {
  17753. console.error('THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17754. }
  17755. return this;
  17756. }
  17757. }
  17758. LineSegments.prototype.isLineSegments = true;
  17759. class LineLoop extends Line {
  17760. constructor(geometry, material) {
  17761. super(geometry, material);
  17762. this.type = 'LineLoop';
  17763. }
  17764. }
  17765. LineLoop.prototype.isLineLoop = true;
  17766. /**
  17767. * parameters = {
  17768. * color: <hex>,
  17769. * opacity: <float>,
  17770. * map: new THREE.Texture( <Image> ),
  17771. * alphaMap: new THREE.Texture( <Image> ),
  17772. *
  17773. * size: <float>,
  17774. * sizeAttenuation: <bool>
  17775. *
  17776. * }
  17777. */
  17778. class PointsMaterial extends Material {
  17779. constructor(parameters) {
  17780. super();
  17781. this.type = 'PointsMaterial';
  17782. this.color = new Color(0xffffff);
  17783. this.map = null;
  17784. this.alphaMap = null;
  17785. this.size = 1;
  17786. this.sizeAttenuation = true;
  17787. this.setValues(parameters);
  17788. }
  17789. copy(source) {
  17790. super.copy(source);
  17791. this.color.copy(source.color);
  17792. this.map = source.map;
  17793. this.alphaMap = source.alphaMap;
  17794. this.size = source.size;
  17795. this.sizeAttenuation = source.sizeAttenuation;
  17796. return this;
  17797. }
  17798. }
  17799. PointsMaterial.prototype.isPointsMaterial = true;
  17800. const _inverseMatrix = /*@__PURE__*/new Matrix4();
  17801. const _ray = /*@__PURE__*/new Ray();
  17802. const _sphere = /*@__PURE__*/new Sphere();
  17803. const _position$2 = /*@__PURE__*/new Vector3();
  17804. class Points extends Object3D {
  17805. constructor(geometry = new BufferGeometry(), material = new PointsMaterial()) {
  17806. super();
  17807. this.type = 'Points';
  17808. this.geometry = geometry;
  17809. this.material = material;
  17810. this.updateMorphTargets();
  17811. }
  17812. copy(source) {
  17813. super.copy(source);
  17814. this.material = source.material;
  17815. this.geometry = source.geometry;
  17816. return this;
  17817. }
  17818. raycast(raycaster, intersects) {
  17819. const geometry = this.geometry;
  17820. const matrixWorld = this.matrixWorld;
  17821. const threshold = raycaster.params.Points.threshold;
  17822. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  17823. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  17824. _sphere.copy(geometry.boundingSphere);
  17825. _sphere.applyMatrix4(matrixWorld);
  17826. _sphere.radius += threshold;
  17827. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  17828. _inverseMatrix.copy(matrixWorld).invert();
  17829. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix);
  17830. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  17831. const localThresholdSq = localThreshold * localThreshold;
  17832. if (geometry.isBufferGeometry) {
  17833. const index = geometry.index;
  17834. const attributes = geometry.attributes;
  17835. const positionAttribute = attributes.position;
  17836. if (index !== null) {
  17837. const start = Math.max(0, drawRange.start);
  17838. const end = Math.min(index.count, drawRange.start + drawRange.count);
  17839. for (let i = start, il = end; i < il; i++) {
  17840. const a = index.getX(i);
  17841. _position$2.fromBufferAttribute(positionAttribute, a);
  17842. testPoint(_position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17843. }
  17844. } else {
  17845. const start = Math.max(0, drawRange.start);
  17846. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  17847. for (let i = start, l = end; i < l; i++) {
  17848. _position$2.fromBufferAttribute(positionAttribute, i);
  17849. testPoint(_position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17850. }
  17851. }
  17852. } else {
  17853. console.error('THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17854. }
  17855. }
  17856. updateMorphTargets() {
  17857. const geometry = this.geometry;
  17858. if (geometry.isBufferGeometry) {
  17859. const morphAttributes = geometry.morphAttributes;
  17860. const keys = Object.keys(morphAttributes);
  17861. if (keys.length > 0) {
  17862. const morphAttribute = morphAttributes[keys[0]];
  17863. if (morphAttribute !== undefined) {
  17864. this.morphTargetInfluences = [];
  17865. this.morphTargetDictionary = {};
  17866. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  17867. const name = morphAttribute[m].name || String(m);
  17868. this.morphTargetInfluences.push(0);
  17869. this.morphTargetDictionary[name] = m;
  17870. }
  17871. }
  17872. }
  17873. } else {
  17874. const morphTargets = geometry.morphTargets;
  17875. if (morphTargets !== undefined && morphTargets.length > 0) {
  17876. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  17877. }
  17878. }
  17879. }
  17880. }
  17881. Points.prototype.isPoints = true;
  17882. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  17883. const rayPointDistanceSq = _ray.distanceSqToPoint(point);
  17884. if (rayPointDistanceSq < localThresholdSq) {
  17885. const intersectPoint = new Vector3();
  17886. _ray.closestPointToPoint(point, intersectPoint);
  17887. intersectPoint.applyMatrix4(matrixWorld);
  17888. const distance = raycaster.ray.origin.distanceTo(intersectPoint);
  17889. if (distance < raycaster.near || distance > raycaster.far) return;
  17890. intersects.push({
  17891. distance: distance,
  17892. distanceToRay: Math.sqrt(rayPointDistanceSq),
  17893. point: intersectPoint,
  17894. index: index,
  17895. face: null,
  17896. object: object
  17897. });
  17898. }
  17899. }
  17900. class VideoTexture extends Texture {
  17901. constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  17902. super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17903. this.format = format !== undefined ? format : RGBFormat;
  17904. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  17905. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  17906. this.generateMipmaps = false;
  17907. const scope = this;
  17908. function updateVideo() {
  17909. scope.needsUpdate = true;
  17910. video.requestVideoFrameCallback(updateVideo);
  17911. }
  17912. if ('requestVideoFrameCallback' in video) {
  17913. video.requestVideoFrameCallback(updateVideo);
  17914. }
  17915. }
  17916. clone() {
  17917. return new this.constructor(this.image).copy(this);
  17918. }
  17919. update() {
  17920. const video = this.image;
  17921. const hasVideoFrameCallback = ('requestVideoFrameCallback' in video);
  17922. if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
  17923. this.needsUpdate = true;
  17924. }
  17925. }
  17926. }
  17927. VideoTexture.prototype.isVideoTexture = true;
  17928. class FramebufferTexture extends Texture {
  17929. constructor(width, height, format) {
  17930. super({
  17931. width,
  17932. height
  17933. });
  17934. this.format = format;
  17935. this.magFilter = NearestFilter;
  17936. this.minFilter = NearestFilter;
  17937. this.generateMipmaps = false;
  17938. this.needsUpdate = true;
  17939. }
  17940. }
  17941. FramebufferTexture.prototype.isFramebufferTexture = true;
  17942. class CompressedTexture extends Texture {
  17943. constructor(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  17944. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  17945. this.image = {
  17946. width: width,
  17947. height: height
  17948. };
  17949. this.mipmaps = mipmaps; // no flipping for cube textures
  17950. // (also flipping doesn't work for compressed textures )
  17951. this.flipY = false; // can't generate mipmaps for compressed textures
  17952. // mips must be embedded in DDS files
  17953. this.generateMipmaps = false;
  17954. }
  17955. }
  17956. CompressedTexture.prototype.isCompressedTexture = true;
  17957. class CanvasTexture extends Texture {
  17958. constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  17959. super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17960. this.needsUpdate = true;
  17961. }
  17962. }
  17963. CanvasTexture.prototype.isCanvasTexture = true;
  17964. class CircleGeometry extends BufferGeometry {
  17965. constructor(radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2) {
  17966. super();
  17967. this.type = 'CircleGeometry';
  17968. this.parameters = {
  17969. radius: radius,
  17970. segments: segments,
  17971. thetaStart: thetaStart,
  17972. thetaLength: thetaLength
  17973. };
  17974. segments = Math.max(3, segments); // buffers
  17975. const indices = [];
  17976. const vertices = [];
  17977. const normals = [];
  17978. const uvs = []; // helper variables
  17979. const vertex = new Vector3();
  17980. const uv = new Vector2(); // center point
  17981. vertices.push(0, 0, 0);
  17982. normals.push(0, 0, 1);
  17983. uvs.push(0.5, 0.5);
  17984. for (let s = 0, i = 3; s <= segments; s++, i += 3) {
  17985. const segment = thetaStart + s / segments * thetaLength; // vertex
  17986. vertex.x = radius * Math.cos(segment);
  17987. vertex.y = radius * Math.sin(segment);
  17988. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17989. normals.push(0, 0, 1); // uvs
  17990. uv.x = (vertices[i] / radius + 1) / 2;
  17991. uv.y = (vertices[i + 1] / radius + 1) / 2;
  17992. uvs.push(uv.x, uv.y);
  17993. } // indices
  17994. for (let i = 1; i <= segments; i++) {
  17995. indices.push(i, i + 1, 0);
  17996. } // build geometry
  17997. this.setIndex(indices);
  17998. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17999. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18000. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18001. }
  18002. static fromJSON(data) {
  18003. return new CircleGeometry(data.radius, data.segments, data.thetaStart, data.thetaLength);
  18004. }
  18005. }
  18006. class CylinderGeometry extends BufferGeometry {
  18007. constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  18008. super();
  18009. this.type = 'CylinderGeometry';
  18010. this.parameters = {
  18011. radiusTop: radiusTop,
  18012. radiusBottom: radiusBottom,
  18013. height: height,
  18014. radialSegments: radialSegments,
  18015. heightSegments: heightSegments,
  18016. openEnded: openEnded,
  18017. thetaStart: thetaStart,
  18018. thetaLength: thetaLength
  18019. };
  18020. const scope = this;
  18021. radialSegments = Math.floor(radialSegments);
  18022. heightSegments = Math.floor(heightSegments); // buffers
  18023. const indices = [];
  18024. const vertices = [];
  18025. const normals = [];
  18026. const uvs = []; // helper variables
  18027. let index = 0;
  18028. const indexArray = [];
  18029. const halfHeight = height / 2;
  18030. let groupStart = 0; // generate geometry
  18031. generateTorso();
  18032. if (openEnded === false) {
  18033. if (radiusTop > 0) generateCap(true);
  18034. if (radiusBottom > 0) generateCap(false);
  18035. } // build geometry
  18036. this.setIndex(indices);
  18037. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18038. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18039. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18040. function generateTorso() {
  18041. const normal = new Vector3();
  18042. const vertex = new Vector3();
  18043. let groupCount = 0; // this will be used to calculate the normal
  18044. const slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  18045. for (let y = 0; y <= heightSegments; y++) {
  18046. const indexRow = [];
  18047. const v = y / heightSegments; // calculate the radius of the current row
  18048. const radius = v * (radiusBottom - radiusTop) + radiusTop;
  18049. for (let x = 0; x <= radialSegments; x++) {
  18050. const u = x / radialSegments;
  18051. const theta = u * thetaLength + thetaStart;
  18052. const sinTheta = Math.sin(theta);
  18053. const cosTheta = Math.cos(theta); // vertex
  18054. vertex.x = radius * sinTheta;
  18055. vertex.y = -v * height + halfHeight;
  18056. vertex.z = radius * cosTheta;
  18057. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18058. normal.set(sinTheta, slope, cosTheta).normalize();
  18059. normals.push(normal.x, normal.y, normal.z); // uv
  18060. uvs.push(u, 1 - v); // save index of vertex in respective row
  18061. indexRow.push(index++);
  18062. } // now save vertices of the row in our index array
  18063. indexArray.push(indexRow);
  18064. } // generate indices
  18065. for (let x = 0; x < radialSegments; x++) {
  18066. for (let y = 0; y < heightSegments; y++) {
  18067. // we use the index array to access the correct indices
  18068. const a = indexArray[y][x];
  18069. const b = indexArray[y + 1][x];
  18070. const c = indexArray[y + 1][x + 1];
  18071. const d = indexArray[y][x + 1]; // faces
  18072. indices.push(a, b, d);
  18073. indices.push(b, c, d); // update group counter
  18074. groupCount += 6;
  18075. }
  18076. } // add a group to the geometry. this will ensure multi material support
  18077. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  18078. groupStart += groupCount;
  18079. }
  18080. function generateCap(top) {
  18081. // save the index of the first center vertex
  18082. const centerIndexStart = index;
  18083. const uv = new Vector2();
  18084. const vertex = new Vector3();
  18085. let groupCount = 0;
  18086. const radius = top === true ? radiusTop : radiusBottom;
  18087. const sign = top === true ? 1 : -1; // first we generate the center vertex data of the cap.
  18088. // because the geometry needs one set of uvs per face,
  18089. // we must generate a center vertex per face/segment
  18090. for (let x = 1; x <= radialSegments; x++) {
  18091. // vertex
  18092. vertices.push(0, halfHeight * sign, 0); // normal
  18093. normals.push(0, sign, 0); // uv
  18094. uvs.push(0.5, 0.5); // increase index
  18095. index++;
  18096. } // save the index of the last center vertex
  18097. const centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  18098. for (let x = 0; x <= radialSegments; x++) {
  18099. const u = x / radialSegments;
  18100. const theta = u * thetaLength + thetaStart;
  18101. const cosTheta = Math.cos(theta);
  18102. const sinTheta = Math.sin(theta); // vertex
  18103. vertex.x = radius * sinTheta;
  18104. vertex.y = halfHeight * sign;
  18105. vertex.z = radius * cosTheta;
  18106. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18107. normals.push(0, sign, 0); // uv
  18108. uv.x = cosTheta * 0.5 + 0.5;
  18109. uv.y = sinTheta * 0.5 * sign + 0.5;
  18110. uvs.push(uv.x, uv.y); // increase index
  18111. index++;
  18112. } // generate indices
  18113. for (let x = 0; x < radialSegments; x++) {
  18114. const c = centerIndexStart + x;
  18115. const i = centerIndexEnd + x;
  18116. if (top === true) {
  18117. // face top
  18118. indices.push(i, i + 1, c);
  18119. } else {
  18120. // face bottom
  18121. indices.push(i + 1, i, c);
  18122. }
  18123. groupCount += 3;
  18124. } // add a group to the geometry. this will ensure multi material support
  18125. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  18126. groupStart += groupCount;
  18127. }
  18128. }
  18129. static fromJSON(data) {
  18130. return new CylinderGeometry(data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  18131. }
  18132. }
  18133. class ConeGeometry extends CylinderGeometry {
  18134. constructor(radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  18135. super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  18136. this.type = 'ConeGeometry';
  18137. this.parameters = {
  18138. radius: radius,
  18139. height: height,
  18140. radialSegments: radialSegments,
  18141. heightSegments: heightSegments,
  18142. openEnded: openEnded,
  18143. thetaStart: thetaStart,
  18144. thetaLength: thetaLength
  18145. };
  18146. }
  18147. static fromJSON(data) {
  18148. return new ConeGeometry(data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  18149. }
  18150. }
  18151. class PolyhedronGeometry extends BufferGeometry {
  18152. constructor(vertices = [], indices = [], radius = 1, detail = 0) {
  18153. super();
  18154. this.type = 'PolyhedronGeometry';
  18155. this.parameters = {
  18156. vertices: vertices,
  18157. indices: indices,
  18158. radius: radius,
  18159. detail: detail
  18160. }; // default buffer data
  18161. const vertexBuffer = [];
  18162. const uvBuffer = []; // the subdivision creates the vertex buffer data
  18163. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  18164. applyRadius(radius); // finally, create the uv data
  18165. generateUVs(); // build non-indexed geometry
  18166. this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  18167. this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  18168. this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  18169. if (detail === 0) {
  18170. this.computeVertexNormals(); // flat normals
  18171. } else {
  18172. this.normalizeNormals(); // smooth normals
  18173. } // helper functions
  18174. function subdivide(detail) {
  18175. const a = new Vector3();
  18176. const b = new Vector3();
  18177. const c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  18178. for (let i = 0; i < indices.length; i += 3) {
  18179. // get the vertices of the face
  18180. getVertexByIndex(indices[i + 0], a);
  18181. getVertexByIndex(indices[i + 1], b);
  18182. getVertexByIndex(indices[i + 2], c); // perform subdivision
  18183. subdivideFace(a, b, c, detail);
  18184. }
  18185. }
  18186. function subdivideFace(a, b, c, detail) {
  18187. const cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision
  18188. const v = []; // construct all of the vertices for this subdivision
  18189. for (let i = 0; i <= cols; i++) {
  18190. v[i] = [];
  18191. const aj = a.clone().lerp(c, i / cols);
  18192. const bj = b.clone().lerp(c, i / cols);
  18193. const rows = cols - i;
  18194. for (let j = 0; j <= rows; j++) {
  18195. if (j === 0 && i === cols) {
  18196. v[i][j] = aj;
  18197. } else {
  18198. v[i][j] = aj.clone().lerp(bj, j / rows);
  18199. }
  18200. }
  18201. } // construct all of the faces
  18202. for (let i = 0; i < cols; i++) {
  18203. for (let j = 0; j < 2 * (cols - i) - 1; j++) {
  18204. const k = Math.floor(j / 2);
  18205. if (j % 2 === 0) {
  18206. pushVertex(v[i][k + 1]);
  18207. pushVertex(v[i + 1][k]);
  18208. pushVertex(v[i][k]);
  18209. } else {
  18210. pushVertex(v[i][k + 1]);
  18211. pushVertex(v[i + 1][k + 1]);
  18212. pushVertex(v[i + 1][k]);
  18213. }
  18214. }
  18215. }
  18216. }
  18217. function applyRadius(radius) {
  18218. const vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  18219. for (let i = 0; i < vertexBuffer.length; i += 3) {
  18220. vertex.x = vertexBuffer[i + 0];
  18221. vertex.y = vertexBuffer[i + 1];
  18222. vertex.z = vertexBuffer[i + 2];
  18223. vertex.normalize().multiplyScalar(radius);
  18224. vertexBuffer[i + 0] = vertex.x;
  18225. vertexBuffer[i + 1] = vertex.y;
  18226. vertexBuffer[i + 2] = vertex.z;
  18227. }
  18228. }
  18229. function generateUVs() {
  18230. const vertex = new Vector3();
  18231. for (let i = 0; i < vertexBuffer.length; i += 3) {
  18232. vertex.x = vertexBuffer[i + 0];
  18233. vertex.y = vertexBuffer[i + 1];
  18234. vertex.z = vertexBuffer[i + 2];
  18235. const u = azimuth(vertex) / 2 / Math.PI + 0.5;
  18236. const v = inclination(vertex) / Math.PI + 0.5;
  18237. uvBuffer.push(u, 1 - v);
  18238. }
  18239. correctUVs();
  18240. correctSeam();
  18241. }
  18242. function correctSeam() {
  18243. // handle case when face straddles the seam, see #3269
  18244. for (let i = 0; i < uvBuffer.length; i += 6) {
  18245. // uv data of a single face
  18246. const x0 = uvBuffer[i + 0];
  18247. const x1 = uvBuffer[i + 2];
  18248. const x2 = uvBuffer[i + 4];
  18249. const max = Math.max(x0, x1, x2);
  18250. const min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  18251. if (max > 0.9 && min < 0.1) {
  18252. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  18253. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  18254. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  18255. }
  18256. }
  18257. }
  18258. function pushVertex(vertex) {
  18259. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  18260. }
  18261. function getVertexByIndex(index, vertex) {
  18262. const stride = index * 3;
  18263. vertex.x = vertices[stride + 0];
  18264. vertex.y = vertices[stride + 1];
  18265. vertex.z = vertices[stride + 2];
  18266. }
  18267. function correctUVs() {
  18268. const a = new Vector3();
  18269. const b = new Vector3();
  18270. const c = new Vector3();
  18271. const centroid = new Vector3();
  18272. const uvA = new Vector2();
  18273. const uvB = new Vector2();
  18274. const uvC = new Vector2();
  18275. for (let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  18276. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  18277. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  18278. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  18279. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  18280. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  18281. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  18282. centroid.copy(a).add(b).add(c).divideScalar(3);
  18283. const azi = azimuth(centroid);
  18284. correctUV(uvA, j + 0, a, azi);
  18285. correctUV(uvB, j + 2, b, azi);
  18286. correctUV(uvC, j + 4, c, azi);
  18287. }
  18288. }
  18289. function correctUV(uv, stride, vector, azimuth) {
  18290. if (azimuth < 0 && uv.x === 1) {
  18291. uvBuffer[stride] = uv.x - 1;
  18292. }
  18293. if (vector.x === 0 && vector.z === 0) {
  18294. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  18295. }
  18296. } // Angle around the Y axis, counter-clockwise when looking from above.
  18297. function azimuth(vector) {
  18298. return Math.atan2(vector.z, -vector.x);
  18299. } // Angle above the XZ plane.
  18300. function inclination(vector) {
  18301. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  18302. }
  18303. }
  18304. static fromJSON(data) {
  18305. return new PolyhedronGeometry(data.vertices, data.indices, data.radius, data.details);
  18306. }
  18307. }
  18308. class DodecahedronGeometry extends PolyhedronGeometry {
  18309. constructor(radius = 1, detail = 0) {
  18310. const t = (1 + Math.sqrt(5)) / 2;
  18311. const r = 1 / t;
  18312. const vertices = [// (±1, ±1, ±1)
  18313. -1, -1, -1, -1, -1, 1, -1, 1, -1, -1, 1, 1, 1, -1, -1, 1, -1, 1, 1, 1, -1, 1, 1, 1, // (0, ±1/φ, ±φ)
  18314. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  18315. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  18316. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  18317. const indices = [3, 11, 7, 3, 7, 15, 3, 15, 13, 7, 19, 17, 7, 17, 6, 7, 6, 15, 17, 4, 8, 17, 8, 10, 17, 10, 6, 8, 0, 16, 8, 16, 2, 8, 2, 10, 0, 12, 1, 0, 1, 18, 0, 18, 16, 6, 10, 2, 6, 2, 13, 6, 13, 15, 2, 16, 18, 2, 18, 3, 2, 3, 13, 18, 1, 9, 18, 9, 11, 18, 11, 3, 4, 14, 12, 4, 12, 0, 4, 0, 8, 11, 9, 5, 11, 5, 19, 11, 19, 7, 19, 5, 14, 19, 14, 4, 19, 4, 17, 1, 12, 14, 1, 14, 5, 1, 5, 9];
  18318. super(vertices, indices, radius, detail);
  18319. this.type = 'DodecahedronGeometry';
  18320. this.parameters = {
  18321. radius: radius,
  18322. detail: detail
  18323. };
  18324. }
  18325. static fromJSON(data) {
  18326. return new DodecahedronGeometry(data.radius, data.detail);
  18327. }
  18328. }
  18329. const _v0 = new Vector3();
  18330. const _v1$1 = new Vector3();
  18331. const _normal = new Vector3();
  18332. const _triangle = new Triangle();
  18333. class EdgesGeometry extends BufferGeometry {
  18334. constructor(geometry = null, thresholdAngle = 1) {
  18335. super();
  18336. this.type = 'EdgesGeometry';
  18337. this.parameters = {
  18338. geometry: geometry,
  18339. thresholdAngle: thresholdAngle
  18340. };
  18341. if (geometry !== null) {
  18342. const precisionPoints = 4;
  18343. const precision = Math.pow(10, precisionPoints);
  18344. const thresholdDot = Math.cos(DEG2RAD * thresholdAngle);
  18345. const indexAttr = geometry.getIndex();
  18346. const positionAttr = geometry.getAttribute('position');
  18347. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  18348. const indexArr = [0, 0, 0];
  18349. const vertKeys = ['a', 'b', 'c'];
  18350. const hashes = new Array(3);
  18351. const edgeData = {};
  18352. const vertices = [];
  18353. for (let i = 0; i < indexCount; i += 3) {
  18354. if (indexAttr) {
  18355. indexArr[0] = indexAttr.getX(i);
  18356. indexArr[1] = indexAttr.getX(i + 1);
  18357. indexArr[2] = indexAttr.getX(i + 2);
  18358. } else {
  18359. indexArr[0] = i;
  18360. indexArr[1] = i + 1;
  18361. indexArr[2] = i + 2;
  18362. }
  18363. const {
  18364. a,
  18365. b,
  18366. c
  18367. } = _triangle;
  18368. a.fromBufferAttribute(positionAttr, indexArr[0]);
  18369. b.fromBufferAttribute(positionAttr, indexArr[1]);
  18370. c.fromBufferAttribute(positionAttr, indexArr[2]);
  18371. _triangle.getNormal(_normal); // create hashes for the edge from the vertices
  18372. hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`;
  18373. hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`;
  18374. hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`; // skip degenerate triangles
  18375. if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
  18376. continue;
  18377. } // iterate over every edge
  18378. for (let j = 0; j < 3; j++) {
  18379. // get the first and next vertex making up the edge
  18380. const jNext = (j + 1) % 3;
  18381. const vecHash0 = hashes[j];
  18382. const vecHash1 = hashes[jNext];
  18383. const v0 = _triangle[vertKeys[j]];
  18384. const v1 = _triangle[vertKeys[jNext]];
  18385. const hash = `${vecHash0}_${vecHash1}`;
  18386. const reverseHash = `${vecHash1}_${vecHash0}`;
  18387. if (reverseHash in edgeData && edgeData[reverseHash]) {
  18388. // if we found a sibling edge add it into the vertex array if
  18389. // it meets the angle threshold and delete the edge from the map.
  18390. if (_normal.dot(edgeData[reverseHash].normal) <= thresholdDot) {
  18391. vertices.push(v0.x, v0.y, v0.z);
  18392. vertices.push(v1.x, v1.y, v1.z);
  18393. }
  18394. edgeData[reverseHash] = null;
  18395. } else if (!(hash in edgeData)) {
  18396. // if we've already got an edge here then skip adding a new one
  18397. edgeData[hash] = {
  18398. index0: indexArr[j],
  18399. index1: indexArr[jNext],
  18400. normal: _normal.clone()
  18401. };
  18402. }
  18403. }
  18404. } // iterate over all remaining, unmatched edges and add them to the vertex array
  18405. for (const key in edgeData) {
  18406. if (edgeData[key]) {
  18407. const {
  18408. index0,
  18409. index1
  18410. } = edgeData[key];
  18411. _v0.fromBufferAttribute(positionAttr, index0);
  18412. _v1$1.fromBufferAttribute(positionAttr, index1);
  18413. vertices.push(_v0.x, _v0.y, _v0.z);
  18414. vertices.push(_v1$1.x, _v1$1.y, _v1$1.z);
  18415. }
  18416. }
  18417. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18418. }
  18419. }
  18420. }
  18421. /**
  18422. * Extensible curve object.
  18423. *
  18424. * Some common of curve methods:
  18425. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  18426. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  18427. * .getPoints(), .getSpacedPoints()
  18428. * .getLength()
  18429. * .updateArcLengths()
  18430. *
  18431. * This following curves inherit from THREE.Curve:
  18432. *
  18433. * -- 2D curves --
  18434. * THREE.ArcCurve
  18435. * THREE.CubicBezierCurve
  18436. * THREE.EllipseCurve
  18437. * THREE.LineCurve
  18438. * THREE.QuadraticBezierCurve
  18439. * THREE.SplineCurve
  18440. *
  18441. * -- 3D curves --
  18442. * THREE.CatmullRomCurve3
  18443. * THREE.CubicBezierCurve3
  18444. * THREE.LineCurve3
  18445. * THREE.QuadraticBezierCurve3
  18446. *
  18447. * A series of curves can be represented as a THREE.CurvePath.
  18448. *
  18449. **/
  18450. class Curve {
  18451. constructor() {
  18452. this.type = 'Curve';
  18453. this.arcLengthDivisions = 200;
  18454. } // Virtual base class method to overwrite and implement in subclasses
  18455. // - t [0 .. 1]
  18456. getPoint() {
  18457. console.warn('THREE.Curve: .getPoint() not implemented.');
  18458. return null;
  18459. } // Get point at relative position in curve according to arc length
  18460. // - u [0 .. 1]
  18461. getPointAt(u, optionalTarget) {
  18462. const t = this.getUtoTmapping(u);
  18463. return this.getPoint(t, optionalTarget);
  18464. } // Get sequence of points using getPoint( t )
  18465. getPoints(divisions = 5) {
  18466. const points = [];
  18467. for (let d = 0; d <= divisions; d++) {
  18468. points.push(this.getPoint(d / divisions));
  18469. }
  18470. return points;
  18471. } // Get sequence of points using getPointAt( u )
  18472. getSpacedPoints(divisions = 5) {
  18473. const points = [];
  18474. for (let d = 0; d <= divisions; d++) {
  18475. points.push(this.getPointAt(d / divisions));
  18476. }
  18477. return points;
  18478. } // Get total curve arc length
  18479. getLength() {
  18480. const lengths = this.getLengths();
  18481. return lengths[lengths.length - 1];
  18482. } // Get list of cumulative segment lengths
  18483. getLengths(divisions = this.arcLengthDivisions) {
  18484. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  18485. return this.cacheArcLengths;
  18486. }
  18487. this.needsUpdate = false;
  18488. const cache = [];
  18489. let current,
  18490. last = this.getPoint(0);
  18491. let sum = 0;
  18492. cache.push(0);
  18493. for (let p = 1; p <= divisions; p++) {
  18494. current = this.getPoint(p / divisions);
  18495. sum += current.distanceTo(last);
  18496. cache.push(sum);
  18497. last = current;
  18498. }
  18499. this.cacheArcLengths = cache;
  18500. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  18501. }
  18502. updateArcLengths() {
  18503. this.needsUpdate = true;
  18504. this.getLengths();
  18505. } // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  18506. getUtoTmapping(u, distance) {
  18507. const arcLengths = this.getLengths();
  18508. let i = 0;
  18509. const il = arcLengths.length;
  18510. let targetArcLength; // The targeted u distance value to get
  18511. if (distance) {
  18512. targetArcLength = distance;
  18513. } else {
  18514. targetArcLength = u * arcLengths[il - 1];
  18515. } // binary search for the index with largest value smaller than target u distance
  18516. let low = 0,
  18517. high = il - 1,
  18518. comparison;
  18519. while (low <= high) {
  18520. 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
  18521. comparison = arcLengths[i] - targetArcLength;
  18522. if (comparison < 0) {
  18523. low = i + 1;
  18524. } else if (comparison > 0) {
  18525. high = i - 1;
  18526. } else {
  18527. high = i;
  18528. break; // DONE
  18529. }
  18530. }
  18531. i = high;
  18532. if (arcLengths[i] === targetArcLength) {
  18533. return i / (il - 1);
  18534. } // we could get finer grain at lengths, or use simple interpolation between two points
  18535. const lengthBefore = arcLengths[i];
  18536. const lengthAfter = arcLengths[i + 1];
  18537. const segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  18538. const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  18539. const t = (i + segmentFraction) / (il - 1);
  18540. return t;
  18541. } // Returns a unit vector tangent at t
  18542. // In case any sub curve does not implement its tangent derivation,
  18543. // 2 points a small delta apart will be used to find its gradient
  18544. // which seems to give a reasonable approximation
  18545. getTangent(t, optionalTarget) {
  18546. const delta = 0.0001;
  18547. let t1 = t - delta;
  18548. let t2 = t + delta; // Capping in case of danger
  18549. if (t1 < 0) t1 = 0;
  18550. if (t2 > 1) t2 = 1;
  18551. const pt1 = this.getPoint(t1);
  18552. const pt2 = this.getPoint(t2);
  18553. const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
  18554. tangent.copy(pt2).sub(pt1).normalize();
  18555. return tangent;
  18556. }
  18557. getTangentAt(u, optionalTarget) {
  18558. const t = this.getUtoTmapping(u);
  18559. return this.getTangent(t, optionalTarget);
  18560. }
  18561. computeFrenetFrames(segments, closed) {
  18562. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18563. const normal = new Vector3();
  18564. const tangents = [];
  18565. const normals = [];
  18566. const binormals = [];
  18567. const vec = new Vector3();
  18568. const mat = new Matrix4(); // compute the tangent vectors for each segment on the curve
  18569. for (let i = 0; i <= segments; i++) {
  18570. const u = i / segments;
  18571. tangents[i] = this.getTangentAt(u, new Vector3());
  18572. } // select an initial normal vector perpendicular to the first tangent vector,
  18573. // and in the direction of the minimum tangent xyz component
  18574. normals[0] = new Vector3();
  18575. binormals[0] = new Vector3();
  18576. let min = Number.MAX_VALUE;
  18577. const tx = Math.abs(tangents[0].x);
  18578. const ty = Math.abs(tangents[0].y);
  18579. const tz = Math.abs(tangents[0].z);
  18580. if (tx <= min) {
  18581. min = tx;
  18582. normal.set(1, 0, 0);
  18583. }
  18584. if (ty <= min) {
  18585. min = ty;
  18586. normal.set(0, 1, 0);
  18587. }
  18588. if (tz <= min) {
  18589. normal.set(0, 0, 1);
  18590. }
  18591. vec.crossVectors(tangents[0], normal).normalize();
  18592. normals[0].crossVectors(tangents[0], vec);
  18593. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  18594. for (let i = 1; i <= segments; i++) {
  18595. normals[i] = normals[i - 1].clone();
  18596. binormals[i] = binormals[i - 1].clone();
  18597. vec.crossVectors(tangents[i - 1], tangents[i]);
  18598. if (vec.length() > Number.EPSILON) {
  18599. vec.normalize();
  18600. const theta = Math.acos(clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  18601. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  18602. }
  18603. binormals[i].crossVectors(tangents[i], normals[i]);
  18604. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18605. if (closed === true) {
  18606. let theta = Math.acos(clamp(normals[0].dot(normals[segments]), -1, 1));
  18607. theta /= segments;
  18608. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  18609. theta = -theta;
  18610. }
  18611. for (let i = 1; i <= segments; i++) {
  18612. // twist a little...
  18613. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  18614. binormals[i].crossVectors(tangents[i], normals[i]);
  18615. }
  18616. }
  18617. return {
  18618. tangents: tangents,
  18619. normals: normals,
  18620. binormals: binormals
  18621. };
  18622. }
  18623. clone() {
  18624. return new this.constructor().copy(this);
  18625. }
  18626. copy(source) {
  18627. this.arcLengthDivisions = source.arcLengthDivisions;
  18628. return this;
  18629. }
  18630. toJSON() {
  18631. const data = {
  18632. metadata: {
  18633. version: 4.5,
  18634. type: 'Curve',
  18635. generator: 'Curve.toJSON'
  18636. }
  18637. };
  18638. data.arcLengthDivisions = this.arcLengthDivisions;
  18639. data.type = this.type;
  18640. return data;
  18641. }
  18642. fromJSON(json) {
  18643. this.arcLengthDivisions = json.arcLengthDivisions;
  18644. return this;
  18645. }
  18646. }
  18647. class EllipseCurve extends Curve {
  18648. constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) {
  18649. super();
  18650. this.type = 'EllipseCurve';
  18651. this.aX = aX;
  18652. this.aY = aY;
  18653. this.xRadius = xRadius;
  18654. this.yRadius = yRadius;
  18655. this.aStartAngle = aStartAngle;
  18656. this.aEndAngle = aEndAngle;
  18657. this.aClockwise = aClockwise;
  18658. this.aRotation = aRotation;
  18659. }
  18660. getPoint(t, optionalTarget) {
  18661. const point = optionalTarget || new Vector2();
  18662. const twoPi = Math.PI * 2;
  18663. let deltaAngle = this.aEndAngle - this.aStartAngle;
  18664. const samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  18665. while (deltaAngle < 0) deltaAngle += twoPi;
  18666. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  18667. if (deltaAngle < Number.EPSILON) {
  18668. if (samePoints) {
  18669. deltaAngle = 0;
  18670. } else {
  18671. deltaAngle = twoPi;
  18672. }
  18673. }
  18674. if (this.aClockwise === true && !samePoints) {
  18675. if (deltaAngle === twoPi) {
  18676. deltaAngle = -twoPi;
  18677. } else {
  18678. deltaAngle = deltaAngle - twoPi;
  18679. }
  18680. }
  18681. const angle = this.aStartAngle + t * deltaAngle;
  18682. let x = this.aX + this.xRadius * Math.cos(angle);
  18683. let y = this.aY + this.yRadius * Math.sin(angle);
  18684. if (this.aRotation !== 0) {
  18685. const cos = Math.cos(this.aRotation);
  18686. const sin = Math.sin(this.aRotation);
  18687. const tx = x - this.aX;
  18688. const ty = y - this.aY; // Rotate the point about the center of the ellipse.
  18689. x = tx * cos - ty * sin + this.aX;
  18690. y = tx * sin + ty * cos + this.aY;
  18691. }
  18692. return point.set(x, y);
  18693. }
  18694. copy(source) {
  18695. super.copy(source);
  18696. this.aX = source.aX;
  18697. this.aY = source.aY;
  18698. this.xRadius = source.xRadius;
  18699. this.yRadius = source.yRadius;
  18700. this.aStartAngle = source.aStartAngle;
  18701. this.aEndAngle = source.aEndAngle;
  18702. this.aClockwise = source.aClockwise;
  18703. this.aRotation = source.aRotation;
  18704. return this;
  18705. }
  18706. toJSON() {
  18707. const data = super.toJSON();
  18708. data.aX = this.aX;
  18709. data.aY = this.aY;
  18710. data.xRadius = this.xRadius;
  18711. data.yRadius = this.yRadius;
  18712. data.aStartAngle = this.aStartAngle;
  18713. data.aEndAngle = this.aEndAngle;
  18714. data.aClockwise = this.aClockwise;
  18715. data.aRotation = this.aRotation;
  18716. return data;
  18717. }
  18718. fromJSON(json) {
  18719. super.fromJSON(json);
  18720. this.aX = json.aX;
  18721. this.aY = json.aY;
  18722. this.xRadius = json.xRadius;
  18723. this.yRadius = json.yRadius;
  18724. this.aStartAngle = json.aStartAngle;
  18725. this.aEndAngle = json.aEndAngle;
  18726. this.aClockwise = json.aClockwise;
  18727. this.aRotation = json.aRotation;
  18728. return this;
  18729. }
  18730. }
  18731. EllipseCurve.prototype.isEllipseCurve = true;
  18732. class ArcCurve extends EllipseCurve {
  18733. constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  18734. super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  18735. this.type = 'ArcCurve';
  18736. }
  18737. }
  18738. ArcCurve.prototype.isArcCurve = true;
  18739. /**
  18740. * Centripetal CatmullRom Curve - which is useful for avoiding
  18741. * cusps and self-intersections in non-uniform catmull rom curves.
  18742. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  18743. *
  18744. * curve.type accepts centripetal(default), chordal and catmullrom
  18745. * curve.tension is used for catmullrom which defaults to 0.5
  18746. */
  18747. /*
  18748. Based on an optimized c++ solution in
  18749. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  18750. - http://ideone.com/NoEbVM
  18751. This CubicPoly class could be used for reusing some variables and calculations,
  18752. but for three.js curve use, it could be possible inlined and flatten into a single function call
  18753. which can be placed in CurveUtils.
  18754. */
  18755. function CubicPoly() {
  18756. let c0 = 0,
  18757. c1 = 0,
  18758. c2 = 0,
  18759. c3 = 0;
  18760. /*
  18761. * Compute coefficients for a cubic polynomial
  18762. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  18763. * such that
  18764. * p(0) = x0, p(1) = x1
  18765. * and
  18766. * p'(0) = t0, p'(1) = t1.
  18767. */
  18768. function init(x0, x1, t0, t1) {
  18769. c0 = x0;
  18770. c1 = t0;
  18771. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  18772. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  18773. }
  18774. return {
  18775. initCatmullRom: function (x0, x1, x2, x3, tension) {
  18776. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  18777. },
  18778. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  18779. // compute tangents when parameterized in [t1,t2]
  18780. let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  18781. let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  18782. t1 *= dt1;
  18783. t2 *= dt1;
  18784. init(x1, x2, t1, t2);
  18785. },
  18786. calc: function (t) {
  18787. const t2 = t * t;
  18788. const t3 = t2 * t;
  18789. return c0 + c1 * t + c2 * t2 + c3 * t3;
  18790. }
  18791. };
  18792. } //
  18793. const tmp = new Vector3();
  18794. const px = new CubicPoly(),
  18795. py = new CubicPoly(),
  18796. pz = new CubicPoly();
  18797. class CatmullRomCurve3 extends Curve {
  18798. constructor(points = [], closed = false, curveType = 'centripetal', tension = 0.5) {
  18799. super();
  18800. this.type = 'CatmullRomCurve3';
  18801. this.points = points;
  18802. this.closed = closed;
  18803. this.curveType = curveType;
  18804. this.tension = tension;
  18805. }
  18806. getPoint(t, optionalTarget = new Vector3()) {
  18807. const point = optionalTarget;
  18808. const points = this.points;
  18809. const l = points.length;
  18810. const p = (l - (this.closed ? 0 : 1)) * t;
  18811. let intPoint = Math.floor(p);
  18812. let weight = p - intPoint;
  18813. if (this.closed) {
  18814. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  18815. } else if (weight === 0 && intPoint === l - 1) {
  18816. intPoint = l - 2;
  18817. weight = 1;
  18818. }
  18819. let p0, p3; // 4 points (p1 & p2 defined below)
  18820. if (this.closed || intPoint > 0) {
  18821. p0 = points[(intPoint - 1) % l];
  18822. } else {
  18823. // extrapolate first point
  18824. tmp.subVectors(points[0], points[1]).add(points[0]);
  18825. p0 = tmp;
  18826. }
  18827. const p1 = points[intPoint % l];
  18828. const p2 = points[(intPoint + 1) % l];
  18829. if (this.closed || intPoint + 2 < l) {
  18830. p3 = points[(intPoint + 2) % l];
  18831. } else {
  18832. // extrapolate last point
  18833. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  18834. p3 = tmp;
  18835. }
  18836. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  18837. // init Centripetal / Chordal Catmull-Rom
  18838. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  18839. let dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  18840. let dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  18841. let dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  18842. if (dt1 < 1e-4) dt1 = 1.0;
  18843. if (dt0 < 1e-4) dt0 = dt1;
  18844. if (dt2 < 1e-4) dt2 = dt1;
  18845. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  18846. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  18847. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  18848. } else if (this.curveType === 'catmullrom') {
  18849. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  18850. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  18851. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  18852. }
  18853. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  18854. return point;
  18855. }
  18856. copy(source) {
  18857. super.copy(source);
  18858. this.points = [];
  18859. for (let i = 0, l = source.points.length; i < l; i++) {
  18860. const point = source.points[i];
  18861. this.points.push(point.clone());
  18862. }
  18863. this.closed = source.closed;
  18864. this.curveType = source.curveType;
  18865. this.tension = source.tension;
  18866. return this;
  18867. }
  18868. toJSON() {
  18869. const data = super.toJSON();
  18870. data.points = [];
  18871. for (let i = 0, l = this.points.length; i < l; i++) {
  18872. const point = this.points[i];
  18873. data.points.push(point.toArray());
  18874. }
  18875. data.closed = this.closed;
  18876. data.curveType = this.curveType;
  18877. data.tension = this.tension;
  18878. return data;
  18879. }
  18880. fromJSON(json) {
  18881. super.fromJSON(json);
  18882. this.points = [];
  18883. for (let i = 0, l = json.points.length; i < l; i++) {
  18884. const point = json.points[i];
  18885. this.points.push(new Vector3().fromArray(point));
  18886. }
  18887. this.closed = json.closed;
  18888. this.curveType = json.curveType;
  18889. this.tension = json.tension;
  18890. return this;
  18891. }
  18892. }
  18893. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  18894. /**
  18895. * Bezier Curves formulas obtained from
  18896. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  18897. */
  18898. function CatmullRom(t, p0, p1, p2, p3) {
  18899. const v0 = (p2 - p0) * 0.5;
  18900. const v1 = (p3 - p1) * 0.5;
  18901. const t2 = t * t;
  18902. const t3 = t * t2;
  18903. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  18904. } //
  18905. function QuadraticBezierP0(t, p) {
  18906. const k = 1 - t;
  18907. return k * k * p;
  18908. }
  18909. function QuadraticBezierP1(t, p) {
  18910. return 2 * (1 - t) * t * p;
  18911. }
  18912. function QuadraticBezierP2(t, p) {
  18913. return t * t * p;
  18914. }
  18915. function QuadraticBezier(t, p0, p1, p2) {
  18916. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  18917. } //
  18918. function CubicBezierP0(t, p) {
  18919. const k = 1 - t;
  18920. return k * k * k * p;
  18921. }
  18922. function CubicBezierP1(t, p) {
  18923. const k = 1 - t;
  18924. return 3 * k * k * t * p;
  18925. }
  18926. function CubicBezierP2(t, p) {
  18927. return 3 * (1 - t) * t * t * p;
  18928. }
  18929. function CubicBezierP3(t, p) {
  18930. return t * t * t * p;
  18931. }
  18932. function CubicBezier(t, p0, p1, p2, p3) {
  18933. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  18934. }
  18935. class CubicBezierCurve extends Curve {
  18936. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) {
  18937. super();
  18938. this.type = 'CubicBezierCurve';
  18939. this.v0 = v0;
  18940. this.v1 = v1;
  18941. this.v2 = v2;
  18942. this.v3 = v3;
  18943. }
  18944. getPoint(t, optionalTarget = new Vector2()) {
  18945. const point = optionalTarget;
  18946. const v0 = this.v0,
  18947. v1 = this.v1,
  18948. v2 = this.v2,
  18949. v3 = this.v3;
  18950. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  18951. return point;
  18952. }
  18953. copy(source) {
  18954. super.copy(source);
  18955. this.v0.copy(source.v0);
  18956. this.v1.copy(source.v1);
  18957. this.v2.copy(source.v2);
  18958. this.v3.copy(source.v3);
  18959. return this;
  18960. }
  18961. toJSON() {
  18962. const data = super.toJSON();
  18963. data.v0 = this.v0.toArray();
  18964. data.v1 = this.v1.toArray();
  18965. data.v2 = this.v2.toArray();
  18966. data.v3 = this.v3.toArray();
  18967. return data;
  18968. }
  18969. fromJSON(json) {
  18970. super.fromJSON(json);
  18971. this.v0.fromArray(json.v0);
  18972. this.v1.fromArray(json.v1);
  18973. this.v2.fromArray(json.v2);
  18974. this.v3.fromArray(json.v3);
  18975. return this;
  18976. }
  18977. }
  18978. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  18979. class CubicBezierCurve3 extends Curve {
  18980. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) {
  18981. super();
  18982. this.type = 'CubicBezierCurve3';
  18983. this.v0 = v0;
  18984. this.v1 = v1;
  18985. this.v2 = v2;
  18986. this.v3 = v3;
  18987. }
  18988. getPoint(t, optionalTarget = new Vector3()) {
  18989. const point = optionalTarget;
  18990. const v0 = this.v0,
  18991. v1 = this.v1,
  18992. v2 = this.v2,
  18993. v3 = this.v3;
  18994. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y), CubicBezier(t, v0.z, v1.z, v2.z, v3.z));
  18995. return point;
  18996. }
  18997. copy(source) {
  18998. super.copy(source);
  18999. this.v0.copy(source.v0);
  19000. this.v1.copy(source.v1);
  19001. this.v2.copy(source.v2);
  19002. this.v3.copy(source.v3);
  19003. return this;
  19004. }
  19005. toJSON() {
  19006. const data = super.toJSON();
  19007. data.v0 = this.v0.toArray();
  19008. data.v1 = this.v1.toArray();
  19009. data.v2 = this.v2.toArray();
  19010. data.v3 = this.v3.toArray();
  19011. return data;
  19012. }
  19013. fromJSON(json) {
  19014. super.fromJSON(json);
  19015. this.v0.fromArray(json.v0);
  19016. this.v1.fromArray(json.v1);
  19017. this.v2.fromArray(json.v2);
  19018. this.v3.fromArray(json.v3);
  19019. return this;
  19020. }
  19021. }
  19022. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  19023. class LineCurve extends Curve {
  19024. constructor(v1 = new Vector2(), v2 = new Vector2()) {
  19025. super();
  19026. this.type = 'LineCurve';
  19027. this.v1 = v1;
  19028. this.v2 = v2;
  19029. }
  19030. getPoint(t, optionalTarget = new Vector2()) {
  19031. const point = optionalTarget;
  19032. if (t === 1) {
  19033. point.copy(this.v2);
  19034. } else {
  19035. point.copy(this.v2).sub(this.v1);
  19036. point.multiplyScalar(t).add(this.v1);
  19037. }
  19038. return point;
  19039. } // Line curve is linear, so we can overwrite default getPointAt
  19040. getPointAt(u, optionalTarget) {
  19041. return this.getPoint(u, optionalTarget);
  19042. }
  19043. getTangent(t, optionalTarget) {
  19044. const tangent = optionalTarget || new Vector2();
  19045. tangent.copy(this.v2).sub(this.v1).normalize();
  19046. return tangent;
  19047. }
  19048. copy(source) {
  19049. super.copy(source);
  19050. this.v1.copy(source.v1);
  19051. this.v2.copy(source.v2);
  19052. return this;
  19053. }
  19054. toJSON() {
  19055. const data = super.toJSON();
  19056. data.v1 = this.v1.toArray();
  19057. data.v2 = this.v2.toArray();
  19058. return data;
  19059. }
  19060. fromJSON(json) {
  19061. super.fromJSON(json);
  19062. this.v1.fromArray(json.v1);
  19063. this.v2.fromArray(json.v2);
  19064. return this;
  19065. }
  19066. }
  19067. LineCurve.prototype.isLineCurve = true;
  19068. class LineCurve3 extends Curve {
  19069. constructor(v1 = new Vector3(), v2 = new Vector3()) {
  19070. super();
  19071. this.type = 'LineCurve3';
  19072. this.isLineCurve3 = true;
  19073. this.v1 = v1;
  19074. this.v2 = v2;
  19075. }
  19076. getPoint(t, optionalTarget = new Vector3()) {
  19077. const point = optionalTarget;
  19078. if (t === 1) {
  19079. point.copy(this.v2);
  19080. } else {
  19081. point.copy(this.v2).sub(this.v1);
  19082. point.multiplyScalar(t).add(this.v1);
  19083. }
  19084. return point;
  19085. } // Line curve is linear, so we can overwrite default getPointAt
  19086. getPointAt(u, optionalTarget) {
  19087. return this.getPoint(u, optionalTarget);
  19088. }
  19089. copy(source) {
  19090. super.copy(source);
  19091. this.v1.copy(source.v1);
  19092. this.v2.copy(source.v2);
  19093. return this;
  19094. }
  19095. toJSON() {
  19096. const data = super.toJSON();
  19097. data.v1 = this.v1.toArray();
  19098. data.v2 = this.v2.toArray();
  19099. return data;
  19100. }
  19101. fromJSON(json) {
  19102. super.fromJSON(json);
  19103. this.v1.fromArray(json.v1);
  19104. this.v2.fromArray(json.v2);
  19105. return this;
  19106. }
  19107. }
  19108. class QuadraticBezierCurve extends Curve {
  19109. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) {
  19110. super();
  19111. this.type = 'QuadraticBezierCurve';
  19112. this.v0 = v0;
  19113. this.v1 = v1;
  19114. this.v2 = v2;
  19115. }
  19116. getPoint(t, optionalTarget = new Vector2()) {
  19117. const point = optionalTarget;
  19118. const v0 = this.v0,
  19119. v1 = this.v1,
  19120. v2 = this.v2;
  19121. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  19122. return point;
  19123. }
  19124. copy(source) {
  19125. super.copy(source);
  19126. this.v0.copy(source.v0);
  19127. this.v1.copy(source.v1);
  19128. this.v2.copy(source.v2);
  19129. return this;
  19130. }
  19131. toJSON() {
  19132. const data = super.toJSON();
  19133. data.v0 = this.v0.toArray();
  19134. data.v1 = this.v1.toArray();
  19135. data.v2 = this.v2.toArray();
  19136. return data;
  19137. }
  19138. fromJSON(json) {
  19139. super.fromJSON(json);
  19140. this.v0.fromArray(json.v0);
  19141. this.v1.fromArray(json.v1);
  19142. this.v2.fromArray(json.v2);
  19143. return this;
  19144. }
  19145. }
  19146. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  19147. class QuadraticBezierCurve3 extends Curve {
  19148. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) {
  19149. super();
  19150. this.type = 'QuadraticBezierCurve3';
  19151. this.v0 = v0;
  19152. this.v1 = v1;
  19153. this.v2 = v2;
  19154. }
  19155. getPoint(t, optionalTarget = new Vector3()) {
  19156. const point = optionalTarget;
  19157. const v0 = this.v0,
  19158. v1 = this.v1,
  19159. v2 = this.v2;
  19160. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y), QuadraticBezier(t, v0.z, v1.z, v2.z));
  19161. return point;
  19162. }
  19163. copy(source) {
  19164. super.copy(source);
  19165. this.v0.copy(source.v0);
  19166. this.v1.copy(source.v1);
  19167. this.v2.copy(source.v2);
  19168. return this;
  19169. }
  19170. toJSON() {
  19171. const data = super.toJSON();
  19172. data.v0 = this.v0.toArray();
  19173. data.v1 = this.v1.toArray();
  19174. data.v2 = this.v2.toArray();
  19175. return data;
  19176. }
  19177. fromJSON(json) {
  19178. super.fromJSON(json);
  19179. this.v0.fromArray(json.v0);
  19180. this.v1.fromArray(json.v1);
  19181. this.v2.fromArray(json.v2);
  19182. return this;
  19183. }
  19184. }
  19185. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  19186. class SplineCurve extends Curve {
  19187. constructor(points = []) {
  19188. super();
  19189. this.type = 'SplineCurve';
  19190. this.points = points;
  19191. }
  19192. getPoint(t, optionalTarget = new Vector2()) {
  19193. const point = optionalTarget;
  19194. const points = this.points;
  19195. const p = (points.length - 1) * t;
  19196. const intPoint = Math.floor(p);
  19197. const weight = p - intPoint;
  19198. const p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  19199. const p1 = points[intPoint];
  19200. const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  19201. const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  19202. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  19203. return point;
  19204. }
  19205. copy(source) {
  19206. super.copy(source);
  19207. this.points = [];
  19208. for (let i = 0, l = source.points.length; i < l; i++) {
  19209. const point = source.points[i];
  19210. this.points.push(point.clone());
  19211. }
  19212. return this;
  19213. }
  19214. toJSON() {
  19215. const data = super.toJSON();
  19216. data.points = [];
  19217. for (let i = 0, l = this.points.length; i < l; i++) {
  19218. const point = this.points[i];
  19219. data.points.push(point.toArray());
  19220. }
  19221. return data;
  19222. }
  19223. fromJSON(json) {
  19224. super.fromJSON(json);
  19225. this.points = [];
  19226. for (let i = 0, l = json.points.length; i < l; i++) {
  19227. const point = json.points[i];
  19228. this.points.push(new Vector2().fromArray(point));
  19229. }
  19230. return this;
  19231. }
  19232. }
  19233. SplineCurve.prototype.isSplineCurve = true;
  19234. var Curves = /*#__PURE__*/Object.freeze({
  19235. __proto__: null,
  19236. ArcCurve: ArcCurve,
  19237. CatmullRomCurve3: CatmullRomCurve3,
  19238. CubicBezierCurve: CubicBezierCurve,
  19239. CubicBezierCurve3: CubicBezierCurve3,
  19240. EllipseCurve: EllipseCurve,
  19241. LineCurve: LineCurve,
  19242. LineCurve3: LineCurve3,
  19243. QuadraticBezierCurve: QuadraticBezierCurve,
  19244. QuadraticBezierCurve3: QuadraticBezierCurve3,
  19245. SplineCurve: SplineCurve
  19246. });
  19247. /**************************************************************
  19248. * Curved Path - a curve path is simply a array of connected
  19249. * curves, but retains the api of a curve
  19250. **************************************************************/
  19251. class CurvePath extends Curve {
  19252. constructor() {
  19253. super();
  19254. this.type = 'CurvePath';
  19255. this.curves = [];
  19256. this.autoClose = false; // Automatically closes the path
  19257. }
  19258. add(curve) {
  19259. this.curves.push(curve);
  19260. }
  19261. closePath() {
  19262. // Add a line curve if start and end of lines are not connected
  19263. const startPoint = this.curves[0].getPoint(0);
  19264. const endPoint = this.curves[this.curves.length - 1].getPoint(1);
  19265. if (!startPoint.equals(endPoint)) {
  19266. this.curves.push(new LineCurve(endPoint, startPoint));
  19267. }
  19268. } // To get accurate point with reference to
  19269. // entire path distance at time t,
  19270. // following has to be done:
  19271. // 1. Length of each sub path have to be known
  19272. // 2. Locate and identify type of curve
  19273. // 3. Get t for the curve
  19274. // 4. Return curve.getPointAt(t')
  19275. getPoint(t, optionalTarget) {
  19276. const d = t * this.getLength();
  19277. const curveLengths = this.getCurveLengths();
  19278. let i = 0; // To think about boundaries points.
  19279. while (i < curveLengths.length) {
  19280. if (curveLengths[i] >= d) {
  19281. const diff = curveLengths[i] - d;
  19282. const curve = this.curves[i];
  19283. const segmentLength = curve.getLength();
  19284. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  19285. return curve.getPointAt(u, optionalTarget);
  19286. }
  19287. i++;
  19288. }
  19289. return null; // loop where sum != 0, sum > d , sum+1 <d
  19290. } // We cannot use the default THREE.Curve getPoint() with getLength() because in
  19291. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  19292. // getPoint() depends on getLength
  19293. getLength() {
  19294. const lens = this.getCurveLengths();
  19295. return lens[lens.length - 1];
  19296. } // cacheLengths must be recalculated.
  19297. updateArcLengths() {
  19298. this.needsUpdate = true;
  19299. this.cacheLengths = null;
  19300. this.getCurveLengths();
  19301. } // Compute lengths and cache them
  19302. // We cannot overwrite getLengths() because UtoT mapping uses it.
  19303. getCurveLengths() {
  19304. // We use cache values if curves and cache array are same length
  19305. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  19306. return this.cacheLengths;
  19307. } // Get length of sub-curve
  19308. // Push sums into cached array
  19309. const lengths = [];
  19310. let sums = 0;
  19311. for (let i = 0, l = this.curves.length; i < l; i++) {
  19312. sums += this.curves[i].getLength();
  19313. lengths.push(sums);
  19314. }
  19315. this.cacheLengths = lengths;
  19316. return lengths;
  19317. }
  19318. getSpacedPoints(divisions = 40) {
  19319. const points = [];
  19320. for (let i = 0; i <= divisions; i++) {
  19321. points.push(this.getPoint(i / divisions));
  19322. }
  19323. if (this.autoClose) {
  19324. points.push(points[0]);
  19325. }
  19326. return points;
  19327. }
  19328. getPoints(divisions = 12) {
  19329. const points = [];
  19330. let last;
  19331. for (let i = 0, curves = this.curves; i < curves.length; i++) {
  19332. const curve = curves[i];
  19333. const resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  19334. const pts = curve.getPoints(resolution);
  19335. for (let j = 0; j < pts.length; j++) {
  19336. const point = pts[j];
  19337. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  19338. points.push(point);
  19339. last = point;
  19340. }
  19341. }
  19342. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  19343. points.push(points[0]);
  19344. }
  19345. return points;
  19346. }
  19347. copy(source) {
  19348. super.copy(source);
  19349. this.curves = [];
  19350. for (let i = 0, l = source.curves.length; i < l; i++) {
  19351. const curve = source.curves[i];
  19352. this.curves.push(curve.clone());
  19353. }
  19354. this.autoClose = source.autoClose;
  19355. return this;
  19356. }
  19357. toJSON() {
  19358. const data = super.toJSON();
  19359. data.autoClose = this.autoClose;
  19360. data.curves = [];
  19361. for (let i = 0, l = this.curves.length; i < l; i++) {
  19362. const curve = this.curves[i];
  19363. data.curves.push(curve.toJSON());
  19364. }
  19365. return data;
  19366. }
  19367. fromJSON(json) {
  19368. super.fromJSON(json);
  19369. this.autoClose = json.autoClose;
  19370. this.curves = [];
  19371. for (let i = 0, l = json.curves.length; i < l; i++) {
  19372. const curve = json.curves[i];
  19373. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  19374. }
  19375. return this;
  19376. }
  19377. }
  19378. class Path extends CurvePath {
  19379. constructor(points) {
  19380. super();
  19381. this.type = 'Path';
  19382. this.currentPoint = new Vector2();
  19383. if (points) {
  19384. this.setFromPoints(points);
  19385. }
  19386. }
  19387. setFromPoints(points) {
  19388. this.moveTo(points[0].x, points[0].y);
  19389. for (let i = 1, l = points.length; i < l; i++) {
  19390. this.lineTo(points[i].x, points[i].y);
  19391. }
  19392. return this;
  19393. }
  19394. moveTo(x, y) {
  19395. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  19396. return this;
  19397. }
  19398. lineTo(x, y) {
  19399. const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  19400. this.curves.push(curve);
  19401. this.currentPoint.set(x, y);
  19402. return this;
  19403. }
  19404. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  19405. const curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  19406. this.curves.push(curve);
  19407. this.currentPoint.set(aX, aY);
  19408. return this;
  19409. }
  19410. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  19411. const curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  19412. this.curves.push(curve);
  19413. this.currentPoint.set(aX, aY);
  19414. return this;
  19415. }
  19416. splineThru(pts
  19417. /*Array of Vector*/
  19418. ) {
  19419. const npts = [this.currentPoint.clone()].concat(pts);
  19420. const curve = new SplineCurve(npts);
  19421. this.curves.push(curve);
  19422. this.currentPoint.copy(pts[pts.length - 1]);
  19423. return this;
  19424. }
  19425. arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  19426. const x0 = this.currentPoint.x;
  19427. const y0 = this.currentPoint.y;
  19428. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  19429. return this;
  19430. }
  19431. absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  19432. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  19433. return this;
  19434. }
  19435. ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  19436. const x0 = this.currentPoint.x;
  19437. const y0 = this.currentPoint.y;
  19438. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  19439. return this;
  19440. }
  19441. absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  19442. const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  19443. if (this.curves.length > 0) {
  19444. // if a previous curve is present, attempt to join
  19445. const firstPoint = curve.getPoint(0);
  19446. if (!firstPoint.equals(this.currentPoint)) {
  19447. this.lineTo(firstPoint.x, firstPoint.y);
  19448. }
  19449. }
  19450. this.curves.push(curve);
  19451. const lastPoint = curve.getPoint(1);
  19452. this.currentPoint.copy(lastPoint);
  19453. return this;
  19454. }
  19455. copy(source) {
  19456. super.copy(source);
  19457. this.currentPoint.copy(source.currentPoint);
  19458. return this;
  19459. }
  19460. toJSON() {
  19461. const data = super.toJSON();
  19462. data.currentPoint = this.currentPoint.toArray();
  19463. return data;
  19464. }
  19465. fromJSON(json) {
  19466. super.fromJSON(json);
  19467. this.currentPoint.fromArray(json.currentPoint);
  19468. return this;
  19469. }
  19470. }
  19471. class Shape extends Path {
  19472. constructor(points) {
  19473. super(points);
  19474. this.uuid = generateUUID();
  19475. this.type = 'Shape';
  19476. this.holes = [];
  19477. }
  19478. getPointsHoles(divisions) {
  19479. const holesPts = [];
  19480. for (let i = 0, l = this.holes.length; i < l; i++) {
  19481. holesPts[i] = this.holes[i].getPoints(divisions);
  19482. }
  19483. return holesPts;
  19484. } // get points of shape and holes (keypoints based on segments parameter)
  19485. extractPoints(divisions) {
  19486. return {
  19487. shape: this.getPoints(divisions),
  19488. holes: this.getPointsHoles(divisions)
  19489. };
  19490. }
  19491. copy(source) {
  19492. super.copy(source);
  19493. this.holes = [];
  19494. for (let i = 0, l = source.holes.length; i < l; i++) {
  19495. const hole = source.holes[i];
  19496. this.holes.push(hole.clone());
  19497. }
  19498. return this;
  19499. }
  19500. toJSON() {
  19501. const data = super.toJSON();
  19502. data.uuid = this.uuid;
  19503. data.holes = [];
  19504. for (let i = 0, l = this.holes.length; i < l; i++) {
  19505. const hole = this.holes[i];
  19506. data.holes.push(hole.toJSON());
  19507. }
  19508. return data;
  19509. }
  19510. fromJSON(json) {
  19511. super.fromJSON(json);
  19512. this.uuid = json.uuid;
  19513. this.holes = [];
  19514. for (let i = 0, l = json.holes.length; i < l; i++) {
  19515. const hole = json.holes[i];
  19516. this.holes.push(new Path().fromJSON(hole));
  19517. }
  19518. return this;
  19519. }
  19520. }
  19521. /**
  19522. * Port from https://github.com/mapbox/earcut (v2.2.2)
  19523. */
  19524. const Earcut = {
  19525. triangulate: function (data, holeIndices, dim = 2) {
  19526. const hasHoles = holeIndices && holeIndices.length;
  19527. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  19528. let outerNode = linkedList(data, 0, outerLen, dim, true);
  19529. const triangles = [];
  19530. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  19531. let minX, minY, maxX, maxY, x, y, invSize;
  19532. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  19533. if (data.length > 80 * dim) {
  19534. minX = maxX = data[0];
  19535. minY = maxY = data[1];
  19536. for (let i = dim; i < outerLen; i += dim) {
  19537. x = data[i];
  19538. y = data[i + 1];
  19539. if (x < minX) minX = x;
  19540. if (y < minY) minY = y;
  19541. if (x > maxX) maxX = x;
  19542. if (y > maxY) maxY = y;
  19543. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  19544. invSize = Math.max(maxX - minX, maxY - minY);
  19545. invSize = invSize !== 0 ? 1 / invSize : 0;
  19546. }
  19547. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  19548. return triangles;
  19549. }
  19550. }; // create a circular doubly linked list from polygon points in the specified winding order
  19551. function linkedList(data, start, end, dim, clockwise) {
  19552. let i, last;
  19553. if (clockwise === signedArea(data, start, end, dim) > 0) {
  19554. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  19555. } else {
  19556. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  19557. }
  19558. if (last && equals(last, last.next)) {
  19559. removeNode(last);
  19560. last = last.next;
  19561. }
  19562. return last;
  19563. } // eliminate colinear or duplicate points
  19564. function filterPoints(start, end) {
  19565. if (!start) return start;
  19566. if (!end) end = start;
  19567. let p = start,
  19568. again;
  19569. do {
  19570. again = false;
  19571. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  19572. removeNode(p);
  19573. p = end = p.prev;
  19574. if (p === p.next) break;
  19575. again = true;
  19576. } else {
  19577. p = p.next;
  19578. }
  19579. } while (again || p !== end);
  19580. return end;
  19581. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  19582. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  19583. if (!ear) return; // interlink polygon nodes in z-order
  19584. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  19585. let stop = ear,
  19586. prev,
  19587. next; // iterate through ears, slicing them one by one
  19588. while (ear.prev !== ear.next) {
  19589. prev = ear.prev;
  19590. next = ear.next;
  19591. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  19592. // cut off the triangle
  19593. triangles.push(prev.i / dim);
  19594. triangles.push(ear.i / dim);
  19595. triangles.push(next.i / dim);
  19596. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  19597. ear = next.next;
  19598. stop = next.next;
  19599. continue;
  19600. }
  19601. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  19602. if (ear === stop) {
  19603. // try filtering points and slicing again
  19604. if (!pass) {
  19605. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  19606. } else if (pass === 1) {
  19607. ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
  19608. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  19609. } else if (pass === 2) {
  19610. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  19611. }
  19612. break;
  19613. }
  19614. }
  19615. } // check whether a polygon node forms a valid ear with adjacent nodes
  19616. function isEar(ear) {
  19617. const a = ear.prev,
  19618. b = ear,
  19619. c = ear.next;
  19620. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  19621. // now make sure we don't have other points inside the potential ear
  19622. let p = ear.next.next;
  19623. while (p !== ear.prev) {
  19624. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  19625. p = p.next;
  19626. }
  19627. return true;
  19628. }
  19629. function isEarHashed(ear, minX, minY, invSize) {
  19630. const a = ear.prev,
  19631. b = ear,
  19632. c = ear.next;
  19633. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  19634. // triangle bbox; min & max are calculated like this for speed
  19635. const minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  19636. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  19637. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  19638. maxTY = a.y > b.y ? a.y > c.y ? a.y : c.y : b.y > c.y ? b.y : c.y; // z-order range for the current triangle bbox;
  19639. const minZ = zOrder(minTX, minTY, minX, minY, invSize),
  19640. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  19641. let p = ear.prevZ,
  19642. n = ear.nextZ; // look for points inside the triangle in both directions
  19643. while (p && p.z >= minZ && n && n.z <= maxZ) {
  19644. if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  19645. p = p.prevZ;
  19646. if (n !== ear.prev && n !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  19647. n = n.nextZ;
  19648. } // look for remaining points in decreasing z-order
  19649. while (p && p.z >= minZ) {
  19650. if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  19651. p = p.prevZ;
  19652. } // look for remaining points in increasing z-order
  19653. while (n && n.z <= maxZ) {
  19654. if (n !== ear.prev && n !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  19655. n = n.nextZ;
  19656. }
  19657. return true;
  19658. } // go through all polygon nodes and cure small local self-intersections
  19659. function cureLocalIntersections(start, triangles, dim) {
  19660. let p = start;
  19661. do {
  19662. const a = p.prev,
  19663. b = p.next.next;
  19664. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  19665. triangles.push(a.i / dim);
  19666. triangles.push(p.i / dim);
  19667. triangles.push(b.i / dim); // remove two nodes involved
  19668. removeNode(p);
  19669. removeNode(p.next);
  19670. p = start = b;
  19671. }
  19672. p = p.next;
  19673. } while (p !== start);
  19674. return filterPoints(p);
  19675. } // try splitting polygon into two and triangulate them independently
  19676. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  19677. // look for a valid diagonal that divides the polygon into two
  19678. let a = start;
  19679. do {
  19680. let b = a.next.next;
  19681. while (b !== a.prev) {
  19682. if (a.i !== b.i && isValidDiagonal(a, b)) {
  19683. // split the polygon in two by the diagonal
  19684. let c = splitPolygon(a, b); // filter colinear points around the cuts
  19685. a = filterPoints(a, a.next);
  19686. c = filterPoints(c, c.next); // run earcut on each half
  19687. earcutLinked(a, triangles, dim, minX, minY, invSize);
  19688. earcutLinked(c, triangles, dim, minX, minY, invSize);
  19689. return;
  19690. }
  19691. b = b.next;
  19692. }
  19693. a = a.next;
  19694. } while (a !== start);
  19695. } // link every hole into the outer loop, producing a single-ring polygon without holes
  19696. function eliminateHoles(data, holeIndices, outerNode, dim) {
  19697. const queue = [];
  19698. let i, len, start, end, list;
  19699. for (i = 0, len = holeIndices.length; i < len; i++) {
  19700. start = holeIndices[i] * dim;
  19701. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  19702. list = linkedList(data, start, end, dim, false);
  19703. if (list === list.next) list.steiner = true;
  19704. queue.push(getLeftmost(list));
  19705. }
  19706. queue.sort(compareX); // process holes from left to right
  19707. for (i = 0; i < queue.length; i++) {
  19708. eliminateHole(queue[i], outerNode);
  19709. outerNode = filterPoints(outerNode, outerNode.next);
  19710. }
  19711. return outerNode;
  19712. }
  19713. function compareX(a, b) {
  19714. return a.x - b.x;
  19715. } // find a bridge between vertices that connects hole with an outer ring and and link it
  19716. function eliminateHole(hole, outerNode) {
  19717. outerNode = findHoleBridge(hole, outerNode);
  19718. if (outerNode) {
  19719. const b = splitPolygon(outerNode, hole); // filter collinear points around the cuts
  19720. filterPoints(outerNode, outerNode.next);
  19721. filterPoints(b, b.next);
  19722. }
  19723. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  19724. function findHoleBridge(hole, outerNode) {
  19725. let p = outerNode;
  19726. const hx = hole.x;
  19727. const hy = hole.y;
  19728. let qx = -Infinity,
  19729. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  19730. // segment's endpoint with lesser x will be potential connection point
  19731. do {
  19732. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  19733. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  19734. if (x <= hx && x > qx) {
  19735. qx = x;
  19736. if (x === hx) {
  19737. if (hy === p.y) return p;
  19738. if (hy === p.next.y) return p.next;
  19739. }
  19740. m = p.x < p.next.x ? p : p.next;
  19741. }
  19742. }
  19743. p = p.next;
  19744. } while (p !== outerNode);
  19745. if (!m) return null;
  19746. if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint
  19747. // look for points inside the triangle of hole point, segment intersection and endpoint;
  19748. // if there are no points found, we have a valid connection;
  19749. // otherwise choose the point of the minimum angle with the ray as connection point
  19750. const stop = m,
  19751. mx = m.x,
  19752. my = m.y;
  19753. let tanMin = Infinity,
  19754. tan;
  19755. p = m;
  19756. do {
  19757. if (hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  19758. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  19759. if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
  19760. m = p;
  19761. tanMin = tan;
  19762. }
  19763. }
  19764. p = p.next;
  19765. } while (p !== stop);
  19766. return m;
  19767. } // whether sector in vertex m contains sector in vertex p in the same coordinates
  19768. function sectorContainsSector(m, p) {
  19769. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  19770. } // interlink polygon nodes in z-order
  19771. function indexCurve(start, minX, minY, invSize) {
  19772. let p = start;
  19773. do {
  19774. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  19775. p.prevZ = p.prev;
  19776. p.nextZ = p.next;
  19777. p = p.next;
  19778. } while (p !== start);
  19779. p.prevZ.nextZ = null;
  19780. p.prevZ = null;
  19781. sortLinked(p);
  19782. } // Simon Tatham's linked list merge sort algorithm
  19783. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  19784. function sortLinked(list) {
  19785. let i,
  19786. p,
  19787. q,
  19788. e,
  19789. tail,
  19790. numMerges,
  19791. pSize,
  19792. qSize,
  19793. inSize = 1;
  19794. do {
  19795. p = list;
  19796. list = null;
  19797. tail = null;
  19798. numMerges = 0;
  19799. while (p) {
  19800. numMerges++;
  19801. q = p;
  19802. pSize = 0;
  19803. for (i = 0; i < inSize; i++) {
  19804. pSize++;
  19805. q = q.nextZ;
  19806. if (!q) break;
  19807. }
  19808. qSize = inSize;
  19809. while (pSize > 0 || qSize > 0 && q) {
  19810. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  19811. e = p;
  19812. p = p.nextZ;
  19813. pSize--;
  19814. } else {
  19815. e = q;
  19816. q = q.nextZ;
  19817. qSize--;
  19818. }
  19819. if (tail) tail.nextZ = e;else list = e;
  19820. e.prevZ = tail;
  19821. tail = e;
  19822. }
  19823. p = q;
  19824. }
  19825. tail.nextZ = null;
  19826. inSize *= 2;
  19827. } while (numMerges > 1);
  19828. return list;
  19829. } // z-order of a point given coords and inverse of the longer side of data bbox
  19830. function zOrder(x, y, minX, minY, invSize) {
  19831. // coords are transformed into non-negative 15-bit integer range
  19832. x = 32767 * (x - minX) * invSize;
  19833. y = 32767 * (y - minY) * invSize;
  19834. x = (x | x << 8) & 0x00FF00FF;
  19835. x = (x | x << 4) & 0x0F0F0F0F;
  19836. x = (x | x << 2) & 0x33333333;
  19837. x = (x | x << 1) & 0x55555555;
  19838. y = (y | y << 8) & 0x00FF00FF;
  19839. y = (y | y << 4) & 0x0F0F0F0F;
  19840. y = (y | y << 2) & 0x33333333;
  19841. y = (y | y << 1) & 0x55555555;
  19842. return x | y << 1;
  19843. } // find the leftmost node of a polygon ring
  19844. function getLeftmost(start) {
  19845. let p = start,
  19846. leftmost = start;
  19847. do {
  19848. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  19849. p = p.next;
  19850. } while (p !== start);
  19851. return leftmost;
  19852. } // check if a point lies within a convex triangle
  19853. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  19854. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  19855. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  19856. function isValidDiagonal(a, b) {
  19857. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && ( // dones't intersect other edges
  19858. locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && ( // locally visible
  19859. area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  19860. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  19861. } // signed area of a triangle
  19862. function area(p, q, r) {
  19863. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  19864. } // check if two points are equal
  19865. function equals(p1, p2) {
  19866. return p1.x === p2.x && p1.y === p2.y;
  19867. } // check if two segments intersect
  19868. function intersects(p1, q1, p2, q2) {
  19869. const o1 = sign(area(p1, q1, p2));
  19870. const o2 = sign(area(p1, q1, q2));
  19871. const o3 = sign(area(p2, q2, p1));
  19872. const o4 = sign(area(p2, q2, q1));
  19873. if (o1 !== o2 && o3 !== o4) return true; // general case
  19874. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  19875. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  19876. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  19877. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  19878. return false;
  19879. } // for collinear points p, q, r, check if point q lies on segment pr
  19880. function onSegment(p, q, r) {
  19881. 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);
  19882. }
  19883. function sign(num) {
  19884. return num > 0 ? 1 : num < 0 ? -1 : 0;
  19885. } // check if a polygon diagonal intersects any polygon segments
  19886. function intersectsPolygon(a, b) {
  19887. let p = a;
  19888. do {
  19889. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects(p, p.next, a, b)) return true;
  19890. p = p.next;
  19891. } while (p !== a);
  19892. return false;
  19893. } // check if a polygon diagonal is locally inside the polygon
  19894. function locallyInside(a, b) {
  19895. return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  19896. } // check if the middle point of a polygon diagonal is inside the polygon
  19897. function middleInside(a, b) {
  19898. let p = a,
  19899. inside = false;
  19900. const px = (a.x + b.x) / 2,
  19901. py = (a.y + b.y) / 2;
  19902. do {
  19903. if (p.y > py !== p.next.y > py && p.next.y !== p.y && px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x) inside = !inside;
  19904. p = p.next;
  19905. } while (p !== a);
  19906. return inside;
  19907. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  19908. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  19909. function splitPolygon(a, b) {
  19910. const a2 = new Node(a.i, a.x, a.y),
  19911. b2 = new Node(b.i, b.x, b.y),
  19912. an = a.next,
  19913. bp = b.prev;
  19914. a.next = b;
  19915. b.prev = a;
  19916. a2.next = an;
  19917. an.prev = a2;
  19918. b2.next = a2;
  19919. a2.prev = b2;
  19920. bp.next = b2;
  19921. b2.prev = bp;
  19922. return b2;
  19923. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  19924. function insertNode(i, x, y, last) {
  19925. const p = new Node(i, x, y);
  19926. if (!last) {
  19927. p.prev = p;
  19928. p.next = p;
  19929. } else {
  19930. p.next = last.next;
  19931. p.prev = last;
  19932. last.next.prev = p;
  19933. last.next = p;
  19934. }
  19935. return p;
  19936. }
  19937. function removeNode(p) {
  19938. p.next.prev = p.prev;
  19939. p.prev.next = p.next;
  19940. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  19941. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  19942. }
  19943. function Node(i, x, y) {
  19944. // vertex index in coordinates array
  19945. this.i = i; // vertex coordinates
  19946. this.x = x;
  19947. this.y = y; // previous and next vertex nodes in a polygon ring
  19948. this.prev = null;
  19949. this.next = null; // z-order curve value
  19950. this.z = null; // previous and next nodes in z-order
  19951. this.prevZ = null;
  19952. this.nextZ = null; // indicates whether this is a steiner point
  19953. this.steiner = false;
  19954. }
  19955. function signedArea(data, start, end, dim) {
  19956. let sum = 0;
  19957. for (let i = start, j = end - dim; i < end; i += dim) {
  19958. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  19959. j = i;
  19960. }
  19961. return sum;
  19962. }
  19963. class ShapeUtils {
  19964. // calculate area of the contour polygon
  19965. static area(contour) {
  19966. const n = contour.length;
  19967. let a = 0.0;
  19968. for (let p = n - 1, q = 0; q < n; p = q++) {
  19969. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  19970. }
  19971. return a * 0.5;
  19972. }
  19973. static isClockWise(pts) {
  19974. return ShapeUtils.area(pts) < 0;
  19975. }
  19976. static triangulateShape(contour, holes) {
  19977. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  19978. const holeIndices = []; // array of hole indices
  19979. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  19980. removeDupEndPts(contour);
  19981. addContour(vertices, contour); //
  19982. let holeIndex = contour.length;
  19983. holes.forEach(removeDupEndPts);
  19984. for (let i = 0; i < holes.length; i++) {
  19985. holeIndices.push(holeIndex);
  19986. holeIndex += holes[i].length;
  19987. addContour(vertices, holes[i]);
  19988. } //
  19989. const triangles = Earcut.triangulate(vertices, holeIndices); //
  19990. for (let i = 0; i < triangles.length; i += 3) {
  19991. faces.push(triangles.slice(i, i + 3));
  19992. }
  19993. return faces;
  19994. }
  19995. }
  19996. function removeDupEndPts(points) {
  19997. const l = points.length;
  19998. if (l > 2 && points[l - 1].equals(points[0])) {
  19999. points.pop();
  20000. }
  20001. }
  20002. function addContour(vertices, contour) {
  20003. for (let i = 0; i < contour.length; i++) {
  20004. vertices.push(contour[i].x);
  20005. vertices.push(contour[i].y);
  20006. }
  20007. }
  20008. /**
  20009. * Creates extruded geometry from a path shape.
  20010. *
  20011. * parameters = {
  20012. *
  20013. * curveSegments: <int>, // number of points on the curves
  20014. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  20015. * depth: <float>, // Depth to extrude the shape
  20016. *
  20017. * bevelEnabled: <bool>, // turn on bevel
  20018. * bevelThickness: <float>, // how deep into the original shape bevel goes
  20019. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  20020. * bevelOffset: <float>, // how far from shape outline does bevel start
  20021. * bevelSegments: <int>, // number of bevel layers
  20022. *
  20023. * extrudePath: <THREE.Curve> // curve to extrude shape along
  20024. *
  20025. * UVGenerator: <Object> // object that provides UV generator functions
  20026. *
  20027. * }
  20028. */
  20029. class ExtrudeGeometry extends BufferGeometry {
  20030. 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 = {}) {
  20031. super();
  20032. this.type = 'ExtrudeGeometry';
  20033. this.parameters = {
  20034. shapes: shapes,
  20035. options: options
  20036. };
  20037. shapes = Array.isArray(shapes) ? shapes : [shapes];
  20038. const scope = this;
  20039. const verticesArray = [];
  20040. const uvArray = [];
  20041. for (let i = 0, l = shapes.length; i < l; i++) {
  20042. const shape = shapes[i];
  20043. addShape(shape);
  20044. } // build geometry
  20045. this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  20046. this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  20047. this.computeVertexNormals(); // functions
  20048. function addShape(shape) {
  20049. const placeholder = []; // options
  20050. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  20051. const steps = options.steps !== undefined ? options.steps : 1;
  20052. let depth = options.depth !== undefined ? options.depth : 1;
  20053. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  20054. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  20055. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  20056. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  20057. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  20058. const extrudePath = options.extrudePath;
  20059. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  20060. if (options.amount !== undefined) {
  20061. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  20062. depth = options.amount;
  20063. } //
  20064. let extrudePts,
  20065. extrudeByPath = false;
  20066. let splineTube, binormal, normal, position2;
  20067. if (extrudePath) {
  20068. extrudePts = extrudePath.getSpacedPoints(steps);
  20069. extrudeByPath = true;
  20070. bevelEnabled = false; // bevels not supported for path extrusion
  20071. // SETUP TNB variables
  20072. // TODO1 - have a .isClosed in spline?
  20073. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  20074. binormal = new Vector3();
  20075. normal = new Vector3();
  20076. position2 = new Vector3();
  20077. } // Safeguards if bevels are not enabled
  20078. if (!bevelEnabled) {
  20079. bevelSegments = 0;
  20080. bevelThickness = 0;
  20081. bevelSize = 0;
  20082. bevelOffset = 0;
  20083. } // Variables initialization
  20084. const shapePoints = shape.extractPoints(curveSegments);
  20085. let vertices = shapePoints.shape;
  20086. const holes = shapePoints.holes;
  20087. const reverse = !ShapeUtils.isClockWise(vertices);
  20088. if (reverse) {
  20089. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  20090. for (let h = 0, hl = holes.length; h < hl; h++) {
  20091. const ahole = holes[h];
  20092. if (ShapeUtils.isClockWise(ahole)) {
  20093. holes[h] = ahole.reverse();
  20094. }
  20095. }
  20096. }
  20097. const faces = ShapeUtils.triangulateShape(vertices, holes);
  20098. /* Vertices */
  20099. const contour = vertices; // vertices has all points but contour has only points of circumference
  20100. for (let h = 0, hl = holes.length; h < hl; h++) {
  20101. const ahole = holes[h];
  20102. vertices = vertices.concat(ahole);
  20103. }
  20104. function scalePt2(pt, vec, size) {
  20105. if (!vec) console.error('THREE.ExtrudeGeometry: vec does not exist');
  20106. return vec.clone().multiplyScalar(size).add(pt);
  20107. }
  20108. const vlen = vertices.length,
  20109. flen = faces.length; // Find directions for point movement
  20110. function getBevelVec(inPt, inPrev, inNext) {
  20111. // computes for inPt the corresponding point inPt' on a new contour
  20112. // shifted by 1 unit (length of normalized vector) to the left
  20113. // if we walk along contour clockwise, this new contour is outside the old one
  20114. //
  20115. // inPt' is the intersection of the two lines parallel to the two
  20116. // adjacent edges of inPt at a distance of 1 unit on the left side.
  20117. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  20118. // good reading for geometry algorithms (here: line-line intersection)
  20119. // http://geomalgorithms.com/a05-_intersect-1.html
  20120. const v_prev_x = inPt.x - inPrev.x,
  20121. v_prev_y = inPt.y - inPrev.y;
  20122. const v_next_x = inNext.x - inPt.x,
  20123. v_next_y = inNext.y - inPt.y;
  20124. const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  20125. const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  20126. if (Math.abs(collinear0) > Number.EPSILON) {
  20127. // not collinear
  20128. // length of vectors for normalizing
  20129. const v_prev_len = Math.sqrt(v_prev_lensq);
  20130. const v_next_len = Math.sqrt(v_next_x * v_next_x + v_next_y * v_next_y); // shift adjacent points by unit vectors to the left
  20131. const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  20132. const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  20133. const ptNextShift_x = inNext.x - v_next_y / v_next_len;
  20134. const ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  20135. const sf = ((ptNextShift_x - ptPrevShift_x) * v_next_y - (ptNextShift_y - ptPrevShift_y) * v_next_x) / (v_prev_x * v_next_y - v_prev_y * v_next_x); // vector from inPt to intersection point
  20136. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  20137. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  20138. // but prevent crazy spikes
  20139. const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  20140. if (v_trans_lensq <= 2) {
  20141. return new Vector2(v_trans_x, v_trans_y);
  20142. } else {
  20143. shrink_by = Math.sqrt(v_trans_lensq / 2);
  20144. }
  20145. } else {
  20146. // handle special case of collinear edges
  20147. let direction_eq = false; // assumes: opposite
  20148. if (v_prev_x > Number.EPSILON) {
  20149. if (v_next_x > Number.EPSILON) {
  20150. direction_eq = true;
  20151. }
  20152. } else {
  20153. if (v_prev_x < -Number.EPSILON) {
  20154. if (v_next_x < -Number.EPSILON) {
  20155. direction_eq = true;
  20156. }
  20157. } else {
  20158. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  20159. direction_eq = true;
  20160. }
  20161. }
  20162. }
  20163. if (direction_eq) {
  20164. // console.log("Warning: lines are a straight sequence");
  20165. v_trans_x = -v_prev_y;
  20166. v_trans_y = v_prev_x;
  20167. shrink_by = Math.sqrt(v_prev_lensq);
  20168. } else {
  20169. // console.log("Warning: lines are a straight spike");
  20170. v_trans_x = v_prev_x;
  20171. v_trans_y = v_prev_y;
  20172. shrink_by = Math.sqrt(v_prev_lensq / 2);
  20173. }
  20174. }
  20175. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  20176. }
  20177. const contourMovements = [];
  20178. for (let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  20179. if (j === il) j = 0;
  20180. if (k === il) k = 0; // (j)---(i)---(k)
  20181. // console.log('i,j,k', i, j , k)
  20182. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  20183. }
  20184. const holesMovements = [];
  20185. let oneHoleMovements,
  20186. verticesMovements = contourMovements.concat();
  20187. for (let h = 0, hl = holes.length; h < hl; h++) {
  20188. const ahole = holes[h];
  20189. oneHoleMovements = [];
  20190. for (let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  20191. if (j === il) j = 0;
  20192. if (k === il) k = 0; // (j)---(i)---(k)
  20193. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  20194. }
  20195. holesMovements.push(oneHoleMovements);
  20196. verticesMovements = verticesMovements.concat(oneHoleMovements);
  20197. } // Loop bevelSegments, 1 for the front, 1 for the back
  20198. for (let b = 0; b < bevelSegments; b++) {
  20199. //for ( b = bevelSegments; b > 0; b -- ) {
  20200. const t = b / bevelSegments;
  20201. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  20202. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  20203. for (let i = 0, il = contour.length; i < il; i++) {
  20204. const vert = scalePt2(contour[i], contourMovements[i], bs);
  20205. v(vert.x, vert.y, -z);
  20206. } // expand holes
  20207. for (let h = 0, hl = holes.length; h < hl; h++) {
  20208. const ahole = holes[h];
  20209. oneHoleMovements = holesMovements[h];
  20210. for (let i = 0, il = ahole.length; i < il; i++) {
  20211. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  20212. v(vert.x, vert.y, -z);
  20213. }
  20214. }
  20215. }
  20216. const bs = bevelSize + bevelOffset; // Back facing vertices
  20217. for (let i = 0; i < vlen; i++) {
  20218. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  20219. if (!extrudeByPath) {
  20220. v(vert.x, vert.y, 0);
  20221. } else {
  20222. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  20223. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  20224. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  20225. position2.copy(extrudePts[0]).add(normal).add(binormal);
  20226. v(position2.x, position2.y, position2.z);
  20227. }
  20228. } // Add stepped vertices...
  20229. // Including front facing vertices
  20230. for (let s = 1; s <= steps; s++) {
  20231. for (let i = 0; i < vlen; i++) {
  20232. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  20233. if (!extrudeByPath) {
  20234. v(vert.x, vert.y, depth / steps * s);
  20235. } else {
  20236. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  20237. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  20238. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  20239. position2.copy(extrudePts[s]).add(normal).add(binormal);
  20240. v(position2.x, position2.y, position2.z);
  20241. }
  20242. }
  20243. } // Add bevel segments planes
  20244. //for ( b = 1; b <= bevelSegments; b ++ ) {
  20245. for (let b = bevelSegments - 1; b >= 0; b--) {
  20246. const t = b / bevelSegments;
  20247. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  20248. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  20249. for (let i = 0, il = contour.length; i < il; i++) {
  20250. const vert = scalePt2(contour[i], contourMovements[i], bs);
  20251. v(vert.x, vert.y, depth + z);
  20252. } // expand holes
  20253. for (let h = 0, hl = holes.length; h < hl; h++) {
  20254. const ahole = holes[h];
  20255. oneHoleMovements = holesMovements[h];
  20256. for (let i = 0, il = ahole.length; i < il; i++) {
  20257. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  20258. if (!extrudeByPath) {
  20259. v(vert.x, vert.y, depth + z);
  20260. } else {
  20261. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  20262. }
  20263. }
  20264. }
  20265. }
  20266. /* Faces */
  20267. // Top and bottom faces
  20268. buildLidFaces(); // Sides faces
  20269. buildSideFaces(); ///// Internal functions
  20270. function buildLidFaces() {
  20271. const start = verticesArray.length / 3;
  20272. if (bevelEnabled) {
  20273. let layer = 0; // steps + 1
  20274. let offset = vlen * layer; // Bottom faces
  20275. for (let i = 0; i < flen; i++) {
  20276. const face = faces[i];
  20277. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  20278. }
  20279. layer = steps + bevelSegments * 2;
  20280. offset = vlen * layer; // Top faces
  20281. for (let i = 0; i < flen; i++) {
  20282. const face = faces[i];
  20283. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  20284. }
  20285. } else {
  20286. // Bottom faces
  20287. for (let i = 0; i < flen; i++) {
  20288. const face = faces[i];
  20289. f3(face[2], face[1], face[0]);
  20290. } // Top faces
  20291. for (let i = 0; i < flen; i++) {
  20292. const face = faces[i];
  20293. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  20294. }
  20295. }
  20296. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  20297. } // Create faces for the z-sides of the shape
  20298. function buildSideFaces() {
  20299. const start = verticesArray.length / 3;
  20300. let layeroffset = 0;
  20301. sidewalls(contour, layeroffset);
  20302. layeroffset += contour.length;
  20303. for (let h = 0, hl = holes.length; h < hl; h++) {
  20304. const ahole = holes[h];
  20305. sidewalls(ahole, layeroffset); //, true
  20306. layeroffset += ahole.length;
  20307. }
  20308. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  20309. }
  20310. function sidewalls(contour, layeroffset) {
  20311. let i = contour.length;
  20312. while (--i >= 0) {
  20313. const j = i;
  20314. let k = i - 1;
  20315. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  20316. for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) {
  20317. const slen1 = vlen * s;
  20318. const slen2 = vlen * (s + 1);
  20319. const a = layeroffset + j + slen1,
  20320. b = layeroffset + k + slen1,
  20321. c = layeroffset + k + slen2,
  20322. d = layeroffset + j + slen2;
  20323. f4(a, b, c, d);
  20324. }
  20325. }
  20326. }
  20327. function v(x, y, z) {
  20328. placeholder.push(x);
  20329. placeholder.push(y);
  20330. placeholder.push(z);
  20331. }
  20332. function f3(a, b, c) {
  20333. addVertex(a);
  20334. addVertex(b);
  20335. addVertex(c);
  20336. const nextIndex = verticesArray.length / 3;
  20337. const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  20338. addUV(uvs[0]);
  20339. addUV(uvs[1]);
  20340. addUV(uvs[2]);
  20341. }
  20342. function f4(a, b, c, d) {
  20343. addVertex(a);
  20344. addVertex(b);
  20345. addVertex(d);
  20346. addVertex(b);
  20347. addVertex(c);
  20348. addVertex(d);
  20349. const nextIndex = verticesArray.length / 3;
  20350. const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  20351. addUV(uvs[0]);
  20352. addUV(uvs[1]);
  20353. addUV(uvs[3]);
  20354. addUV(uvs[1]);
  20355. addUV(uvs[2]);
  20356. addUV(uvs[3]);
  20357. }
  20358. function addVertex(index) {
  20359. verticesArray.push(placeholder[index * 3 + 0]);
  20360. verticesArray.push(placeholder[index * 3 + 1]);
  20361. verticesArray.push(placeholder[index * 3 + 2]);
  20362. }
  20363. function addUV(vector2) {
  20364. uvArray.push(vector2.x);
  20365. uvArray.push(vector2.y);
  20366. }
  20367. }
  20368. }
  20369. toJSON() {
  20370. const data = super.toJSON();
  20371. const shapes = this.parameters.shapes;
  20372. const options = this.parameters.options;
  20373. return toJSON$1(shapes, options, data);
  20374. }
  20375. static fromJSON(data, shapes) {
  20376. const geometryShapes = [];
  20377. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  20378. const shape = shapes[data.shapes[j]];
  20379. geometryShapes.push(shape);
  20380. }
  20381. const extrudePath = data.options.extrudePath;
  20382. if (extrudePath !== undefined) {
  20383. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  20384. }
  20385. return new ExtrudeGeometry(geometryShapes, data.options);
  20386. }
  20387. }
  20388. const WorldUVGenerator = {
  20389. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  20390. const a_x = vertices[indexA * 3];
  20391. const a_y = vertices[indexA * 3 + 1];
  20392. const b_x = vertices[indexB * 3];
  20393. const b_y = vertices[indexB * 3 + 1];
  20394. const c_x = vertices[indexC * 3];
  20395. const c_y = vertices[indexC * 3 + 1];
  20396. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  20397. },
  20398. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  20399. const a_x = vertices[indexA * 3];
  20400. const a_y = vertices[indexA * 3 + 1];
  20401. const a_z = vertices[indexA * 3 + 2];
  20402. const b_x = vertices[indexB * 3];
  20403. const b_y = vertices[indexB * 3 + 1];
  20404. const b_z = vertices[indexB * 3 + 2];
  20405. const c_x = vertices[indexC * 3];
  20406. const c_y = vertices[indexC * 3 + 1];
  20407. const c_z = vertices[indexC * 3 + 2];
  20408. const d_x = vertices[indexD * 3];
  20409. const d_y = vertices[indexD * 3 + 1];
  20410. const d_z = vertices[indexD * 3 + 2];
  20411. if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) {
  20412. return [new Vector2(a_x, 1 - a_z), new Vector2(b_x, 1 - b_z), new Vector2(c_x, 1 - c_z), new Vector2(d_x, 1 - d_z)];
  20413. } else {
  20414. return [new Vector2(a_y, 1 - a_z), new Vector2(b_y, 1 - b_z), new Vector2(c_y, 1 - c_z), new Vector2(d_y, 1 - d_z)];
  20415. }
  20416. }
  20417. };
  20418. function toJSON$1(shapes, options, data) {
  20419. data.shapes = [];
  20420. if (Array.isArray(shapes)) {
  20421. for (let i = 0, l = shapes.length; i < l; i++) {
  20422. const shape = shapes[i];
  20423. data.shapes.push(shape.uuid);
  20424. }
  20425. } else {
  20426. data.shapes.push(shapes.uuid);
  20427. }
  20428. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  20429. return data;
  20430. }
  20431. class IcosahedronGeometry extends PolyhedronGeometry {
  20432. constructor(radius = 1, detail = 0) {
  20433. const t = (1 + Math.sqrt(5)) / 2;
  20434. const vertices = [-1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, 0, -1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, t, 0, -1, t, 0, 1, -t, 0, -1, -t, 0, 1];
  20435. const indices = [0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1];
  20436. super(vertices, indices, radius, detail);
  20437. this.type = 'IcosahedronGeometry';
  20438. this.parameters = {
  20439. radius: radius,
  20440. detail: detail
  20441. };
  20442. }
  20443. static fromJSON(data) {
  20444. return new IcosahedronGeometry(data.radius, data.detail);
  20445. }
  20446. }
  20447. class LatheGeometry extends BufferGeometry {
  20448. 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) {
  20449. super();
  20450. this.type = 'LatheGeometry';
  20451. this.parameters = {
  20452. points: points,
  20453. segments: segments,
  20454. phiStart: phiStart,
  20455. phiLength: phiLength
  20456. };
  20457. segments = Math.floor(segments); // clamp phiLength so it's in range of [ 0, 2PI ]
  20458. phiLength = clamp(phiLength, 0, Math.PI * 2); // buffers
  20459. const indices = [];
  20460. const vertices = [];
  20461. const uvs = [];
  20462. const initNormals = [];
  20463. const normals = []; // helper variables
  20464. const inverseSegments = 1.0 / segments;
  20465. const vertex = new Vector3();
  20466. const uv = new Vector2();
  20467. const normal = new Vector3();
  20468. const curNormal = new Vector3();
  20469. const prevNormal = new Vector3();
  20470. let dx = 0;
  20471. let dy = 0; // pre-compute normals for initial "meridian"
  20472. for (let j = 0; j <= points.length - 1; j++) {
  20473. switch (j) {
  20474. case 0:
  20475. // special handling for 1st vertex on path
  20476. dx = points[j + 1].x - points[j].x;
  20477. dy = points[j + 1].y - points[j].y;
  20478. normal.x = dy * 1.0;
  20479. normal.y = -dx;
  20480. normal.z = dy * 0.0;
  20481. prevNormal.copy(normal);
  20482. normal.normalize();
  20483. initNormals.push(normal.x, normal.y, normal.z);
  20484. break;
  20485. case points.length - 1:
  20486. // special handling for last Vertex on path
  20487. initNormals.push(prevNormal.x, prevNormal.y, prevNormal.z);
  20488. break;
  20489. default:
  20490. // default handling for all vertices in between
  20491. dx = points[j + 1].x - points[j].x;
  20492. dy = points[j + 1].y - points[j].y;
  20493. normal.x = dy * 1.0;
  20494. normal.y = -dx;
  20495. normal.z = dy * 0.0;
  20496. curNormal.copy(normal);
  20497. normal.x += prevNormal.x;
  20498. normal.y += prevNormal.y;
  20499. normal.z += prevNormal.z;
  20500. normal.normalize();
  20501. initNormals.push(normal.x, normal.y, normal.z);
  20502. prevNormal.copy(curNormal);
  20503. }
  20504. } // generate vertices, uvs and normals
  20505. for (let i = 0; i <= segments; i++) {
  20506. const phi = phiStart + i * inverseSegments * phiLength;
  20507. const sin = Math.sin(phi);
  20508. const cos = Math.cos(phi);
  20509. for (let j = 0; j <= points.length - 1; j++) {
  20510. // vertex
  20511. vertex.x = points[j].x * sin;
  20512. vertex.y = points[j].y;
  20513. vertex.z = points[j].x * cos;
  20514. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  20515. uv.x = i / segments;
  20516. uv.y = j / (points.length - 1);
  20517. uvs.push(uv.x, uv.y); // normal
  20518. const x = initNormals[3 * j + 0] * sin;
  20519. const y = initNormals[3 * j + 1];
  20520. const z = initNormals[3 * j + 0] * cos;
  20521. normals.push(x, y, z);
  20522. }
  20523. } // indices
  20524. for (let i = 0; i < segments; i++) {
  20525. for (let j = 0; j < points.length - 1; j++) {
  20526. const base = j + i * points.length;
  20527. const a = base;
  20528. const b = base + points.length;
  20529. const c = base + points.length + 1;
  20530. const d = base + 1; // faces
  20531. indices.push(a, b, d);
  20532. indices.push(b, c, d);
  20533. }
  20534. } // build geometry
  20535. this.setIndex(indices);
  20536. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20537. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20538. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20539. }
  20540. static fromJSON(data) {
  20541. return new LatheGeometry(data.points, data.segments, data.phiStart, data.phiLength);
  20542. }
  20543. }
  20544. class OctahedronGeometry extends PolyhedronGeometry {
  20545. constructor(radius = 1, detail = 0) {
  20546. const vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  20547. const indices = [0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2];
  20548. super(vertices, indices, radius, detail);
  20549. this.type = 'OctahedronGeometry';
  20550. this.parameters = {
  20551. radius: radius,
  20552. detail: detail
  20553. };
  20554. }
  20555. static fromJSON(data) {
  20556. return new OctahedronGeometry(data.radius, data.detail);
  20557. }
  20558. }
  20559. class RingGeometry extends BufferGeometry {
  20560. constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) {
  20561. super();
  20562. this.type = 'RingGeometry';
  20563. this.parameters = {
  20564. innerRadius: innerRadius,
  20565. outerRadius: outerRadius,
  20566. thetaSegments: thetaSegments,
  20567. phiSegments: phiSegments,
  20568. thetaStart: thetaStart,
  20569. thetaLength: thetaLength
  20570. };
  20571. thetaSegments = Math.max(3, thetaSegments);
  20572. phiSegments = Math.max(1, phiSegments); // buffers
  20573. const indices = [];
  20574. const vertices = [];
  20575. const normals = [];
  20576. const uvs = []; // some helper variables
  20577. let radius = innerRadius;
  20578. const radiusStep = (outerRadius - innerRadius) / phiSegments;
  20579. const vertex = new Vector3();
  20580. const uv = new Vector2(); // generate vertices, normals and uvs
  20581. for (let j = 0; j <= phiSegments; j++) {
  20582. for (let i = 0; i <= thetaSegments; i++) {
  20583. // values are generate from the inside of the ring to the outside
  20584. const segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  20585. vertex.x = radius * Math.cos(segment);
  20586. vertex.y = radius * Math.sin(segment);
  20587. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20588. normals.push(0, 0, 1); // uv
  20589. uv.x = (vertex.x / outerRadius + 1) / 2;
  20590. uv.y = (vertex.y / outerRadius + 1) / 2;
  20591. uvs.push(uv.x, uv.y);
  20592. } // increase the radius for next row of vertices
  20593. radius += radiusStep;
  20594. } // indices
  20595. for (let j = 0; j < phiSegments; j++) {
  20596. const thetaSegmentLevel = j * (thetaSegments + 1);
  20597. for (let i = 0; i < thetaSegments; i++) {
  20598. const segment = i + thetaSegmentLevel;
  20599. const a = segment;
  20600. const b = segment + thetaSegments + 1;
  20601. const c = segment + thetaSegments + 2;
  20602. const d = segment + 1; // faces
  20603. indices.push(a, b, d);
  20604. indices.push(b, c, d);
  20605. }
  20606. } // build geometry
  20607. this.setIndex(indices);
  20608. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20609. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20610. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20611. }
  20612. static fromJSON(data) {
  20613. return new RingGeometry(data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  20614. }
  20615. }
  20616. class ShapeGeometry extends BufferGeometry {
  20617. constructor(shapes = new Shape([new Vector2(0, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), curveSegments = 12) {
  20618. super();
  20619. this.type = 'ShapeGeometry';
  20620. this.parameters = {
  20621. shapes: shapes,
  20622. curveSegments: curveSegments
  20623. }; // buffers
  20624. const indices = [];
  20625. const vertices = [];
  20626. const normals = [];
  20627. const uvs = []; // helper variables
  20628. let groupStart = 0;
  20629. let groupCount = 0; // allow single and array values for "shapes" parameter
  20630. if (Array.isArray(shapes) === false) {
  20631. addShape(shapes);
  20632. } else {
  20633. for (let i = 0; i < shapes.length; i++) {
  20634. addShape(shapes[i]);
  20635. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  20636. groupStart += groupCount;
  20637. groupCount = 0;
  20638. }
  20639. } // build geometry
  20640. this.setIndex(indices);
  20641. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20642. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20643. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  20644. function addShape(shape) {
  20645. const indexOffset = vertices.length / 3;
  20646. const points = shape.extractPoints(curveSegments);
  20647. let shapeVertices = points.shape;
  20648. const shapeHoles = points.holes; // check direction of vertices
  20649. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  20650. shapeVertices = shapeVertices.reverse();
  20651. }
  20652. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  20653. const shapeHole = shapeHoles[i];
  20654. if (ShapeUtils.isClockWise(shapeHole) === true) {
  20655. shapeHoles[i] = shapeHole.reverse();
  20656. }
  20657. }
  20658. const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  20659. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  20660. const shapeHole = shapeHoles[i];
  20661. shapeVertices = shapeVertices.concat(shapeHole);
  20662. } // vertices, normals, uvs
  20663. for (let i = 0, l = shapeVertices.length; i < l; i++) {
  20664. const vertex = shapeVertices[i];
  20665. vertices.push(vertex.x, vertex.y, 0);
  20666. normals.push(0, 0, 1);
  20667. uvs.push(vertex.x, vertex.y); // world uvs
  20668. } // incides
  20669. for (let i = 0, l = faces.length; i < l; i++) {
  20670. const face = faces[i];
  20671. const a = face[0] + indexOffset;
  20672. const b = face[1] + indexOffset;
  20673. const c = face[2] + indexOffset;
  20674. indices.push(a, b, c);
  20675. groupCount += 3;
  20676. }
  20677. }
  20678. }
  20679. toJSON() {
  20680. const data = super.toJSON();
  20681. const shapes = this.parameters.shapes;
  20682. return toJSON(shapes, data);
  20683. }
  20684. static fromJSON(data, shapes) {
  20685. const geometryShapes = [];
  20686. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  20687. const shape = shapes[data.shapes[j]];
  20688. geometryShapes.push(shape);
  20689. }
  20690. return new ShapeGeometry(geometryShapes, data.curveSegments);
  20691. }
  20692. }
  20693. function toJSON(shapes, data) {
  20694. data.shapes = [];
  20695. if (Array.isArray(shapes)) {
  20696. for (let i = 0, l = shapes.length; i < l; i++) {
  20697. const shape = shapes[i];
  20698. data.shapes.push(shape.uuid);
  20699. }
  20700. } else {
  20701. data.shapes.push(shapes.uuid);
  20702. }
  20703. return data;
  20704. }
  20705. class SphereGeometry extends BufferGeometry {
  20706. constructor(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) {
  20707. super();
  20708. this.type = 'SphereGeometry';
  20709. this.parameters = {
  20710. radius: radius,
  20711. widthSegments: widthSegments,
  20712. heightSegments: heightSegments,
  20713. phiStart: phiStart,
  20714. phiLength: phiLength,
  20715. thetaStart: thetaStart,
  20716. thetaLength: thetaLength
  20717. };
  20718. widthSegments = Math.max(3, Math.floor(widthSegments));
  20719. heightSegments = Math.max(2, Math.floor(heightSegments));
  20720. const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  20721. let index = 0;
  20722. const grid = [];
  20723. const vertex = new Vector3();
  20724. const normal = new Vector3(); // buffers
  20725. const indices = [];
  20726. const vertices = [];
  20727. const normals = [];
  20728. const uvs = []; // generate vertices, normals and uvs
  20729. for (let iy = 0; iy <= heightSegments; iy++) {
  20730. const verticesRow = [];
  20731. const v = iy / heightSegments; // special case for the poles
  20732. let uOffset = 0;
  20733. if (iy == 0 && thetaStart == 0) {
  20734. uOffset = 0.5 / widthSegments;
  20735. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  20736. uOffset = -0.5 / widthSegments;
  20737. }
  20738. for (let ix = 0; ix <= widthSegments; ix++) {
  20739. const u = ix / widthSegments; // vertex
  20740. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  20741. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  20742. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  20743. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20744. normal.copy(vertex).normalize();
  20745. normals.push(normal.x, normal.y, normal.z); // uv
  20746. uvs.push(u + uOffset, 1 - v);
  20747. verticesRow.push(index++);
  20748. }
  20749. grid.push(verticesRow);
  20750. } // indices
  20751. for (let iy = 0; iy < heightSegments; iy++) {
  20752. for (let ix = 0; ix < widthSegments; ix++) {
  20753. const a = grid[iy][ix + 1];
  20754. const b = grid[iy][ix];
  20755. const c = grid[iy + 1][ix];
  20756. const d = grid[iy + 1][ix + 1];
  20757. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  20758. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  20759. }
  20760. } // build geometry
  20761. this.setIndex(indices);
  20762. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20763. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20764. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20765. }
  20766. static fromJSON(data) {
  20767. return new SphereGeometry(data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  20768. }
  20769. }
  20770. class TetrahedronGeometry extends PolyhedronGeometry {
  20771. constructor(radius = 1, detail = 0) {
  20772. const vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  20773. const indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  20774. super(vertices, indices, radius, detail);
  20775. this.type = 'TetrahedronGeometry';
  20776. this.parameters = {
  20777. radius: radius,
  20778. detail: detail
  20779. };
  20780. }
  20781. static fromJSON(data) {
  20782. return new TetrahedronGeometry(data.radius, data.detail);
  20783. }
  20784. }
  20785. class TorusGeometry extends BufferGeometry {
  20786. constructor(radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) {
  20787. super();
  20788. this.type = 'TorusGeometry';
  20789. this.parameters = {
  20790. radius: radius,
  20791. tube: tube,
  20792. radialSegments: radialSegments,
  20793. tubularSegments: tubularSegments,
  20794. arc: arc
  20795. };
  20796. radialSegments = Math.floor(radialSegments);
  20797. tubularSegments = Math.floor(tubularSegments); // buffers
  20798. const indices = [];
  20799. const vertices = [];
  20800. const normals = [];
  20801. const uvs = []; // helper variables
  20802. const center = new Vector3();
  20803. const vertex = new Vector3();
  20804. const normal = new Vector3(); // generate vertices, normals and uvs
  20805. for (let j = 0; j <= radialSegments; j++) {
  20806. for (let i = 0; i <= tubularSegments; i++) {
  20807. const u = i / tubularSegments * arc;
  20808. const v = j / radialSegments * Math.PI * 2; // vertex
  20809. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  20810. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  20811. vertex.z = tube * Math.sin(v);
  20812. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20813. center.x = radius * Math.cos(u);
  20814. center.y = radius * Math.sin(u);
  20815. normal.subVectors(vertex, center).normalize();
  20816. normals.push(normal.x, normal.y, normal.z); // uv
  20817. uvs.push(i / tubularSegments);
  20818. uvs.push(j / radialSegments);
  20819. }
  20820. } // generate indices
  20821. for (let j = 1; j <= radialSegments; j++) {
  20822. for (let i = 1; i <= tubularSegments; i++) {
  20823. // indices
  20824. const a = (tubularSegments + 1) * j + i - 1;
  20825. const b = (tubularSegments + 1) * (j - 1) + i - 1;
  20826. const c = (tubularSegments + 1) * (j - 1) + i;
  20827. const d = (tubularSegments + 1) * j + i; // faces
  20828. indices.push(a, b, d);
  20829. indices.push(b, c, d);
  20830. }
  20831. } // build geometry
  20832. this.setIndex(indices);
  20833. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20834. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20835. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20836. }
  20837. static fromJSON(data) {
  20838. return new TorusGeometry(data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  20839. }
  20840. }
  20841. class TorusKnotGeometry extends BufferGeometry {
  20842. constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) {
  20843. super();
  20844. this.type = 'TorusKnotGeometry';
  20845. this.parameters = {
  20846. radius: radius,
  20847. tube: tube,
  20848. tubularSegments: tubularSegments,
  20849. radialSegments: radialSegments,
  20850. p: p,
  20851. q: q
  20852. };
  20853. tubularSegments = Math.floor(tubularSegments);
  20854. radialSegments = Math.floor(radialSegments); // buffers
  20855. const indices = [];
  20856. const vertices = [];
  20857. const normals = [];
  20858. const uvs = []; // helper variables
  20859. const vertex = new Vector3();
  20860. const normal = new Vector3();
  20861. const P1 = new Vector3();
  20862. const P2 = new Vector3();
  20863. const B = new Vector3();
  20864. const T = new Vector3();
  20865. const N = new Vector3(); // generate vertices, normals and uvs
  20866. for (let i = 0; i <= tubularSegments; ++i) {
  20867. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  20868. const u = i / tubularSegments * p * Math.PI * 2; // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  20869. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  20870. calculatePositionOnCurve(u, p, q, radius, P1);
  20871. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  20872. T.subVectors(P2, P1);
  20873. N.addVectors(P2, P1);
  20874. B.crossVectors(T, N);
  20875. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  20876. B.normalize();
  20877. N.normalize();
  20878. for (let j = 0; j <= radialSegments; ++j) {
  20879. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  20880. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  20881. const v = j / radialSegments * Math.PI * 2;
  20882. const cx = -tube * Math.cos(v);
  20883. const cy = tube * Math.sin(v); // now calculate the final vertex position.
  20884. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  20885. vertex.x = P1.x + (cx * N.x + cy * B.x);
  20886. vertex.y = P1.y + (cx * N.y + cy * B.y);
  20887. vertex.z = P1.z + (cx * N.z + cy * B.z);
  20888. vertices.push(vertex.x, vertex.y, vertex.z); // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  20889. normal.subVectors(vertex, P1).normalize();
  20890. normals.push(normal.x, normal.y, normal.z); // uv
  20891. uvs.push(i / tubularSegments);
  20892. uvs.push(j / radialSegments);
  20893. }
  20894. } // generate indices
  20895. for (let j = 1; j <= tubularSegments; j++) {
  20896. for (let i = 1; i <= radialSegments; i++) {
  20897. // indices
  20898. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  20899. const b = (radialSegments + 1) * j + (i - 1);
  20900. const c = (radialSegments + 1) * j + i;
  20901. const d = (radialSegments + 1) * (j - 1) + i; // faces
  20902. indices.push(a, b, d);
  20903. indices.push(b, c, d);
  20904. }
  20905. } // build geometry
  20906. this.setIndex(indices);
  20907. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20908. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20909. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  20910. function calculatePositionOnCurve(u, p, q, radius, position) {
  20911. const cu = Math.cos(u);
  20912. const su = Math.sin(u);
  20913. const quOverP = q / p * u;
  20914. const cs = Math.cos(quOverP);
  20915. position.x = radius * (2 + cs) * 0.5 * cu;
  20916. position.y = radius * (2 + cs) * su * 0.5;
  20917. position.z = radius * Math.sin(quOverP) * 0.5;
  20918. }
  20919. }
  20920. static fromJSON(data) {
  20921. return new TorusKnotGeometry(data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  20922. }
  20923. }
  20924. class TubeGeometry extends BufferGeometry {
  20925. 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) {
  20926. super();
  20927. this.type = 'TubeGeometry';
  20928. this.parameters = {
  20929. path: path,
  20930. tubularSegments: tubularSegments,
  20931. radius: radius,
  20932. radialSegments: radialSegments,
  20933. closed: closed
  20934. };
  20935. const frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  20936. this.tangents = frames.tangents;
  20937. this.normals = frames.normals;
  20938. this.binormals = frames.binormals; // helper variables
  20939. const vertex = new Vector3();
  20940. const normal = new Vector3();
  20941. const uv = new Vector2();
  20942. let P = new Vector3(); // buffer
  20943. const vertices = [];
  20944. const normals = [];
  20945. const uvs = [];
  20946. const indices = []; // create buffer data
  20947. generateBufferData(); // build geometry
  20948. this.setIndex(indices);
  20949. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20950. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20951. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  20952. function generateBufferData() {
  20953. for (let i = 0; i < tubularSegments; i++) {
  20954. generateSegment(i);
  20955. } // if the geometry is not closed, generate the last row of vertices and normals
  20956. // at the regular position on the given path
  20957. //
  20958. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  20959. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  20960. // this makes it easy compute correct values for closed geometries
  20961. generateUVs(); // finally create faces
  20962. generateIndices();
  20963. }
  20964. function generateSegment(i) {
  20965. // we use getPointAt to sample evenly distributed points from the given path
  20966. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  20967. const N = frames.normals[i];
  20968. const B = frames.binormals[i]; // generate normals and vertices for the current segment
  20969. for (let j = 0; j <= radialSegments; j++) {
  20970. const v = j / radialSegments * Math.PI * 2;
  20971. const sin = Math.sin(v);
  20972. const cos = -Math.cos(v); // normal
  20973. normal.x = cos * N.x + sin * B.x;
  20974. normal.y = cos * N.y + sin * B.y;
  20975. normal.z = cos * N.z + sin * B.z;
  20976. normal.normalize();
  20977. normals.push(normal.x, normal.y, normal.z); // vertex
  20978. vertex.x = P.x + radius * normal.x;
  20979. vertex.y = P.y + radius * normal.y;
  20980. vertex.z = P.z + radius * normal.z;
  20981. vertices.push(vertex.x, vertex.y, vertex.z);
  20982. }
  20983. }
  20984. function generateIndices() {
  20985. for (let j = 1; j <= tubularSegments; j++) {
  20986. for (let i = 1; i <= radialSegments; i++) {
  20987. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  20988. const b = (radialSegments + 1) * j + (i - 1);
  20989. const c = (radialSegments + 1) * j + i;
  20990. const d = (radialSegments + 1) * (j - 1) + i; // faces
  20991. indices.push(a, b, d);
  20992. indices.push(b, c, d);
  20993. }
  20994. }
  20995. }
  20996. function generateUVs() {
  20997. for (let i = 0; i <= tubularSegments; i++) {
  20998. for (let j = 0; j <= radialSegments; j++) {
  20999. uv.x = i / tubularSegments;
  21000. uv.y = j / radialSegments;
  21001. uvs.push(uv.x, uv.y);
  21002. }
  21003. }
  21004. }
  21005. }
  21006. toJSON() {
  21007. const data = super.toJSON();
  21008. data.path = this.parameters.path.toJSON();
  21009. return data;
  21010. }
  21011. static fromJSON(data) {
  21012. // This only works for built-in curves (e.g. CatmullRomCurve3).
  21013. // User defined curves or instances of CurvePath will not be deserialized.
  21014. return new TubeGeometry(new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  21015. }
  21016. }
  21017. class WireframeGeometry extends BufferGeometry {
  21018. constructor(geometry = null) {
  21019. super();
  21020. this.type = 'WireframeGeometry';
  21021. this.parameters = {
  21022. geometry: geometry
  21023. };
  21024. if (geometry !== null) {
  21025. // buffer
  21026. const vertices = [];
  21027. const edges = new Set(); // helper variables
  21028. const start = new Vector3();
  21029. const end = new Vector3();
  21030. if (geometry.index !== null) {
  21031. // indexed BufferGeometry
  21032. const position = geometry.attributes.position;
  21033. const indices = geometry.index;
  21034. let groups = geometry.groups;
  21035. if (groups.length === 0) {
  21036. groups = [{
  21037. start: 0,
  21038. count: indices.count,
  21039. materialIndex: 0
  21040. }];
  21041. } // create a data structure that contains all eges without duplicates
  21042. for (let o = 0, ol = groups.length; o < ol; ++o) {
  21043. const group = groups[o];
  21044. const groupStart = group.start;
  21045. const groupCount = group.count;
  21046. for (let i = groupStart, l = groupStart + groupCount; i < l; i += 3) {
  21047. for (let j = 0; j < 3; j++) {
  21048. const index1 = indices.getX(i + j);
  21049. const index2 = indices.getX(i + (j + 1) % 3);
  21050. start.fromBufferAttribute(position, index1);
  21051. end.fromBufferAttribute(position, index2);
  21052. if (isUniqueEdge(start, end, edges) === true) {
  21053. vertices.push(start.x, start.y, start.z);
  21054. vertices.push(end.x, end.y, end.z);
  21055. }
  21056. }
  21057. }
  21058. }
  21059. } else {
  21060. // non-indexed BufferGeometry
  21061. const position = geometry.attributes.position;
  21062. for (let i = 0, l = position.count / 3; i < l; i++) {
  21063. for (let j = 0; j < 3; j++) {
  21064. // three edges per triangle, an edge is represented as (index1, index2)
  21065. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  21066. const index1 = 3 * i + j;
  21067. const index2 = 3 * i + (j + 1) % 3;
  21068. start.fromBufferAttribute(position, index1);
  21069. end.fromBufferAttribute(position, index2);
  21070. if (isUniqueEdge(start, end, edges) === true) {
  21071. vertices.push(start.x, start.y, start.z);
  21072. vertices.push(end.x, end.y, end.z);
  21073. }
  21074. }
  21075. }
  21076. } // build geometry
  21077. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21078. }
  21079. }
  21080. }
  21081. function isUniqueEdge(start, end, edges) {
  21082. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  21083. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  21084. if (edges.has(hash1) === true || edges.has(hash2) === true) {
  21085. return false;
  21086. } else {
  21087. edges.add(hash1, hash2);
  21088. return true;
  21089. }
  21090. }
  21091. var Geometries = /*#__PURE__*/Object.freeze({
  21092. __proto__: null,
  21093. BoxGeometry: BoxGeometry,
  21094. BoxBufferGeometry: BoxGeometry,
  21095. CircleGeometry: CircleGeometry,
  21096. CircleBufferGeometry: CircleGeometry,
  21097. ConeGeometry: ConeGeometry,
  21098. ConeBufferGeometry: ConeGeometry,
  21099. CylinderGeometry: CylinderGeometry,
  21100. CylinderBufferGeometry: CylinderGeometry,
  21101. DodecahedronGeometry: DodecahedronGeometry,
  21102. DodecahedronBufferGeometry: DodecahedronGeometry,
  21103. EdgesGeometry: EdgesGeometry,
  21104. ExtrudeGeometry: ExtrudeGeometry,
  21105. ExtrudeBufferGeometry: ExtrudeGeometry,
  21106. IcosahedronGeometry: IcosahedronGeometry,
  21107. IcosahedronBufferGeometry: IcosahedronGeometry,
  21108. LatheGeometry: LatheGeometry,
  21109. LatheBufferGeometry: LatheGeometry,
  21110. OctahedronGeometry: OctahedronGeometry,
  21111. OctahedronBufferGeometry: OctahedronGeometry,
  21112. PlaneGeometry: PlaneGeometry,
  21113. PlaneBufferGeometry: PlaneGeometry,
  21114. PolyhedronGeometry: PolyhedronGeometry,
  21115. PolyhedronBufferGeometry: PolyhedronGeometry,
  21116. RingGeometry: RingGeometry,
  21117. RingBufferGeometry: RingGeometry,
  21118. ShapeGeometry: ShapeGeometry,
  21119. ShapeBufferGeometry: ShapeGeometry,
  21120. SphereGeometry: SphereGeometry,
  21121. SphereBufferGeometry: SphereGeometry,
  21122. TetrahedronGeometry: TetrahedronGeometry,
  21123. TetrahedronBufferGeometry: TetrahedronGeometry,
  21124. TorusGeometry: TorusGeometry,
  21125. TorusBufferGeometry: TorusGeometry,
  21126. TorusKnotGeometry: TorusKnotGeometry,
  21127. TorusKnotBufferGeometry: TorusKnotGeometry,
  21128. TubeGeometry: TubeGeometry,
  21129. TubeBufferGeometry: TubeGeometry,
  21130. WireframeGeometry: WireframeGeometry
  21131. });
  21132. /**
  21133. * parameters = {
  21134. * color: <THREE.Color>
  21135. * }
  21136. */
  21137. class ShadowMaterial extends Material {
  21138. constructor(parameters) {
  21139. super();
  21140. this.type = 'ShadowMaterial';
  21141. this.color = new Color(0x000000);
  21142. this.transparent = true;
  21143. this.setValues(parameters);
  21144. }
  21145. copy(source) {
  21146. super.copy(source);
  21147. this.color.copy(source.color);
  21148. return this;
  21149. }
  21150. }
  21151. ShadowMaterial.prototype.isShadowMaterial = true;
  21152. /**
  21153. * parameters = {
  21154. * color: <hex>,
  21155. * roughness: <float>,
  21156. * metalness: <float>,
  21157. * opacity: <float>,
  21158. *
  21159. * map: new THREE.Texture( <Image> ),
  21160. *
  21161. * lightMap: new THREE.Texture( <Image> ),
  21162. * lightMapIntensity: <float>
  21163. *
  21164. * aoMap: new THREE.Texture( <Image> ),
  21165. * aoMapIntensity: <float>
  21166. *
  21167. * emissive: <hex>,
  21168. * emissiveIntensity: <float>
  21169. * emissiveMap: new THREE.Texture( <Image> ),
  21170. *
  21171. * bumpMap: new THREE.Texture( <Image> ),
  21172. * bumpScale: <float>,
  21173. *
  21174. * normalMap: new THREE.Texture( <Image> ),
  21175. * normalMapType: THREE.TangentSpaceNormalMap,
  21176. * normalScale: <Vector2>,
  21177. *
  21178. * displacementMap: new THREE.Texture( <Image> ),
  21179. * displacementScale: <float>,
  21180. * displacementBias: <float>,
  21181. *
  21182. * roughnessMap: new THREE.Texture( <Image> ),
  21183. *
  21184. * metalnessMap: new THREE.Texture( <Image> ),
  21185. *
  21186. * alphaMap: new THREE.Texture( <Image> ),
  21187. *
  21188. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21189. * envMapIntensity: <float>
  21190. *
  21191. * refractionRatio: <float>,
  21192. *
  21193. * wireframe: <boolean>,
  21194. * wireframeLinewidth: <float>,
  21195. *
  21196. * flatShading: <bool>
  21197. * }
  21198. */
  21199. class MeshStandardMaterial extends Material {
  21200. constructor(parameters) {
  21201. super();
  21202. this.defines = {
  21203. 'STANDARD': ''
  21204. };
  21205. this.type = 'MeshStandardMaterial';
  21206. this.color = new Color(0xffffff); // diffuse
  21207. this.roughness = 1.0;
  21208. this.metalness = 0.0;
  21209. this.map = null;
  21210. this.lightMap = null;
  21211. this.lightMapIntensity = 1.0;
  21212. this.aoMap = null;
  21213. this.aoMapIntensity = 1.0;
  21214. this.emissive = new Color(0x000000);
  21215. this.emissiveIntensity = 1.0;
  21216. this.emissiveMap = null;
  21217. this.bumpMap = null;
  21218. this.bumpScale = 1;
  21219. this.normalMap = null;
  21220. this.normalMapType = TangentSpaceNormalMap;
  21221. this.normalScale = new Vector2(1, 1);
  21222. this.displacementMap = null;
  21223. this.displacementScale = 1;
  21224. this.displacementBias = 0;
  21225. this.roughnessMap = null;
  21226. this.metalnessMap = null;
  21227. this.alphaMap = null;
  21228. this.envMap = null;
  21229. this.envMapIntensity = 1.0;
  21230. this.refractionRatio = 0.98;
  21231. this.wireframe = false;
  21232. this.wireframeLinewidth = 1;
  21233. this.wireframeLinecap = 'round';
  21234. this.wireframeLinejoin = 'round';
  21235. this.flatShading = false;
  21236. this.setValues(parameters);
  21237. }
  21238. copy(source) {
  21239. super.copy(source);
  21240. this.defines = {
  21241. 'STANDARD': ''
  21242. };
  21243. this.color.copy(source.color);
  21244. this.roughness = source.roughness;
  21245. this.metalness = source.metalness;
  21246. this.map = source.map;
  21247. this.lightMap = source.lightMap;
  21248. this.lightMapIntensity = source.lightMapIntensity;
  21249. this.aoMap = source.aoMap;
  21250. this.aoMapIntensity = source.aoMapIntensity;
  21251. this.emissive.copy(source.emissive);
  21252. this.emissiveMap = source.emissiveMap;
  21253. this.emissiveIntensity = source.emissiveIntensity;
  21254. this.bumpMap = source.bumpMap;
  21255. this.bumpScale = source.bumpScale;
  21256. this.normalMap = source.normalMap;
  21257. this.normalMapType = source.normalMapType;
  21258. this.normalScale.copy(source.normalScale);
  21259. this.displacementMap = source.displacementMap;
  21260. this.displacementScale = source.displacementScale;
  21261. this.displacementBias = source.displacementBias;
  21262. this.roughnessMap = source.roughnessMap;
  21263. this.metalnessMap = source.metalnessMap;
  21264. this.alphaMap = source.alphaMap;
  21265. this.envMap = source.envMap;
  21266. this.envMapIntensity = source.envMapIntensity;
  21267. this.refractionRatio = source.refractionRatio;
  21268. this.wireframe = source.wireframe;
  21269. this.wireframeLinewidth = source.wireframeLinewidth;
  21270. this.wireframeLinecap = source.wireframeLinecap;
  21271. this.wireframeLinejoin = source.wireframeLinejoin;
  21272. this.flatShading = source.flatShading;
  21273. return this;
  21274. }
  21275. }
  21276. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  21277. /**
  21278. * parameters = {
  21279. * clearcoat: <float>,
  21280. * clearcoatMap: new THREE.Texture( <Image> ),
  21281. * clearcoatRoughness: <float>,
  21282. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  21283. * clearcoatNormalScale: <Vector2>,
  21284. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  21285. *
  21286. * ior: <float>,
  21287. * reflectivity: <float>,
  21288. *
  21289. * sheen: <float>,
  21290. * sheenColor: <Color>,
  21291. * sheenColorMap: new THREE.Texture( <Image> ),
  21292. * sheenRoughness: <float>,
  21293. * sheenRoughnessMap: new THREE.Texture( <Image> ),
  21294. *
  21295. * transmission: <float>,
  21296. * transmissionMap: new THREE.Texture( <Image> ),
  21297. *
  21298. * thickness: <float>,
  21299. * thicknessMap: new THREE.Texture( <Image> ),
  21300. * attenuationDistance: <float>,
  21301. * attenuationColor: <Color>,
  21302. *
  21303. * specularIntensity: <float>,
  21304. * specularIntensityMap: new THREE.Texture( <Image> ),
  21305. * specularColor: <Color>,
  21306. * specularColorMap: new THREE.Texture( <Image> )
  21307. * }
  21308. */
  21309. class MeshPhysicalMaterial extends MeshStandardMaterial {
  21310. constructor(parameters) {
  21311. super();
  21312. this.defines = {
  21313. 'STANDARD': '',
  21314. 'PHYSICAL': ''
  21315. };
  21316. this.type = 'MeshPhysicalMaterial';
  21317. this.clearcoatMap = null;
  21318. this.clearcoatRoughness = 0.0;
  21319. this.clearcoatRoughnessMap = null;
  21320. this.clearcoatNormalScale = new Vector2(1, 1);
  21321. this.clearcoatNormalMap = null;
  21322. this.ior = 1.5;
  21323. Object.defineProperty(this, 'reflectivity', {
  21324. get: function () {
  21325. return clamp(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1);
  21326. },
  21327. set: function (reflectivity) {
  21328. this.ior = (1 + 0.4 * reflectivity) / (1 - 0.4 * reflectivity);
  21329. }
  21330. });
  21331. this.sheenColor = new Color(0x000000);
  21332. this.sheenColorMap = null;
  21333. this.sheenRoughness = 1.0;
  21334. this.sheenRoughnessMap = null;
  21335. this.transmissionMap = null;
  21336. this.thickness = 0;
  21337. this.thicknessMap = null;
  21338. this.attenuationDistance = 0.0;
  21339. this.attenuationColor = new Color(1, 1, 1);
  21340. this.specularIntensity = 1.0;
  21341. this.specularIntensityMap = null;
  21342. this.specularColor = new Color(1, 1, 1);
  21343. this.specularColorMap = null;
  21344. this._sheen = 0.0;
  21345. this._clearcoat = 0;
  21346. this._transmission = 0;
  21347. this.setValues(parameters);
  21348. }
  21349. get sheen() {
  21350. return this._sheen;
  21351. }
  21352. set sheen(value) {
  21353. if (this._sheen > 0 !== value > 0) {
  21354. this.version++;
  21355. }
  21356. this._sheen = value;
  21357. }
  21358. get clearcoat() {
  21359. return this._clearcoat;
  21360. }
  21361. set clearcoat(value) {
  21362. if (this._clearcoat > 0 !== value > 0) {
  21363. this.version++;
  21364. }
  21365. this._clearcoat = value;
  21366. }
  21367. get transmission() {
  21368. return this._transmission;
  21369. }
  21370. set transmission(value) {
  21371. if (this._transmission > 0 !== value > 0) {
  21372. this.version++;
  21373. }
  21374. this._transmission = value;
  21375. }
  21376. copy(source) {
  21377. super.copy(source);
  21378. this.defines = {
  21379. 'STANDARD': '',
  21380. 'PHYSICAL': ''
  21381. };
  21382. this.clearcoat = source.clearcoat;
  21383. this.clearcoatMap = source.clearcoatMap;
  21384. this.clearcoatRoughness = source.clearcoatRoughness;
  21385. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  21386. this.clearcoatNormalMap = source.clearcoatNormalMap;
  21387. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  21388. this.ior = source.ior;
  21389. this.sheen = source.sheen;
  21390. this.sheenColor.copy(source.sheenColor);
  21391. this.sheenColorMap = source.sheenColorMap;
  21392. this.sheenRoughness = source.sheenRoughness;
  21393. this.sheenRoughnessMap = source.sheenRoughnessMap;
  21394. this.transmission = source.transmission;
  21395. this.transmissionMap = source.transmissionMap;
  21396. this.thickness = source.thickness;
  21397. this.thicknessMap = source.thicknessMap;
  21398. this.attenuationDistance = source.attenuationDistance;
  21399. this.attenuationColor.copy(source.attenuationColor);
  21400. this.specularIntensity = source.specularIntensity;
  21401. this.specularIntensityMap = source.specularIntensityMap;
  21402. this.specularColor.copy(source.specularColor);
  21403. this.specularColorMap = source.specularColorMap;
  21404. return this;
  21405. }
  21406. }
  21407. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  21408. /**
  21409. * parameters = {
  21410. * color: <hex>,
  21411. * specular: <hex>,
  21412. * shininess: <float>,
  21413. * opacity: <float>,
  21414. *
  21415. * map: new THREE.Texture( <Image> ),
  21416. *
  21417. * lightMap: new THREE.Texture( <Image> ),
  21418. * lightMapIntensity: <float>
  21419. *
  21420. * aoMap: new THREE.Texture( <Image> ),
  21421. * aoMapIntensity: <float>
  21422. *
  21423. * emissive: <hex>,
  21424. * emissiveIntensity: <float>
  21425. * emissiveMap: new THREE.Texture( <Image> ),
  21426. *
  21427. * bumpMap: new THREE.Texture( <Image> ),
  21428. * bumpScale: <float>,
  21429. *
  21430. * normalMap: new THREE.Texture( <Image> ),
  21431. * normalMapType: THREE.TangentSpaceNormalMap,
  21432. * normalScale: <Vector2>,
  21433. *
  21434. * displacementMap: new THREE.Texture( <Image> ),
  21435. * displacementScale: <float>,
  21436. * displacementBias: <float>,
  21437. *
  21438. * specularMap: new THREE.Texture( <Image> ),
  21439. *
  21440. * alphaMap: new THREE.Texture( <Image> ),
  21441. *
  21442. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21443. * combine: THREE.MultiplyOperation,
  21444. * reflectivity: <float>,
  21445. * refractionRatio: <float>,
  21446. *
  21447. * wireframe: <boolean>,
  21448. * wireframeLinewidth: <float>,
  21449. *
  21450. * flatShading: <bool>
  21451. * }
  21452. */
  21453. class MeshPhongMaterial extends Material {
  21454. constructor(parameters) {
  21455. super();
  21456. this.type = 'MeshPhongMaterial';
  21457. this.color = new Color(0xffffff); // diffuse
  21458. this.specular = new Color(0x111111);
  21459. this.shininess = 30;
  21460. this.map = null;
  21461. this.lightMap = null;
  21462. this.lightMapIntensity = 1.0;
  21463. this.aoMap = null;
  21464. this.aoMapIntensity = 1.0;
  21465. this.emissive = new Color(0x000000);
  21466. this.emissiveIntensity = 1.0;
  21467. this.emissiveMap = null;
  21468. this.bumpMap = null;
  21469. this.bumpScale = 1;
  21470. this.normalMap = null;
  21471. this.normalMapType = TangentSpaceNormalMap;
  21472. this.normalScale = new Vector2(1, 1);
  21473. this.displacementMap = null;
  21474. this.displacementScale = 1;
  21475. this.displacementBias = 0;
  21476. this.specularMap = null;
  21477. this.alphaMap = null;
  21478. this.envMap = null;
  21479. this.combine = MultiplyOperation;
  21480. this.reflectivity = 1;
  21481. this.refractionRatio = 0.98;
  21482. this.wireframe = false;
  21483. this.wireframeLinewidth = 1;
  21484. this.wireframeLinecap = 'round';
  21485. this.wireframeLinejoin = 'round';
  21486. this.flatShading = false;
  21487. this.setValues(parameters);
  21488. }
  21489. copy(source) {
  21490. super.copy(source);
  21491. this.color.copy(source.color);
  21492. this.specular.copy(source.specular);
  21493. this.shininess = source.shininess;
  21494. this.map = source.map;
  21495. this.lightMap = source.lightMap;
  21496. this.lightMapIntensity = source.lightMapIntensity;
  21497. this.aoMap = source.aoMap;
  21498. this.aoMapIntensity = source.aoMapIntensity;
  21499. this.emissive.copy(source.emissive);
  21500. this.emissiveMap = source.emissiveMap;
  21501. this.emissiveIntensity = source.emissiveIntensity;
  21502. this.bumpMap = source.bumpMap;
  21503. this.bumpScale = source.bumpScale;
  21504. this.normalMap = source.normalMap;
  21505. this.normalMapType = source.normalMapType;
  21506. this.normalScale.copy(source.normalScale);
  21507. this.displacementMap = source.displacementMap;
  21508. this.displacementScale = source.displacementScale;
  21509. this.displacementBias = source.displacementBias;
  21510. this.specularMap = source.specularMap;
  21511. this.alphaMap = source.alphaMap;
  21512. this.envMap = source.envMap;
  21513. this.combine = source.combine;
  21514. this.reflectivity = source.reflectivity;
  21515. this.refractionRatio = source.refractionRatio;
  21516. this.wireframe = source.wireframe;
  21517. this.wireframeLinewidth = source.wireframeLinewidth;
  21518. this.wireframeLinecap = source.wireframeLinecap;
  21519. this.wireframeLinejoin = source.wireframeLinejoin;
  21520. this.flatShading = source.flatShading;
  21521. return this;
  21522. }
  21523. }
  21524. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  21525. /**
  21526. * parameters = {
  21527. * color: <hex>,
  21528. *
  21529. * map: new THREE.Texture( <Image> ),
  21530. * gradientMap: new THREE.Texture( <Image> ),
  21531. *
  21532. * lightMap: new THREE.Texture( <Image> ),
  21533. * lightMapIntensity: <float>
  21534. *
  21535. * aoMap: new THREE.Texture( <Image> ),
  21536. * aoMapIntensity: <float>
  21537. *
  21538. * emissive: <hex>,
  21539. * emissiveIntensity: <float>
  21540. * emissiveMap: new THREE.Texture( <Image> ),
  21541. *
  21542. * bumpMap: new THREE.Texture( <Image> ),
  21543. * bumpScale: <float>,
  21544. *
  21545. * normalMap: new THREE.Texture( <Image> ),
  21546. * normalMapType: THREE.TangentSpaceNormalMap,
  21547. * normalScale: <Vector2>,
  21548. *
  21549. * displacementMap: new THREE.Texture( <Image> ),
  21550. * displacementScale: <float>,
  21551. * displacementBias: <float>,
  21552. *
  21553. * alphaMap: new THREE.Texture( <Image> ),
  21554. *
  21555. * wireframe: <boolean>,
  21556. * wireframeLinewidth: <float>,
  21557. *
  21558. * }
  21559. */
  21560. class MeshToonMaterial extends Material {
  21561. constructor(parameters) {
  21562. super();
  21563. this.defines = {
  21564. 'TOON': ''
  21565. };
  21566. this.type = 'MeshToonMaterial';
  21567. this.color = new Color(0xffffff);
  21568. this.map = null;
  21569. this.gradientMap = null;
  21570. this.lightMap = null;
  21571. this.lightMapIntensity = 1.0;
  21572. this.aoMap = null;
  21573. this.aoMapIntensity = 1.0;
  21574. this.emissive = new Color(0x000000);
  21575. this.emissiveIntensity = 1.0;
  21576. this.emissiveMap = null;
  21577. this.bumpMap = null;
  21578. this.bumpScale = 1;
  21579. this.normalMap = null;
  21580. this.normalMapType = TangentSpaceNormalMap;
  21581. this.normalScale = new Vector2(1, 1);
  21582. this.displacementMap = null;
  21583. this.displacementScale = 1;
  21584. this.displacementBias = 0;
  21585. this.alphaMap = null;
  21586. this.wireframe = false;
  21587. this.wireframeLinewidth = 1;
  21588. this.wireframeLinecap = 'round';
  21589. this.wireframeLinejoin = 'round';
  21590. this.setValues(parameters);
  21591. }
  21592. copy(source) {
  21593. super.copy(source);
  21594. this.color.copy(source.color);
  21595. this.map = source.map;
  21596. this.gradientMap = source.gradientMap;
  21597. this.lightMap = source.lightMap;
  21598. this.lightMapIntensity = source.lightMapIntensity;
  21599. this.aoMap = source.aoMap;
  21600. this.aoMapIntensity = source.aoMapIntensity;
  21601. this.emissive.copy(source.emissive);
  21602. this.emissiveMap = source.emissiveMap;
  21603. this.emissiveIntensity = source.emissiveIntensity;
  21604. this.bumpMap = source.bumpMap;
  21605. this.bumpScale = source.bumpScale;
  21606. this.normalMap = source.normalMap;
  21607. this.normalMapType = source.normalMapType;
  21608. this.normalScale.copy(source.normalScale);
  21609. this.displacementMap = source.displacementMap;
  21610. this.displacementScale = source.displacementScale;
  21611. this.displacementBias = source.displacementBias;
  21612. this.alphaMap = source.alphaMap;
  21613. this.wireframe = source.wireframe;
  21614. this.wireframeLinewidth = source.wireframeLinewidth;
  21615. this.wireframeLinecap = source.wireframeLinecap;
  21616. this.wireframeLinejoin = source.wireframeLinejoin;
  21617. return this;
  21618. }
  21619. }
  21620. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  21621. /**
  21622. * parameters = {
  21623. * opacity: <float>,
  21624. *
  21625. * bumpMap: new THREE.Texture( <Image> ),
  21626. * bumpScale: <float>,
  21627. *
  21628. * normalMap: new THREE.Texture( <Image> ),
  21629. * normalMapType: THREE.TangentSpaceNormalMap,
  21630. * normalScale: <Vector2>,
  21631. *
  21632. * displacementMap: new THREE.Texture( <Image> ),
  21633. * displacementScale: <float>,
  21634. * displacementBias: <float>,
  21635. *
  21636. * wireframe: <boolean>,
  21637. * wireframeLinewidth: <float>
  21638. *
  21639. * flatShading: <bool>
  21640. * }
  21641. */
  21642. class MeshNormalMaterial extends Material {
  21643. constructor(parameters) {
  21644. super();
  21645. this.type = 'MeshNormalMaterial';
  21646. this.bumpMap = null;
  21647. this.bumpScale = 1;
  21648. this.normalMap = null;
  21649. this.normalMapType = TangentSpaceNormalMap;
  21650. this.normalScale = new Vector2(1, 1);
  21651. this.displacementMap = null;
  21652. this.displacementScale = 1;
  21653. this.displacementBias = 0;
  21654. this.wireframe = false;
  21655. this.wireframeLinewidth = 1;
  21656. this.fog = false;
  21657. this.flatShading = false;
  21658. this.setValues(parameters);
  21659. }
  21660. copy(source) {
  21661. super.copy(source);
  21662. this.bumpMap = source.bumpMap;
  21663. this.bumpScale = source.bumpScale;
  21664. this.normalMap = source.normalMap;
  21665. this.normalMapType = source.normalMapType;
  21666. this.normalScale.copy(source.normalScale);
  21667. this.displacementMap = source.displacementMap;
  21668. this.displacementScale = source.displacementScale;
  21669. this.displacementBias = source.displacementBias;
  21670. this.wireframe = source.wireframe;
  21671. this.wireframeLinewidth = source.wireframeLinewidth;
  21672. this.flatShading = source.flatShading;
  21673. return this;
  21674. }
  21675. }
  21676. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  21677. /**
  21678. * parameters = {
  21679. * color: <hex>,
  21680. * opacity: <float>,
  21681. *
  21682. * map: new THREE.Texture( <Image> ),
  21683. *
  21684. * lightMap: new THREE.Texture( <Image> ),
  21685. * lightMapIntensity: <float>
  21686. *
  21687. * aoMap: new THREE.Texture( <Image> ),
  21688. * aoMapIntensity: <float>
  21689. *
  21690. * emissive: <hex>,
  21691. * emissiveIntensity: <float>
  21692. * emissiveMap: new THREE.Texture( <Image> ),
  21693. *
  21694. * specularMap: new THREE.Texture( <Image> ),
  21695. *
  21696. * alphaMap: new THREE.Texture( <Image> ),
  21697. *
  21698. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21699. * combine: THREE.Multiply,
  21700. * reflectivity: <float>,
  21701. * refractionRatio: <float>,
  21702. *
  21703. * wireframe: <boolean>,
  21704. * wireframeLinewidth: <float>,
  21705. *
  21706. * }
  21707. */
  21708. class MeshLambertMaterial extends Material {
  21709. constructor(parameters) {
  21710. super();
  21711. this.type = 'MeshLambertMaterial';
  21712. this.color = new Color(0xffffff); // diffuse
  21713. this.map = null;
  21714. this.lightMap = null;
  21715. this.lightMapIntensity = 1.0;
  21716. this.aoMap = null;
  21717. this.aoMapIntensity = 1.0;
  21718. this.emissive = new Color(0x000000);
  21719. this.emissiveIntensity = 1.0;
  21720. this.emissiveMap = null;
  21721. this.specularMap = null;
  21722. this.alphaMap = null;
  21723. this.envMap = null;
  21724. this.combine = MultiplyOperation;
  21725. this.reflectivity = 1;
  21726. this.refractionRatio = 0.98;
  21727. this.wireframe = false;
  21728. this.wireframeLinewidth = 1;
  21729. this.wireframeLinecap = 'round';
  21730. this.wireframeLinejoin = 'round';
  21731. this.setValues(parameters);
  21732. }
  21733. copy(source) {
  21734. super.copy(source);
  21735. this.color.copy(source.color);
  21736. this.map = source.map;
  21737. this.lightMap = source.lightMap;
  21738. this.lightMapIntensity = source.lightMapIntensity;
  21739. this.aoMap = source.aoMap;
  21740. this.aoMapIntensity = source.aoMapIntensity;
  21741. this.emissive.copy(source.emissive);
  21742. this.emissiveMap = source.emissiveMap;
  21743. this.emissiveIntensity = source.emissiveIntensity;
  21744. this.specularMap = source.specularMap;
  21745. this.alphaMap = source.alphaMap;
  21746. this.envMap = source.envMap;
  21747. this.combine = source.combine;
  21748. this.reflectivity = source.reflectivity;
  21749. this.refractionRatio = source.refractionRatio;
  21750. this.wireframe = source.wireframe;
  21751. this.wireframeLinewidth = source.wireframeLinewidth;
  21752. this.wireframeLinecap = source.wireframeLinecap;
  21753. this.wireframeLinejoin = source.wireframeLinejoin;
  21754. return this;
  21755. }
  21756. }
  21757. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  21758. /**
  21759. * parameters = {
  21760. * color: <hex>,
  21761. * opacity: <float>,
  21762. *
  21763. * matcap: new THREE.Texture( <Image> ),
  21764. *
  21765. * map: new THREE.Texture( <Image> ),
  21766. *
  21767. * bumpMap: new THREE.Texture( <Image> ),
  21768. * bumpScale: <float>,
  21769. *
  21770. * normalMap: new THREE.Texture( <Image> ),
  21771. * normalMapType: THREE.TangentSpaceNormalMap,
  21772. * normalScale: <Vector2>,
  21773. *
  21774. * displacementMap: new THREE.Texture( <Image> ),
  21775. * displacementScale: <float>,
  21776. * displacementBias: <float>,
  21777. *
  21778. * alphaMap: new THREE.Texture( <Image> ),
  21779. *
  21780. * flatShading: <bool>
  21781. * }
  21782. */
  21783. class MeshMatcapMaterial extends Material {
  21784. constructor(parameters) {
  21785. super();
  21786. this.defines = {
  21787. 'MATCAP': ''
  21788. };
  21789. this.type = 'MeshMatcapMaterial';
  21790. this.color = new Color(0xffffff); // diffuse
  21791. this.matcap = null;
  21792. this.map = null;
  21793. this.bumpMap = null;
  21794. this.bumpScale = 1;
  21795. this.normalMap = null;
  21796. this.normalMapType = TangentSpaceNormalMap;
  21797. this.normalScale = new Vector2(1, 1);
  21798. this.displacementMap = null;
  21799. this.displacementScale = 1;
  21800. this.displacementBias = 0;
  21801. this.alphaMap = null;
  21802. this.flatShading = false;
  21803. this.setValues(parameters);
  21804. }
  21805. copy(source) {
  21806. super.copy(source);
  21807. this.defines = {
  21808. 'MATCAP': ''
  21809. };
  21810. this.color.copy(source.color);
  21811. this.matcap = source.matcap;
  21812. this.map = source.map;
  21813. this.bumpMap = source.bumpMap;
  21814. this.bumpScale = source.bumpScale;
  21815. this.normalMap = source.normalMap;
  21816. this.normalMapType = source.normalMapType;
  21817. this.normalScale.copy(source.normalScale);
  21818. this.displacementMap = source.displacementMap;
  21819. this.displacementScale = source.displacementScale;
  21820. this.displacementBias = source.displacementBias;
  21821. this.alphaMap = source.alphaMap;
  21822. this.flatShading = source.flatShading;
  21823. return this;
  21824. }
  21825. }
  21826. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  21827. /**
  21828. * parameters = {
  21829. * color: <hex>,
  21830. * opacity: <float>,
  21831. *
  21832. * linewidth: <float>,
  21833. *
  21834. * scale: <float>,
  21835. * dashSize: <float>,
  21836. * gapSize: <float>
  21837. * }
  21838. */
  21839. class LineDashedMaterial extends LineBasicMaterial {
  21840. constructor(parameters) {
  21841. super();
  21842. this.type = 'LineDashedMaterial';
  21843. this.scale = 1;
  21844. this.dashSize = 3;
  21845. this.gapSize = 1;
  21846. this.setValues(parameters);
  21847. }
  21848. copy(source) {
  21849. super.copy(source);
  21850. this.scale = source.scale;
  21851. this.dashSize = source.dashSize;
  21852. this.gapSize = source.gapSize;
  21853. return this;
  21854. }
  21855. }
  21856. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  21857. var Materials = /*#__PURE__*/Object.freeze({
  21858. __proto__: null,
  21859. ShadowMaterial: ShadowMaterial,
  21860. SpriteMaterial: SpriteMaterial,
  21861. RawShaderMaterial: RawShaderMaterial,
  21862. ShaderMaterial: ShaderMaterial,
  21863. PointsMaterial: PointsMaterial,
  21864. MeshPhysicalMaterial: MeshPhysicalMaterial,
  21865. MeshStandardMaterial: MeshStandardMaterial,
  21866. MeshPhongMaterial: MeshPhongMaterial,
  21867. MeshToonMaterial: MeshToonMaterial,
  21868. MeshNormalMaterial: MeshNormalMaterial,
  21869. MeshLambertMaterial: MeshLambertMaterial,
  21870. MeshDepthMaterial: MeshDepthMaterial,
  21871. MeshDistanceMaterial: MeshDistanceMaterial,
  21872. MeshBasicMaterial: MeshBasicMaterial,
  21873. MeshMatcapMaterial: MeshMatcapMaterial,
  21874. LineDashedMaterial: LineDashedMaterial,
  21875. LineBasicMaterial: LineBasicMaterial,
  21876. Material: Material
  21877. });
  21878. const AnimationUtils = {
  21879. // same as Array.prototype.slice, but also works on typed arrays
  21880. arraySlice: function (array, from, to) {
  21881. if (AnimationUtils.isTypedArray(array)) {
  21882. // in ios9 array.subarray(from, undefined) will return empty array
  21883. // but array.subarray(from) or array.subarray(from, len) is correct
  21884. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  21885. }
  21886. return array.slice(from, to);
  21887. },
  21888. // converts an array to a specific type
  21889. convertArray: function (array, type, forceClone) {
  21890. if (!array || // let 'undefined' and 'null' pass
  21891. !forceClone && array.constructor === type) return array;
  21892. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  21893. return new type(array); // create typed array
  21894. }
  21895. return Array.prototype.slice.call(array); // create Array
  21896. },
  21897. isTypedArray: function (object) {
  21898. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  21899. },
  21900. // returns an array by which times and values can be sorted
  21901. getKeyframeOrder: function (times) {
  21902. function compareTime(i, j) {
  21903. return times[i] - times[j];
  21904. }
  21905. const n = times.length;
  21906. const result = new Array(n);
  21907. for (let i = 0; i !== n; ++i) result[i] = i;
  21908. result.sort(compareTime);
  21909. return result;
  21910. },
  21911. // uses the array previously returned by 'getKeyframeOrder' to sort data
  21912. sortedArray: function (values, stride, order) {
  21913. const nValues = values.length;
  21914. const result = new values.constructor(nValues);
  21915. for (let i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  21916. const srcOffset = order[i] * stride;
  21917. for (let j = 0; j !== stride; ++j) {
  21918. result[dstOffset++] = values[srcOffset + j];
  21919. }
  21920. }
  21921. return result;
  21922. },
  21923. // function for parsing AOS keyframe formats
  21924. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  21925. let i = 1,
  21926. key = jsonKeys[0];
  21927. while (key !== undefined && key[valuePropertyName] === undefined) {
  21928. key = jsonKeys[i++];
  21929. }
  21930. if (key === undefined) return; // no data
  21931. let value = key[valuePropertyName];
  21932. if (value === undefined) return; // no data
  21933. if (Array.isArray(value)) {
  21934. do {
  21935. value = key[valuePropertyName];
  21936. if (value !== undefined) {
  21937. times.push(key.time);
  21938. values.push.apply(values, value); // push all elements
  21939. }
  21940. key = jsonKeys[i++];
  21941. } while (key !== undefined);
  21942. } else if (value.toArray !== undefined) {
  21943. // ...assume THREE.Math-ish
  21944. do {
  21945. value = key[valuePropertyName];
  21946. if (value !== undefined) {
  21947. times.push(key.time);
  21948. value.toArray(values, values.length);
  21949. }
  21950. key = jsonKeys[i++];
  21951. } while (key !== undefined);
  21952. } else {
  21953. // otherwise push as-is
  21954. do {
  21955. value = key[valuePropertyName];
  21956. if (value !== undefined) {
  21957. times.push(key.time);
  21958. values.push(value);
  21959. }
  21960. key = jsonKeys[i++];
  21961. } while (key !== undefined);
  21962. }
  21963. },
  21964. subclip: function (sourceClip, name, startFrame, endFrame, fps = 30) {
  21965. const clip = sourceClip.clone();
  21966. clip.name = name;
  21967. const tracks = [];
  21968. for (let i = 0; i < clip.tracks.length; ++i) {
  21969. const track = clip.tracks[i];
  21970. const valueSize = track.getValueSize();
  21971. const times = [];
  21972. const values = [];
  21973. for (let j = 0; j < track.times.length; ++j) {
  21974. const frame = track.times[j] * fps;
  21975. if (frame < startFrame || frame >= endFrame) continue;
  21976. times.push(track.times[j]);
  21977. for (let k = 0; k < valueSize; ++k) {
  21978. values.push(track.values[j * valueSize + k]);
  21979. }
  21980. }
  21981. if (times.length === 0) continue;
  21982. track.times = AnimationUtils.convertArray(times, track.times.constructor);
  21983. track.values = AnimationUtils.convertArray(values, track.values.constructor);
  21984. tracks.push(track);
  21985. }
  21986. clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
  21987. let minStartTime = Infinity;
  21988. for (let i = 0; i < clip.tracks.length; ++i) {
  21989. if (minStartTime > clip.tracks[i].times[0]) {
  21990. minStartTime = clip.tracks[i].times[0];
  21991. }
  21992. } // shift all tracks such that clip begins at t=0
  21993. for (let i = 0; i < clip.tracks.length; ++i) {
  21994. clip.tracks[i].shift(-1 * minStartTime);
  21995. }
  21996. clip.resetDuration();
  21997. return clip;
  21998. },
  21999. makeClipAdditive: function (targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) {
  22000. if (fps <= 0) fps = 30;
  22001. const numTracks = referenceClip.tracks.length;
  22002. const referenceTime = referenceFrame / fps; // Make each track's values relative to the values at the reference frame
  22003. for (let i = 0; i < numTracks; ++i) {
  22004. const referenceTrack = referenceClip.tracks[i];
  22005. const referenceTrackType = referenceTrack.ValueTypeName; // Skip this track if it's non-numeric
  22006. if (referenceTrackType === 'bool' || referenceTrackType === 'string') continue; // Find the track in the target clip whose name and type matches the reference track
  22007. const targetTrack = targetClip.tracks.find(function (track) {
  22008. return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
  22009. });
  22010. if (targetTrack === undefined) continue;
  22011. let referenceOffset = 0;
  22012. const referenceValueSize = referenceTrack.getValueSize();
  22013. if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  22014. referenceOffset = referenceValueSize / 3;
  22015. }
  22016. let targetOffset = 0;
  22017. const targetValueSize = targetTrack.getValueSize();
  22018. if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  22019. targetOffset = targetValueSize / 3;
  22020. }
  22021. const lastIndex = referenceTrack.times.length - 1;
  22022. let referenceValue; // Find the value to subtract out of the track
  22023. if (referenceTime <= referenceTrack.times[0]) {
  22024. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  22025. const startIndex = referenceOffset;
  22026. const endIndex = referenceValueSize - referenceOffset;
  22027. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  22028. } else if (referenceTime >= referenceTrack.times[lastIndex]) {
  22029. // Reference frame is after the last keyframe, so just use the last keyframe
  22030. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  22031. const endIndex = startIndex + referenceValueSize - referenceOffset;
  22032. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  22033. } else {
  22034. // Interpolate to the reference value
  22035. const interpolant = referenceTrack.createInterpolant();
  22036. const startIndex = referenceOffset;
  22037. const endIndex = referenceValueSize - referenceOffset;
  22038. interpolant.evaluate(referenceTime);
  22039. referenceValue = AnimationUtils.arraySlice(interpolant.resultBuffer, startIndex, endIndex);
  22040. } // Conjugate the quaternion
  22041. if (referenceTrackType === 'quaternion') {
  22042. const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
  22043. referenceQuat.toArray(referenceValue);
  22044. } // Subtract the reference value from all of the track values
  22045. const numTimes = targetTrack.times.length;
  22046. for (let j = 0; j < numTimes; ++j) {
  22047. const valueStart = j * targetValueSize + targetOffset;
  22048. if (referenceTrackType === 'quaternion') {
  22049. // Multiply the conjugate for quaternion track types
  22050. Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
  22051. } else {
  22052. const valueEnd = targetValueSize - targetOffset * 2; // Subtract each value for all other numeric track types
  22053. for (let k = 0; k < valueEnd; ++k) {
  22054. targetTrack.values[valueStart + k] -= referenceValue[k];
  22055. }
  22056. }
  22057. }
  22058. }
  22059. targetClip.blendMode = AdditiveAnimationBlendMode;
  22060. return targetClip;
  22061. }
  22062. };
  22063. /**
  22064. * Abstract base class of interpolants over parametric samples.
  22065. *
  22066. * The parameter domain is one dimensional, typically the time or a path
  22067. * along a curve defined by the data.
  22068. *
  22069. * The sample values can have any dimensionality and derived classes may
  22070. * apply special interpretations to the data.
  22071. *
  22072. * This class provides the interval seek in a Template Method, deferring
  22073. * the actual interpolation to derived classes.
  22074. *
  22075. * Time complexity is O(1) for linear access crossing at most two points
  22076. * and O(log N) for random access, where N is the number of positions.
  22077. *
  22078. * References:
  22079. *
  22080. * http://www.oodesign.com/template-method-pattern.html
  22081. *
  22082. */
  22083. class Interpolant {
  22084. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22085. this.parameterPositions = parameterPositions;
  22086. this._cachedIndex = 0;
  22087. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  22088. this.sampleValues = sampleValues;
  22089. this.valueSize = sampleSize;
  22090. this.settings = null;
  22091. this.DefaultSettings_ = {};
  22092. }
  22093. evaluate(t) {
  22094. const pp = this.parameterPositions;
  22095. let i1 = this._cachedIndex,
  22096. t1 = pp[i1],
  22097. t0 = pp[i1 - 1];
  22098. validate_interval: {
  22099. seek: {
  22100. let right;
  22101. linear_scan: {
  22102. //- See http://jsperf.com/comparison-to-undefined/3
  22103. //- slower code:
  22104. //-
  22105. //- if ( t >= t1 || t1 === undefined ) {
  22106. forward_scan: if (!(t < t1)) {
  22107. for (let giveUpAt = i1 + 2;;) {
  22108. if (t1 === undefined) {
  22109. if (t < t0) break forward_scan; // after end
  22110. i1 = pp.length;
  22111. this._cachedIndex = i1;
  22112. return this.afterEnd_(i1 - 1, t, t0);
  22113. }
  22114. if (i1 === giveUpAt) break; // this loop
  22115. t0 = t1;
  22116. t1 = pp[++i1];
  22117. if (t < t1) {
  22118. // we have arrived at the sought interval
  22119. break seek;
  22120. }
  22121. } // prepare binary search on the right side of the index
  22122. right = pp.length;
  22123. break linear_scan;
  22124. } //- slower code:
  22125. //- if ( t < t0 || t0 === undefined ) {
  22126. if (!(t >= t0)) {
  22127. // looping?
  22128. const t1global = pp[1];
  22129. if (t < t1global) {
  22130. i1 = 2; // + 1, using the scan for the details
  22131. t0 = t1global;
  22132. } // linear reverse scan
  22133. for (let giveUpAt = i1 - 2;;) {
  22134. if (t0 === undefined) {
  22135. // before start
  22136. this._cachedIndex = 0;
  22137. return this.beforeStart_(0, t, t1);
  22138. }
  22139. if (i1 === giveUpAt) break; // this loop
  22140. t1 = t0;
  22141. t0 = pp[--i1 - 1];
  22142. if (t >= t0) {
  22143. // we have arrived at the sought interval
  22144. break seek;
  22145. }
  22146. } // prepare binary search on the left side of the index
  22147. right = i1;
  22148. i1 = 0;
  22149. break linear_scan;
  22150. } // the interval is valid
  22151. break validate_interval;
  22152. } // linear scan
  22153. // binary search
  22154. while (i1 < right) {
  22155. const mid = i1 + right >>> 1;
  22156. if (t < pp[mid]) {
  22157. right = mid;
  22158. } else {
  22159. i1 = mid + 1;
  22160. }
  22161. }
  22162. t1 = pp[i1];
  22163. t0 = pp[i1 - 1]; // check boundary cases, again
  22164. if (t0 === undefined) {
  22165. this._cachedIndex = 0;
  22166. return this.beforeStart_(0, t, t1);
  22167. }
  22168. if (t1 === undefined) {
  22169. i1 = pp.length;
  22170. this._cachedIndex = i1;
  22171. return this.afterEnd_(i1 - 1, t0, t);
  22172. }
  22173. } // seek
  22174. this._cachedIndex = i1;
  22175. this.intervalChanged_(i1, t0, t1);
  22176. } // validate_interval
  22177. return this.interpolate_(i1, t0, t, t1);
  22178. }
  22179. getSettings_() {
  22180. return this.settings || this.DefaultSettings_;
  22181. }
  22182. copySampleValue_(index) {
  22183. // copies a sample value to the result buffer
  22184. const result = this.resultBuffer,
  22185. values = this.sampleValues,
  22186. stride = this.valueSize,
  22187. offset = index * stride;
  22188. for (let i = 0; i !== stride; ++i) {
  22189. result[i] = values[offset + i];
  22190. }
  22191. return result;
  22192. } // Template methods for derived classes:
  22193. interpolate_() {
  22194. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  22195. }
  22196. intervalChanged_() {// empty
  22197. }
  22198. } // ALIAS DEFINITIONS
  22199. Interpolant.prototype.beforeStart_ = Interpolant.prototype.copySampleValue_;
  22200. Interpolant.prototype.afterEnd_ = Interpolant.prototype.copySampleValue_;
  22201. /**
  22202. * Fast and simple cubic spline interpolant.
  22203. *
  22204. * It was derived from a Hermitian construction setting the first derivative
  22205. * at each sample position to the linear slope between neighboring positions
  22206. * over their parameter interval.
  22207. */
  22208. class CubicInterpolant extends Interpolant {
  22209. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22210. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22211. this._weightPrev = -0;
  22212. this._offsetPrev = -0;
  22213. this._weightNext = -0;
  22214. this._offsetNext = -0;
  22215. this.DefaultSettings_ = {
  22216. endingStart: ZeroCurvatureEnding,
  22217. endingEnd: ZeroCurvatureEnding
  22218. };
  22219. }
  22220. intervalChanged_(i1, t0, t1) {
  22221. const pp = this.parameterPositions;
  22222. let iPrev = i1 - 2,
  22223. iNext = i1 + 1,
  22224. tPrev = pp[iPrev],
  22225. tNext = pp[iNext];
  22226. if (tPrev === undefined) {
  22227. switch (this.getSettings_().endingStart) {
  22228. case ZeroSlopeEnding:
  22229. // f'(t0) = 0
  22230. iPrev = i1;
  22231. tPrev = 2 * t0 - t1;
  22232. break;
  22233. case WrapAroundEnding:
  22234. // use the other end of the curve
  22235. iPrev = pp.length - 2;
  22236. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  22237. break;
  22238. default:
  22239. // ZeroCurvatureEnding
  22240. // f''(t0) = 0 a.k.a. Natural Spline
  22241. iPrev = i1;
  22242. tPrev = t1;
  22243. }
  22244. }
  22245. if (tNext === undefined) {
  22246. switch (this.getSettings_().endingEnd) {
  22247. case ZeroSlopeEnding:
  22248. // f'(tN) = 0
  22249. iNext = i1;
  22250. tNext = 2 * t1 - t0;
  22251. break;
  22252. case WrapAroundEnding:
  22253. // use the other end of the curve
  22254. iNext = 1;
  22255. tNext = t1 + pp[1] - pp[0];
  22256. break;
  22257. default:
  22258. // ZeroCurvatureEnding
  22259. // f''(tN) = 0, a.k.a. Natural Spline
  22260. iNext = i1 - 1;
  22261. tNext = t0;
  22262. }
  22263. }
  22264. const halfDt = (t1 - t0) * 0.5,
  22265. stride = this.valueSize;
  22266. this._weightPrev = halfDt / (t0 - tPrev);
  22267. this._weightNext = halfDt / (tNext - t1);
  22268. this._offsetPrev = iPrev * stride;
  22269. this._offsetNext = iNext * stride;
  22270. }
  22271. interpolate_(i1, t0, t, t1) {
  22272. const result = this.resultBuffer,
  22273. values = this.sampleValues,
  22274. stride = this.valueSize,
  22275. o1 = i1 * stride,
  22276. o0 = o1 - stride,
  22277. oP = this._offsetPrev,
  22278. oN = this._offsetNext,
  22279. wP = this._weightPrev,
  22280. wN = this._weightNext,
  22281. p = (t - t0) / (t1 - t0),
  22282. pp = p * p,
  22283. ppp = pp * p; // evaluate polynomials
  22284. const sP = -wP * ppp + 2 * wP * pp - wP * p;
  22285. const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  22286. const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  22287. const sN = wN * ppp - wN * pp; // combine data linearly
  22288. for (let i = 0; i !== stride; ++i) {
  22289. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  22290. }
  22291. return result;
  22292. }
  22293. }
  22294. class LinearInterpolant extends Interpolant {
  22295. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22296. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22297. }
  22298. interpolate_(i1, t0, t, t1) {
  22299. const result = this.resultBuffer,
  22300. values = this.sampleValues,
  22301. stride = this.valueSize,
  22302. offset1 = i1 * stride,
  22303. offset0 = offset1 - stride,
  22304. weight1 = (t - t0) / (t1 - t0),
  22305. weight0 = 1 - weight1;
  22306. for (let i = 0; i !== stride; ++i) {
  22307. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  22308. }
  22309. return result;
  22310. }
  22311. }
  22312. /**
  22313. *
  22314. * Interpolant that evaluates to the sample value at the position preceeding
  22315. * the parameter.
  22316. */
  22317. class DiscreteInterpolant extends Interpolant {
  22318. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22319. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22320. }
  22321. interpolate_(i1
  22322. /*, t0, t, t1 */
  22323. ) {
  22324. return this.copySampleValue_(i1 - 1);
  22325. }
  22326. }
  22327. class KeyframeTrack {
  22328. constructor(name, times, values, interpolation) {
  22329. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  22330. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  22331. this.name = name;
  22332. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  22333. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  22334. this.setInterpolation(interpolation || this.DefaultInterpolation);
  22335. } // Serialization (in static context, because of constructor invocation
  22336. // and automatic invocation of .toJSON):
  22337. static toJSON(track) {
  22338. const trackType = track.constructor;
  22339. let json; // derived classes can define a static toJSON method
  22340. if (trackType.toJSON !== this.toJSON) {
  22341. json = trackType.toJSON(track);
  22342. } else {
  22343. // by default, we assume the data can be serialized as-is
  22344. json = {
  22345. 'name': track.name,
  22346. 'times': AnimationUtils.convertArray(track.times, Array),
  22347. 'values': AnimationUtils.convertArray(track.values, Array)
  22348. };
  22349. const interpolation = track.getInterpolation();
  22350. if (interpolation !== track.DefaultInterpolation) {
  22351. json.interpolation = interpolation;
  22352. }
  22353. }
  22354. json.type = track.ValueTypeName; // mandatory
  22355. return json;
  22356. }
  22357. InterpolantFactoryMethodDiscrete(result) {
  22358. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  22359. }
  22360. InterpolantFactoryMethodLinear(result) {
  22361. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  22362. }
  22363. InterpolantFactoryMethodSmooth(result) {
  22364. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  22365. }
  22366. setInterpolation(interpolation) {
  22367. let factoryMethod;
  22368. switch (interpolation) {
  22369. case InterpolateDiscrete:
  22370. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  22371. break;
  22372. case InterpolateLinear:
  22373. factoryMethod = this.InterpolantFactoryMethodLinear;
  22374. break;
  22375. case InterpolateSmooth:
  22376. factoryMethod = this.InterpolantFactoryMethodSmooth;
  22377. break;
  22378. }
  22379. if (factoryMethod === undefined) {
  22380. const message = 'unsupported interpolation for ' + this.ValueTypeName + ' keyframe track named ' + this.name;
  22381. if (this.createInterpolant === undefined) {
  22382. // fall back to default, unless the default itself is messed up
  22383. if (interpolation !== this.DefaultInterpolation) {
  22384. this.setInterpolation(this.DefaultInterpolation);
  22385. } else {
  22386. throw new Error(message); // fatal, in this case
  22387. }
  22388. }
  22389. console.warn('THREE.KeyframeTrack:', message);
  22390. return this;
  22391. }
  22392. this.createInterpolant = factoryMethod;
  22393. return this;
  22394. }
  22395. getInterpolation() {
  22396. switch (this.createInterpolant) {
  22397. case this.InterpolantFactoryMethodDiscrete:
  22398. return InterpolateDiscrete;
  22399. case this.InterpolantFactoryMethodLinear:
  22400. return InterpolateLinear;
  22401. case this.InterpolantFactoryMethodSmooth:
  22402. return InterpolateSmooth;
  22403. }
  22404. }
  22405. getValueSize() {
  22406. return this.values.length / this.times.length;
  22407. } // move all keyframes either forwards or backwards in time
  22408. shift(timeOffset) {
  22409. if (timeOffset !== 0.0) {
  22410. const times = this.times;
  22411. for (let i = 0, n = times.length; i !== n; ++i) {
  22412. times[i] += timeOffset;
  22413. }
  22414. }
  22415. return this;
  22416. } // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  22417. scale(timeScale) {
  22418. if (timeScale !== 1.0) {
  22419. const times = this.times;
  22420. for (let i = 0, n = times.length; i !== n; ++i) {
  22421. times[i] *= timeScale;
  22422. }
  22423. }
  22424. return this;
  22425. } // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  22426. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  22427. trim(startTime, endTime) {
  22428. const times = this.times,
  22429. nKeys = times.length;
  22430. let from = 0,
  22431. to = nKeys - 1;
  22432. while (from !== nKeys && times[from] < startTime) {
  22433. ++from;
  22434. }
  22435. while (to !== -1 && times[to] > endTime) {
  22436. --to;
  22437. }
  22438. ++to; // inclusive -> exclusive bound
  22439. if (from !== 0 || to !== nKeys) {
  22440. // empty tracks are forbidden, so keep at least one keyframe
  22441. if (from >= to) {
  22442. to = Math.max(to, 1);
  22443. from = to - 1;
  22444. }
  22445. const stride = this.getValueSize();
  22446. this.times = AnimationUtils.arraySlice(times, from, to);
  22447. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  22448. }
  22449. return this;
  22450. } // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  22451. validate() {
  22452. let valid = true;
  22453. const valueSize = this.getValueSize();
  22454. if (valueSize - Math.floor(valueSize) !== 0) {
  22455. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  22456. valid = false;
  22457. }
  22458. const times = this.times,
  22459. values = this.values,
  22460. nKeys = times.length;
  22461. if (nKeys === 0) {
  22462. console.error('THREE.KeyframeTrack: Track is empty.', this);
  22463. valid = false;
  22464. }
  22465. let prevTime = null;
  22466. for (let i = 0; i !== nKeys; i++) {
  22467. const currTime = times[i];
  22468. if (typeof currTime === 'number' && isNaN(currTime)) {
  22469. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  22470. valid = false;
  22471. break;
  22472. }
  22473. if (prevTime !== null && prevTime > currTime) {
  22474. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  22475. valid = false;
  22476. break;
  22477. }
  22478. prevTime = currTime;
  22479. }
  22480. if (values !== undefined) {
  22481. if (AnimationUtils.isTypedArray(values)) {
  22482. for (let i = 0, n = values.length; i !== n; ++i) {
  22483. const value = values[i];
  22484. if (isNaN(value)) {
  22485. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  22486. valid = false;
  22487. break;
  22488. }
  22489. }
  22490. }
  22491. }
  22492. return valid;
  22493. } // removes equivalent sequential keys as common in morph target sequences
  22494. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  22495. optimize() {
  22496. // times or values may be shared with other tracks, so overwriting is unsafe
  22497. const times = AnimationUtils.arraySlice(this.times),
  22498. values = AnimationUtils.arraySlice(this.values),
  22499. stride = this.getValueSize(),
  22500. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  22501. lastIndex = times.length - 1;
  22502. let writeIndex = 1;
  22503. for (let i = 1; i < lastIndex; ++i) {
  22504. let keep = false;
  22505. const time = times[i];
  22506. const timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  22507. if (time !== timeNext && (i !== 1 || time !== times[0])) {
  22508. if (!smoothInterpolation) {
  22509. // remove unnecessary keyframes same as their neighbors
  22510. const offset = i * stride,
  22511. offsetP = offset - stride,
  22512. offsetN = offset + stride;
  22513. for (let j = 0; j !== stride; ++j) {
  22514. const value = values[offset + j];
  22515. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  22516. keep = true;
  22517. break;
  22518. }
  22519. }
  22520. } else {
  22521. keep = true;
  22522. }
  22523. } // in-place compaction
  22524. if (keep) {
  22525. if (i !== writeIndex) {
  22526. times[writeIndex] = times[i];
  22527. const readOffset = i * stride,
  22528. writeOffset = writeIndex * stride;
  22529. for (let j = 0; j !== stride; ++j) {
  22530. values[writeOffset + j] = values[readOffset + j];
  22531. }
  22532. }
  22533. ++writeIndex;
  22534. }
  22535. } // flush last keyframe (compaction looks ahead)
  22536. if (lastIndex > 0) {
  22537. times[writeIndex] = times[lastIndex];
  22538. for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  22539. values[writeOffset + j] = values[readOffset + j];
  22540. }
  22541. ++writeIndex;
  22542. }
  22543. if (writeIndex !== times.length) {
  22544. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  22545. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  22546. } else {
  22547. this.times = times;
  22548. this.values = values;
  22549. }
  22550. return this;
  22551. }
  22552. clone() {
  22553. const times = AnimationUtils.arraySlice(this.times, 0);
  22554. const values = AnimationUtils.arraySlice(this.values, 0);
  22555. const TypedKeyframeTrack = this.constructor;
  22556. const track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  22557. track.createInterpolant = this.createInterpolant;
  22558. return track;
  22559. }
  22560. }
  22561. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  22562. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  22563. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  22564. /**
  22565. * A Track of Boolean keyframe values.
  22566. */
  22567. class BooleanKeyframeTrack extends KeyframeTrack {}
  22568. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  22569. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  22570. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22571. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22572. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; // Note: Actually this track could have a optimized / compressed
  22573. /**
  22574. * A Track of keyframe values that represent color.
  22575. */
  22576. class ColorKeyframeTrack extends KeyframeTrack {}
  22577. ColorKeyframeTrack.prototype.ValueTypeName = 'color'; // ValueBufferType is inherited
  22578. /**
  22579. * A Track of numeric keyframe values.
  22580. */
  22581. class NumberKeyframeTrack extends KeyframeTrack {}
  22582. NumberKeyframeTrack.prototype.ValueTypeName = 'number'; // ValueBufferType is inherited
  22583. /**
  22584. * Spherical linear unit quaternion interpolant.
  22585. */
  22586. class QuaternionLinearInterpolant extends Interpolant {
  22587. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22588. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22589. }
  22590. interpolate_(i1, t0, t, t1) {
  22591. const result = this.resultBuffer,
  22592. values = this.sampleValues,
  22593. stride = this.valueSize,
  22594. alpha = (t - t0) / (t1 - t0);
  22595. let offset = i1 * stride;
  22596. for (let end = offset + stride; offset !== end; offset += 4) {
  22597. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  22598. }
  22599. return result;
  22600. }
  22601. }
  22602. /**
  22603. * A Track of quaternion keyframe values.
  22604. */
  22605. class QuaternionKeyframeTrack extends KeyframeTrack {
  22606. InterpolantFactoryMethodLinear(result) {
  22607. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  22608. }
  22609. }
  22610. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion'; // ValueBufferType is inherited
  22611. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  22612. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22613. /**
  22614. * A Track that interpolates Strings
  22615. */
  22616. class StringKeyframeTrack extends KeyframeTrack {}
  22617. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  22618. StringKeyframeTrack.prototype.ValueBufferType = Array;
  22619. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22620. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22621. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22622. /**
  22623. * A Track of vectored keyframe values.
  22624. */
  22625. class VectorKeyframeTrack extends KeyframeTrack {}
  22626. VectorKeyframeTrack.prototype.ValueTypeName = 'vector'; // ValueBufferType is inherited
  22627. class AnimationClip {
  22628. constructor(name, duration = -1, tracks, blendMode = NormalAnimationBlendMode) {
  22629. this.name = name;
  22630. this.tracks = tracks;
  22631. this.duration = duration;
  22632. this.blendMode = blendMode;
  22633. this.uuid = generateUUID(); // this means it should figure out its duration by scanning the tracks
  22634. if (this.duration < 0) {
  22635. this.resetDuration();
  22636. }
  22637. }
  22638. static parse(json) {
  22639. const tracks = [],
  22640. jsonTracks = json.tracks,
  22641. frameTime = 1.0 / (json.fps || 1.0);
  22642. for (let i = 0, n = jsonTracks.length; i !== n; ++i) {
  22643. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  22644. }
  22645. const clip = new this(json.name, json.duration, tracks, json.blendMode);
  22646. clip.uuid = json.uuid;
  22647. return clip;
  22648. }
  22649. static toJSON(clip) {
  22650. const tracks = [],
  22651. clipTracks = clip.tracks;
  22652. const json = {
  22653. 'name': clip.name,
  22654. 'duration': clip.duration,
  22655. 'tracks': tracks,
  22656. 'uuid': clip.uuid,
  22657. 'blendMode': clip.blendMode
  22658. };
  22659. for (let i = 0, n = clipTracks.length; i !== n; ++i) {
  22660. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  22661. }
  22662. return json;
  22663. }
  22664. static CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) {
  22665. const numMorphTargets = morphTargetSequence.length;
  22666. const tracks = [];
  22667. for (let i = 0; i < numMorphTargets; i++) {
  22668. let times = [];
  22669. let values = [];
  22670. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  22671. values.push(0, 1, 0);
  22672. const order = AnimationUtils.getKeyframeOrder(times);
  22673. times = AnimationUtils.sortedArray(times, 1, order);
  22674. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  22675. // last frame as well for perfect loop.
  22676. if (!noLoop && times[0] === 0) {
  22677. times.push(numMorphTargets);
  22678. values.push(values[0]);
  22679. }
  22680. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  22681. }
  22682. return new this(name, -1, tracks);
  22683. }
  22684. static findByName(objectOrClipArray, name) {
  22685. let clipArray = objectOrClipArray;
  22686. if (!Array.isArray(objectOrClipArray)) {
  22687. const o = objectOrClipArray;
  22688. clipArray = o.geometry && o.geometry.animations || o.animations;
  22689. }
  22690. for (let i = 0; i < clipArray.length; i++) {
  22691. if (clipArray[i].name === name) {
  22692. return clipArray[i];
  22693. }
  22694. }
  22695. return null;
  22696. }
  22697. static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {
  22698. const animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  22699. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  22700. const pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  22701. // patterns like Walk_001, Walk_002, Run_001, Run_002
  22702. for (let i = 0, il = morphTargets.length; i < il; i++) {
  22703. const morphTarget = morphTargets[i];
  22704. const parts = morphTarget.name.match(pattern);
  22705. if (parts && parts.length > 1) {
  22706. const name = parts[1];
  22707. let animationMorphTargets = animationToMorphTargets[name];
  22708. if (!animationMorphTargets) {
  22709. animationToMorphTargets[name] = animationMorphTargets = [];
  22710. }
  22711. animationMorphTargets.push(morphTarget);
  22712. }
  22713. }
  22714. const clips = [];
  22715. for (const name in animationToMorphTargets) {
  22716. clips.push(this.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  22717. }
  22718. return clips;
  22719. } // parse the animation.hierarchy format
  22720. static parseAnimation(animation, bones) {
  22721. if (!animation) {
  22722. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  22723. return null;
  22724. }
  22725. const addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  22726. // only return track if there are actually keys.
  22727. if (animationKeys.length !== 0) {
  22728. const times = [];
  22729. const values = [];
  22730. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  22731. if (times.length !== 0) {
  22732. destTracks.push(new trackType(trackName, times, values));
  22733. }
  22734. }
  22735. };
  22736. const tracks = [];
  22737. const clipName = animation.name || 'default';
  22738. const fps = animation.fps || 30;
  22739. const blendMode = animation.blendMode; // automatic length determination in AnimationClip.
  22740. let duration = animation.length || -1;
  22741. const hierarchyTracks = animation.hierarchy || [];
  22742. for (let h = 0; h < hierarchyTracks.length; h++) {
  22743. const animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  22744. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  22745. if (animationKeys[0].morphTargets) {
  22746. // figure out all morph targets used in this track
  22747. const morphTargetNames = {};
  22748. let k;
  22749. for (k = 0; k < animationKeys.length; k++) {
  22750. if (animationKeys[k].morphTargets) {
  22751. for (let m = 0; m < animationKeys[k].morphTargets.length; m++) {
  22752. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  22753. }
  22754. }
  22755. } // create a track for each morph target with all zero
  22756. // morphTargetInfluences except for the keys in which
  22757. // the morphTarget is named.
  22758. for (const morphTargetName in morphTargetNames) {
  22759. const times = [];
  22760. const values = [];
  22761. for (let m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  22762. const animationKey = animationKeys[k];
  22763. times.push(animationKey.time);
  22764. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  22765. }
  22766. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  22767. }
  22768. duration = morphTargetNames.length * (fps || 1.0);
  22769. } else {
  22770. // ...assume skeletal animation
  22771. const boneName = '.bones[' + bones[h].name + ']';
  22772. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  22773. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  22774. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  22775. }
  22776. }
  22777. if (tracks.length === 0) {
  22778. return null;
  22779. }
  22780. const clip = new this(clipName, duration, tracks, blendMode);
  22781. return clip;
  22782. }
  22783. resetDuration() {
  22784. const tracks = this.tracks;
  22785. let duration = 0;
  22786. for (let i = 0, n = tracks.length; i !== n; ++i) {
  22787. const track = this.tracks[i];
  22788. duration = Math.max(duration, track.times[track.times.length - 1]);
  22789. }
  22790. this.duration = duration;
  22791. return this;
  22792. }
  22793. trim() {
  22794. for (let i = 0; i < this.tracks.length; i++) {
  22795. this.tracks[i].trim(0, this.duration);
  22796. }
  22797. return this;
  22798. }
  22799. validate() {
  22800. let valid = true;
  22801. for (let i = 0; i < this.tracks.length; i++) {
  22802. valid = valid && this.tracks[i].validate();
  22803. }
  22804. return valid;
  22805. }
  22806. optimize() {
  22807. for (let i = 0; i < this.tracks.length; i++) {
  22808. this.tracks[i].optimize();
  22809. }
  22810. return this;
  22811. }
  22812. clone() {
  22813. const tracks = [];
  22814. for (let i = 0; i < this.tracks.length; i++) {
  22815. tracks.push(this.tracks[i].clone());
  22816. }
  22817. return new this.constructor(this.name, this.duration, tracks, this.blendMode);
  22818. }
  22819. toJSON() {
  22820. return this.constructor.toJSON(this);
  22821. }
  22822. }
  22823. function getTrackTypeForValueTypeName(typeName) {
  22824. switch (typeName.toLowerCase()) {
  22825. case 'scalar':
  22826. case 'double':
  22827. case 'float':
  22828. case 'number':
  22829. case 'integer':
  22830. return NumberKeyframeTrack;
  22831. case 'vector':
  22832. case 'vector2':
  22833. case 'vector3':
  22834. case 'vector4':
  22835. return VectorKeyframeTrack;
  22836. case 'color':
  22837. return ColorKeyframeTrack;
  22838. case 'quaternion':
  22839. return QuaternionKeyframeTrack;
  22840. case 'bool':
  22841. case 'boolean':
  22842. return BooleanKeyframeTrack;
  22843. case 'string':
  22844. return StringKeyframeTrack;
  22845. }
  22846. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  22847. }
  22848. function parseKeyframeTrack(json) {
  22849. if (json.type === undefined) {
  22850. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  22851. }
  22852. const trackType = getTrackTypeForValueTypeName(json.type);
  22853. if (json.times === undefined) {
  22854. const times = [],
  22855. values = [];
  22856. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  22857. json.times = times;
  22858. json.values = values;
  22859. } // derived classes can define a static parse method
  22860. if (trackType.parse !== undefined) {
  22861. return trackType.parse(json);
  22862. } else {
  22863. // by default, we assume a constructor compatible with the base
  22864. return new trackType(json.name, json.times, json.values, json.interpolation);
  22865. }
  22866. }
  22867. const Cache = {
  22868. enabled: false,
  22869. files: {},
  22870. add: function (key, file) {
  22871. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  22872. this.files[key] = file;
  22873. },
  22874. get: function (key) {
  22875. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  22876. return this.files[key];
  22877. },
  22878. remove: function (key) {
  22879. delete this.files[key];
  22880. },
  22881. clear: function () {
  22882. this.files = {};
  22883. }
  22884. };
  22885. class LoadingManager {
  22886. constructor(onLoad, onProgress, onError) {
  22887. const scope = this;
  22888. let isLoading = false;
  22889. let itemsLoaded = 0;
  22890. let itemsTotal = 0;
  22891. let urlModifier = undefined;
  22892. const handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  22893. // in the constructor
  22894. this.onStart = undefined;
  22895. this.onLoad = onLoad;
  22896. this.onProgress = onProgress;
  22897. this.onError = onError;
  22898. this.itemStart = function (url) {
  22899. itemsTotal++;
  22900. if (isLoading === false) {
  22901. if (scope.onStart !== undefined) {
  22902. scope.onStart(url, itemsLoaded, itemsTotal);
  22903. }
  22904. }
  22905. isLoading = true;
  22906. };
  22907. this.itemEnd = function (url) {
  22908. itemsLoaded++;
  22909. if (scope.onProgress !== undefined) {
  22910. scope.onProgress(url, itemsLoaded, itemsTotal);
  22911. }
  22912. if (itemsLoaded === itemsTotal) {
  22913. isLoading = false;
  22914. if (scope.onLoad !== undefined) {
  22915. scope.onLoad();
  22916. }
  22917. }
  22918. };
  22919. this.itemError = function (url) {
  22920. if (scope.onError !== undefined) {
  22921. scope.onError(url);
  22922. }
  22923. };
  22924. this.resolveURL = function (url) {
  22925. if (urlModifier) {
  22926. return urlModifier(url);
  22927. }
  22928. return url;
  22929. };
  22930. this.setURLModifier = function (transform) {
  22931. urlModifier = transform;
  22932. return this;
  22933. };
  22934. this.addHandler = function (regex, loader) {
  22935. handlers.push(regex, loader);
  22936. return this;
  22937. };
  22938. this.removeHandler = function (regex) {
  22939. const index = handlers.indexOf(regex);
  22940. if (index !== -1) {
  22941. handlers.splice(index, 2);
  22942. }
  22943. return this;
  22944. };
  22945. this.getHandler = function (file) {
  22946. for (let i = 0, l = handlers.length; i < l; i += 2) {
  22947. const regex = handlers[i];
  22948. const loader = handlers[i + 1];
  22949. if (regex.global) regex.lastIndex = 0; // see #17920
  22950. if (regex.test(file)) {
  22951. return loader;
  22952. }
  22953. }
  22954. return null;
  22955. };
  22956. }
  22957. }
  22958. const DefaultLoadingManager = new LoadingManager();
  22959. class Loader {
  22960. constructor(manager) {
  22961. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  22962. this.crossOrigin = 'anonymous';
  22963. this.withCredentials = false;
  22964. this.path = '';
  22965. this.resourcePath = '';
  22966. this.requestHeader = {};
  22967. }
  22968. load() {}
  22969. loadAsync(url, onProgress) {
  22970. const scope = this;
  22971. return new Promise(function (resolve, reject) {
  22972. scope.load(url, resolve, onProgress, reject);
  22973. });
  22974. }
  22975. parse() {}
  22976. setCrossOrigin(crossOrigin) {
  22977. this.crossOrigin = crossOrigin;
  22978. return this;
  22979. }
  22980. setWithCredentials(value) {
  22981. this.withCredentials = value;
  22982. return this;
  22983. }
  22984. setPath(path) {
  22985. this.path = path;
  22986. return this;
  22987. }
  22988. setResourcePath(resourcePath) {
  22989. this.resourcePath = resourcePath;
  22990. return this;
  22991. }
  22992. setRequestHeader(requestHeader) {
  22993. this.requestHeader = requestHeader;
  22994. return this;
  22995. }
  22996. }
  22997. const loading = {};
  22998. class FileLoader extends Loader {
  22999. constructor(manager) {
  23000. super(manager);
  23001. }
  23002. load(url, onLoad, onProgress, onError) {
  23003. if (url === undefined) url = '';
  23004. if (this.path !== undefined) url = this.path + url;
  23005. url = this.manager.resolveURL(url);
  23006. const cached = Cache.get(url);
  23007. if (cached !== undefined) {
  23008. this.manager.itemStart(url);
  23009. setTimeout(() => {
  23010. if (onLoad) onLoad(cached);
  23011. this.manager.itemEnd(url);
  23012. }, 0);
  23013. return cached;
  23014. } // Check if request is duplicate
  23015. if (loading[url] !== undefined) {
  23016. loading[url].push({
  23017. onLoad: onLoad,
  23018. onProgress: onProgress,
  23019. onError: onError
  23020. });
  23021. return;
  23022. } // Initialise array for duplicate requests
  23023. loading[url] = [];
  23024. loading[url].push({
  23025. onLoad: onLoad,
  23026. onProgress: onProgress,
  23027. onError: onError
  23028. }); // create request
  23029. const req = new Request(url, {
  23030. headers: new Headers(this.requestHeader),
  23031. credentials: this.withCredentials ? 'include' : 'same-origin' // An abort controller could be added within a future PR
  23032. }); // start the fetch
  23033. fetch(req).then(response => {
  23034. if (response.status === 200 || response.status === 0) {
  23035. // Some browsers return HTTP Status 0 when using non-http protocol
  23036. // e.g. 'file://' or 'data://'. Handle as success.
  23037. if (response.status === 0) {
  23038. console.warn('THREE.FileLoader: HTTP Status 0 received.');
  23039. }
  23040. const callbacks = loading[url];
  23041. const reader = response.body.getReader();
  23042. const contentLength = response.headers.get('Content-Length');
  23043. const total = contentLength ? parseInt(contentLength) : 0;
  23044. const lengthComputable = total !== 0;
  23045. let loaded = 0; // periodically read data into the new stream tracking while download progress
  23046. return new ReadableStream({
  23047. start(controller) {
  23048. readData();
  23049. function readData() {
  23050. reader.read().then(({
  23051. done,
  23052. value
  23053. }) => {
  23054. if (done) {
  23055. controller.close();
  23056. } else {
  23057. loaded += value.byteLength;
  23058. const event = new ProgressEvent('progress', {
  23059. lengthComputable,
  23060. loaded,
  23061. total
  23062. });
  23063. for (let i = 0, il = callbacks.length; i < il; i++) {
  23064. const callback = callbacks[i];
  23065. if (callback.onProgress) callback.onProgress(event);
  23066. }
  23067. controller.enqueue(value);
  23068. readData();
  23069. }
  23070. });
  23071. }
  23072. }
  23073. });
  23074. } else {
  23075. throw Error(`fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`);
  23076. }
  23077. }).then(stream => {
  23078. const response = new Response(stream);
  23079. switch (this.responseType) {
  23080. case 'arraybuffer':
  23081. return response.arrayBuffer();
  23082. case 'blob':
  23083. return response.blob();
  23084. case 'document':
  23085. return response.text().then(text => {
  23086. const parser = new DOMParser();
  23087. return parser.parseFromString(text, this.mimeType);
  23088. });
  23089. case 'json':
  23090. return response.json();
  23091. default:
  23092. return response.text();
  23093. }
  23094. }).then(data => {
  23095. // Add to cache only on HTTP success, so that we do not cache
  23096. // error response bodies as proper responses to requests.
  23097. Cache.add(url, data);
  23098. const callbacks = loading[url];
  23099. delete loading[url];
  23100. for (let i = 0, il = callbacks.length; i < il; i++) {
  23101. const callback = callbacks[i];
  23102. if (callback.onLoad) callback.onLoad(data);
  23103. }
  23104. }).catch(err => {
  23105. // Abort errors and other errors are handled the same
  23106. const callbacks = loading[url];
  23107. if (callbacks === undefined) {
  23108. // When onLoad was called and url was deleted in `loading`
  23109. this.manager.itemError(url);
  23110. throw err;
  23111. }
  23112. delete loading[url];
  23113. for (let i = 0, il = callbacks.length; i < il; i++) {
  23114. const callback = callbacks[i];
  23115. if (callback.onError) callback.onError(err);
  23116. }
  23117. this.manager.itemError(url);
  23118. }).finally(() => {
  23119. this.manager.itemEnd(url);
  23120. });
  23121. this.manager.itemStart(url);
  23122. }
  23123. setResponseType(value) {
  23124. this.responseType = value;
  23125. return this;
  23126. }
  23127. setMimeType(value) {
  23128. this.mimeType = value;
  23129. return this;
  23130. }
  23131. }
  23132. class AnimationLoader extends Loader {
  23133. constructor(manager) {
  23134. super(manager);
  23135. }
  23136. load(url, onLoad, onProgress, onError) {
  23137. const scope = this;
  23138. const loader = new FileLoader(this.manager);
  23139. loader.setPath(this.path);
  23140. loader.setRequestHeader(this.requestHeader);
  23141. loader.setWithCredentials(this.withCredentials);
  23142. loader.load(url, function (text) {
  23143. try {
  23144. onLoad(scope.parse(JSON.parse(text)));
  23145. } catch (e) {
  23146. if (onError) {
  23147. onError(e);
  23148. } else {
  23149. console.error(e);
  23150. }
  23151. scope.manager.itemError(url);
  23152. }
  23153. }, onProgress, onError);
  23154. }
  23155. parse(json) {
  23156. const animations = [];
  23157. for (let i = 0; i < json.length; i++) {
  23158. const clip = AnimationClip.parse(json[i]);
  23159. animations.push(clip);
  23160. }
  23161. return animations;
  23162. }
  23163. }
  23164. /**
  23165. * Abstract Base class to block based textures loader (dds, pvr, ...)
  23166. *
  23167. * Sub classes have to implement the parse() method which will be used in load().
  23168. */
  23169. class CompressedTextureLoader extends Loader {
  23170. constructor(manager) {
  23171. super(manager);
  23172. }
  23173. load(url, onLoad, onProgress, onError) {
  23174. const scope = this;
  23175. const images = [];
  23176. const texture = new CompressedTexture();
  23177. const loader = new FileLoader(this.manager);
  23178. loader.setPath(this.path);
  23179. loader.setResponseType('arraybuffer');
  23180. loader.setRequestHeader(this.requestHeader);
  23181. loader.setWithCredentials(scope.withCredentials);
  23182. let loaded = 0;
  23183. function loadTexture(i) {
  23184. loader.load(url[i], function (buffer) {
  23185. const texDatas = scope.parse(buffer, true);
  23186. images[i] = {
  23187. width: texDatas.width,
  23188. height: texDatas.height,
  23189. format: texDatas.format,
  23190. mipmaps: texDatas.mipmaps
  23191. };
  23192. loaded += 1;
  23193. if (loaded === 6) {
  23194. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  23195. texture.image = images;
  23196. texture.format = texDatas.format;
  23197. texture.needsUpdate = true;
  23198. if (onLoad) onLoad(texture);
  23199. }
  23200. }, onProgress, onError);
  23201. }
  23202. if (Array.isArray(url)) {
  23203. for (let i = 0, il = url.length; i < il; ++i) {
  23204. loadTexture(i);
  23205. }
  23206. } else {
  23207. // compressed cubemap texture stored in a single DDS file
  23208. loader.load(url, function (buffer) {
  23209. const texDatas = scope.parse(buffer, true);
  23210. if (texDatas.isCubemap) {
  23211. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  23212. for (let f = 0; f < faces; f++) {
  23213. images[f] = {
  23214. mipmaps: []
  23215. };
  23216. for (let i = 0; i < texDatas.mipmapCount; i++) {
  23217. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  23218. images[f].format = texDatas.format;
  23219. images[f].width = texDatas.width;
  23220. images[f].height = texDatas.height;
  23221. }
  23222. }
  23223. texture.image = images;
  23224. } else {
  23225. texture.image.width = texDatas.width;
  23226. texture.image.height = texDatas.height;
  23227. texture.mipmaps = texDatas.mipmaps;
  23228. }
  23229. if (texDatas.mipmapCount === 1) {
  23230. texture.minFilter = LinearFilter;
  23231. }
  23232. texture.format = texDatas.format;
  23233. texture.needsUpdate = true;
  23234. if (onLoad) onLoad(texture);
  23235. }, onProgress, onError);
  23236. }
  23237. return texture;
  23238. }
  23239. }
  23240. class ImageLoader extends Loader {
  23241. constructor(manager) {
  23242. super(manager);
  23243. }
  23244. load(url, onLoad, onProgress, onError) {
  23245. if (this.path !== undefined) url = this.path + url;
  23246. url = this.manager.resolveURL(url);
  23247. const scope = this;
  23248. const cached = Cache.get(url);
  23249. if (cached !== undefined) {
  23250. scope.manager.itemStart(url);
  23251. setTimeout(function () {
  23252. if (onLoad) onLoad(cached);
  23253. scope.manager.itemEnd(url);
  23254. }, 0);
  23255. return cached;
  23256. }
  23257. const image = createElementNS('img');
  23258. function onImageLoad() {
  23259. removeEventListeners();
  23260. Cache.add(url, this);
  23261. if (onLoad) onLoad(this);
  23262. scope.manager.itemEnd(url);
  23263. }
  23264. function onImageError(event) {
  23265. removeEventListeners();
  23266. if (onError) onError(event);
  23267. scope.manager.itemError(url);
  23268. scope.manager.itemEnd(url);
  23269. }
  23270. function removeEventListeners() {
  23271. image.removeEventListener('load', onImageLoad, false);
  23272. image.removeEventListener('error', onImageError, false);
  23273. }
  23274. image.addEventListener('load', onImageLoad, false);
  23275. image.addEventListener('error', onImageError, false);
  23276. if (url.substr(0, 5) !== 'data:') {
  23277. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  23278. }
  23279. scope.manager.itemStart(url);
  23280. image.src = url;
  23281. return image;
  23282. }
  23283. }
  23284. class CubeTextureLoader extends Loader {
  23285. constructor(manager) {
  23286. super(manager);
  23287. }
  23288. load(urls, onLoad, onProgress, onError) {
  23289. const texture = new CubeTexture();
  23290. const loader = new ImageLoader(this.manager);
  23291. loader.setCrossOrigin(this.crossOrigin);
  23292. loader.setPath(this.path);
  23293. let loaded = 0;
  23294. function loadTexture(i) {
  23295. loader.load(urls[i], function (image) {
  23296. texture.images[i] = image;
  23297. loaded++;
  23298. if (loaded === 6) {
  23299. texture.needsUpdate = true;
  23300. if (onLoad) onLoad(texture);
  23301. }
  23302. }, undefined, onError);
  23303. }
  23304. for (let i = 0; i < urls.length; ++i) {
  23305. loadTexture(i);
  23306. }
  23307. return texture;
  23308. }
  23309. }
  23310. /**
  23311. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  23312. *
  23313. * Sub classes have to implement the parse() method which will be used in load().
  23314. */
  23315. class DataTextureLoader extends Loader {
  23316. constructor(manager) {
  23317. super(manager);
  23318. }
  23319. load(url, onLoad, onProgress, onError) {
  23320. const scope = this;
  23321. const texture = new DataTexture();
  23322. const loader = new FileLoader(this.manager);
  23323. loader.setResponseType('arraybuffer');
  23324. loader.setRequestHeader(this.requestHeader);
  23325. loader.setPath(this.path);
  23326. loader.setWithCredentials(scope.withCredentials);
  23327. loader.load(url, function (buffer) {
  23328. const texData = scope.parse(buffer);
  23329. if (!texData) return;
  23330. if (texData.image !== undefined) {
  23331. texture.image = texData.image;
  23332. } else if (texData.data !== undefined) {
  23333. texture.image.width = texData.width;
  23334. texture.image.height = texData.height;
  23335. texture.image.data = texData.data;
  23336. }
  23337. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  23338. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  23339. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  23340. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  23341. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  23342. if (texData.encoding !== undefined) {
  23343. texture.encoding = texData.encoding;
  23344. }
  23345. if (texData.flipY !== undefined) {
  23346. texture.flipY = texData.flipY;
  23347. }
  23348. if (texData.format !== undefined) {
  23349. texture.format = texData.format;
  23350. }
  23351. if (texData.type !== undefined) {
  23352. texture.type = texData.type;
  23353. }
  23354. if (texData.mipmaps !== undefined) {
  23355. texture.mipmaps = texData.mipmaps;
  23356. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  23357. }
  23358. if (texData.mipmapCount === 1) {
  23359. texture.minFilter = LinearFilter;
  23360. }
  23361. if (texData.generateMipmaps !== undefined) {
  23362. texture.generateMipmaps = texData.generateMipmaps;
  23363. }
  23364. texture.needsUpdate = true;
  23365. if (onLoad) onLoad(texture, texData);
  23366. }, onProgress, onError);
  23367. return texture;
  23368. }
  23369. }
  23370. class TextureLoader extends Loader {
  23371. constructor(manager) {
  23372. super(manager);
  23373. }
  23374. load(url, onLoad, onProgress, onError) {
  23375. const texture = new Texture();
  23376. const loader = new ImageLoader(this.manager);
  23377. loader.setCrossOrigin(this.crossOrigin);
  23378. loader.setPath(this.path);
  23379. loader.load(url, function (image) {
  23380. texture.image = image;
  23381. texture.needsUpdate = true;
  23382. if (onLoad !== undefined) {
  23383. onLoad(texture);
  23384. }
  23385. }, onProgress, onError);
  23386. return texture;
  23387. }
  23388. }
  23389. class Light extends Object3D {
  23390. constructor(color, intensity = 1) {
  23391. super();
  23392. this.type = 'Light';
  23393. this.color = new Color(color);
  23394. this.intensity = intensity;
  23395. }
  23396. dispose() {// Empty here in base class; some subclasses override.
  23397. }
  23398. copy(source) {
  23399. super.copy(source);
  23400. this.color.copy(source.color);
  23401. this.intensity = source.intensity;
  23402. return this;
  23403. }
  23404. toJSON(meta) {
  23405. const data = super.toJSON(meta);
  23406. data.object.color = this.color.getHex();
  23407. data.object.intensity = this.intensity;
  23408. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  23409. if (this.distance !== undefined) data.object.distance = this.distance;
  23410. if (this.angle !== undefined) data.object.angle = this.angle;
  23411. if (this.decay !== undefined) data.object.decay = this.decay;
  23412. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  23413. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  23414. return data;
  23415. }
  23416. }
  23417. Light.prototype.isLight = true;
  23418. class HemisphereLight extends Light {
  23419. constructor(skyColor, groundColor, intensity) {
  23420. super(skyColor, intensity);
  23421. this.type = 'HemisphereLight';
  23422. this.position.copy(Object3D.DefaultUp);
  23423. this.updateMatrix();
  23424. this.groundColor = new Color(groundColor);
  23425. }
  23426. copy(source) {
  23427. Light.prototype.copy.call(this, source);
  23428. this.groundColor.copy(source.groundColor);
  23429. return this;
  23430. }
  23431. }
  23432. HemisphereLight.prototype.isHemisphereLight = true;
  23433. const _projScreenMatrix$1 = /*@__PURE__*/new Matrix4();
  23434. const _lightPositionWorld$1 = /*@__PURE__*/new Vector3();
  23435. const _lookTarget$1 = /*@__PURE__*/new Vector3();
  23436. class LightShadow {
  23437. constructor(camera) {
  23438. this.camera = camera;
  23439. this.bias = 0;
  23440. this.normalBias = 0;
  23441. this.radius = 1;
  23442. this.blurSamples = 8;
  23443. this.mapSize = new Vector2(512, 512);
  23444. this.map = null;
  23445. this.mapPass = null;
  23446. this.matrix = new Matrix4();
  23447. this.autoUpdate = true;
  23448. this.needsUpdate = false;
  23449. this._frustum = new Frustum();
  23450. this._frameExtents = new Vector2(1, 1);
  23451. this._viewportCount = 1;
  23452. this._viewports = [new Vector4(0, 0, 1, 1)];
  23453. }
  23454. getViewportCount() {
  23455. return this._viewportCount;
  23456. }
  23457. getFrustum() {
  23458. return this._frustum;
  23459. }
  23460. updateMatrices(light) {
  23461. const shadowCamera = this.camera;
  23462. const shadowMatrix = this.matrix;
  23463. _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld);
  23464. shadowCamera.position.copy(_lightPositionWorld$1);
  23465. _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld);
  23466. shadowCamera.lookAt(_lookTarget$1);
  23467. shadowCamera.updateMatrixWorld();
  23468. _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  23469. this._frustum.setFromProjectionMatrix(_projScreenMatrix$1);
  23470. shadowMatrix.set(0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0);
  23471. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  23472. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  23473. }
  23474. getViewport(viewportIndex) {
  23475. return this._viewports[viewportIndex];
  23476. }
  23477. getFrameExtents() {
  23478. return this._frameExtents;
  23479. }
  23480. dispose() {
  23481. if (this.map) {
  23482. this.map.dispose();
  23483. }
  23484. if (this.mapPass) {
  23485. this.mapPass.dispose();
  23486. }
  23487. }
  23488. copy(source) {
  23489. this.camera = source.camera.clone();
  23490. this.bias = source.bias;
  23491. this.radius = source.radius;
  23492. this.mapSize.copy(source.mapSize);
  23493. return this;
  23494. }
  23495. clone() {
  23496. return new this.constructor().copy(this);
  23497. }
  23498. toJSON() {
  23499. const object = {};
  23500. if (this.bias !== 0) object.bias = this.bias;
  23501. if (this.normalBias !== 0) object.normalBias = this.normalBias;
  23502. if (this.radius !== 1) object.radius = this.radius;
  23503. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  23504. object.camera = this.camera.toJSON(false).object;
  23505. delete object.camera.matrix;
  23506. return object;
  23507. }
  23508. }
  23509. class SpotLightShadow extends LightShadow {
  23510. constructor() {
  23511. super(new PerspectiveCamera(50, 1, 0.5, 500));
  23512. this.focus = 1;
  23513. }
  23514. updateMatrices(light) {
  23515. const camera = this.camera;
  23516. const fov = RAD2DEG * 2 * light.angle * this.focus;
  23517. const aspect = this.mapSize.width / this.mapSize.height;
  23518. const far = light.distance || camera.far;
  23519. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  23520. camera.fov = fov;
  23521. camera.aspect = aspect;
  23522. camera.far = far;
  23523. camera.updateProjectionMatrix();
  23524. }
  23525. super.updateMatrices(light);
  23526. }
  23527. copy(source) {
  23528. super.copy(source);
  23529. this.focus = source.focus;
  23530. return this;
  23531. }
  23532. }
  23533. SpotLightShadow.prototype.isSpotLightShadow = true;
  23534. class SpotLight extends Light {
  23535. constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1) {
  23536. super(color, intensity);
  23537. this.type = 'SpotLight';
  23538. this.position.copy(Object3D.DefaultUp);
  23539. this.updateMatrix();
  23540. this.target = new Object3D();
  23541. this.distance = distance;
  23542. this.angle = angle;
  23543. this.penumbra = penumbra;
  23544. this.decay = decay; // for physically correct lights, should be 2.
  23545. this.shadow = new SpotLightShadow();
  23546. }
  23547. get power() {
  23548. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23549. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  23550. return this.intensity * Math.PI;
  23551. }
  23552. set power(power) {
  23553. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23554. this.intensity = power / Math.PI;
  23555. }
  23556. dispose() {
  23557. this.shadow.dispose();
  23558. }
  23559. copy(source) {
  23560. super.copy(source);
  23561. this.distance = source.distance;
  23562. this.angle = source.angle;
  23563. this.penumbra = source.penumbra;
  23564. this.decay = source.decay;
  23565. this.target = source.target.clone();
  23566. this.shadow = source.shadow.clone();
  23567. return this;
  23568. }
  23569. }
  23570. SpotLight.prototype.isSpotLight = true;
  23571. const _projScreenMatrix = /*@__PURE__*/new Matrix4();
  23572. const _lightPositionWorld = /*@__PURE__*/new Vector3();
  23573. const _lookTarget = /*@__PURE__*/new Vector3();
  23574. class PointLightShadow extends LightShadow {
  23575. constructor() {
  23576. super(new PerspectiveCamera(90, 1, 0.5, 500));
  23577. this._frameExtents = new Vector2(4, 2);
  23578. this._viewportCount = 6;
  23579. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  23580. // following orientation:
  23581. //
  23582. // xzXZ
  23583. // y Y
  23584. //
  23585. // X - Positive x direction
  23586. // x - Negative x direction
  23587. // Y - Positive y direction
  23588. // y - Negative y direction
  23589. // Z - Positive z direction
  23590. // z - Negative z direction
  23591. // positive X
  23592. new Vector4(2, 1, 1, 1), // negative X
  23593. new Vector4(0, 1, 1, 1), // positive Z
  23594. new Vector4(3, 1, 1, 1), // negative Z
  23595. new Vector4(1, 1, 1, 1), // positive Y
  23596. new Vector4(3, 0, 1, 1), // negative Y
  23597. new Vector4(1, 0, 1, 1)];
  23598. this._cubeDirections = [new Vector3(1, 0, 0), new Vector3(-1, 0, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1), new Vector3(0, 1, 0), new Vector3(0, -1, 0)];
  23599. this._cubeUps = [new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1)];
  23600. }
  23601. updateMatrices(light, viewportIndex = 0) {
  23602. const camera = this.camera;
  23603. const shadowMatrix = this.matrix;
  23604. const far = light.distance || camera.far;
  23605. if (far !== camera.far) {
  23606. camera.far = far;
  23607. camera.updateProjectionMatrix();
  23608. }
  23609. _lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23610. camera.position.copy(_lightPositionWorld);
  23611. _lookTarget.copy(camera.position);
  23612. _lookTarget.add(this._cubeDirections[viewportIndex]);
  23613. camera.up.copy(this._cubeUps[viewportIndex]);
  23614. camera.lookAt(_lookTarget);
  23615. camera.updateMatrixWorld();
  23616. shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z);
  23617. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  23618. this._frustum.setFromProjectionMatrix(_projScreenMatrix);
  23619. }
  23620. }
  23621. PointLightShadow.prototype.isPointLightShadow = true;
  23622. class PointLight extends Light {
  23623. constructor(color, intensity, distance = 0, decay = 1) {
  23624. super(color, intensity);
  23625. this.type = 'PointLight';
  23626. this.distance = distance;
  23627. this.decay = decay; // for physically correct lights, should be 2.
  23628. this.shadow = new PointLightShadow();
  23629. }
  23630. get power() {
  23631. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23632. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  23633. return this.intensity * 4 * Math.PI;
  23634. }
  23635. set power(power) {
  23636. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23637. this.intensity = power / (4 * Math.PI);
  23638. }
  23639. dispose() {
  23640. this.shadow.dispose();
  23641. }
  23642. copy(source) {
  23643. super.copy(source);
  23644. this.distance = source.distance;
  23645. this.decay = source.decay;
  23646. this.shadow = source.shadow.clone();
  23647. return this;
  23648. }
  23649. }
  23650. PointLight.prototype.isPointLight = true;
  23651. class DirectionalLightShadow extends LightShadow {
  23652. constructor() {
  23653. super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  23654. }
  23655. }
  23656. DirectionalLightShadow.prototype.isDirectionalLightShadow = true;
  23657. class DirectionalLight extends Light {
  23658. constructor(color, intensity) {
  23659. super(color, intensity);
  23660. this.type = 'DirectionalLight';
  23661. this.position.copy(Object3D.DefaultUp);
  23662. this.updateMatrix();
  23663. this.target = new Object3D();
  23664. this.shadow = new DirectionalLightShadow();
  23665. }
  23666. dispose() {
  23667. this.shadow.dispose();
  23668. }
  23669. copy(source) {
  23670. super.copy(source);
  23671. this.target = source.target.clone();
  23672. this.shadow = source.shadow.clone();
  23673. return this;
  23674. }
  23675. }
  23676. DirectionalLight.prototype.isDirectionalLight = true;
  23677. class AmbientLight extends Light {
  23678. constructor(color, intensity) {
  23679. super(color, intensity);
  23680. this.type = 'AmbientLight';
  23681. }
  23682. }
  23683. AmbientLight.prototype.isAmbientLight = true;
  23684. class RectAreaLight extends Light {
  23685. constructor(color, intensity, width = 10, height = 10) {
  23686. super(color, intensity);
  23687. this.type = 'RectAreaLight';
  23688. this.width = width;
  23689. this.height = height;
  23690. }
  23691. get power() {
  23692. // compute the light's luminous power (in lumens) from its intensity (in nits)
  23693. return this.intensity * this.width * this.height * Math.PI;
  23694. }
  23695. set power(power) {
  23696. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  23697. this.intensity = power / (this.width * this.height * Math.PI);
  23698. }
  23699. copy(source) {
  23700. super.copy(source);
  23701. this.width = source.width;
  23702. this.height = source.height;
  23703. return this;
  23704. }
  23705. toJSON(meta) {
  23706. const data = super.toJSON(meta);
  23707. data.object.width = this.width;
  23708. data.object.height = this.height;
  23709. return data;
  23710. }
  23711. }
  23712. RectAreaLight.prototype.isRectAreaLight = true;
  23713. /**
  23714. * Primary reference:
  23715. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23716. *
  23717. * Secondary reference:
  23718. * https://www.ppsloan.org/publications/StupidSH36.pdf
  23719. */
  23720. // 3-band SH defined by 9 coefficients
  23721. class SphericalHarmonics3 {
  23722. constructor() {
  23723. this.coefficients = [];
  23724. for (let i = 0; i < 9; i++) {
  23725. this.coefficients.push(new Vector3());
  23726. }
  23727. }
  23728. set(coefficients) {
  23729. for (let i = 0; i < 9; i++) {
  23730. this.coefficients[i].copy(coefficients[i]);
  23731. }
  23732. return this;
  23733. }
  23734. zero() {
  23735. for (let i = 0; i < 9; i++) {
  23736. this.coefficients[i].set(0, 0, 0);
  23737. }
  23738. return this;
  23739. } // get the radiance in the direction of the normal
  23740. // target is a Vector3
  23741. getAt(normal, target) {
  23742. // normal is assumed to be unit length
  23743. const x = normal.x,
  23744. y = normal.y,
  23745. z = normal.z;
  23746. const coeff = this.coefficients; // band 0
  23747. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  23748. target.addScaledVector(coeff[1], 0.488603 * y);
  23749. target.addScaledVector(coeff[2], 0.488603 * z);
  23750. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  23751. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  23752. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  23753. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  23754. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  23755. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  23756. return target;
  23757. } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  23758. // target is a Vector3
  23759. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23760. getIrradianceAt(normal, target) {
  23761. // normal is assumed to be unit length
  23762. const x = normal.x,
  23763. y = normal.y,
  23764. z = normal.z;
  23765. const coeff = this.coefficients; // band 0
  23766. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  23767. // band 1
  23768. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  23769. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  23770. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  23771. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  23772. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  23773. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  23774. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  23775. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  23776. return target;
  23777. }
  23778. add(sh) {
  23779. for (let i = 0; i < 9; i++) {
  23780. this.coefficients[i].add(sh.coefficients[i]);
  23781. }
  23782. return this;
  23783. }
  23784. addScaledSH(sh, s) {
  23785. for (let i = 0; i < 9; i++) {
  23786. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  23787. }
  23788. return this;
  23789. }
  23790. scale(s) {
  23791. for (let i = 0; i < 9; i++) {
  23792. this.coefficients[i].multiplyScalar(s);
  23793. }
  23794. return this;
  23795. }
  23796. lerp(sh, alpha) {
  23797. for (let i = 0; i < 9; i++) {
  23798. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  23799. }
  23800. return this;
  23801. }
  23802. equals(sh) {
  23803. for (let i = 0; i < 9; i++) {
  23804. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  23805. return false;
  23806. }
  23807. }
  23808. return true;
  23809. }
  23810. copy(sh) {
  23811. return this.set(sh.coefficients);
  23812. }
  23813. clone() {
  23814. return new this.constructor().copy(this);
  23815. }
  23816. fromArray(array, offset = 0) {
  23817. const coefficients = this.coefficients;
  23818. for (let i = 0; i < 9; i++) {
  23819. coefficients[i].fromArray(array, offset + i * 3);
  23820. }
  23821. return this;
  23822. }
  23823. toArray(array = [], offset = 0) {
  23824. const coefficients = this.coefficients;
  23825. for (let i = 0; i < 9; i++) {
  23826. coefficients[i].toArray(array, offset + i * 3);
  23827. }
  23828. return array;
  23829. } // evaluate the basis functions
  23830. // shBasis is an Array[ 9 ]
  23831. static getBasisAt(normal, shBasis) {
  23832. // normal is assumed to be unit length
  23833. const x = normal.x,
  23834. y = normal.y,
  23835. z = normal.z; // band 0
  23836. shBasis[0] = 0.282095; // band 1
  23837. shBasis[1] = 0.488603 * y;
  23838. shBasis[2] = 0.488603 * z;
  23839. shBasis[3] = 0.488603 * x; // band 2
  23840. shBasis[4] = 1.092548 * x * y;
  23841. shBasis[5] = 1.092548 * y * z;
  23842. shBasis[6] = 0.315392 * (3 * z * z - 1);
  23843. shBasis[7] = 1.092548 * x * z;
  23844. shBasis[8] = 0.546274 * (x * x - y * y);
  23845. }
  23846. }
  23847. SphericalHarmonics3.prototype.isSphericalHarmonics3 = true;
  23848. class LightProbe extends Light {
  23849. constructor(sh = new SphericalHarmonics3(), intensity = 1) {
  23850. super(undefined, intensity);
  23851. this.sh = sh;
  23852. }
  23853. copy(source) {
  23854. super.copy(source);
  23855. this.sh.copy(source.sh);
  23856. return this;
  23857. }
  23858. fromJSON(json) {
  23859. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  23860. this.sh.fromArray(json.sh);
  23861. return this;
  23862. }
  23863. toJSON(meta) {
  23864. const data = super.toJSON(meta);
  23865. data.object.sh = this.sh.toArray();
  23866. return data;
  23867. }
  23868. }
  23869. LightProbe.prototype.isLightProbe = true;
  23870. class MaterialLoader extends Loader {
  23871. constructor(manager) {
  23872. super(manager);
  23873. this.textures = {};
  23874. }
  23875. load(url, onLoad, onProgress, onError) {
  23876. const scope = this;
  23877. const loader = new FileLoader(scope.manager);
  23878. loader.setPath(scope.path);
  23879. loader.setRequestHeader(scope.requestHeader);
  23880. loader.setWithCredentials(scope.withCredentials);
  23881. loader.load(url, function (text) {
  23882. try {
  23883. onLoad(scope.parse(JSON.parse(text)));
  23884. } catch (e) {
  23885. if (onError) {
  23886. onError(e);
  23887. } else {
  23888. console.error(e);
  23889. }
  23890. scope.manager.itemError(url);
  23891. }
  23892. }, onProgress, onError);
  23893. }
  23894. parse(json) {
  23895. const textures = this.textures;
  23896. function getTexture(name) {
  23897. if (textures[name] === undefined) {
  23898. console.warn('THREE.MaterialLoader: Undefined texture', name);
  23899. }
  23900. return textures[name];
  23901. }
  23902. const material = new Materials[json.type]();
  23903. if (json.uuid !== undefined) material.uuid = json.uuid;
  23904. if (json.name !== undefined) material.name = json.name;
  23905. if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
  23906. if (json.roughness !== undefined) material.roughness = json.roughness;
  23907. if (json.metalness !== undefined) material.metalness = json.metalness;
  23908. if (json.sheen !== undefined) material.sheen = json.sheen;
  23909. if (json.sheenColor !== undefined) material.sheenColor = new Color().setHex(json.sheenColor);
  23910. if (json.sheenRoughness !== undefined) material.sheenRoughness = json.sheenRoughness;
  23911. if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
  23912. if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
  23913. if (json.specularIntensity !== undefined) material.specularIntensity = json.specularIntensity;
  23914. if (json.specularColor !== undefined && material.specularColor !== undefined) material.specularColor.setHex(json.specularColor);
  23915. if (json.shininess !== undefined) material.shininess = json.shininess;
  23916. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  23917. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  23918. if (json.transmission !== undefined) material.transmission = json.transmission;
  23919. if (json.thickness !== undefined) material.thickness = json.thickness;
  23920. if (json.attenuationDistance !== undefined) material.attenuationDistance = json.attenuationDistance;
  23921. if (json.attenuationColor !== undefined && material.attenuationColor !== undefined) material.attenuationColor.setHex(json.attenuationColor);
  23922. if (json.fog !== undefined) material.fog = json.fog;
  23923. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  23924. if (json.blending !== undefined) material.blending = json.blending;
  23925. if (json.combine !== undefined) material.combine = json.combine;
  23926. if (json.side !== undefined) material.side = json.side;
  23927. if (json.shadowSide !== undefined) material.shadowSide = json.shadowSide;
  23928. if (json.opacity !== undefined) material.opacity = json.opacity;
  23929. if (json.format !== undefined) material.format = json.format;
  23930. if (json.transparent !== undefined) material.transparent = json.transparent;
  23931. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  23932. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  23933. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  23934. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  23935. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  23936. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  23937. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  23938. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  23939. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  23940. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  23941. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  23942. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  23943. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  23944. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  23945. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  23946. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  23947. if (json.rotation !== undefined) material.rotation = json.rotation;
  23948. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  23949. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  23950. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  23951. if (json.scale !== undefined) material.scale = json.scale;
  23952. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  23953. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  23954. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  23955. if (json.dithering !== undefined) material.dithering = json.dithering;
  23956. if (json.alphaToCoverage !== undefined) material.alphaToCoverage = json.alphaToCoverage;
  23957. if (json.premultipliedAlpha !== undefined) material.premultipliedAlpha = json.premultipliedAlpha;
  23958. if (json.visible !== undefined) material.visible = json.visible;
  23959. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  23960. if (json.userData !== undefined) material.userData = json.userData;
  23961. if (json.vertexColors !== undefined) {
  23962. if (typeof json.vertexColors === 'number') {
  23963. material.vertexColors = json.vertexColors > 0 ? true : false;
  23964. } else {
  23965. material.vertexColors = json.vertexColors;
  23966. }
  23967. } // Shader Material
  23968. if (json.uniforms !== undefined) {
  23969. for (const name in json.uniforms) {
  23970. const uniform = json.uniforms[name];
  23971. material.uniforms[name] = {};
  23972. switch (uniform.type) {
  23973. case 't':
  23974. material.uniforms[name].value = getTexture(uniform.value);
  23975. break;
  23976. case 'c':
  23977. material.uniforms[name].value = new Color().setHex(uniform.value);
  23978. break;
  23979. case 'v2':
  23980. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  23981. break;
  23982. case 'v3':
  23983. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  23984. break;
  23985. case 'v4':
  23986. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  23987. break;
  23988. case 'm3':
  23989. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  23990. break;
  23991. case 'm4':
  23992. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  23993. break;
  23994. default:
  23995. material.uniforms[name].value = uniform.value;
  23996. }
  23997. }
  23998. }
  23999. if (json.defines !== undefined) material.defines = json.defines;
  24000. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  24001. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  24002. if (json.extensions !== undefined) {
  24003. for (const key in json.extensions) {
  24004. material.extensions[key] = json.extensions[key];
  24005. }
  24006. } // Deprecated
  24007. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  24008. // for PointsMaterial
  24009. if (json.size !== undefined) material.size = json.size;
  24010. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  24011. if (json.map !== undefined) material.map = getTexture(json.map);
  24012. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  24013. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  24014. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  24015. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  24016. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  24017. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  24018. if (json.normalScale !== undefined) {
  24019. let normalScale = json.normalScale;
  24020. if (Array.isArray(normalScale) === false) {
  24021. // Blender exporter used to export a scalar. See #7459
  24022. normalScale = [normalScale, normalScale];
  24023. }
  24024. material.normalScale = new Vector2().fromArray(normalScale);
  24025. }
  24026. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  24027. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  24028. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  24029. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  24030. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  24031. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  24032. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  24033. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  24034. if (json.specularIntensityMap !== undefined) material.specularIntensityMap = getTexture(json.specularIntensityMap);
  24035. if (json.specularColorMap !== undefined) material.specularColorMap = getTexture(json.specularColorMap);
  24036. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  24037. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  24038. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  24039. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  24040. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  24041. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  24042. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  24043. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  24044. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  24045. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  24046. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  24047. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  24048. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  24049. if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
  24050. if (json.thicknessMap !== undefined) material.thicknessMap = getTexture(json.thicknessMap);
  24051. if (json.sheenColorMap !== undefined) material.sheenColorMap = getTexture(json.sheenColorMap);
  24052. if (json.sheenRoughnessMap !== undefined) material.sheenRoughnessMap = getTexture(json.sheenRoughnessMap);
  24053. return material;
  24054. }
  24055. setTextures(value) {
  24056. this.textures = value;
  24057. return this;
  24058. }
  24059. }
  24060. class LoaderUtils {
  24061. static decodeText(array) {
  24062. if (typeof TextDecoder !== 'undefined') {
  24063. return new TextDecoder().decode(array);
  24064. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24065. // throws a "maximum call stack size exceeded" error for large arrays.
  24066. let s = '';
  24067. for (let i = 0, il = array.length; i < il; i++) {
  24068. // Implicitly assumes little-endian.
  24069. s += String.fromCharCode(array[i]);
  24070. }
  24071. try {
  24072. // merges multi-byte utf-8 characters.
  24073. return decodeURIComponent(escape(s));
  24074. } catch (e) {
  24075. // see #16358
  24076. return s;
  24077. }
  24078. }
  24079. static extractUrlBase(url) {
  24080. const index = url.lastIndexOf('/');
  24081. if (index === -1) return './';
  24082. return url.substr(0, index + 1);
  24083. }
  24084. static resolveURL(url, path) {
  24085. // Invalid URL
  24086. if (typeof url !== 'string' || url === '') return ''; // Host Relative URL
  24087. if (/^https?:\/\//i.test(path) && /^\//.test(url)) {
  24088. path = path.replace(/(^https?:\/\/[^\/]+).*/i, '$1');
  24089. } // Absolute URL http://,https://,//
  24090. if (/^(https?:)?\/\//i.test(url)) return url; // Data URI
  24091. if (/^data:.*,.*$/i.test(url)) return url; // Blob URL
  24092. if (/^blob:.*$/i.test(url)) return url; // Relative URL
  24093. return path + url;
  24094. }
  24095. }
  24096. class InstancedBufferGeometry extends BufferGeometry {
  24097. constructor() {
  24098. super();
  24099. this.type = 'InstancedBufferGeometry';
  24100. this.instanceCount = Infinity;
  24101. }
  24102. copy(source) {
  24103. super.copy(source);
  24104. this.instanceCount = source.instanceCount;
  24105. return this;
  24106. }
  24107. clone() {
  24108. return new this.constructor().copy(this);
  24109. }
  24110. toJSON() {
  24111. const data = super.toJSON(this);
  24112. data.instanceCount = this.instanceCount;
  24113. data.isInstancedBufferGeometry = true;
  24114. return data;
  24115. }
  24116. }
  24117. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  24118. class BufferGeometryLoader extends Loader {
  24119. constructor(manager) {
  24120. super(manager);
  24121. }
  24122. load(url, onLoad, onProgress, onError) {
  24123. const scope = this;
  24124. const loader = new FileLoader(scope.manager);
  24125. loader.setPath(scope.path);
  24126. loader.setRequestHeader(scope.requestHeader);
  24127. loader.setWithCredentials(scope.withCredentials);
  24128. loader.load(url, function (text) {
  24129. try {
  24130. onLoad(scope.parse(JSON.parse(text)));
  24131. } catch (e) {
  24132. if (onError) {
  24133. onError(e);
  24134. } else {
  24135. console.error(e);
  24136. }
  24137. scope.manager.itemError(url);
  24138. }
  24139. }, onProgress, onError);
  24140. }
  24141. parse(json) {
  24142. const interleavedBufferMap = {};
  24143. const arrayBufferMap = {};
  24144. function getInterleavedBuffer(json, uuid) {
  24145. if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
  24146. const interleavedBuffers = json.interleavedBuffers;
  24147. const interleavedBuffer = interleavedBuffers[uuid];
  24148. const buffer = getArrayBuffer(json, interleavedBuffer.buffer);
  24149. const array = getTypedArray(interleavedBuffer.type, buffer);
  24150. const ib = new InterleavedBuffer(array, interleavedBuffer.stride);
  24151. ib.uuid = interleavedBuffer.uuid;
  24152. interleavedBufferMap[uuid] = ib;
  24153. return ib;
  24154. }
  24155. function getArrayBuffer(json, uuid) {
  24156. if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
  24157. const arrayBuffers = json.arrayBuffers;
  24158. const arrayBuffer = arrayBuffers[uuid];
  24159. const ab = new Uint32Array(arrayBuffer).buffer;
  24160. arrayBufferMap[uuid] = ab;
  24161. return ab;
  24162. }
  24163. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24164. const index = json.data.index;
  24165. if (index !== undefined) {
  24166. const typedArray = getTypedArray(index.type, index.array);
  24167. geometry.setIndex(new BufferAttribute(typedArray, 1));
  24168. }
  24169. const attributes = json.data.attributes;
  24170. for (const key in attributes) {
  24171. const attribute = attributes[key];
  24172. let bufferAttribute;
  24173. if (attribute.isInterleavedBufferAttribute) {
  24174. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  24175. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  24176. } else {
  24177. const typedArray = getTypedArray(attribute.type, attribute.array);
  24178. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  24179. bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  24180. }
  24181. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24182. if (attribute.usage !== undefined) bufferAttribute.setUsage(attribute.usage);
  24183. if (attribute.updateRange !== undefined) {
  24184. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  24185. bufferAttribute.updateRange.count = attribute.updateRange.count;
  24186. }
  24187. geometry.setAttribute(key, bufferAttribute);
  24188. }
  24189. const morphAttributes = json.data.morphAttributes;
  24190. if (morphAttributes) {
  24191. for (const key in morphAttributes) {
  24192. const attributeArray = morphAttributes[key];
  24193. const array = [];
  24194. for (let i = 0, il = attributeArray.length; i < il; i++) {
  24195. const attribute = attributeArray[i];
  24196. let bufferAttribute;
  24197. if (attribute.isInterleavedBufferAttribute) {
  24198. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  24199. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  24200. } else {
  24201. const typedArray = getTypedArray(attribute.type, attribute.array);
  24202. bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  24203. }
  24204. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24205. array.push(bufferAttribute);
  24206. }
  24207. geometry.morphAttributes[key] = array;
  24208. }
  24209. }
  24210. const morphTargetsRelative = json.data.morphTargetsRelative;
  24211. if (morphTargetsRelative) {
  24212. geometry.morphTargetsRelative = true;
  24213. }
  24214. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  24215. if (groups !== undefined) {
  24216. for (let i = 0, n = groups.length; i !== n; ++i) {
  24217. const group = groups[i];
  24218. geometry.addGroup(group.start, group.count, group.materialIndex);
  24219. }
  24220. }
  24221. const boundingSphere = json.data.boundingSphere;
  24222. if (boundingSphere !== undefined) {
  24223. const center = new Vector3();
  24224. if (boundingSphere.center !== undefined) {
  24225. center.fromArray(boundingSphere.center);
  24226. }
  24227. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  24228. }
  24229. if (json.name) geometry.name = json.name;
  24230. if (json.userData) geometry.userData = json.userData;
  24231. return geometry;
  24232. }
  24233. }
  24234. class ObjectLoader extends Loader {
  24235. constructor(manager) {
  24236. super(manager);
  24237. }
  24238. load(url, onLoad, onProgress, onError) {
  24239. const scope = this;
  24240. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  24241. this.resourcePath = this.resourcePath || path;
  24242. const loader = new FileLoader(this.manager);
  24243. loader.setPath(this.path);
  24244. loader.setRequestHeader(this.requestHeader);
  24245. loader.setWithCredentials(this.withCredentials);
  24246. loader.load(url, function (text) {
  24247. let json = null;
  24248. try {
  24249. json = JSON.parse(text);
  24250. } catch (error) {
  24251. if (onError !== undefined) onError(error);
  24252. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  24253. return;
  24254. }
  24255. const metadata = json.metadata;
  24256. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  24257. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  24258. return;
  24259. }
  24260. scope.parse(json, onLoad);
  24261. }, onProgress, onError);
  24262. }
  24263. async loadAsync(url, onProgress) {
  24264. const scope = this;
  24265. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  24266. this.resourcePath = this.resourcePath || path;
  24267. const loader = new FileLoader(this.manager);
  24268. loader.setPath(this.path);
  24269. loader.setRequestHeader(this.requestHeader);
  24270. loader.setWithCredentials(this.withCredentials);
  24271. const text = await loader.loadAsync(url, onProgress);
  24272. const json = JSON.parse(text);
  24273. const metadata = json.metadata;
  24274. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  24275. throw new Error('THREE.ObjectLoader: Can\'t load ' + url);
  24276. }
  24277. return await scope.parseAsync(json);
  24278. }
  24279. parse(json, onLoad) {
  24280. const animations = this.parseAnimations(json.animations);
  24281. const shapes = this.parseShapes(json.shapes);
  24282. const geometries = this.parseGeometries(json.geometries, shapes);
  24283. const images = this.parseImages(json.images, function () {
  24284. if (onLoad !== undefined) onLoad(object);
  24285. });
  24286. const textures = this.parseTextures(json.textures, images);
  24287. const materials = this.parseMaterials(json.materials, textures);
  24288. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  24289. const skeletons = this.parseSkeletons(json.skeletons, object);
  24290. this.bindSkeletons(object, skeletons); //
  24291. if (onLoad !== undefined) {
  24292. let hasImages = false;
  24293. for (const uuid in images) {
  24294. if (images[uuid] instanceof HTMLImageElement) {
  24295. hasImages = true;
  24296. break;
  24297. }
  24298. }
  24299. if (hasImages === false) onLoad(object);
  24300. }
  24301. return object;
  24302. }
  24303. async parseAsync(json) {
  24304. const animations = this.parseAnimations(json.animations);
  24305. const shapes = this.parseShapes(json.shapes);
  24306. const geometries = this.parseGeometries(json.geometries, shapes);
  24307. const images = await this.parseImagesAsync(json.images);
  24308. const textures = this.parseTextures(json.textures, images);
  24309. const materials = this.parseMaterials(json.materials, textures);
  24310. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  24311. const skeletons = this.parseSkeletons(json.skeletons, object);
  24312. this.bindSkeletons(object, skeletons);
  24313. return object;
  24314. }
  24315. parseShapes(json) {
  24316. const shapes = {};
  24317. if (json !== undefined) {
  24318. for (let i = 0, l = json.length; i < l; i++) {
  24319. const shape = new Shape().fromJSON(json[i]);
  24320. shapes[shape.uuid] = shape;
  24321. }
  24322. }
  24323. return shapes;
  24324. }
  24325. parseSkeletons(json, object) {
  24326. const skeletons = {};
  24327. const bones = {}; // generate bone lookup table
  24328. object.traverse(function (child) {
  24329. if (child.isBone) bones[child.uuid] = child;
  24330. }); // create skeletons
  24331. if (json !== undefined) {
  24332. for (let i = 0, l = json.length; i < l; i++) {
  24333. const skeleton = new Skeleton().fromJSON(json[i], bones);
  24334. skeletons[skeleton.uuid] = skeleton;
  24335. }
  24336. }
  24337. return skeletons;
  24338. }
  24339. parseGeometries(json, shapes) {
  24340. const geometries = {};
  24341. if (json !== undefined) {
  24342. const bufferGeometryLoader = new BufferGeometryLoader();
  24343. for (let i = 0, l = json.length; i < l; i++) {
  24344. let geometry;
  24345. const data = json[i];
  24346. switch (data.type) {
  24347. case 'BufferGeometry':
  24348. case 'InstancedBufferGeometry':
  24349. geometry = bufferGeometryLoader.parse(data);
  24350. break;
  24351. case 'Geometry':
  24352. console.error('THREE.ObjectLoader: The legacy Geometry type is no longer supported.');
  24353. break;
  24354. default:
  24355. if (data.type in Geometries) {
  24356. geometry = Geometries[data.type].fromJSON(data, shapes);
  24357. } else {
  24358. console.warn(`THREE.ObjectLoader: Unsupported geometry type "${data.type}"`);
  24359. }
  24360. }
  24361. geometry.uuid = data.uuid;
  24362. if (data.name !== undefined) geometry.name = data.name;
  24363. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  24364. geometries[data.uuid] = geometry;
  24365. }
  24366. }
  24367. return geometries;
  24368. }
  24369. parseMaterials(json, textures) {
  24370. const cache = {}; // MultiMaterial
  24371. const materials = {};
  24372. if (json !== undefined) {
  24373. const loader = new MaterialLoader();
  24374. loader.setTextures(textures);
  24375. for (let i = 0, l = json.length; i < l; i++) {
  24376. const data = json[i];
  24377. if (data.type === 'MultiMaterial') {
  24378. // Deprecated
  24379. const array = [];
  24380. for (let j = 0; j < data.materials.length; j++) {
  24381. const material = data.materials[j];
  24382. if (cache[material.uuid] === undefined) {
  24383. cache[material.uuid] = loader.parse(material);
  24384. }
  24385. array.push(cache[material.uuid]);
  24386. }
  24387. materials[data.uuid] = array;
  24388. } else {
  24389. if (cache[data.uuid] === undefined) {
  24390. cache[data.uuid] = loader.parse(data);
  24391. }
  24392. materials[data.uuid] = cache[data.uuid];
  24393. }
  24394. }
  24395. }
  24396. return materials;
  24397. }
  24398. parseAnimations(json) {
  24399. const animations = {};
  24400. if (json !== undefined) {
  24401. for (let i = 0; i < json.length; i++) {
  24402. const data = json[i];
  24403. const clip = AnimationClip.parse(data);
  24404. animations[clip.uuid] = clip;
  24405. }
  24406. }
  24407. return animations;
  24408. }
  24409. parseImages(json, onLoad) {
  24410. const scope = this;
  24411. const images = {};
  24412. let loader;
  24413. function loadImage(url) {
  24414. scope.manager.itemStart(url);
  24415. return loader.load(url, function () {
  24416. scope.manager.itemEnd(url);
  24417. }, undefined, function () {
  24418. scope.manager.itemError(url);
  24419. scope.manager.itemEnd(url);
  24420. });
  24421. }
  24422. function deserializeImage(image) {
  24423. if (typeof image === 'string') {
  24424. const url = image;
  24425. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  24426. return loadImage(path);
  24427. } else {
  24428. if (image.data) {
  24429. return {
  24430. data: getTypedArray(image.type, image.data),
  24431. width: image.width,
  24432. height: image.height
  24433. };
  24434. } else {
  24435. return null;
  24436. }
  24437. }
  24438. }
  24439. if (json !== undefined && json.length > 0) {
  24440. const manager = new LoadingManager(onLoad);
  24441. loader = new ImageLoader(manager);
  24442. loader.setCrossOrigin(this.crossOrigin);
  24443. for (let i = 0, il = json.length; i < il; i++) {
  24444. const image = json[i];
  24445. const url = image.url;
  24446. if (Array.isArray(url)) {
  24447. // load array of images e.g CubeTexture
  24448. images[image.uuid] = [];
  24449. for (let j = 0, jl = url.length; j < jl; j++) {
  24450. const currentUrl = url[j];
  24451. const deserializedImage = deserializeImage(currentUrl);
  24452. if (deserializedImage !== null) {
  24453. if (deserializedImage instanceof HTMLImageElement) {
  24454. images[image.uuid].push(deserializedImage);
  24455. } else {
  24456. // special case: handle array of data textures for cube textures
  24457. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  24458. }
  24459. }
  24460. }
  24461. } else {
  24462. // load single image
  24463. const deserializedImage = deserializeImage(image.url);
  24464. if (deserializedImage !== null) {
  24465. images[image.uuid] = deserializedImage;
  24466. }
  24467. }
  24468. }
  24469. }
  24470. return images;
  24471. }
  24472. async parseImagesAsync(json) {
  24473. const scope = this;
  24474. const images = {};
  24475. let loader;
  24476. async function deserializeImage(image) {
  24477. if (typeof image === 'string') {
  24478. const url = image;
  24479. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  24480. return await loader.loadAsync(path);
  24481. } else {
  24482. if (image.data) {
  24483. return {
  24484. data: getTypedArray(image.type, image.data),
  24485. width: image.width,
  24486. height: image.height
  24487. };
  24488. } else {
  24489. return null;
  24490. }
  24491. }
  24492. }
  24493. if (json !== undefined && json.length > 0) {
  24494. loader = new ImageLoader(this.manager);
  24495. loader.setCrossOrigin(this.crossOrigin);
  24496. for (let i = 0, il = json.length; i < il; i++) {
  24497. const image = json[i];
  24498. const url = image.url;
  24499. if (Array.isArray(url)) {
  24500. // load array of images e.g CubeTexture
  24501. images[image.uuid] = [];
  24502. for (let j = 0, jl = url.length; j < jl; j++) {
  24503. const currentUrl = url[j];
  24504. const deserializedImage = await deserializeImage(currentUrl);
  24505. if (deserializedImage !== null) {
  24506. if (deserializedImage instanceof HTMLImageElement) {
  24507. images[image.uuid].push(deserializedImage);
  24508. } else {
  24509. // special case: handle array of data textures for cube textures
  24510. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  24511. }
  24512. }
  24513. }
  24514. } else {
  24515. // load single image
  24516. const deserializedImage = await deserializeImage(image.url);
  24517. if (deserializedImage !== null) {
  24518. images[image.uuid] = deserializedImage;
  24519. }
  24520. }
  24521. }
  24522. }
  24523. return images;
  24524. }
  24525. parseTextures(json, images) {
  24526. function parseConstant(value, type) {
  24527. if (typeof value === 'number') return value;
  24528. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  24529. return type[value];
  24530. }
  24531. const textures = {};
  24532. if (json !== undefined) {
  24533. for (let i = 0, l = json.length; i < l; i++) {
  24534. const data = json[i];
  24535. if (data.image === undefined) {
  24536. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  24537. }
  24538. if (images[data.image] === undefined) {
  24539. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  24540. }
  24541. let texture;
  24542. const image = images[data.image];
  24543. if (Array.isArray(image)) {
  24544. texture = new CubeTexture(image);
  24545. if (image.length === 6) texture.needsUpdate = true;
  24546. } else {
  24547. if (image && image.data) {
  24548. texture = new DataTexture(image.data, image.width, image.height);
  24549. } else {
  24550. texture = new Texture(image);
  24551. }
  24552. if (image) texture.needsUpdate = true; // textures can have undefined image data
  24553. }
  24554. texture.uuid = data.uuid;
  24555. if (data.name !== undefined) texture.name = data.name;
  24556. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  24557. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  24558. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  24559. if (data.center !== undefined) texture.center.fromArray(data.center);
  24560. if (data.rotation !== undefined) texture.rotation = data.rotation;
  24561. if (data.wrap !== undefined) {
  24562. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  24563. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  24564. }
  24565. if (data.format !== undefined) texture.format = data.format;
  24566. if (data.type !== undefined) texture.type = data.type;
  24567. if (data.encoding !== undefined) texture.encoding = data.encoding;
  24568. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  24569. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  24570. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  24571. if (data.flipY !== undefined) texture.flipY = data.flipY;
  24572. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  24573. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  24574. if (data.userData !== undefined) texture.userData = data.userData;
  24575. textures[data.uuid] = texture;
  24576. }
  24577. }
  24578. return textures;
  24579. }
  24580. parseObject(data, geometries, materials, textures, animations) {
  24581. let object;
  24582. function getGeometry(name) {
  24583. if (geometries[name] === undefined) {
  24584. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  24585. }
  24586. return geometries[name];
  24587. }
  24588. function getMaterial(name) {
  24589. if (name === undefined) return undefined;
  24590. if (Array.isArray(name)) {
  24591. const array = [];
  24592. for (let i = 0, l = name.length; i < l; i++) {
  24593. const uuid = name[i];
  24594. if (materials[uuid] === undefined) {
  24595. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  24596. }
  24597. array.push(materials[uuid]);
  24598. }
  24599. return array;
  24600. }
  24601. if (materials[name] === undefined) {
  24602. console.warn('THREE.ObjectLoader: Undefined material', name);
  24603. }
  24604. return materials[name];
  24605. }
  24606. function getTexture(uuid) {
  24607. if (textures[uuid] === undefined) {
  24608. console.warn('THREE.ObjectLoader: Undefined texture', uuid);
  24609. }
  24610. return textures[uuid];
  24611. }
  24612. let geometry, material;
  24613. switch (data.type) {
  24614. case 'Scene':
  24615. object = new Scene();
  24616. if (data.background !== undefined) {
  24617. if (Number.isInteger(data.background)) {
  24618. object.background = new Color(data.background);
  24619. } else {
  24620. object.background = getTexture(data.background);
  24621. }
  24622. }
  24623. if (data.environment !== undefined) {
  24624. object.environment = getTexture(data.environment);
  24625. }
  24626. if (data.fog !== undefined) {
  24627. if (data.fog.type === 'Fog') {
  24628. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  24629. } else if (data.fog.type === 'FogExp2') {
  24630. object.fog = new FogExp2(data.fog.color, data.fog.density);
  24631. }
  24632. }
  24633. break;
  24634. case 'PerspectiveCamera':
  24635. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  24636. if (data.focus !== undefined) object.focus = data.focus;
  24637. if (data.zoom !== undefined) object.zoom = data.zoom;
  24638. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  24639. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  24640. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24641. break;
  24642. case 'OrthographicCamera':
  24643. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  24644. if (data.zoom !== undefined) object.zoom = data.zoom;
  24645. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24646. break;
  24647. case 'AmbientLight':
  24648. object = new AmbientLight(data.color, data.intensity);
  24649. break;
  24650. case 'DirectionalLight':
  24651. object = new DirectionalLight(data.color, data.intensity);
  24652. break;
  24653. case 'PointLight':
  24654. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  24655. break;
  24656. case 'RectAreaLight':
  24657. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  24658. break;
  24659. case 'SpotLight':
  24660. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  24661. break;
  24662. case 'HemisphereLight':
  24663. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  24664. break;
  24665. case 'LightProbe':
  24666. object = new LightProbe().fromJSON(data);
  24667. break;
  24668. case 'SkinnedMesh':
  24669. geometry = getGeometry(data.geometry);
  24670. material = getMaterial(data.material);
  24671. object = new SkinnedMesh(geometry, material);
  24672. if (data.bindMode !== undefined) object.bindMode = data.bindMode;
  24673. if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
  24674. if (data.skeleton !== undefined) object.skeleton = data.skeleton;
  24675. break;
  24676. case 'Mesh':
  24677. geometry = getGeometry(data.geometry);
  24678. material = getMaterial(data.material);
  24679. object = new Mesh(geometry, material);
  24680. break;
  24681. case 'InstancedMesh':
  24682. geometry = getGeometry(data.geometry);
  24683. material = getMaterial(data.material);
  24684. const count = data.count;
  24685. const instanceMatrix = data.instanceMatrix;
  24686. const instanceColor = data.instanceColor;
  24687. object = new InstancedMesh(geometry, material, count);
  24688. object.instanceMatrix = new InstancedBufferAttribute(new Float32Array(instanceMatrix.array), 16);
  24689. if (instanceColor !== undefined) object.instanceColor = new InstancedBufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize);
  24690. break;
  24691. case 'LOD':
  24692. object = new LOD();
  24693. break;
  24694. case 'Line':
  24695. object = new Line(getGeometry(data.geometry), getMaterial(data.material));
  24696. break;
  24697. case 'LineLoop':
  24698. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  24699. break;
  24700. case 'LineSegments':
  24701. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  24702. break;
  24703. case 'PointCloud':
  24704. case 'Points':
  24705. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  24706. break;
  24707. case 'Sprite':
  24708. object = new Sprite(getMaterial(data.material));
  24709. break;
  24710. case 'Group':
  24711. object = new Group();
  24712. break;
  24713. case 'Bone':
  24714. object = new Bone();
  24715. break;
  24716. default:
  24717. object = new Object3D();
  24718. }
  24719. object.uuid = data.uuid;
  24720. if (data.name !== undefined) object.name = data.name;
  24721. if (data.matrix !== undefined) {
  24722. object.matrix.fromArray(data.matrix);
  24723. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  24724. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  24725. } else {
  24726. if (data.position !== undefined) object.position.fromArray(data.position);
  24727. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  24728. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  24729. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  24730. }
  24731. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  24732. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  24733. if (data.shadow) {
  24734. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  24735. if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
  24736. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  24737. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  24738. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  24739. }
  24740. if (data.visible !== undefined) object.visible = data.visible;
  24741. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  24742. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  24743. if (data.userData !== undefined) object.userData = data.userData;
  24744. if (data.layers !== undefined) object.layers.mask = data.layers;
  24745. if (data.children !== undefined) {
  24746. const children = data.children;
  24747. for (let i = 0; i < children.length; i++) {
  24748. object.add(this.parseObject(children[i], geometries, materials, textures, animations));
  24749. }
  24750. }
  24751. if (data.animations !== undefined) {
  24752. const objectAnimations = data.animations;
  24753. for (let i = 0; i < objectAnimations.length; i++) {
  24754. const uuid = objectAnimations[i];
  24755. object.animations.push(animations[uuid]);
  24756. }
  24757. }
  24758. if (data.type === 'LOD') {
  24759. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  24760. const levels = data.levels;
  24761. for (let l = 0; l < levels.length; l++) {
  24762. const level = levels[l];
  24763. const child = object.getObjectByProperty('uuid', level.object);
  24764. if (child !== undefined) {
  24765. object.addLevel(child, level.distance);
  24766. }
  24767. }
  24768. }
  24769. return object;
  24770. }
  24771. bindSkeletons(object, skeletons) {
  24772. if (Object.keys(skeletons).length === 0) return;
  24773. object.traverse(function (child) {
  24774. if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
  24775. const skeleton = skeletons[child.skeleton];
  24776. if (skeleton === undefined) {
  24777. console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
  24778. } else {
  24779. child.bind(skeleton, child.bindMatrix);
  24780. }
  24781. }
  24782. });
  24783. }
  24784. /* DEPRECATED */
  24785. setTexturePath(value) {
  24786. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  24787. return this.setResourcePath(value);
  24788. }
  24789. }
  24790. const TEXTURE_MAPPING = {
  24791. UVMapping: UVMapping,
  24792. CubeReflectionMapping: CubeReflectionMapping,
  24793. CubeRefractionMapping: CubeRefractionMapping,
  24794. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  24795. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  24796. CubeUVReflectionMapping: CubeUVReflectionMapping,
  24797. CubeUVRefractionMapping: CubeUVRefractionMapping
  24798. };
  24799. const TEXTURE_WRAPPING = {
  24800. RepeatWrapping: RepeatWrapping,
  24801. ClampToEdgeWrapping: ClampToEdgeWrapping,
  24802. MirroredRepeatWrapping: MirroredRepeatWrapping
  24803. };
  24804. const TEXTURE_FILTER = {
  24805. NearestFilter: NearestFilter,
  24806. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  24807. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  24808. LinearFilter: LinearFilter,
  24809. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  24810. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  24811. };
  24812. class ImageBitmapLoader extends Loader {
  24813. constructor(manager) {
  24814. super(manager);
  24815. if (typeof createImageBitmap === 'undefined') {
  24816. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  24817. }
  24818. if (typeof fetch === 'undefined') {
  24819. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  24820. }
  24821. this.options = {
  24822. premultiplyAlpha: 'none'
  24823. };
  24824. }
  24825. setOptions(options) {
  24826. this.options = options;
  24827. return this;
  24828. }
  24829. load(url, onLoad, onProgress, onError) {
  24830. if (url === undefined) url = '';
  24831. if (this.path !== undefined) url = this.path + url;
  24832. url = this.manager.resolveURL(url);
  24833. const scope = this;
  24834. const cached = Cache.get(url);
  24835. if (cached !== undefined) {
  24836. scope.manager.itemStart(url);
  24837. setTimeout(function () {
  24838. if (onLoad) onLoad(cached);
  24839. scope.manager.itemEnd(url);
  24840. }, 0);
  24841. return cached;
  24842. }
  24843. const fetchOptions = {};
  24844. fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
  24845. fetchOptions.headers = this.requestHeader;
  24846. fetch(url, fetchOptions).then(function (res) {
  24847. return res.blob();
  24848. }).then(function (blob) {
  24849. return createImageBitmap(blob, Object.assign(scope.options, {
  24850. colorSpaceConversion: 'none'
  24851. }));
  24852. }).then(function (imageBitmap) {
  24853. Cache.add(url, imageBitmap);
  24854. if (onLoad) onLoad(imageBitmap);
  24855. scope.manager.itemEnd(url);
  24856. }).catch(function (e) {
  24857. if (onError) onError(e);
  24858. scope.manager.itemError(url);
  24859. scope.manager.itemEnd(url);
  24860. });
  24861. scope.manager.itemStart(url);
  24862. }
  24863. }
  24864. ImageBitmapLoader.prototype.isImageBitmapLoader = true;
  24865. let _context;
  24866. const AudioContext = {
  24867. getContext: function () {
  24868. if (_context === undefined) {
  24869. _context = new (window.AudioContext || window.webkitAudioContext)();
  24870. }
  24871. return _context;
  24872. },
  24873. setContext: function (value) {
  24874. _context = value;
  24875. }
  24876. };
  24877. class AudioLoader extends Loader {
  24878. constructor(manager) {
  24879. super(manager);
  24880. }
  24881. load(url, onLoad, onProgress, onError) {
  24882. const scope = this;
  24883. const loader = new FileLoader(this.manager);
  24884. loader.setResponseType('arraybuffer');
  24885. loader.setPath(this.path);
  24886. loader.setRequestHeader(this.requestHeader);
  24887. loader.setWithCredentials(this.withCredentials);
  24888. loader.load(url, function (buffer) {
  24889. try {
  24890. // Create a copy of the buffer. The `decodeAudioData` method
  24891. // detaches the buffer when complete, preventing reuse.
  24892. const bufferCopy = buffer.slice(0);
  24893. const context = AudioContext.getContext();
  24894. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  24895. onLoad(audioBuffer);
  24896. });
  24897. } catch (e) {
  24898. if (onError) {
  24899. onError(e);
  24900. } else {
  24901. console.error(e);
  24902. }
  24903. scope.manager.itemError(url);
  24904. }
  24905. }, onProgress, onError);
  24906. }
  24907. }
  24908. class HemisphereLightProbe extends LightProbe {
  24909. constructor(skyColor, groundColor, intensity = 1) {
  24910. super(undefined, intensity);
  24911. const color1 = new Color().set(skyColor);
  24912. const color2 = new Color().set(groundColor);
  24913. const sky = new Vector3(color1.r, color1.g, color1.b);
  24914. const ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  24915. const c0 = Math.sqrt(Math.PI);
  24916. const c1 = c0 * Math.sqrt(0.75);
  24917. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  24918. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  24919. }
  24920. }
  24921. HemisphereLightProbe.prototype.isHemisphereLightProbe = true;
  24922. class AmbientLightProbe extends LightProbe {
  24923. constructor(color, intensity = 1) {
  24924. super(undefined, intensity);
  24925. const color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  24926. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  24927. }
  24928. }
  24929. AmbientLightProbe.prototype.isAmbientLightProbe = true;
  24930. const _eyeRight = /*@__PURE__*/new Matrix4();
  24931. const _eyeLeft = /*@__PURE__*/new Matrix4();
  24932. const _projectionMatrix = /*@__PURE__*/new Matrix4();
  24933. class StereoCamera {
  24934. constructor() {
  24935. this.type = 'StereoCamera';
  24936. this.aspect = 1;
  24937. this.eyeSep = 0.064;
  24938. this.cameraL = new PerspectiveCamera();
  24939. this.cameraL.layers.enable(1);
  24940. this.cameraL.matrixAutoUpdate = false;
  24941. this.cameraR = new PerspectiveCamera();
  24942. this.cameraR.layers.enable(2);
  24943. this.cameraR.matrixAutoUpdate = false;
  24944. this._cache = {
  24945. focus: null,
  24946. fov: null,
  24947. aspect: null,
  24948. near: null,
  24949. far: null,
  24950. zoom: null,
  24951. eyeSep: null
  24952. };
  24953. }
  24954. update(camera) {
  24955. const cache = this._cache;
  24956. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  24957. if (needsUpdate) {
  24958. cache.focus = camera.focus;
  24959. cache.fov = camera.fov;
  24960. cache.aspect = camera.aspect * this.aspect;
  24961. cache.near = camera.near;
  24962. cache.far = camera.far;
  24963. cache.zoom = camera.zoom;
  24964. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  24965. // http://paulbourke.net/stereographics/stereorender/
  24966. _projectionMatrix.copy(camera.projectionMatrix);
  24967. const eyeSepHalf = cache.eyeSep / 2;
  24968. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  24969. const ymax = cache.near * Math.tan(DEG2RAD * cache.fov * 0.5) / cache.zoom;
  24970. let xmin, xmax; // translate xOffset
  24971. _eyeLeft.elements[12] = -eyeSepHalf;
  24972. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  24973. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  24974. xmax = ymax * cache.aspect + eyeSepOnProjection;
  24975. _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  24976. _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  24977. this.cameraL.projectionMatrix.copy(_projectionMatrix); // for right eye
  24978. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  24979. xmax = ymax * cache.aspect - eyeSepOnProjection;
  24980. _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  24981. _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  24982. this.cameraR.projectionMatrix.copy(_projectionMatrix);
  24983. }
  24984. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  24985. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  24986. }
  24987. }
  24988. class Clock {
  24989. constructor(autoStart = true) {
  24990. this.autoStart = autoStart;
  24991. this.startTime = 0;
  24992. this.oldTime = 0;
  24993. this.elapsedTime = 0;
  24994. this.running = false;
  24995. }
  24996. start() {
  24997. this.startTime = now();
  24998. this.oldTime = this.startTime;
  24999. this.elapsedTime = 0;
  25000. this.running = true;
  25001. }
  25002. stop() {
  25003. this.getElapsedTime();
  25004. this.running = false;
  25005. this.autoStart = false;
  25006. }
  25007. getElapsedTime() {
  25008. this.getDelta();
  25009. return this.elapsedTime;
  25010. }
  25011. getDelta() {
  25012. let diff = 0;
  25013. if (this.autoStart && !this.running) {
  25014. this.start();
  25015. return 0;
  25016. }
  25017. if (this.running) {
  25018. const newTime = now();
  25019. diff = (newTime - this.oldTime) / 1000;
  25020. this.oldTime = newTime;
  25021. this.elapsedTime += diff;
  25022. }
  25023. return diff;
  25024. }
  25025. }
  25026. function now() {
  25027. return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  25028. }
  25029. const _position$1 = /*@__PURE__*/new Vector3();
  25030. const _quaternion$1 = /*@__PURE__*/new Quaternion();
  25031. const _scale$1 = /*@__PURE__*/new Vector3();
  25032. const _orientation$1 = /*@__PURE__*/new Vector3();
  25033. class AudioListener extends Object3D {
  25034. constructor() {
  25035. super();
  25036. this.type = 'AudioListener';
  25037. this.context = AudioContext.getContext();
  25038. this.gain = this.context.createGain();
  25039. this.gain.connect(this.context.destination);
  25040. this.filter = null;
  25041. this.timeDelta = 0; // private
  25042. this._clock = new Clock();
  25043. }
  25044. getInput() {
  25045. return this.gain;
  25046. }
  25047. removeFilter() {
  25048. if (this.filter !== null) {
  25049. this.gain.disconnect(this.filter);
  25050. this.filter.disconnect(this.context.destination);
  25051. this.gain.connect(this.context.destination);
  25052. this.filter = null;
  25053. }
  25054. return this;
  25055. }
  25056. getFilter() {
  25057. return this.filter;
  25058. }
  25059. setFilter(value) {
  25060. if (this.filter !== null) {
  25061. this.gain.disconnect(this.filter);
  25062. this.filter.disconnect(this.context.destination);
  25063. } else {
  25064. this.gain.disconnect(this.context.destination);
  25065. }
  25066. this.filter = value;
  25067. this.gain.connect(this.filter);
  25068. this.filter.connect(this.context.destination);
  25069. return this;
  25070. }
  25071. getMasterVolume() {
  25072. return this.gain.gain.value;
  25073. }
  25074. setMasterVolume(value) {
  25075. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25076. return this;
  25077. }
  25078. updateMatrixWorld(force) {
  25079. super.updateMatrixWorld(force);
  25080. const listener = this.context.listener;
  25081. const up = this.up;
  25082. this.timeDelta = this._clock.getDelta();
  25083. this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1);
  25084. _orientation$1.set(0, 0, -1).applyQuaternion(_quaternion$1);
  25085. if (listener.positionX) {
  25086. // code path for Chrome (see #14393)
  25087. const endTime = this.context.currentTime + this.timeDelta;
  25088. listener.positionX.linearRampToValueAtTime(_position$1.x, endTime);
  25089. listener.positionY.linearRampToValueAtTime(_position$1.y, endTime);
  25090. listener.positionZ.linearRampToValueAtTime(_position$1.z, endTime);
  25091. listener.forwardX.linearRampToValueAtTime(_orientation$1.x, endTime);
  25092. listener.forwardY.linearRampToValueAtTime(_orientation$1.y, endTime);
  25093. listener.forwardZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  25094. listener.upX.linearRampToValueAtTime(up.x, endTime);
  25095. listener.upY.linearRampToValueAtTime(up.y, endTime);
  25096. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  25097. } else {
  25098. listener.setPosition(_position$1.x, _position$1.y, _position$1.z);
  25099. listener.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z);
  25100. }
  25101. }
  25102. }
  25103. class Audio extends Object3D {
  25104. constructor(listener) {
  25105. super();
  25106. this.type = 'Audio';
  25107. this.listener = listener;
  25108. this.context = listener.context;
  25109. this.gain = this.context.createGain();
  25110. this.gain.connect(listener.getInput());
  25111. this.autoplay = false;
  25112. this.buffer = null;
  25113. this.detune = 0;
  25114. this.loop = false;
  25115. this.loopStart = 0;
  25116. this.loopEnd = 0;
  25117. this.offset = 0;
  25118. this.duration = undefined;
  25119. this.playbackRate = 1;
  25120. this.isPlaying = false;
  25121. this.hasPlaybackControl = true;
  25122. this.source = null;
  25123. this.sourceType = 'empty';
  25124. this._startedAt = 0;
  25125. this._progress = 0;
  25126. this._connected = false;
  25127. this.filters = [];
  25128. }
  25129. getOutput() {
  25130. return this.gain;
  25131. }
  25132. setNodeSource(audioNode) {
  25133. this.hasPlaybackControl = false;
  25134. this.sourceType = 'audioNode';
  25135. this.source = audioNode;
  25136. this.connect();
  25137. return this;
  25138. }
  25139. setMediaElementSource(mediaElement) {
  25140. this.hasPlaybackControl = false;
  25141. this.sourceType = 'mediaNode';
  25142. this.source = this.context.createMediaElementSource(mediaElement);
  25143. this.connect();
  25144. return this;
  25145. }
  25146. setMediaStreamSource(mediaStream) {
  25147. this.hasPlaybackControl = false;
  25148. this.sourceType = 'mediaStreamNode';
  25149. this.source = this.context.createMediaStreamSource(mediaStream);
  25150. this.connect();
  25151. return this;
  25152. }
  25153. setBuffer(audioBuffer) {
  25154. this.buffer = audioBuffer;
  25155. this.sourceType = 'buffer';
  25156. if (this.autoplay) this.play();
  25157. return this;
  25158. }
  25159. play(delay = 0) {
  25160. if (this.isPlaying === true) {
  25161. console.warn('THREE.Audio: Audio is already playing.');
  25162. return;
  25163. }
  25164. if (this.hasPlaybackControl === false) {
  25165. console.warn('THREE.Audio: this Audio has no playback control.');
  25166. return;
  25167. }
  25168. this._startedAt = this.context.currentTime + delay;
  25169. const source = this.context.createBufferSource();
  25170. source.buffer = this.buffer;
  25171. source.loop = this.loop;
  25172. source.loopStart = this.loopStart;
  25173. source.loopEnd = this.loopEnd;
  25174. source.onended = this.onEnded.bind(this);
  25175. source.start(this._startedAt, this._progress + this.offset, this.duration);
  25176. this.isPlaying = true;
  25177. this.source = source;
  25178. this.setDetune(this.detune);
  25179. this.setPlaybackRate(this.playbackRate);
  25180. return this.connect();
  25181. }
  25182. pause() {
  25183. if (this.hasPlaybackControl === false) {
  25184. console.warn('THREE.Audio: this Audio has no playback control.');
  25185. return;
  25186. }
  25187. if (this.isPlaying === true) {
  25188. // update current progress
  25189. this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  25190. if (this.loop === true) {
  25191. // ensure _progress does not exceed duration with looped audios
  25192. this._progress = this._progress % (this.duration || this.buffer.duration);
  25193. }
  25194. this.source.stop();
  25195. this.source.onended = null;
  25196. this.isPlaying = false;
  25197. }
  25198. return this;
  25199. }
  25200. stop() {
  25201. if (this.hasPlaybackControl === false) {
  25202. console.warn('THREE.Audio: this Audio has no playback control.');
  25203. return;
  25204. }
  25205. this._progress = 0;
  25206. this.source.stop();
  25207. this.source.onended = null;
  25208. this.isPlaying = false;
  25209. return this;
  25210. }
  25211. connect() {
  25212. if (this.filters.length > 0) {
  25213. this.source.connect(this.filters[0]);
  25214. for (let i = 1, l = this.filters.length; i < l; i++) {
  25215. this.filters[i - 1].connect(this.filters[i]);
  25216. }
  25217. this.filters[this.filters.length - 1].connect(this.getOutput());
  25218. } else {
  25219. this.source.connect(this.getOutput());
  25220. }
  25221. this._connected = true;
  25222. return this;
  25223. }
  25224. disconnect() {
  25225. if (this.filters.length > 0) {
  25226. this.source.disconnect(this.filters[0]);
  25227. for (let i = 1, l = this.filters.length; i < l; i++) {
  25228. this.filters[i - 1].disconnect(this.filters[i]);
  25229. }
  25230. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  25231. } else {
  25232. this.source.disconnect(this.getOutput());
  25233. }
  25234. this._connected = false;
  25235. return this;
  25236. }
  25237. getFilters() {
  25238. return this.filters;
  25239. }
  25240. setFilters(value) {
  25241. if (!value) value = [];
  25242. if (this._connected === true) {
  25243. this.disconnect();
  25244. this.filters = value.slice();
  25245. this.connect();
  25246. } else {
  25247. this.filters = value.slice();
  25248. }
  25249. return this;
  25250. }
  25251. setDetune(value) {
  25252. this.detune = value;
  25253. if (this.source.detune === undefined) return; // only set detune when available
  25254. if (this.isPlaying === true) {
  25255. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  25256. }
  25257. return this;
  25258. }
  25259. getDetune() {
  25260. return this.detune;
  25261. }
  25262. getFilter() {
  25263. return this.getFilters()[0];
  25264. }
  25265. setFilter(filter) {
  25266. return this.setFilters(filter ? [filter] : []);
  25267. }
  25268. setPlaybackRate(value) {
  25269. if (this.hasPlaybackControl === false) {
  25270. console.warn('THREE.Audio: this Audio has no playback control.');
  25271. return;
  25272. }
  25273. this.playbackRate = value;
  25274. if (this.isPlaying === true) {
  25275. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  25276. }
  25277. return this;
  25278. }
  25279. getPlaybackRate() {
  25280. return this.playbackRate;
  25281. }
  25282. onEnded() {
  25283. this.isPlaying = false;
  25284. }
  25285. getLoop() {
  25286. if (this.hasPlaybackControl === false) {
  25287. console.warn('THREE.Audio: this Audio has no playback control.');
  25288. return false;
  25289. }
  25290. return this.loop;
  25291. }
  25292. setLoop(value) {
  25293. if (this.hasPlaybackControl === false) {
  25294. console.warn('THREE.Audio: this Audio has no playback control.');
  25295. return;
  25296. }
  25297. this.loop = value;
  25298. if (this.isPlaying === true) {
  25299. this.source.loop = this.loop;
  25300. }
  25301. return this;
  25302. }
  25303. setLoopStart(value) {
  25304. this.loopStart = value;
  25305. return this;
  25306. }
  25307. setLoopEnd(value) {
  25308. this.loopEnd = value;
  25309. return this;
  25310. }
  25311. getVolume() {
  25312. return this.gain.gain.value;
  25313. }
  25314. setVolume(value) {
  25315. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25316. return this;
  25317. }
  25318. }
  25319. const _position = /*@__PURE__*/new Vector3();
  25320. const _quaternion = /*@__PURE__*/new Quaternion();
  25321. const _scale = /*@__PURE__*/new Vector3();
  25322. const _orientation = /*@__PURE__*/new Vector3();
  25323. class PositionalAudio extends Audio {
  25324. constructor(listener) {
  25325. super(listener);
  25326. this.panner = this.context.createPanner();
  25327. this.panner.panningModel = 'HRTF';
  25328. this.panner.connect(this.gain);
  25329. }
  25330. getOutput() {
  25331. return this.panner;
  25332. }
  25333. getRefDistance() {
  25334. return this.panner.refDistance;
  25335. }
  25336. setRefDistance(value) {
  25337. this.panner.refDistance = value;
  25338. return this;
  25339. }
  25340. getRolloffFactor() {
  25341. return this.panner.rolloffFactor;
  25342. }
  25343. setRolloffFactor(value) {
  25344. this.panner.rolloffFactor = value;
  25345. return this;
  25346. }
  25347. getDistanceModel() {
  25348. return this.panner.distanceModel;
  25349. }
  25350. setDistanceModel(value) {
  25351. this.panner.distanceModel = value;
  25352. return this;
  25353. }
  25354. getMaxDistance() {
  25355. return this.panner.maxDistance;
  25356. }
  25357. setMaxDistance(value) {
  25358. this.panner.maxDistance = value;
  25359. return this;
  25360. }
  25361. setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25362. this.panner.coneInnerAngle = coneInnerAngle;
  25363. this.panner.coneOuterAngle = coneOuterAngle;
  25364. this.panner.coneOuterGain = coneOuterGain;
  25365. return this;
  25366. }
  25367. updateMatrixWorld(force) {
  25368. super.updateMatrixWorld(force);
  25369. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  25370. this.matrixWorld.decompose(_position, _quaternion, _scale);
  25371. _orientation.set(0, 0, 1).applyQuaternion(_quaternion);
  25372. const panner = this.panner;
  25373. if (panner.positionX) {
  25374. // code path for Chrome and Firefox (see #14393)
  25375. const endTime = this.context.currentTime + this.listener.timeDelta;
  25376. panner.positionX.linearRampToValueAtTime(_position.x, endTime);
  25377. panner.positionY.linearRampToValueAtTime(_position.y, endTime);
  25378. panner.positionZ.linearRampToValueAtTime(_position.z, endTime);
  25379. panner.orientationX.linearRampToValueAtTime(_orientation.x, endTime);
  25380. panner.orientationY.linearRampToValueAtTime(_orientation.y, endTime);
  25381. panner.orientationZ.linearRampToValueAtTime(_orientation.z, endTime);
  25382. } else {
  25383. panner.setPosition(_position.x, _position.y, _position.z);
  25384. panner.setOrientation(_orientation.x, _orientation.y, _orientation.z);
  25385. }
  25386. }
  25387. }
  25388. class AudioAnalyser {
  25389. constructor(audio, fftSize = 2048) {
  25390. this.analyser = audio.context.createAnalyser();
  25391. this.analyser.fftSize = fftSize;
  25392. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  25393. audio.getOutput().connect(this.analyser);
  25394. }
  25395. getFrequencyData() {
  25396. this.analyser.getByteFrequencyData(this.data);
  25397. return this.data;
  25398. }
  25399. getAverageFrequency() {
  25400. let value = 0;
  25401. const data = this.getFrequencyData();
  25402. for (let i = 0; i < data.length; i++) {
  25403. value += data[i];
  25404. }
  25405. return value / data.length;
  25406. }
  25407. }
  25408. class PropertyMixer {
  25409. constructor(binding, typeName, valueSize) {
  25410. this.binding = binding;
  25411. this.valueSize = valueSize;
  25412. let mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  25413. //
  25414. // interpolators can use .buffer as their .result
  25415. // the data then goes to 'incoming'
  25416. //
  25417. // 'accu0' and 'accu1' are used frame-interleaved for
  25418. // the cumulative result and are compared to detect
  25419. // changes
  25420. //
  25421. // 'orig' stores the original state of the property
  25422. //
  25423. // 'add' is used for additive cumulative results
  25424. //
  25425. // 'work' is optional and is only present for quaternion types. It is used
  25426. // to store intermediate quaternion multiplication results
  25427. switch (typeName) {
  25428. case 'quaternion':
  25429. mixFunction = this._slerp;
  25430. mixFunctionAdditive = this._slerpAdditive;
  25431. setIdentity = this._setAdditiveIdentityQuaternion;
  25432. this.buffer = new Float64Array(valueSize * 6);
  25433. this._workIndex = 5;
  25434. break;
  25435. case 'string':
  25436. case 'bool':
  25437. mixFunction = this._select; // Use the regular mix function and for additive on these types,
  25438. // additive is not relevant for non-numeric types
  25439. mixFunctionAdditive = this._select;
  25440. setIdentity = this._setAdditiveIdentityOther;
  25441. this.buffer = new Array(valueSize * 5);
  25442. break;
  25443. default:
  25444. mixFunction = this._lerp;
  25445. mixFunctionAdditive = this._lerpAdditive;
  25446. setIdentity = this._setAdditiveIdentityNumeric;
  25447. this.buffer = new Float64Array(valueSize * 5);
  25448. }
  25449. this._mixBufferRegion = mixFunction;
  25450. this._mixBufferRegionAdditive = mixFunctionAdditive;
  25451. this._setIdentity = setIdentity;
  25452. this._origIndex = 3;
  25453. this._addIndex = 4;
  25454. this.cumulativeWeight = 0;
  25455. this.cumulativeWeightAdditive = 0;
  25456. this.useCount = 0;
  25457. this.referenceCount = 0;
  25458. } // accumulate data in the 'incoming' region into 'accu<i>'
  25459. accumulate(accuIndex, weight) {
  25460. // note: happily accumulating nothing when weight = 0, the caller knows
  25461. // the weight and shouldn't have made the call in the first place
  25462. const buffer = this.buffer,
  25463. stride = this.valueSize,
  25464. offset = accuIndex * stride + stride;
  25465. let currentWeight = this.cumulativeWeight;
  25466. if (currentWeight === 0) {
  25467. // accuN := incoming * weight
  25468. for (let i = 0; i !== stride; ++i) {
  25469. buffer[offset + i] = buffer[i];
  25470. }
  25471. currentWeight = weight;
  25472. } else {
  25473. // accuN := accuN + incoming * weight
  25474. currentWeight += weight;
  25475. const mix = weight / currentWeight;
  25476. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  25477. }
  25478. this.cumulativeWeight = currentWeight;
  25479. } // accumulate data in the 'incoming' region into 'add'
  25480. accumulateAdditive(weight) {
  25481. const buffer = this.buffer,
  25482. stride = this.valueSize,
  25483. offset = stride * this._addIndex;
  25484. if (this.cumulativeWeightAdditive === 0) {
  25485. // add = identity
  25486. this._setIdentity();
  25487. } // add := add + incoming * weight
  25488. this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
  25489. this.cumulativeWeightAdditive += weight;
  25490. } // apply the state of 'accu<i>' to the binding when accus differ
  25491. apply(accuIndex) {
  25492. const stride = this.valueSize,
  25493. buffer = this.buffer,
  25494. offset = accuIndex * stride + stride,
  25495. weight = this.cumulativeWeight,
  25496. weightAdditive = this.cumulativeWeightAdditive,
  25497. binding = this.binding;
  25498. this.cumulativeWeight = 0;
  25499. this.cumulativeWeightAdditive = 0;
  25500. if (weight < 1) {
  25501. // accuN := accuN + original * ( 1 - cumulativeWeight )
  25502. const originalValueOffset = stride * this._origIndex;
  25503. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  25504. }
  25505. if (weightAdditive > 0) {
  25506. // accuN := accuN + additive accuN
  25507. this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
  25508. }
  25509. for (let i = stride, e = stride + stride; i !== e; ++i) {
  25510. if (buffer[i] !== buffer[i + stride]) {
  25511. // value has changed -> update scene graph
  25512. binding.setValue(buffer, offset);
  25513. break;
  25514. }
  25515. }
  25516. } // remember the state of the bound property and copy it to both accus
  25517. saveOriginalState() {
  25518. const binding = this.binding;
  25519. const buffer = this.buffer,
  25520. stride = this.valueSize,
  25521. originalValueOffset = stride * this._origIndex;
  25522. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  25523. for (let i = stride, e = originalValueOffset; i !== e; ++i) {
  25524. buffer[i] = buffer[originalValueOffset + i % stride];
  25525. } // Add to identity for additive
  25526. this._setIdentity();
  25527. this.cumulativeWeight = 0;
  25528. this.cumulativeWeightAdditive = 0;
  25529. } // apply the state previously taken via 'saveOriginalState' to the binding
  25530. restoreOriginalState() {
  25531. const originalValueOffset = this.valueSize * 3;
  25532. this.binding.setValue(this.buffer, originalValueOffset);
  25533. }
  25534. _setAdditiveIdentityNumeric() {
  25535. const startIndex = this._addIndex * this.valueSize;
  25536. const endIndex = startIndex + this.valueSize;
  25537. for (let i = startIndex; i < endIndex; i++) {
  25538. this.buffer[i] = 0;
  25539. }
  25540. }
  25541. _setAdditiveIdentityQuaternion() {
  25542. this._setAdditiveIdentityNumeric();
  25543. this.buffer[this._addIndex * this.valueSize + 3] = 1;
  25544. }
  25545. _setAdditiveIdentityOther() {
  25546. const startIndex = this._origIndex * this.valueSize;
  25547. const targetIndex = this._addIndex * this.valueSize;
  25548. for (let i = 0; i < this.valueSize; i++) {
  25549. this.buffer[targetIndex + i] = this.buffer[startIndex + i];
  25550. }
  25551. } // mix functions
  25552. _select(buffer, dstOffset, srcOffset, t, stride) {
  25553. if (t >= 0.5) {
  25554. for (let i = 0; i !== stride; ++i) {
  25555. buffer[dstOffset + i] = buffer[srcOffset + i];
  25556. }
  25557. }
  25558. }
  25559. _slerp(buffer, dstOffset, srcOffset, t) {
  25560. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  25561. }
  25562. _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  25563. const workOffset = this._workIndex * stride; // Store result in intermediate buffer offset
  25564. Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
  25565. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
  25566. }
  25567. _lerp(buffer, dstOffset, srcOffset, t, stride) {
  25568. const s = 1 - t;
  25569. for (let i = 0; i !== stride; ++i) {
  25570. const j = dstOffset + i;
  25571. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  25572. }
  25573. }
  25574. _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  25575. for (let i = 0; i !== stride; ++i) {
  25576. const j = dstOffset + i;
  25577. buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
  25578. }
  25579. }
  25580. }
  25581. // Characters [].:/ are reserved for track binding syntax.
  25582. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  25583. const _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  25584. // only latin characters, and the unicode \p{L} is not yet supported. So
  25585. // instead, we exclude reserved characters and match everything else.
  25586. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  25587. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  25588. // be matched to parse the rest of the track name.
  25589. const _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  25590. const _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  25591. // characters. Accessor may contain any character except closing bracket.
  25592. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  25593. // contain any non-bracket characters.
  25594. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  25595. const _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  25596. const _supportedObjectNames = ['material', 'materials', 'bones'];
  25597. class Composite {
  25598. constructor(targetGroup, path, optionalParsedPath) {
  25599. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  25600. this._targetGroup = targetGroup;
  25601. this._bindings = targetGroup.subscribe_(path, parsedPath);
  25602. }
  25603. getValue(array, offset) {
  25604. this.bind(); // bind all binding
  25605. const firstValidIndex = this._targetGroup.nCachedObjects_,
  25606. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  25607. if (binding !== undefined) binding.getValue(array, offset);
  25608. }
  25609. setValue(array, offset) {
  25610. const bindings = this._bindings;
  25611. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25612. bindings[i].setValue(array, offset);
  25613. }
  25614. }
  25615. bind() {
  25616. const bindings = this._bindings;
  25617. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25618. bindings[i].bind();
  25619. }
  25620. }
  25621. unbind() {
  25622. const bindings = this._bindings;
  25623. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25624. bindings[i].unbind();
  25625. }
  25626. }
  25627. } // Note: This class uses a State pattern on a per-method basis:
  25628. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  25629. // prototype version of these methods with one that represents
  25630. // the bound state. When the property is not found, the methods
  25631. // become no-ops.
  25632. class PropertyBinding {
  25633. constructor(rootNode, path, parsedPath) {
  25634. this.path = path;
  25635. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  25636. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  25637. this.rootNode = rootNode; // initial state of these methods that calls 'bind'
  25638. this.getValue = this._getValue_unbound;
  25639. this.setValue = this._setValue_unbound;
  25640. }
  25641. static create(root, path, parsedPath) {
  25642. if (!(root && root.isAnimationObjectGroup)) {
  25643. return new PropertyBinding(root, path, parsedPath);
  25644. } else {
  25645. return new PropertyBinding.Composite(root, path, parsedPath);
  25646. }
  25647. }
  25648. /**
  25649. * Replaces spaces with underscores and removes unsupported characters from
  25650. * node names, to ensure compatibility with parseTrackName().
  25651. *
  25652. * @param {string} name Node name to be sanitized.
  25653. * @return {string}
  25654. */
  25655. static sanitizeNodeName(name) {
  25656. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  25657. }
  25658. static parseTrackName(trackName) {
  25659. const matches = _trackRe.exec(trackName);
  25660. if (!matches) {
  25661. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  25662. }
  25663. const results = {
  25664. // directoryName: matches[ 1 ], // (tschw) currently unused
  25665. nodeName: matches[2],
  25666. objectName: matches[3],
  25667. objectIndex: matches[4],
  25668. propertyName: matches[5],
  25669. // required
  25670. propertyIndex: matches[6]
  25671. };
  25672. const lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  25673. if (lastDot !== undefined && lastDot !== -1) {
  25674. const objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
  25675. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  25676. // 'bar' could be the objectName, or part of a nodeName (which can
  25677. // include '.' characters).
  25678. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  25679. results.nodeName = results.nodeName.substring(0, lastDot);
  25680. results.objectName = objectName;
  25681. }
  25682. }
  25683. if (results.propertyName === null || results.propertyName.length === 0) {
  25684. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  25685. }
  25686. return results;
  25687. }
  25688. static findNode(root, nodeName) {
  25689. if (!nodeName || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  25690. return root;
  25691. } // search into skeleton bones.
  25692. if (root.skeleton) {
  25693. const bone = root.skeleton.getBoneByName(nodeName);
  25694. if (bone !== undefined) {
  25695. return bone;
  25696. }
  25697. } // search into node subtree.
  25698. if (root.children) {
  25699. const searchNodeSubtree = function (children) {
  25700. for (let i = 0; i < children.length; i++) {
  25701. const childNode = children[i];
  25702. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  25703. return childNode;
  25704. }
  25705. const result = searchNodeSubtree(childNode.children);
  25706. if (result) return result;
  25707. }
  25708. return null;
  25709. };
  25710. const subTreeNode = searchNodeSubtree(root.children);
  25711. if (subTreeNode) {
  25712. return subTreeNode;
  25713. }
  25714. }
  25715. return null;
  25716. } // these are used to "bind" a nonexistent property
  25717. _getValue_unavailable() {}
  25718. _setValue_unavailable() {} // Getters
  25719. _getValue_direct(buffer, offset) {
  25720. buffer[offset] = this.targetObject[this.propertyName];
  25721. }
  25722. _getValue_array(buffer, offset) {
  25723. const source = this.resolvedProperty;
  25724. for (let i = 0, n = source.length; i !== n; ++i) {
  25725. buffer[offset++] = source[i];
  25726. }
  25727. }
  25728. _getValue_arrayElement(buffer, offset) {
  25729. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  25730. }
  25731. _getValue_toArray(buffer, offset) {
  25732. this.resolvedProperty.toArray(buffer, offset);
  25733. } // Direct
  25734. _setValue_direct(buffer, offset) {
  25735. this.targetObject[this.propertyName] = buffer[offset];
  25736. }
  25737. _setValue_direct_setNeedsUpdate(buffer, offset) {
  25738. this.targetObject[this.propertyName] = buffer[offset];
  25739. this.targetObject.needsUpdate = true;
  25740. }
  25741. _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  25742. this.targetObject[this.propertyName] = buffer[offset];
  25743. this.targetObject.matrixWorldNeedsUpdate = true;
  25744. } // EntireArray
  25745. _setValue_array(buffer, offset) {
  25746. const dest = this.resolvedProperty;
  25747. for (let i = 0, n = dest.length; i !== n; ++i) {
  25748. dest[i] = buffer[offset++];
  25749. }
  25750. }
  25751. _setValue_array_setNeedsUpdate(buffer, offset) {
  25752. const dest = this.resolvedProperty;
  25753. for (let i = 0, n = dest.length; i !== n; ++i) {
  25754. dest[i] = buffer[offset++];
  25755. }
  25756. this.targetObject.needsUpdate = true;
  25757. }
  25758. _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  25759. const dest = this.resolvedProperty;
  25760. for (let i = 0, n = dest.length; i !== n; ++i) {
  25761. dest[i] = buffer[offset++];
  25762. }
  25763. this.targetObject.matrixWorldNeedsUpdate = true;
  25764. } // ArrayElement
  25765. _setValue_arrayElement(buffer, offset) {
  25766. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25767. }
  25768. _setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  25769. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25770. this.targetObject.needsUpdate = true;
  25771. }
  25772. _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  25773. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25774. this.targetObject.matrixWorldNeedsUpdate = true;
  25775. } // HasToFromArray
  25776. _setValue_fromArray(buffer, offset) {
  25777. this.resolvedProperty.fromArray(buffer, offset);
  25778. }
  25779. _setValue_fromArray_setNeedsUpdate(buffer, offset) {
  25780. this.resolvedProperty.fromArray(buffer, offset);
  25781. this.targetObject.needsUpdate = true;
  25782. }
  25783. _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  25784. this.resolvedProperty.fromArray(buffer, offset);
  25785. this.targetObject.matrixWorldNeedsUpdate = true;
  25786. }
  25787. _getValue_unbound(targetArray, offset) {
  25788. this.bind();
  25789. this.getValue(targetArray, offset);
  25790. }
  25791. _setValue_unbound(sourceArray, offset) {
  25792. this.bind();
  25793. this.setValue(sourceArray, offset);
  25794. } // create getter / setter pair for a property in the scene graph
  25795. bind() {
  25796. let targetObject = this.node;
  25797. const parsedPath = this.parsedPath;
  25798. const objectName = parsedPath.objectName;
  25799. const propertyName = parsedPath.propertyName;
  25800. let propertyIndex = parsedPath.propertyIndex;
  25801. if (!targetObject) {
  25802. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  25803. this.node = targetObject;
  25804. } // set fail state so we can just 'return' on error
  25805. this.getValue = this._getValue_unavailable;
  25806. this.setValue = this._setValue_unavailable; // ensure there is a value node
  25807. if (!targetObject) {
  25808. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  25809. return;
  25810. }
  25811. if (objectName) {
  25812. let objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  25813. switch (objectName) {
  25814. case 'materials':
  25815. if (!targetObject.material) {
  25816. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  25817. return;
  25818. }
  25819. if (!targetObject.material.materials) {
  25820. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  25821. return;
  25822. }
  25823. targetObject = targetObject.material.materials;
  25824. break;
  25825. case 'bones':
  25826. if (!targetObject.skeleton) {
  25827. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  25828. return;
  25829. } // potential future optimization: skip this if propertyIndex is already an integer
  25830. // and convert the integer string to a true integer.
  25831. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  25832. for (let i = 0; i < targetObject.length; i++) {
  25833. if (targetObject[i].name === objectIndex) {
  25834. objectIndex = i;
  25835. break;
  25836. }
  25837. }
  25838. break;
  25839. default:
  25840. if (targetObject[objectName] === undefined) {
  25841. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  25842. return;
  25843. }
  25844. targetObject = targetObject[objectName];
  25845. }
  25846. if (objectIndex !== undefined) {
  25847. if (targetObject[objectIndex] === undefined) {
  25848. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  25849. return;
  25850. }
  25851. targetObject = targetObject[objectIndex];
  25852. }
  25853. } // resolve property
  25854. const nodeProperty = targetObject[propertyName];
  25855. if (nodeProperty === undefined) {
  25856. const nodeName = parsedPath.nodeName;
  25857. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  25858. return;
  25859. } // determine versioning scheme
  25860. let versioning = this.Versioning.None;
  25861. this.targetObject = targetObject;
  25862. if (targetObject.needsUpdate !== undefined) {
  25863. // material
  25864. versioning = this.Versioning.NeedsUpdate;
  25865. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  25866. // node transform
  25867. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  25868. } // determine how the property gets bound
  25869. let bindingType = this.BindingType.Direct;
  25870. if (propertyIndex !== undefined) {
  25871. // access a sub element of the property array (only primitives are supported right now)
  25872. if (propertyName === 'morphTargetInfluences') {
  25873. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  25874. // support resolving morphTarget names into indices.
  25875. if (!targetObject.geometry) {
  25876. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  25877. return;
  25878. }
  25879. if (targetObject.geometry.isBufferGeometry) {
  25880. if (!targetObject.geometry.morphAttributes) {
  25881. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  25882. return;
  25883. }
  25884. if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
  25885. propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
  25886. }
  25887. } else {
  25888. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this);
  25889. return;
  25890. }
  25891. }
  25892. bindingType = this.BindingType.ArrayElement;
  25893. this.resolvedProperty = nodeProperty;
  25894. this.propertyIndex = propertyIndex;
  25895. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  25896. // must use copy for Object3D.Euler/Quaternion
  25897. bindingType = this.BindingType.HasFromToArray;
  25898. this.resolvedProperty = nodeProperty;
  25899. } else if (Array.isArray(nodeProperty)) {
  25900. bindingType = this.BindingType.EntireArray;
  25901. this.resolvedProperty = nodeProperty;
  25902. } else {
  25903. this.propertyName = propertyName;
  25904. } // select getter / setter
  25905. this.getValue = this.GetterByBindingType[bindingType];
  25906. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  25907. }
  25908. unbind() {
  25909. this.node = null; // back to the prototype version of getValue / setValue
  25910. // note: avoiding to mutate the shape of 'this' via 'delete'
  25911. this.getValue = this._getValue_unbound;
  25912. this.setValue = this._setValue_unbound;
  25913. }
  25914. }
  25915. PropertyBinding.Composite = Composite;
  25916. PropertyBinding.prototype.BindingType = {
  25917. Direct: 0,
  25918. EntireArray: 1,
  25919. ArrayElement: 2,
  25920. HasFromToArray: 3
  25921. };
  25922. PropertyBinding.prototype.Versioning = {
  25923. None: 0,
  25924. NeedsUpdate: 1,
  25925. MatrixWorldNeedsUpdate: 2
  25926. };
  25927. PropertyBinding.prototype.GetterByBindingType = [PropertyBinding.prototype._getValue_direct, PropertyBinding.prototype._getValue_array, PropertyBinding.prototype._getValue_arrayElement, PropertyBinding.prototype._getValue_toArray];
  25928. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [[// Direct
  25929. PropertyBinding.prototype._setValue_direct, PropertyBinding.prototype._setValue_direct_setNeedsUpdate, PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate], [// EntireArray
  25930. PropertyBinding.prototype._setValue_array, PropertyBinding.prototype._setValue_array_setNeedsUpdate, PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate], [// ArrayElement
  25931. PropertyBinding.prototype._setValue_arrayElement, PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate], [// HasToFromArray
  25932. PropertyBinding.prototype._setValue_fromArray, PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];
  25933. /**
  25934. *
  25935. * A group of objects that receives a shared animation state.
  25936. *
  25937. * Usage:
  25938. *
  25939. * - Add objects you would otherwise pass as 'root' to the
  25940. * constructor or the .clipAction method of AnimationMixer.
  25941. *
  25942. * - Instead pass this object as 'root'.
  25943. *
  25944. * - You can also add and remove objects later when the mixer
  25945. * is running.
  25946. *
  25947. * Note:
  25948. *
  25949. * Objects of this class appear as one object to the mixer,
  25950. * so cache control of the individual objects must be done
  25951. * on the group.
  25952. *
  25953. * Limitation:
  25954. *
  25955. * - The animated properties must be compatible among the
  25956. * all objects in the group.
  25957. *
  25958. * - A single property can either be controlled through a
  25959. * target group or directly, but not both.
  25960. */
  25961. class AnimationObjectGroup {
  25962. constructor() {
  25963. this.uuid = generateUUID(); // cached objects followed by the active ones
  25964. this._objects = Array.prototype.slice.call(arguments);
  25965. this.nCachedObjects_ = 0; // threshold
  25966. // note: read by PropertyBinding.Composite
  25967. const indices = {};
  25968. this._indicesByUUID = indices; // for bookkeeping
  25969. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25970. indices[arguments[i].uuid] = i;
  25971. }
  25972. this._paths = []; // inside: string
  25973. this._parsedPaths = []; // inside: { we don't care, here }
  25974. this._bindings = []; // inside: Array< PropertyBinding >
  25975. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  25976. const scope = this;
  25977. this.stats = {
  25978. objects: {
  25979. get total() {
  25980. return scope._objects.length;
  25981. },
  25982. get inUse() {
  25983. return this.total - scope.nCachedObjects_;
  25984. }
  25985. },
  25986. get bindingsPerObject() {
  25987. return scope._bindings.length;
  25988. }
  25989. };
  25990. }
  25991. add() {
  25992. const objects = this._objects,
  25993. indicesByUUID = this._indicesByUUID,
  25994. paths = this._paths,
  25995. parsedPaths = this._parsedPaths,
  25996. bindings = this._bindings,
  25997. nBindings = bindings.length;
  25998. let knownObject = undefined,
  25999. nObjects = objects.length,
  26000. nCachedObjects = this.nCachedObjects_;
  26001. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26002. const object = arguments[i],
  26003. uuid = object.uuid;
  26004. let index = indicesByUUID[uuid];
  26005. if (index === undefined) {
  26006. // unknown object -> add it to the ACTIVE region
  26007. index = nObjects++;
  26008. indicesByUUID[uuid] = index;
  26009. objects.push(object); // accounting is done, now do the same for all bindings
  26010. for (let j = 0, m = nBindings; j !== m; ++j) {
  26011. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  26012. }
  26013. } else if (index < nCachedObjects) {
  26014. knownObject = objects[index]; // move existing object to the ACTIVE region
  26015. const firstActiveIndex = --nCachedObjects,
  26016. lastCachedObject = objects[firstActiveIndex];
  26017. indicesByUUID[lastCachedObject.uuid] = index;
  26018. objects[index] = lastCachedObject;
  26019. indicesByUUID[uuid] = firstActiveIndex;
  26020. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  26021. for (let j = 0, m = nBindings; j !== m; ++j) {
  26022. const bindingsForPath = bindings[j],
  26023. lastCached = bindingsForPath[firstActiveIndex];
  26024. let binding = bindingsForPath[index];
  26025. bindingsForPath[index] = lastCached;
  26026. if (binding === undefined) {
  26027. // since we do not bother to create new bindings
  26028. // for objects that are cached, the binding may
  26029. // or may not exist
  26030. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  26031. }
  26032. bindingsForPath[firstActiveIndex] = binding;
  26033. }
  26034. } else if (objects[index] !== knownObject) {
  26035. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  26036. } // else the object is already where we want it to be
  26037. } // for arguments
  26038. this.nCachedObjects_ = nCachedObjects;
  26039. }
  26040. remove() {
  26041. const objects = this._objects,
  26042. indicesByUUID = this._indicesByUUID,
  26043. bindings = this._bindings,
  26044. nBindings = bindings.length;
  26045. let nCachedObjects = this.nCachedObjects_;
  26046. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26047. const object = arguments[i],
  26048. uuid = object.uuid,
  26049. index = indicesByUUID[uuid];
  26050. if (index !== undefined && index >= nCachedObjects) {
  26051. // move existing object into the CACHED region
  26052. const lastCachedIndex = nCachedObjects++,
  26053. firstActiveObject = objects[lastCachedIndex];
  26054. indicesByUUID[firstActiveObject.uuid] = index;
  26055. objects[index] = firstActiveObject;
  26056. indicesByUUID[uuid] = lastCachedIndex;
  26057. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  26058. for (let j = 0, m = nBindings; j !== m; ++j) {
  26059. const bindingsForPath = bindings[j],
  26060. firstActive = bindingsForPath[lastCachedIndex],
  26061. binding = bindingsForPath[index];
  26062. bindingsForPath[index] = firstActive;
  26063. bindingsForPath[lastCachedIndex] = binding;
  26064. }
  26065. }
  26066. } // for arguments
  26067. this.nCachedObjects_ = nCachedObjects;
  26068. } // remove & forget
  26069. uncache() {
  26070. const objects = this._objects,
  26071. indicesByUUID = this._indicesByUUID,
  26072. bindings = this._bindings,
  26073. nBindings = bindings.length;
  26074. let nCachedObjects = this.nCachedObjects_,
  26075. nObjects = objects.length;
  26076. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26077. const object = arguments[i],
  26078. uuid = object.uuid,
  26079. index = indicesByUUID[uuid];
  26080. if (index !== undefined) {
  26081. delete indicesByUUID[uuid];
  26082. if (index < nCachedObjects) {
  26083. // object is cached, shrink the CACHED region
  26084. const firstActiveIndex = --nCachedObjects,
  26085. lastCachedObject = objects[firstActiveIndex],
  26086. lastIndex = --nObjects,
  26087. lastObject = objects[lastIndex]; // last cached object takes this object's place
  26088. indicesByUUID[lastCachedObject.uuid] = index;
  26089. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  26090. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  26091. objects[firstActiveIndex] = lastObject;
  26092. objects.pop(); // accounting is done, now do the same for all bindings
  26093. for (let j = 0, m = nBindings; j !== m; ++j) {
  26094. const bindingsForPath = bindings[j],
  26095. lastCached = bindingsForPath[firstActiveIndex],
  26096. last = bindingsForPath[lastIndex];
  26097. bindingsForPath[index] = lastCached;
  26098. bindingsForPath[firstActiveIndex] = last;
  26099. bindingsForPath.pop();
  26100. }
  26101. } else {
  26102. // object is active, just swap with the last and pop
  26103. const lastIndex = --nObjects,
  26104. lastObject = objects[lastIndex];
  26105. if (lastIndex > 0) {
  26106. indicesByUUID[lastObject.uuid] = index;
  26107. }
  26108. objects[index] = lastObject;
  26109. objects.pop(); // accounting is done, now do the same for all bindings
  26110. for (let j = 0, m = nBindings; j !== m; ++j) {
  26111. const bindingsForPath = bindings[j];
  26112. bindingsForPath[index] = bindingsForPath[lastIndex];
  26113. bindingsForPath.pop();
  26114. }
  26115. } // cached or active
  26116. } // if object is known
  26117. } // for arguments
  26118. this.nCachedObjects_ = nCachedObjects;
  26119. } // Internal interface used by befriended PropertyBinding.Composite:
  26120. subscribe_(path, parsedPath) {
  26121. // returns an array of bindings for the given path that is changed
  26122. // according to the contained objects in the group
  26123. const indicesByPath = this._bindingsIndicesByPath;
  26124. let index = indicesByPath[path];
  26125. const bindings = this._bindings;
  26126. if (index !== undefined) return bindings[index];
  26127. const paths = this._paths,
  26128. parsedPaths = this._parsedPaths,
  26129. objects = this._objects,
  26130. nObjects = objects.length,
  26131. nCachedObjects = this.nCachedObjects_,
  26132. bindingsForPath = new Array(nObjects);
  26133. index = bindings.length;
  26134. indicesByPath[path] = index;
  26135. paths.push(path);
  26136. parsedPaths.push(parsedPath);
  26137. bindings.push(bindingsForPath);
  26138. for (let i = nCachedObjects, n = objects.length; i !== n; ++i) {
  26139. const object = objects[i];
  26140. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  26141. }
  26142. return bindingsForPath;
  26143. }
  26144. unsubscribe_(path) {
  26145. // tells the group to forget about a property path and no longer
  26146. // update the array previously obtained with 'subscribe_'
  26147. const indicesByPath = this._bindingsIndicesByPath,
  26148. index = indicesByPath[path];
  26149. if (index !== undefined) {
  26150. const paths = this._paths,
  26151. parsedPaths = this._parsedPaths,
  26152. bindings = this._bindings,
  26153. lastBindingsIndex = bindings.length - 1,
  26154. lastBindings = bindings[lastBindingsIndex],
  26155. lastBindingsPath = path[lastBindingsIndex];
  26156. indicesByPath[lastBindingsPath] = index;
  26157. bindings[index] = lastBindings;
  26158. bindings.pop();
  26159. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  26160. parsedPaths.pop();
  26161. paths[index] = paths[lastBindingsIndex];
  26162. paths.pop();
  26163. }
  26164. }
  26165. }
  26166. AnimationObjectGroup.prototype.isAnimationObjectGroup = true;
  26167. class AnimationAction {
  26168. constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) {
  26169. this._mixer = mixer;
  26170. this._clip = clip;
  26171. this._localRoot = localRoot;
  26172. this.blendMode = blendMode;
  26173. const tracks = clip.tracks,
  26174. nTracks = tracks.length,
  26175. interpolants = new Array(nTracks);
  26176. const interpolantSettings = {
  26177. endingStart: ZeroCurvatureEnding,
  26178. endingEnd: ZeroCurvatureEnding
  26179. };
  26180. for (let i = 0; i !== nTracks; ++i) {
  26181. const interpolant = tracks[i].createInterpolant(null);
  26182. interpolants[i] = interpolant;
  26183. interpolant.settings = interpolantSettings;
  26184. }
  26185. this._interpolantSettings = interpolantSettings;
  26186. this._interpolants = interpolants; // bound by the mixer
  26187. // inside: PropertyMixer (managed by the mixer)
  26188. this._propertyBindings = new Array(nTracks);
  26189. this._cacheIndex = null; // for the memory manager
  26190. this._byClipCacheIndex = null; // for the memory manager
  26191. this._timeScaleInterpolant = null;
  26192. this._weightInterpolant = null;
  26193. this.loop = LoopRepeat;
  26194. this._loopCount = -1; // global mixer time when the action is to be started
  26195. // it's set back to 'null' upon start of the action
  26196. this._startTime = null; // scaled local time of the action
  26197. // gets clamped or wrapped to 0..clip.duration according to loop
  26198. this.time = 0;
  26199. this.timeScale = 1;
  26200. this._effectiveTimeScale = 1;
  26201. this.weight = 1;
  26202. this._effectiveWeight = 1;
  26203. this.repetitions = Infinity; // no. of repetitions when looping
  26204. this.paused = false; // true -> zero effective time scale
  26205. this.enabled = true; // false -> zero effective weight
  26206. this.clampWhenFinished = false; // keep feeding the last frame?
  26207. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  26208. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  26209. } // State & Scheduling
  26210. play() {
  26211. this._mixer._activateAction(this);
  26212. return this;
  26213. }
  26214. stop() {
  26215. this._mixer._deactivateAction(this);
  26216. return this.reset();
  26217. }
  26218. reset() {
  26219. this.paused = false;
  26220. this.enabled = true;
  26221. this.time = 0; // restart clip
  26222. this._loopCount = -1; // forget previous loops
  26223. this._startTime = null; // forget scheduling
  26224. return this.stopFading().stopWarping();
  26225. }
  26226. isRunning() {
  26227. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  26228. } // return true when play has been called
  26229. isScheduled() {
  26230. return this._mixer._isActiveAction(this);
  26231. }
  26232. startAt(time) {
  26233. this._startTime = time;
  26234. return this;
  26235. }
  26236. setLoop(mode, repetitions) {
  26237. this.loop = mode;
  26238. this.repetitions = repetitions;
  26239. return this;
  26240. } // Weight
  26241. // set the weight stopping any scheduled fading
  26242. // although .enabled = false yields an effective weight of zero, this
  26243. // method does *not* change .enabled, because it would be confusing
  26244. setEffectiveWeight(weight) {
  26245. this.weight = weight; // note: same logic as when updated at runtime
  26246. this._effectiveWeight = this.enabled ? weight : 0;
  26247. return this.stopFading();
  26248. } // return the weight considering fading and .enabled
  26249. getEffectiveWeight() {
  26250. return this._effectiveWeight;
  26251. }
  26252. fadeIn(duration) {
  26253. return this._scheduleFading(duration, 0, 1);
  26254. }
  26255. fadeOut(duration) {
  26256. return this._scheduleFading(duration, 1, 0);
  26257. }
  26258. crossFadeFrom(fadeOutAction, duration, warp) {
  26259. fadeOutAction.fadeOut(duration);
  26260. this.fadeIn(duration);
  26261. if (warp) {
  26262. const fadeInDuration = this._clip.duration,
  26263. fadeOutDuration = fadeOutAction._clip.duration,
  26264. startEndRatio = fadeOutDuration / fadeInDuration,
  26265. endStartRatio = fadeInDuration / fadeOutDuration;
  26266. fadeOutAction.warp(1.0, startEndRatio, duration);
  26267. this.warp(endStartRatio, 1.0, duration);
  26268. }
  26269. return this;
  26270. }
  26271. crossFadeTo(fadeInAction, duration, warp) {
  26272. return fadeInAction.crossFadeFrom(this, duration, warp);
  26273. }
  26274. stopFading() {
  26275. const weightInterpolant = this._weightInterpolant;
  26276. if (weightInterpolant !== null) {
  26277. this._weightInterpolant = null;
  26278. this._mixer._takeBackControlInterpolant(weightInterpolant);
  26279. }
  26280. return this;
  26281. } // Time Scale Control
  26282. // set the time scale stopping any scheduled warping
  26283. // although .paused = true yields an effective time scale of zero, this
  26284. // method does *not* change .paused, because it would be confusing
  26285. setEffectiveTimeScale(timeScale) {
  26286. this.timeScale = timeScale;
  26287. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  26288. return this.stopWarping();
  26289. } // return the time scale considering warping and .paused
  26290. getEffectiveTimeScale() {
  26291. return this._effectiveTimeScale;
  26292. }
  26293. setDuration(duration) {
  26294. this.timeScale = this._clip.duration / duration;
  26295. return this.stopWarping();
  26296. }
  26297. syncWith(action) {
  26298. this.time = action.time;
  26299. this.timeScale = action.timeScale;
  26300. return this.stopWarping();
  26301. }
  26302. halt(duration) {
  26303. return this.warp(this._effectiveTimeScale, 0, duration);
  26304. }
  26305. warp(startTimeScale, endTimeScale, duration) {
  26306. const mixer = this._mixer,
  26307. now = mixer.time,
  26308. timeScale = this.timeScale;
  26309. let interpolant = this._timeScaleInterpolant;
  26310. if (interpolant === null) {
  26311. interpolant = mixer._lendControlInterpolant();
  26312. this._timeScaleInterpolant = interpolant;
  26313. }
  26314. const times = interpolant.parameterPositions,
  26315. values = interpolant.sampleValues;
  26316. times[0] = now;
  26317. times[1] = now + duration;
  26318. values[0] = startTimeScale / timeScale;
  26319. values[1] = endTimeScale / timeScale;
  26320. return this;
  26321. }
  26322. stopWarping() {
  26323. const timeScaleInterpolant = this._timeScaleInterpolant;
  26324. if (timeScaleInterpolant !== null) {
  26325. this._timeScaleInterpolant = null;
  26326. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  26327. }
  26328. return this;
  26329. } // Object Accessors
  26330. getMixer() {
  26331. return this._mixer;
  26332. }
  26333. getClip() {
  26334. return this._clip;
  26335. }
  26336. getRoot() {
  26337. return this._localRoot || this._mixer._root;
  26338. } // Interna
  26339. _update(time, deltaTime, timeDirection, accuIndex) {
  26340. // called by the mixer
  26341. if (!this.enabled) {
  26342. // call ._updateWeight() to update ._effectiveWeight
  26343. this._updateWeight(time);
  26344. return;
  26345. }
  26346. const startTime = this._startTime;
  26347. if (startTime !== null) {
  26348. // check for scheduled start of action
  26349. const timeRunning = (time - startTime) * timeDirection;
  26350. if (timeRunning < 0 || timeDirection === 0) {
  26351. return; // yet to come / don't decide when delta = 0
  26352. } // start
  26353. this._startTime = null; // unschedule
  26354. deltaTime = timeDirection * timeRunning;
  26355. } // apply time scale and advance time
  26356. deltaTime *= this._updateTimeScale(time);
  26357. const clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  26358. // an effective weight of 0
  26359. const weight = this._updateWeight(time);
  26360. if (weight > 0) {
  26361. const interpolants = this._interpolants;
  26362. const propertyMixers = this._propertyBindings;
  26363. switch (this.blendMode) {
  26364. case AdditiveAnimationBlendMode:
  26365. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26366. interpolants[j].evaluate(clipTime);
  26367. propertyMixers[j].accumulateAdditive(weight);
  26368. }
  26369. break;
  26370. case NormalAnimationBlendMode:
  26371. default:
  26372. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26373. interpolants[j].evaluate(clipTime);
  26374. propertyMixers[j].accumulate(accuIndex, weight);
  26375. }
  26376. }
  26377. }
  26378. }
  26379. _updateWeight(time) {
  26380. let weight = 0;
  26381. if (this.enabled) {
  26382. weight = this.weight;
  26383. const interpolant = this._weightInterpolant;
  26384. if (interpolant !== null) {
  26385. const interpolantValue = interpolant.evaluate(time)[0];
  26386. weight *= interpolantValue;
  26387. if (time > interpolant.parameterPositions[1]) {
  26388. this.stopFading();
  26389. if (interpolantValue === 0) {
  26390. // faded out, disable
  26391. this.enabled = false;
  26392. }
  26393. }
  26394. }
  26395. }
  26396. this._effectiveWeight = weight;
  26397. return weight;
  26398. }
  26399. _updateTimeScale(time) {
  26400. let timeScale = 0;
  26401. if (!this.paused) {
  26402. timeScale = this.timeScale;
  26403. const interpolant = this._timeScaleInterpolant;
  26404. if (interpolant !== null) {
  26405. const interpolantValue = interpolant.evaluate(time)[0];
  26406. timeScale *= interpolantValue;
  26407. if (time > interpolant.parameterPositions[1]) {
  26408. this.stopWarping();
  26409. if (timeScale === 0) {
  26410. // motion has halted, pause
  26411. this.paused = true;
  26412. } else {
  26413. // warp done - apply final time scale
  26414. this.timeScale = timeScale;
  26415. }
  26416. }
  26417. }
  26418. }
  26419. this._effectiveTimeScale = timeScale;
  26420. return timeScale;
  26421. }
  26422. _updateTime(deltaTime) {
  26423. const duration = this._clip.duration;
  26424. const loop = this.loop;
  26425. let time = this.time + deltaTime;
  26426. let loopCount = this._loopCount;
  26427. const pingPong = loop === LoopPingPong;
  26428. if (deltaTime === 0) {
  26429. if (loopCount === -1) return time;
  26430. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  26431. }
  26432. if (loop === LoopOnce) {
  26433. if (loopCount === -1) {
  26434. // just started
  26435. this._loopCount = 0;
  26436. this._setEndings(true, true, false);
  26437. }
  26438. handle_stop: {
  26439. if (time >= duration) {
  26440. time = duration;
  26441. } else if (time < 0) {
  26442. time = 0;
  26443. } else {
  26444. this.time = time;
  26445. break handle_stop;
  26446. }
  26447. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26448. this.time = time;
  26449. this._mixer.dispatchEvent({
  26450. type: 'finished',
  26451. action: this,
  26452. direction: deltaTime < 0 ? -1 : 1
  26453. });
  26454. }
  26455. } else {
  26456. // repetitive Repeat or PingPong
  26457. if (loopCount === -1) {
  26458. // just started
  26459. if (deltaTime >= 0) {
  26460. loopCount = 0;
  26461. this._setEndings(true, this.repetitions === 0, pingPong);
  26462. } else {
  26463. // when looping in reverse direction, the initial
  26464. // transition through zero counts as a repetition,
  26465. // so leave loopCount at -1
  26466. this._setEndings(this.repetitions === 0, true, pingPong);
  26467. }
  26468. }
  26469. if (time >= duration || time < 0) {
  26470. // wrap around
  26471. const loopDelta = Math.floor(time / duration); // signed
  26472. time -= duration * loopDelta;
  26473. loopCount += Math.abs(loopDelta);
  26474. const pending = this.repetitions - loopCount;
  26475. if (pending <= 0) {
  26476. // have to stop (switch state, clamp time, fire event)
  26477. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26478. time = deltaTime > 0 ? duration : 0;
  26479. this.time = time;
  26480. this._mixer.dispatchEvent({
  26481. type: 'finished',
  26482. action: this,
  26483. direction: deltaTime > 0 ? 1 : -1
  26484. });
  26485. } else {
  26486. // keep running
  26487. if (pending === 1) {
  26488. // entering the last round
  26489. const atStart = deltaTime < 0;
  26490. this._setEndings(atStart, !atStart, pingPong);
  26491. } else {
  26492. this._setEndings(false, false, pingPong);
  26493. }
  26494. this._loopCount = loopCount;
  26495. this.time = time;
  26496. this._mixer.dispatchEvent({
  26497. type: 'loop',
  26498. action: this,
  26499. loopDelta: loopDelta
  26500. });
  26501. }
  26502. } else {
  26503. this.time = time;
  26504. }
  26505. if (pingPong && (loopCount & 1) === 1) {
  26506. // invert time for the "pong round"
  26507. return duration - time;
  26508. }
  26509. }
  26510. return time;
  26511. }
  26512. _setEndings(atStart, atEnd, pingPong) {
  26513. const settings = this._interpolantSettings;
  26514. if (pingPong) {
  26515. settings.endingStart = ZeroSlopeEnding;
  26516. settings.endingEnd = ZeroSlopeEnding;
  26517. } else {
  26518. // assuming for LoopOnce atStart == atEnd == true
  26519. if (atStart) {
  26520. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26521. } else {
  26522. settings.endingStart = WrapAroundEnding;
  26523. }
  26524. if (atEnd) {
  26525. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26526. } else {
  26527. settings.endingEnd = WrapAroundEnding;
  26528. }
  26529. }
  26530. }
  26531. _scheduleFading(duration, weightNow, weightThen) {
  26532. const mixer = this._mixer,
  26533. now = mixer.time;
  26534. let interpolant = this._weightInterpolant;
  26535. if (interpolant === null) {
  26536. interpolant = mixer._lendControlInterpolant();
  26537. this._weightInterpolant = interpolant;
  26538. }
  26539. const times = interpolant.parameterPositions,
  26540. values = interpolant.sampleValues;
  26541. times[0] = now;
  26542. values[0] = weightNow;
  26543. times[1] = now + duration;
  26544. values[1] = weightThen;
  26545. return this;
  26546. }
  26547. }
  26548. class AnimationMixer extends EventDispatcher {
  26549. constructor(root) {
  26550. super();
  26551. this._root = root;
  26552. this._initMemoryManager();
  26553. this._accuIndex = 0;
  26554. this.time = 0;
  26555. this.timeScale = 1.0;
  26556. }
  26557. _bindAction(action, prototypeAction) {
  26558. const root = action._localRoot || this._root,
  26559. tracks = action._clip.tracks,
  26560. nTracks = tracks.length,
  26561. bindings = action._propertyBindings,
  26562. interpolants = action._interpolants,
  26563. rootUuid = root.uuid,
  26564. bindingsByRoot = this._bindingsByRootAndName;
  26565. let bindingsByName = bindingsByRoot[rootUuid];
  26566. if (bindingsByName === undefined) {
  26567. bindingsByName = {};
  26568. bindingsByRoot[rootUuid] = bindingsByName;
  26569. }
  26570. for (let i = 0; i !== nTracks; ++i) {
  26571. const track = tracks[i],
  26572. trackName = track.name;
  26573. let binding = bindingsByName[trackName];
  26574. if (binding !== undefined) {
  26575. bindings[i] = binding;
  26576. } else {
  26577. binding = bindings[i];
  26578. if (binding !== undefined) {
  26579. // existing binding, make sure the cache knows
  26580. if (binding._cacheIndex === null) {
  26581. ++binding.referenceCount;
  26582. this._addInactiveBinding(binding, rootUuid, trackName);
  26583. }
  26584. continue;
  26585. }
  26586. const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  26587. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  26588. ++binding.referenceCount;
  26589. this._addInactiveBinding(binding, rootUuid, trackName);
  26590. bindings[i] = binding;
  26591. }
  26592. interpolants[i].resultBuffer = binding.buffer;
  26593. }
  26594. }
  26595. _activateAction(action) {
  26596. if (!this._isActiveAction(action)) {
  26597. if (action._cacheIndex === null) {
  26598. // this action has been forgotten by the cache, but the user
  26599. // appears to be still using it -> rebind
  26600. const rootUuid = (action._localRoot || this._root).uuid,
  26601. clipUuid = action._clip.uuid,
  26602. actionsForClip = this._actionsByClip[clipUuid];
  26603. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  26604. this._addInactiveAction(action, clipUuid, rootUuid);
  26605. }
  26606. const bindings = action._propertyBindings; // increment reference counts / sort out state
  26607. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26608. const binding = bindings[i];
  26609. if (binding.useCount++ === 0) {
  26610. this._lendBinding(binding);
  26611. binding.saveOriginalState();
  26612. }
  26613. }
  26614. this._lendAction(action);
  26615. }
  26616. }
  26617. _deactivateAction(action) {
  26618. if (this._isActiveAction(action)) {
  26619. const bindings = action._propertyBindings; // decrement reference counts / sort out state
  26620. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26621. const binding = bindings[i];
  26622. if (--binding.useCount === 0) {
  26623. binding.restoreOriginalState();
  26624. this._takeBackBinding(binding);
  26625. }
  26626. }
  26627. this._takeBackAction(action);
  26628. }
  26629. } // Memory manager
  26630. _initMemoryManager() {
  26631. this._actions = []; // 'nActiveActions' followed by inactive ones
  26632. this._nActiveActions = 0;
  26633. this._actionsByClip = {}; // inside:
  26634. // {
  26635. // knownActions: Array< AnimationAction > - used as prototypes
  26636. // actionByRoot: AnimationAction - lookup
  26637. // }
  26638. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  26639. this._nActiveBindings = 0;
  26640. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  26641. this._controlInterpolants = []; // same game as above
  26642. this._nActiveControlInterpolants = 0;
  26643. const scope = this;
  26644. this.stats = {
  26645. actions: {
  26646. get total() {
  26647. return scope._actions.length;
  26648. },
  26649. get inUse() {
  26650. return scope._nActiveActions;
  26651. }
  26652. },
  26653. bindings: {
  26654. get total() {
  26655. return scope._bindings.length;
  26656. },
  26657. get inUse() {
  26658. return scope._nActiveBindings;
  26659. }
  26660. },
  26661. controlInterpolants: {
  26662. get total() {
  26663. return scope._controlInterpolants.length;
  26664. },
  26665. get inUse() {
  26666. return scope._nActiveControlInterpolants;
  26667. }
  26668. }
  26669. };
  26670. } // Memory management for AnimationAction objects
  26671. _isActiveAction(action) {
  26672. const index = action._cacheIndex;
  26673. return index !== null && index < this._nActiveActions;
  26674. }
  26675. _addInactiveAction(action, clipUuid, rootUuid) {
  26676. const actions = this._actions,
  26677. actionsByClip = this._actionsByClip;
  26678. let actionsForClip = actionsByClip[clipUuid];
  26679. if (actionsForClip === undefined) {
  26680. actionsForClip = {
  26681. knownActions: [action],
  26682. actionByRoot: {}
  26683. };
  26684. action._byClipCacheIndex = 0;
  26685. actionsByClip[clipUuid] = actionsForClip;
  26686. } else {
  26687. const knownActions = actionsForClip.knownActions;
  26688. action._byClipCacheIndex = knownActions.length;
  26689. knownActions.push(action);
  26690. }
  26691. action._cacheIndex = actions.length;
  26692. actions.push(action);
  26693. actionsForClip.actionByRoot[rootUuid] = action;
  26694. }
  26695. _removeInactiveAction(action) {
  26696. const actions = this._actions,
  26697. lastInactiveAction = actions[actions.length - 1],
  26698. cacheIndex = action._cacheIndex;
  26699. lastInactiveAction._cacheIndex = cacheIndex;
  26700. actions[cacheIndex] = lastInactiveAction;
  26701. actions.pop();
  26702. action._cacheIndex = null;
  26703. const clipUuid = action._clip.uuid,
  26704. actionsByClip = this._actionsByClip,
  26705. actionsForClip = actionsByClip[clipUuid],
  26706. knownActionsForClip = actionsForClip.knownActions,
  26707. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  26708. byClipCacheIndex = action._byClipCacheIndex;
  26709. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  26710. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  26711. knownActionsForClip.pop();
  26712. action._byClipCacheIndex = null;
  26713. const actionByRoot = actionsForClip.actionByRoot,
  26714. rootUuid = (action._localRoot || this._root).uuid;
  26715. delete actionByRoot[rootUuid];
  26716. if (knownActionsForClip.length === 0) {
  26717. delete actionsByClip[clipUuid];
  26718. }
  26719. this._removeInactiveBindingsForAction(action);
  26720. }
  26721. _removeInactiveBindingsForAction(action) {
  26722. const bindings = action._propertyBindings;
  26723. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26724. const binding = bindings[i];
  26725. if (--binding.referenceCount === 0) {
  26726. this._removeInactiveBinding(binding);
  26727. }
  26728. }
  26729. }
  26730. _lendAction(action) {
  26731. // [ active actions | inactive actions ]
  26732. // [ active actions >| inactive actions ]
  26733. // s a
  26734. // <-swap->
  26735. // a s
  26736. const actions = this._actions,
  26737. prevIndex = action._cacheIndex,
  26738. lastActiveIndex = this._nActiveActions++,
  26739. firstInactiveAction = actions[lastActiveIndex];
  26740. action._cacheIndex = lastActiveIndex;
  26741. actions[lastActiveIndex] = action;
  26742. firstInactiveAction._cacheIndex = prevIndex;
  26743. actions[prevIndex] = firstInactiveAction;
  26744. }
  26745. _takeBackAction(action) {
  26746. // [ active actions | inactive actions ]
  26747. // [ active actions |< inactive actions ]
  26748. // a s
  26749. // <-swap->
  26750. // s a
  26751. const actions = this._actions,
  26752. prevIndex = action._cacheIndex,
  26753. firstInactiveIndex = --this._nActiveActions,
  26754. lastActiveAction = actions[firstInactiveIndex];
  26755. action._cacheIndex = firstInactiveIndex;
  26756. actions[firstInactiveIndex] = action;
  26757. lastActiveAction._cacheIndex = prevIndex;
  26758. actions[prevIndex] = lastActiveAction;
  26759. } // Memory management for PropertyMixer objects
  26760. _addInactiveBinding(binding, rootUuid, trackName) {
  26761. const bindingsByRoot = this._bindingsByRootAndName,
  26762. bindings = this._bindings;
  26763. let bindingByName = bindingsByRoot[rootUuid];
  26764. if (bindingByName === undefined) {
  26765. bindingByName = {};
  26766. bindingsByRoot[rootUuid] = bindingByName;
  26767. }
  26768. bindingByName[trackName] = binding;
  26769. binding._cacheIndex = bindings.length;
  26770. bindings.push(binding);
  26771. }
  26772. _removeInactiveBinding(binding) {
  26773. const bindings = this._bindings,
  26774. propBinding = binding.binding,
  26775. rootUuid = propBinding.rootNode.uuid,
  26776. trackName = propBinding.path,
  26777. bindingsByRoot = this._bindingsByRootAndName,
  26778. bindingByName = bindingsByRoot[rootUuid],
  26779. lastInactiveBinding = bindings[bindings.length - 1],
  26780. cacheIndex = binding._cacheIndex;
  26781. lastInactiveBinding._cacheIndex = cacheIndex;
  26782. bindings[cacheIndex] = lastInactiveBinding;
  26783. bindings.pop();
  26784. delete bindingByName[trackName];
  26785. if (Object.keys(bindingByName).length === 0) {
  26786. delete bindingsByRoot[rootUuid];
  26787. }
  26788. }
  26789. _lendBinding(binding) {
  26790. const bindings = this._bindings,
  26791. prevIndex = binding._cacheIndex,
  26792. lastActiveIndex = this._nActiveBindings++,
  26793. firstInactiveBinding = bindings[lastActiveIndex];
  26794. binding._cacheIndex = lastActiveIndex;
  26795. bindings[lastActiveIndex] = binding;
  26796. firstInactiveBinding._cacheIndex = prevIndex;
  26797. bindings[prevIndex] = firstInactiveBinding;
  26798. }
  26799. _takeBackBinding(binding) {
  26800. const bindings = this._bindings,
  26801. prevIndex = binding._cacheIndex,
  26802. firstInactiveIndex = --this._nActiveBindings,
  26803. lastActiveBinding = bindings[firstInactiveIndex];
  26804. binding._cacheIndex = firstInactiveIndex;
  26805. bindings[firstInactiveIndex] = binding;
  26806. lastActiveBinding._cacheIndex = prevIndex;
  26807. bindings[prevIndex] = lastActiveBinding;
  26808. } // Memory management of Interpolants for weight and time scale
  26809. _lendControlInterpolant() {
  26810. const interpolants = this._controlInterpolants,
  26811. lastActiveIndex = this._nActiveControlInterpolants++;
  26812. let interpolant = interpolants[lastActiveIndex];
  26813. if (interpolant === undefined) {
  26814. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  26815. interpolant.__cacheIndex = lastActiveIndex;
  26816. interpolants[lastActiveIndex] = interpolant;
  26817. }
  26818. return interpolant;
  26819. }
  26820. _takeBackControlInterpolant(interpolant) {
  26821. const interpolants = this._controlInterpolants,
  26822. prevIndex = interpolant.__cacheIndex,
  26823. firstInactiveIndex = --this._nActiveControlInterpolants,
  26824. lastActiveInterpolant = interpolants[firstInactiveIndex];
  26825. interpolant.__cacheIndex = firstInactiveIndex;
  26826. interpolants[firstInactiveIndex] = interpolant;
  26827. lastActiveInterpolant.__cacheIndex = prevIndex;
  26828. interpolants[prevIndex] = lastActiveInterpolant;
  26829. } // return an action for a clip optionally using a custom root target
  26830. // object (this method allocates a lot of dynamic memory in case a
  26831. // previously unknown clip/root combination is specified)
  26832. clipAction(clip, optionalRoot, blendMode) {
  26833. const root = optionalRoot || this._root,
  26834. rootUuid = root.uuid;
  26835. let clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
  26836. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  26837. const actionsForClip = this._actionsByClip[clipUuid];
  26838. let prototypeAction = null;
  26839. if (blendMode === undefined) {
  26840. if (clipObject !== null) {
  26841. blendMode = clipObject.blendMode;
  26842. } else {
  26843. blendMode = NormalAnimationBlendMode;
  26844. }
  26845. }
  26846. if (actionsForClip !== undefined) {
  26847. const existingAction = actionsForClip.actionByRoot[rootUuid];
  26848. if (existingAction !== undefined && existingAction.blendMode === blendMode) {
  26849. return existingAction;
  26850. } // we know the clip, so we don't have to parse all
  26851. // the bindings again but can just copy
  26852. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  26853. if (clipObject === null) clipObject = prototypeAction._clip;
  26854. } // clip must be known when specified via string
  26855. if (clipObject === null) return null; // allocate all resources required to run it
  26856. const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
  26857. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  26858. this._addInactiveAction(newAction, clipUuid, rootUuid);
  26859. return newAction;
  26860. } // get an existing action
  26861. existingAction(clip, optionalRoot) {
  26862. const root = optionalRoot || this._root,
  26863. rootUuid = root.uuid,
  26864. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  26865. clipUuid = clipObject ? clipObject.uuid : clip,
  26866. actionsForClip = this._actionsByClip[clipUuid];
  26867. if (actionsForClip !== undefined) {
  26868. return actionsForClip.actionByRoot[rootUuid] || null;
  26869. }
  26870. return null;
  26871. } // deactivates all previously scheduled actions
  26872. stopAllAction() {
  26873. const actions = this._actions,
  26874. nActions = this._nActiveActions;
  26875. for (let i = nActions - 1; i >= 0; --i) {
  26876. actions[i].stop();
  26877. }
  26878. return this;
  26879. } // advance the time and update apply the animation
  26880. update(deltaTime) {
  26881. deltaTime *= this.timeScale;
  26882. const actions = this._actions,
  26883. nActions = this._nActiveActions,
  26884. time = this.time += deltaTime,
  26885. timeDirection = Math.sign(deltaTime),
  26886. accuIndex = this._accuIndex ^= 1; // run active actions
  26887. for (let i = 0; i !== nActions; ++i) {
  26888. const action = actions[i];
  26889. action._update(time, deltaTime, timeDirection, accuIndex);
  26890. } // update scene graph
  26891. const bindings = this._bindings,
  26892. nBindings = this._nActiveBindings;
  26893. for (let i = 0; i !== nBindings; ++i) {
  26894. bindings[i].apply(accuIndex);
  26895. }
  26896. return this;
  26897. } // Allows you to seek to a specific time in an animation.
  26898. setTime(timeInSeconds) {
  26899. this.time = 0; // Zero out time attribute for AnimationMixer object;
  26900. for (let i = 0; i < this._actions.length; i++) {
  26901. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  26902. }
  26903. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  26904. } // return this mixer's root target object
  26905. getRoot() {
  26906. return this._root;
  26907. } // free all resources specific to a particular clip
  26908. uncacheClip(clip) {
  26909. const actions = this._actions,
  26910. clipUuid = clip.uuid,
  26911. actionsByClip = this._actionsByClip,
  26912. actionsForClip = actionsByClip[clipUuid];
  26913. if (actionsForClip !== undefined) {
  26914. // note: just calling _removeInactiveAction would mess up the
  26915. // iteration state and also require updating the state we can
  26916. // just throw away
  26917. const actionsToRemove = actionsForClip.knownActions;
  26918. for (let i = 0, n = actionsToRemove.length; i !== n; ++i) {
  26919. const action = actionsToRemove[i];
  26920. this._deactivateAction(action);
  26921. const cacheIndex = action._cacheIndex,
  26922. lastInactiveAction = actions[actions.length - 1];
  26923. action._cacheIndex = null;
  26924. action._byClipCacheIndex = null;
  26925. lastInactiveAction._cacheIndex = cacheIndex;
  26926. actions[cacheIndex] = lastInactiveAction;
  26927. actions.pop();
  26928. this._removeInactiveBindingsForAction(action);
  26929. }
  26930. delete actionsByClip[clipUuid];
  26931. }
  26932. } // free all resources specific to a particular root target object
  26933. uncacheRoot(root) {
  26934. const rootUuid = root.uuid,
  26935. actionsByClip = this._actionsByClip;
  26936. for (const clipUuid in actionsByClip) {
  26937. const actionByRoot = actionsByClip[clipUuid].actionByRoot,
  26938. action = actionByRoot[rootUuid];
  26939. if (action !== undefined) {
  26940. this._deactivateAction(action);
  26941. this._removeInactiveAction(action);
  26942. }
  26943. }
  26944. const bindingsByRoot = this._bindingsByRootAndName,
  26945. bindingByName = bindingsByRoot[rootUuid];
  26946. if (bindingByName !== undefined) {
  26947. for (const trackName in bindingByName) {
  26948. const binding = bindingByName[trackName];
  26949. binding.restoreOriginalState();
  26950. this._removeInactiveBinding(binding);
  26951. }
  26952. }
  26953. } // remove a targeted clip from the cache
  26954. uncacheAction(clip, optionalRoot) {
  26955. const action = this.existingAction(clip, optionalRoot);
  26956. if (action !== null) {
  26957. this._deactivateAction(action);
  26958. this._removeInactiveAction(action);
  26959. }
  26960. }
  26961. }
  26962. AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array(1);
  26963. class Uniform {
  26964. constructor(value) {
  26965. if (typeof value === 'string') {
  26966. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  26967. value = arguments[1];
  26968. }
  26969. this.value = value;
  26970. }
  26971. clone() {
  26972. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  26973. }
  26974. }
  26975. class InstancedInterleavedBuffer extends InterleavedBuffer {
  26976. constructor(array, stride, meshPerAttribute = 1) {
  26977. super(array, stride);
  26978. this.meshPerAttribute = meshPerAttribute;
  26979. }
  26980. copy(source) {
  26981. super.copy(source);
  26982. this.meshPerAttribute = source.meshPerAttribute;
  26983. return this;
  26984. }
  26985. clone(data) {
  26986. const ib = super.clone(data);
  26987. ib.meshPerAttribute = this.meshPerAttribute;
  26988. return ib;
  26989. }
  26990. toJSON(data) {
  26991. const json = super.toJSON(data);
  26992. json.isInstancedInterleavedBuffer = true;
  26993. json.meshPerAttribute = this.meshPerAttribute;
  26994. return json;
  26995. }
  26996. }
  26997. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  26998. class GLBufferAttribute {
  26999. constructor(buffer, type, itemSize, elementSize, count) {
  27000. this.buffer = buffer;
  27001. this.type = type;
  27002. this.itemSize = itemSize;
  27003. this.elementSize = elementSize;
  27004. this.count = count;
  27005. this.version = 0;
  27006. }
  27007. set needsUpdate(value) {
  27008. if (value === true) this.version++;
  27009. }
  27010. setBuffer(buffer) {
  27011. this.buffer = buffer;
  27012. return this;
  27013. }
  27014. setType(type, elementSize) {
  27015. this.type = type;
  27016. this.elementSize = elementSize;
  27017. return this;
  27018. }
  27019. setItemSize(itemSize) {
  27020. this.itemSize = itemSize;
  27021. return this;
  27022. }
  27023. setCount(count) {
  27024. this.count = count;
  27025. return this;
  27026. }
  27027. }
  27028. GLBufferAttribute.prototype.isGLBufferAttribute = true;
  27029. class Raycaster {
  27030. constructor(origin, direction, near = 0, far = Infinity) {
  27031. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  27032. this.near = near;
  27033. this.far = far;
  27034. this.camera = null;
  27035. this.layers = new Layers();
  27036. this.params = {
  27037. Mesh: {},
  27038. Line: {
  27039. threshold: 1
  27040. },
  27041. LOD: {},
  27042. Points: {
  27043. threshold: 1
  27044. },
  27045. Sprite: {}
  27046. };
  27047. }
  27048. set(origin, direction) {
  27049. // direction is assumed to be normalized (for accurate distance calculations)
  27050. this.ray.set(origin, direction);
  27051. }
  27052. setFromCamera(coords, camera) {
  27053. if (camera && camera.isPerspectiveCamera) {
  27054. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  27055. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  27056. this.camera = camera;
  27057. } else if (camera && camera.isOrthographicCamera) {
  27058. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  27059. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  27060. this.camera = camera;
  27061. } else {
  27062. console.error('THREE.Raycaster: Unsupported camera type: ' + camera.type);
  27063. }
  27064. }
  27065. intersectObject(object, recursive = true, intersects = []) {
  27066. intersectObject(object, this, intersects, recursive);
  27067. intersects.sort(ascSort);
  27068. return intersects;
  27069. }
  27070. intersectObjects(objects, recursive = true, intersects = []) {
  27071. for (let i = 0, l = objects.length; i < l; i++) {
  27072. intersectObject(objects[i], this, intersects, recursive);
  27073. }
  27074. intersects.sort(ascSort);
  27075. return intersects;
  27076. }
  27077. }
  27078. function ascSort(a, b) {
  27079. return a.distance - b.distance;
  27080. }
  27081. function intersectObject(object, raycaster, intersects, recursive) {
  27082. if (object.layers.test(raycaster.layers)) {
  27083. object.raycast(raycaster, intersects);
  27084. }
  27085. if (recursive === true) {
  27086. const children = object.children;
  27087. for (let i = 0, l = children.length; i < l; i++) {
  27088. intersectObject(children[i], raycaster, intersects, true);
  27089. }
  27090. }
  27091. }
  27092. /**
  27093. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27094. *
  27095. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  27096. * The azimuthal angle (theta) is measured from the positive z-axis.
  27097. */
  27098. class Spherical {
  27099. constructor(radius = 1, phi = 0, theta = 0) {
  27100. this.radius = radius;
  27101. this.phi = phi; // polar angle
  27102. this.theta = theta; // azimuthal angle
  27103. return this;
  27104. }
  27105. set(radius, phi, theta) {
  27106. this.radius = radius;
  27107. this.phi = phi;
  27108. this.theta = theta;
  27109. return this;
  27110. }
  27111. copy(other) {
  27112. this.radius = other.radius;
  27113. this.phi = other.phi;
  27114. this.theta = other.theta;
  27115. return this;
  27116. } // restrict phi to be betwee EPS and PI-EPS
  27117. makeSafe() {
  27118. const EPS = 0.000001;
  27119. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  27120. return this;
  27121. }
  27122. setFromVector3(v) {
  27123. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27124. }
  27125. setFromCartesianCoords(x, y, z) {
  27126. this.radius = Math.sqrt(x * x + y * y + z * z);
  27127. if (this.radius === 0) {
  27128. this.theta = 0;
  27129. this.phi = 0;
  27130. } else {
  27131. this.theta = Math.atan2(x, z);
  27132. this.phi = Math.acos(clamp(y / this.radius, -1, 1));
  27133. }
  27134. return this;
  27135. }
  27136. clone() {
  27137. return new this.constructor().copy(this);
  27138. }
  27139. }
  27140. /**
  27141. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27142. */
  27143. class Cylindrical {
  27144. constructor(radius = 1, theta = 0, y = 0) {
  27145. this.radius = radius; // distance from the origin to a point in the x-z plane
  27146. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27147. this.y = y; // height above the x-z plane
  27148. return this;
  27149. }
  27150. set(radius, theta, y) {
  27151. this.radius = radius;
  27152. this.theta = theta;
  27153. this.y = y;
  27154. return this;
  27155. }
  27156. copy(other) {
  27157. this.radius = other.radius;
  27158. this.theta = other.theta;
  27159. this.y = other.y;
  27160. return this;
  27161. }
  27162. setFromVector3(v) {
  27163. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27164. }
  27165. setFromCartesianCoords(x, y, z) {
  27166. this.radius = Math.sqrt(x * x + z * z);
  27167. this.theta = Math.atan2(x, z);
  27168. this.y = y;
  27169. return this;
  27170. }
  27171. clone() {
  27172. return new this.constructor().copy(this);
  27173. }
  27174. }
  27175. const _vector$4 = /*@__PURE__*/new Vector2();
  27176. class Box2 {
  27177. constructor(min = new Vector2(+Infinity, +Infinity), max = new Vector2(-Infinity, -Infinity)) {
  27178. this.min = min;
  27179. this.max = max;
  27180. }
  27181. set(min, max) {
  27182. this.min.copy(min);
  27183. this.max.copy(max);
  27184. return this;
  27185. }
  27186. setFromPoints(points) {
  27187. this.makeEmpty();
  27188. for (let i = 0, il = points.length; i < il; i++) {
  27189. this.expandByPoint(points[i]);
  27190. }
  27191. return this;
  27192. }
  27193. setFromCenterAndSize(center, size) {
  27194. const halfSize = _vector$4.copy(size).multiplyScalar(0.5);
  27195. this.min.copy(center).sub(halfSize);
  27196. this.max.copy(center).add(halfSize);
  27197. return this;
  27198. }
  27199. clone() {
  27200. return new this.constructor().copy(this);
  27201. }
  27202. copy(box) {
  27203. this.min.copy(box.min);
  27204. this.max.copy(box.max);
  27205. return this;
  27206. }
  27207. makeEmpty() {
  27208. this.min.x = this.min.y = +Infinity;
  27209. this.max.x = this.max.y = -Infinity;
  27210. return this;
  27211. }
  27212. isEmpty() {
  27213. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27214. return this.max.x < this.min.x || this.max.y < this.min.y;
  27215. }
  27216. getCenter(target) {
  27217. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  27218. }
  27219. getSize(target) {
  27220. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  27221. }
  27222. expandByPoint(point) {
  27223. this.min.min(point);
  27224. this.max.max(point);
  27225. return this;
  27226. }
  27227. expandByVector(vector) {
  27228. this.min.sub(vector);
  27229. this.max.add(vector);
  27230. return this;
  27231. }
  27232. expandByScalar(scalar) {
  27233. this.min.addScalar(-scalar);
  27234. this.max.addScalar(scalar);
  27235. return this;
  27236. }
  27237. containsPoint(point) {
  27238. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  27239. }
  27240. containsBox(box) {
  27241. return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y;
  27242. }
  27243. getParameter(point, target) {
  27244. // This can potentially have a divide by zero if the box
  27245. // has a size dimension of 0.
  27246. return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y));
  27247. }
  27248. intersectsBox(box) {
  27249. // using 4 splitting planes to rule out intersections
  27250. return box.max.x < this.min.x || box.min.x > this.max.x || box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  27251. }
  27252. clampPoint(point, target) {
  27253. return target.copy(point).clamp(this.min, this.max);
  27254. }
  27255. distanceToPoint(point) {
  27256. const clampedPoint = _vector$4.copy(point).clamp(this.min, this.max);
  27257. return clampedPoint.sub(point).length();
  27258. }
  27259. intersect(box) {
  27260. this.min.max(box.min);
  27261. this.max.min(box.max);
  27262. return this;
  27263. }
  27264. union(box) {
  27265. this.min.min(box.min);
  27266. this.max.max(box.max);
  27267. return this;
  27268. }
  27269. translate(offset) {
  27270. this.min.add(offset);
  27271. this.max.add(offset);
  27272. return this;
  27273. }
  27274. equals(box) {
  27275. return box.min.equals(this.min) && box.max.equals(this.max);
  27276. }
  27277. }
  27278. Box2.prototype.isBox2 = true;
  27279. const _startP = /*@__PURE__*/new Vector3();
  27280. const _startEnd = /*@__PURE__*/new Vector3();
  27281. class Line3 {
  27282. constructor(start = new Vector3(), end = new Vector3()) {
  27283. this.start = start;
  27284. this.end = end;
  27285. }
  27286. set(start, end) {
  27287. this.start.copy(start);
  27288. this.end.copy(end);
  27289. return this;
  27290. }
  27291. copy(line) {
  27292. this.start.copy(line.start);
  27293. this.end.copy(line.end);
  27294. return this;
  27295. }
  27296. getCenter(target) {
  27297. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  27298. }
  27299. delta(target) {
  27300. return target.subVectors(this.end, this.start);
  27301. }
  27302. distanceSq() {
  27303. return this.start.distanceToSquared(this.end);
  27304. }
  27305. distance() {
  27306. return this.start.distanceTo(this.end);
  27307. }
  27308. at(t, target) {
  27309. return this.delta(target).multiplyScalar(t).add(this.start);
  27310. }
  27311. closestPointToPointParameter(point, clampToLine) {
  27312. _startP.subVectors(point, this.start);
  27313. _startEnd.subVectors(this.end, this.start);
  27314. const startEnd2 = _startEnd.dot(_startEnd);
  27315. const startEnd_startP = _startEnd.dot(_startP);
  27316. let t = startEnd_startP / startEnd2;
  27317. if (clampToLine) {
  27318. t = clamp(t, 0, 1);
  27319. }
  27320. return t;
  27321. }
  27322. closestPointToPoint(point, clampToLine, target) {
  27323. const t = this.closestPointToPointParameter(point, clampToLine);
  27324. return this.delta(target).multiplyScalar(t).add(this.start);
  27325. }
  27326. applyMatrix4(matrix) {
  27327. this.start.applyMatrix4(matrix);
  27328. this.end.applyMatrix4(matrix);
  27329. return this;
  27330. }
  27331. equals(line) {
  27332. return line.start.equals(this.start) && line.end.equals(this.end);
  27333. }
  27334. clone() {
  27335. return new this.constructor().copy(this);
  27336. }
  27337. }
  27338. const _vector$3 = /*@__PURE__*/new Vector3();
  27339. class SpotLightHelper extends Object3D {
  27340. constructor(light, color) {
  27341. super();
  27342. this.light = light;
  27343. this.light.updateMatrixWorld();
  27344. this.matrix = light.matrixWorld;
  27345. this.matrixAutoUpdate = false;
  27346. this.color = color;
  27347. const geometry = new BufferGeometry();
  27348. const positions = [0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, -1, 1];
  27349. for (let i = 0, j = 1, l = 32; i < l; i++, j++) {
  27350. const p1 = i / l * Math.PI * 2;
  27351. const p2 = j / l * Math.PI * 2;
  27352. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  27353. }
  27354. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27355. const material = new LineBasicMaterial({
  27356. fog: false,
  27357. toneMapped: false
  27358. });
  27359. this.cone = new LineSegments(geometry, material);
  27360. this.add(this.cone);
  27361. this.update();
  27362. }
  27363. dispose() {
  27364. this.cone.geometry.dispose();
  27365. this.cone.material.dispose();
  27366. }
  27367. update() {
  27368. this.light.updateMatrixWorld();
  27369. const coneLength = this.light.distance ? this.light.distance : 1000;
  27370. const coneWidth = coneLength * Math.tan(this.light.angle);
  27371. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  27372. _vector$3.setFromMatrixPosition(this.light.target.matrixWorld);
  27373. this.cone.lookAt(_vector$3);
  27374. if (this.color !== undefined) {
  27375. this.cone.material.color.set(this.color);
  27376. } else {
  27377. this.cone.material.color.copy(this.light.color);
  27378. }
  27379. }
  27380. }
  27381. const _vector$2 = /*@__PURE__*/new Vector3();
  27382. const _boneMatrix = /*@__PURE__*/new Matrix4();
  27383. const _matrixWorldInv = /*@__PURE__*/new Matrix4();
  27384. class SkeletonHelper extends LineSegments {
  27385. constructor(object) {
  27386. const bones = getBoneList(object);
  27387. const geometry = new BufferGeometry();
  27388. const vertices = [];
  27389. const colors = [];
  27390. const color1 = new Color(0, 0, 1);
  27391. const color2 = new Color(0, 1, 0);
  27392. for (let i = 0; i < bones.length; i++) {
  27393. const bone = bones[i];
  27394. if (bone.parent && bone.parent.isBone) {
  27395. vertices.push(0, 0, 0);
  27396. vertices.push(0, 0, 0);
  27397. colors.push(color1.r, color1.g, color1.b);
  27398. colors.push(color2.r, color2.g, color2.b);
  27399. }
  27400. }
  27401. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27402. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27403. const material = new LineBasicMaterial({
  27404. vertexColors: true,
  27405. depthTest: false,
  27406. depthWrite: false,
  27407. toneMapped: false,
  27408. transparent: true
  27409. });
  27410. super(geometry, material);
  27411. this.type = 'SkeletonHelper';
  27412. this.isSkeletonHelper = true;
  27413. this.root = object;
  27414. this.bones = bones;
  27415. this.matrix = object.matrixWorld;
  27416. this.matrixAutoUpdate = false;
  27417. }
  27418. updateMatrixWorld(force) {
  27419. const bones = this.bones;
  27420. const geometry = this.geometry;
  27421. const position = geometry.getAttribute('position');
  27422. _matrixWorldInv.copy(this.root.matrixWorld).invert();
  27423. for (let i = 0, j = 0; i < bones.length; i++) {
  27424. const bone = bones[i];
  27425. if (bone.parent && bone.parent.isBone) {
  27426. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  27427. _vector$2.setFromMatrixPosition(_boneMatrix);
  27428. position.setXYZ(j, _vector$2.x, _vector$2.y, _vector$2.z);
  27429. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  27430. _vector$2.setFromMatrixPosition(_boneMatrix);
  27431. position.setXYZ(j + 1, _vector$2.x, _vector$2.y, _vector$2.z);
  27432. j += 2;
  27433. }
  27434. }
  27435. geometry.getAttribute('position').needsUpdate = true;
  27436. super.updateMatrixWorld(force);
  27437. }
  27438. }
  27439. function getBoneList(object) {
  27440. const boneList = [];
  27441. if (object && object.isBone) {
  27442. boneList.push(object);
  27443. }
  27444. for (let i = 0; i < object.children.length; i++) {
  27445. boneList.push.apply(boneList, getBoneList(object.children[i]));
  27446. }
  27447. return boneList;
  27448. }
  27449. class PointLightHelper extends Mesh {
  27450. constructor(light, sphereSize, color) {
  27451. const geometry = new SphereGeometry(sphereSize, 4, 2);
  27452. const material = new MeshBasicMaterial({
  27453. wireframe: true,
  27454. fog: false,
  27455. toneMapped: false
  27456. });
  27457. super(geometry, material);
  27458. this.light = light;
  27459. this.light.updateMatrixWorld();
  27460. this.color = color;
  27461. this.type = 'PointLightHelper';
  27462. this.matrix = this.light.matrixWorld;
  27463. this.matrixAutoUpdate = false;
  27464. this.update();
  27465. /*
  27466. // TODO: delete this comment?
  27467. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  27468. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  27469. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  27470. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  27471. const d = light.distance;
  27472. if ( d === 0.0 ) {
  27473. this.lightDistance.visible = false;
  27474. } else {
  27475. this.lightDistance.scale.set( d, d, d );
  27476. }
  27477. this.add( this.lightDistance );
  27478. */
  27479. }
  27480. dispose() {
  27481. this.geometry.dispose();
  27482. this.material.dispose();
  27483. }
  27484. update() {
  27485. if (this.color !== undefined) {
  27486. this.material.color.set(this.color);
  27487. } else {
  27488. this.material.color.copy(this.light.color);
  27489. }
  27490. /*
  27491. const d = this.light.distance;
  27492. if ( d === 0.0 ) {
  27493. this.lightDistance.visible = false;
  27494. } else {
  27495. this.lightDistance.visible = true;
  27496. this.lightDistance.scale.set( d, d, d );
  27497. }
  27498. */
  27499. }
  27500. }
  27501. const _vector$1 = /*@__PURE__*/new Vector3();
  27502. const _color1 = /*@__PURE__*/new Color();
  27503. const _color2 = /*@__PURE__*/new Color();
  27504. class HemisphereLightHelper extends Object3D {
  27505. constructor(light, size, color) {
  27506. super();
  27507. this.light = light;
  27508. this.light.updateMatrixWorld();
  27509. this.matrix = light.matrixWorld;
  27510. this.matrixAutoUpdate = false;
  27511. this.color = color;
  27512. const geometry = new OctahedronGeometry(size);
  27513. geometry.rotateY(Math.PI * 0.5);
  27514. this.material = new MeshBasicMaterial({
  27515. wireframe: true,
  27516. fog: false,
  27517. toneMapped: false
  27518. });
  27519. if (this.color === undefined) this.material.vertexColors = true;
  27520. const position = geometry.getAttribute('position');
  27521. const colors = new Float32Array(position.count * 3);
  27522. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  27523. this.add(new Mesh(geometry, this.material));
  27524. this.update();
  27525. }
  27526. dispose() {
  27527. this.children[0].geometry.dispose();
  27528. this.children[0].material.dispose();
  27529. }
  27530. update() {
  27531. const mesh = this.children[0];
  27532. if (this.color !== undefined) {
  27533. this.material.color.set(this.color);
  27534. } else {
  27535. const colors = mesh.geometry.getAttribute('color');
  27536. _color1.copy(this.light.color);
  27537. _color2.copy(this.light.groundColor);
  27538. for (let i = 0, l = colors.count; i < l; i++) {
  27539. const color = i < l / 2 ? _color1 : _color2;
  27540. colors.setXYZ(i, color.r, color.g, color.b);
  27541. }
  27542. colors.needsUpdate = true;
  27543. }
  27544. mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate());
  27545. }
  27546. }
  27547. class GridHelper extends LineSegments {
  27548. constructor(size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888) {
  27549. color1 = new Color(color1);
  27550. color2 = new Color(color2);
  27551. const center = divisions / 2;
  27552. const step = size / divisions;
  27553. const halfSize = size / 2;
  27554. const vertices = [],
  27555. colors = [];
  27556. for (let i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  27557. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  27558. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  27559. const color = i === center ? color1 : color2;
  27560. color.toArray(colors, j);
  27561. j += 3;
  27562. color.toArray(colors, j);
  27563. j += 3;
  27564. color.toArray(colors, j);
  27565. j += 3;
  27566. color.toArray(colors, j);
  27567. j += 3;
  27568. }
  27569. const geometry = new BufferGeometry();
  27570. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27571. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27572. const material = new LineBasicMaterial({
  27573. vertexColors: true,
  27574. toneMapped: false
  27575. });
  27576. super(geometry, material);
  27577. this.type = 'GridHelper';
  27578. }
  27579. }
  27580. class PolarGridHelper extends LineSegments {
  27581. constructor(radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888) {
  27582. color1 = new Color(color1);
  27583. color2 = new Color(color2);
  27584. const vertices = [];
  27585. const colors = []; // create the radials
  27586. for (let i = 0; i <= radials; i++) {
  27587. const v = i / radials * (Math.PI * 2);
  27588. const x = Math.sin(v) * radius;
  27589. const z = Math.cos(v) * radius;
  27590. vertices.push(0, 0, 0);
  27591. vertices.push(x, 0, z);
  27592. const color = i & 1 ? color1 : color2;
  27593. colors.push(color.r, color.g, color.b);
  27594. colors.push(color.r, color.g, color.b);
  27595. } // create the circles
  27596. for (let i = 0; i <= circles; i++) {
  27597. const color = i & 1 ? color1 : color2;
  27598. const r = radius - radius / circles * i;
  27599. for (let j = 0; j < divisions; j++) {
  27600. // first vertex
  27601. let v = j / divisions * (Math.PI * 2);
  27602. let x = Math.sin(v) * r;
  27603. let z = Math.cos(v) * r;
  27604. vertices.push(x, 0, z);
  27605. colors.push(color.r, color.g, color.b); // second vertex
  27606. v = (j + 1) / divisions * (Math.PI * 2);
  27607. x = Math.sin(v) * r;
  27608. z = Math.cos(v) * r;
  27609. vertices.push(x, 0, z);
  27610. colors.push(color.r, color.g, color.b);
  27611. }
  27612. }
  27613. const geometry = new BufferGeometry();
  27614. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27615. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27616. const material = new LineBasicMaterial({
  27617. vertexColors: true,
  27618. toneMapped: false
  27619. });
  27620. super(geometry, material);
  27621. this.type = 'PolarGridHelper';
  27622. }
  27623. }
  27624. const _v1 = /*@__PURE__*/new Vector3();
  27625. const _v2 = /*@__PURE__*/new Vector3();
  27626. const _v3 = /*@__PURE__*/new Vector3();
  27627. class DirectionalLightHelper extends Object3D {
  27628. constructor(light, size, color) {
  27629. super();
  27630. this.light = light;
  27631. this.light.updateMatrixWorld();
  27632. this.matrix = light.matrixWorld;
  27633. this.matrixAutoUpdate = false;
  27634. this.color = color;
  27635. if (size === undefined) size = 1;
  27636. let geometry = new BufferGeometry();
  27637. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  27638. const material = new LineBasicMaterial({
  27639. fog: false,
  27640. toneMapped: false
  27641. });
  27642. this.lightPlane = new Line(geometry, material);
  27643. this.add(this.lightPlane);
  27644. geometry = new BufferGeometry();
  27645. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  27646. this.targetLine = new Line(geometry, material);
  27647. this.add(this.targetLine);
  27648. this.update();
  27649. }
  27650. dispose() {
  27651. this.lightPlane.geometry.dispose();
  27652. this.lightPlane.material.dispose();
  27653. this.targetLine.geometry.dispose();
  27654. this.targetLine.material.dispose();
  27655. }
  27656. update() {
  27657. _v1.setFromMatrixPosition(this.light.matrixWorld);
  27658. _v2.setFromMatrixPosition(this.light.target.matrixWorld);
  27659. _v3.subVectors(_v2, _v1);
  27660. this.lightPlane.lookAt(_v2);
  27661. if (this.color !== undefined) {
  27662. this.lightPlane.material.color.set(this.color);
  27663. this.targetLine.material.color.set(this.color);
  27664. } else {
  27665. this.lightPlane.material.color.copy(this.light.color);
  27666. this.targetLine.material.color.copy(this.light.color);
  27667. }
  27668. this.targetLine.lookAt(_v2);
  27669. this.targetLine.scale.z = _v3.length();
  27670. }
  27671. }
  27672. const _vector = /*@__PURE__*/new Vector3();
  27673. const _camera = /*@__PURE__*/new Camera();
  27674. /**
  27675. * - shows frustum, line of sight and up of the camera
  27676. * - suitable for fast updates
  27677. * - based on frustum visualization in lightgl.js shadowmap example
  27678. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  27679. */
  27680. class CameraHelper extends LineSegments {
  27681. constructor(camera) {
  27682. const geometry = new BufferGeometry();
  27683. const material = new LineBasicMaterial({
  27684. color: 0xffffff,
  27685. vertexColors: true,
  27686. toneMapped: false
  27687. });
  27688. const vertices = [];
  27689. const colors = [];
  27690. const pointMap = {}; // colors
  27691. const colorFrustum = new Color(0xffaa00);
  27692. const colorCone = new Color(0xff0000);
  27693. const colorUp = new Color(0x00aaff);
  27694. const colorTarget = new Color(0xffffff);
  27695. const colorCross = new Color(0x333333); // near
  27696. addLine('n1', 'n2', colorFrustum);
  27697. addLine('n2', 'n4', colorFrustum);
  27698. addLine('n4', 'n3', colorFrustum);
  27699. addLine('n3', 'n1', colorFrustum); // far
  27700. addLine('f1', 'f2', colorFrustum);
  27701. addLine('f2', 'f4', colorFrustum);
  27702. addLine('f4', 'f3', colorFrustum);
  27703. addLine('f3', 'f1', colorFrustum); // sides
  27704. addLine('n1', 'f1', colorFrustum);
  27705. addLine('n2', 'f2', colorFrustum);
  27706. addLine('n3', 'f3', colorFrustum);
  27707. addLine('n4', 'f4', colorFrustum); // cone
  27708. addLine('p', 'n1', colorCone);
  27709. addLine('p', 'n2', colorCone);
  27710. addLine('p', 'n3', colorCone);
  27711. addLine('p', 'n4', colorCone); // up
  27712. addLine('u1', 'u2', colorUp);
  27713. addLine('u2', 'u3', colorUp);
  27714. addLine('u3', 'u1', colorUp); // target
  27715. addLine('c', 't', colorTarget);
  27716. addLine('p', 'c', colorCross); // cross
  27717. addLine('cn1', 'cn2', colorCross);
  27718. addLine('cn3', 'cn4', colorCross);
  27719. addLine('cf1', 'cf2', colorCross);
  27720. addLine('cf3', 'cf4', colorCross);
  27721. function addLine(a, b, color) {
  27722. addPoint(a, color);
  27723. addPoint(b, color);
  27724. }
  27725. function addPoint(id, color) {
  27726. vertices.push(0, 0, 0);
  27727. colors.push(color.r, color.g, color.b);
  27728. if (pointMap[id] === undefined) {
  27729. pointMap[id] = [];
  27730. }
  27731. pointMap[id].push(vertices.length / 3 - 1);
  27732. }
  27733. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27734. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27735. super(geometry, material);
  27736. this.type = 'CameraHelper';
  27737. this.camera = camera;
  27738. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  27739. this.matrix = camera.matrixWorld;
  27740. this.matrixAutoUpdate = false;
  27741. this.pointMap = pointMap;
  27742. this.update();
  27743. }
  27744. update() {
  27745. const geometry = this.geometry;
  27746. const pointMap = this.pointMap;
  27747. const w = 1,
  27748. h = 1; // we need just camera projection matrix inverse
  27749. // world matrix must be identity
  27750. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  27751. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  27752. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  27753. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  27754. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  27755. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  27756. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  27757. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  27758. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  27759. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  27760. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  27761. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  27762. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  27763. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  27764. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  27765. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  27766. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  27767. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  27768. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  27769. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  27770. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  27771. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  27772. geometry.getAttribute('position').needsUpdate = true;
  27773. }
  27774. dispose() {
  27775. this.geometry.dispose();
  27776. this.material.dispose();
  27777. }
  27778. }
  27779. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  27780. _vector.set(x, y, z).unproject(camera);
  27781. const points = pointMap[point];
  27782. if (points !== undefined) {
  27783. const position = geometry.getAttribute('position');
  27784. for (let i = 0, l = points.length; i < l; i++) {
  27785. position.setXYZ(points[i], _vector.x, _vector.y, _vector.z);
  27786. }
  27787. }
  27788. }
  27789. const _box = /*@__PURE__*/new Box3();
  27790. class BoxHelper extends LineSegments {
  27791. constructor(object, color = 0xffff00) {
  27792. 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]);
  27793. const positions = new Float32Array(8 * 3);
  27794. const geometry = new BufferGeometry();
  27795. geometry.setIndex(new BufferAttribute(indices, 1));
  27796. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  27797. super(geometry, new LineBasicMaterial({
  27798. color: color,
  27799. toneMapped: false
  27800. }));
  27801. this.object = object;
  27802. this.type = 'BoxHelper';
  27803. this.matrixAutoUpdate = false;
  27804. this.update();
  27805. }
  27806. update(object) {
  27807. if (object !== undefined) {
  27808. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  27809. }
  27810. if (this.object !== undefined) {
  27811. _box.setFromObject(this.object);
  27812. }
  27813. if (_box.isEmpty()) return;
  27814. const min = _box.min;
  27815. const max = _box.max;
  27816. /*
  27817. 5____4
  27818. 1/___0/|
  27819. | 6__|_7
  27820. 2/___3/
  27821. 0: max.x, max.y, max.z
  27822. 1: min.x, max.y, max.z
  27823. 2: min.x, min.y, max.z
  27824. 3: max.x, min.y, max.z
  27825. 4: max.x, max.y, min.z
  27826. 5: min.x, max.y, min.z
  27827. 6: min.x, min.y, min.z
  27828. 7: max.x, min.y, min.z
  27829. */
  27830. const position = this.geometry.attributes.position;
  27831. const array = position.array;
  27832. array[0] = max.x;
  27833. array[1] = max.y;
  27834. array[2] = max.z;
  27835. array[3] = min.x;
  27836. array[4] = max.y;
  27837. array[5] = max.z;
  27838. array[6] = min.x;
  27839. array[7] = min.y;
  27840. array[8] = max.z;
  27841. array[9] = max.x;
  27842. array[10] = min.y;
  27843. array[11] = max.z;
  27844. array[12] = max.x;
  27845. array[13] = max.y;
  27846. array[14] = min.z;
  27847. array[15] = min.x;
  27848. array[16] = max.y;
  27849. array[17] = min.z;
  27850. array[18] = min.x;
  27851. array[19] = min.y;
  27852. array[20] = min.z;
  27853. array[21] = max.x;
  27854. array[22] = min.y;
  27855. array[23] = min.z;
  27856. position.needsUpdate = true;
  27857. this.geometry.computeBoundingSphere();
  27858. }
  27859. setFromObject(object) {
  27860. this.object = object;
  27861. this.update();
  27862. return this;
  27863. }
  27864. copy(source) {
  27865. LineSegments.prototype.copy.call(this, source);
  27866. this.object = source.object;
  27867. return this;
  27868. }
  27869. }
  27870. class Box3Helper extends LineSegments {
  27871. constructor(box, color = 0xffff00) {
  27872. 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]);
  27873. 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];
  27874. const geometry = new BufferGeometry();
  27875. geometry.setIndex(new BufferAttribute(indices, 1));
  27876. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27877. super(geometry, new LineBasicMaterial({
  27878. color: color,
  27879. toneMapped: false
  27880. }));
  27881. this.box = box;
  27882. this.type = 'Box3Helper';
  27883. this.geometry.computeBoundingSphere();
  27884. }
  27885. updateMatrixWorld(force) {
  27886. const box = this.box;
  27887. if (box.isEmpty()) return;
  27888. box.getCenter(this.position);
  27889. box.getSize(this.scale);
  27890. this.scale.multiplyScalar(0.5);
  27891. super.updateMatrixWorld(force);
  27892. }
  27893. }
  27894. class PlaneHelper extends Line {
  27895. constructor(plane, size = 1, hex = 0xffff00) {
  27896. const color = hex;
  27897. 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, 0, 0, 1, 0, 0, 0];
  27898. const geometry = new BufferGeometry();
  27899. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27900. geometry.computeBoundingSphere();
  27901. super(geometry, new LineBasicMaterial({
  27902. color: color,
  27903. toneMapped: false
  27904. }));
  27905. this.type = 'PlaneHelper';
  27906. this.plane = plane;
  27907. this.size = size;
  27908. const positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  27909. const geometry2 = new BufferGeometry();
  27910. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  27911. geometry2.computeBoundingSphere();
  27912. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  27913. color: color,
  27914. opacity: 0.2,
  27915. transparent: true,
  27916. depthWrite: false,
  27917. toneMapped: false
  27918. })));
  27919. }
  27920. updateMatrixWorld(force) {
  27921. let scale = -this.plane.constant;
  27922. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  27923. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  27924. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  27925. this.lookAt(this.plane.normal);
  27926. super.updateMatrixWorld(force);
  27927. }
  27928. }
  27929. const _axis = /*@__PURE__*/new Vector3();
  27930. let _lineGeometry, _coneGeometry;
  27931. class ArrowHelper extends Object3D {
  27932. // dir is assumed to be normalized
  27933. 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) {
  27934. super();
  27935. this.type = 'ArrowHelper';
  27936. if (_lineGeometry === undefined) {
  27937. _lineGeometry = new BufferGeometry();
  27938. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  27939. _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1);
  27940. _coneGeometry.translate(0, -0.5, 0);
  27941. }
  27942. this.position.copy(origin);
  27943. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  27944. color: color,
  27945. toneMapped: false
  27946. }));
  27947. this.line.matrixAutoUpdate = false;
  27948. this.add(this.line);
  27949. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  27950. color: color,
  27951. toneMapped: false
  27952. }));
  27953. this.cone.matrixAutoUpdate = false;
  27954. this.add(this.cone);
  27955. this.setDirection(dir);
  27956. this.setLength(length, headLength, headWidth);
  27957. }
  27958. setDirection(dir) {
  27959. // dir is assumed to be normalized
  27960. if (dir.y > 0.99999) {
  27961. this.quaternion.set(0, 0, 0, 1);
  27962. } else if (dir.y < -0.99999) {
  27963. this.quaternion.set(1, 0, 0, 0);
  27964. } else {
  27965. _axis.set(dir.z, 0, -dir.x).normalize();
  27966. const radians = Math.acos(dir.y);
  27967. this.quaternion.setFromAxisAngle(_axis, radians);
  27968. }
  27969. }
  27970. setLength(length, headLength = length * 0.2, headWidth = headLength * 0.2) {
  27971. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  27972. this.line.updateMatrix();
  27973. this.cone.scale.set(headWidth, headLength, headWidth);
  27974. this.cone.position.y = length;
  27975. this.cone.updateMatrix();
  27976. }
  27977. setColor(color) {
  27978. this.line.material.color.set(color);
  27979. this.cone.material.color.set(color);
  27980. }
  27981. copy(source) {
  27982. super.copy(source, false);
  27983. this.line.copy(source.line);
  27984. this.cone.copy(source.cone);
  27985. return this;
  27986. }
  27987. }
  27988. class AxesHelper extends LineSegments {
  27989. constructor(size = 1) {
  27990. const vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  27991. const colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  27992. const geometry = new BufferGeometry();
  27993. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27994. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27995. const material = new LineBasicMaterial({
  27996. vertexColors: true,
  27997. toneMapped: false
  27998. });
  27999. super(geometry, material);
  28000. this.type = 'AxesHelper';
  28001. }
  28002. setColors(xAxisColor, yAxisColor, zAxisColor) {
  28003. const color = new Color();
  28004. const array = this.geometry.attributes.color.array;
  28005. color.set(xAxisColor);
  28006. color.toArray(array, 0);
  28007. color.toArray(array, 3);
  28008. color.set(yAxisColor);
  28009. color.toArray(array, 6);
  28010. color.toArray(array, 9);
  28011. color.set(zAxisColor);
  28012. color.toArray(array, 12);
  28013. color.toArray(array, 15);
  28014. this.geometry.attributes.color.needsUpdate = true;
  28015. return this;
  28016. }
  28017. dispose() {
  28018. this.geometry.dispose();
  28019. this.material.dispose();
  28020. }
  28021. }
  28022. class ShapePath {
  28023. constructor() {
  28024. this.type = 'ShapePath';
  28025. this.color = new Color();
  28026. this.subPaths = [];
  28027. this.currentPath = null;
  28028. }
  28029. moveTo(x, y) {
  28030. this.currentPath = new Path();
  28031. this.subPaths.push(this.currentPath);
  28032. this.currentPath.moveTo(x, y);
  28033. return this;
  28034. }
  28035. lineTo(x, y) {
  28036. this.currentPath.lineTo(x, y);
  28037. return this;
  28038. }
  28039. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  28040. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  28041. return this;
  28042. }
  28043. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  28044. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  28045. return this;
  28046. }
  28047. splineThru(pts) {
  28048. this.currentPath.splineThru(pts);
  28049. return this;
  28050. }
  28051. toShapes(isCCW, noHoles) {
  28052. function toShapesNoHoles(inSubpaths) {
  28053. const shapes = [];
  28054. for (let i = 0, l = inSubpaths.length; i < l; i++) {
  28055. const tmpPath = inSubpaths[i];
  28056. const tmpShape = new Shape();
  28057. tmpShape.curves = tmpPath.curves;
  28058. shapes.push(tmpShape);
  28059. }
  28060. return shapes;
  28061. }
  28062. function isPointInsidePolygon(inPt, inPolygon) {
  28063. const polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  28064. // toggling of inside/outside at every single! intersection point of an edge
  28065. // with the horizontal line through inPt, left of inPt
  28066. // not counting lowerY endpoints of edges and whole edges on that line
  28067. let inside = false;
  28068. for (let p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  28069. let edgeLowPt = inPolygon[p];
  28070. let edgeHighPt = inPolygon[q];
  28071. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  28072. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  28073. if (Math.abs(edgeDy) > Number.EPSILON) {
  28074. // not parallel
  28075. if (edgeDy < 0) {
  28076. edgeLowPt = inPolygon[q];
  28077. edgeDx = -edgeDx;
  28078. edgeHighPt = inPolygon[p];
  28079. edgeDy = -edgeDy;
  28080. }
  28081. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  28082. if (inPt.y === edgeLowPt.y) {
  28083. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  28084. // continue; // no intersection or edgeLowPt => doesn't count !!!
  28085. } else {
  28086. const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  28087. if (perpEdge === 0) return true; // inPt is on contour ?
  28088. if (perpEdge < 0) continue;
  28089. inside = !inside; // true intersection left of inPt
  28090. }
  28091. } else {
  28092. // parallel or collinear
  28093. if (inPt.y !== edgeLowPt.y) continue; // parallel
  28094. // edge lies on the same horizontal line as inPt
  28095. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  28096. // continue;
  28097. }
  28098. }
  28099. return inside;
  28100. }
  28101. const isClockWise = ShapeUtils.isClockWise;
  28102. const subPaths = this.subPaths;
  28103. if (subPaths.length === 0) return [];
  28104. if (noHoles === true) return toShapesNoHoles(subPaths);
  28105. let solid, tmpPath, tmpShape;
  28106. const shapes = [];
  28107. if (subPaths.length === 1) {
  28108. tmpPath = subPaths[0];
  28109. tmpShape = new Shape();
  28110. tmpShape.curves = tmpPath.curves;
  28111. shapes.push(tmpShape);
  28112. return shapes;
  28113. }
  28114. let holesFirst = !isClockWise(subPaths[0].getPoints());
  28115. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  28116. const betterShapeHoles = [];
  28117. const newShapes = [];
  28118. let newShapeHoles = [];
  28119. let mainIdx = 0;
  28120. let tmpPoints;
  28121. newShapes[mainIdx] = undefined;
  28122. newShapeHoles[mainIdx] = [];
  28123. for (let i = 0, l = subPaths.length; i < l; i++) {
  28124. tmpPath = subPaths[i];
  28125. tmpPoints = tmpPath.getPoints();
  28126. solid = isClockWise(tmpPoints);
  28127. solid = isCCW ? !solid : solid;
  28128. if (solid) {
  28129. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  28130. newShapes[mainIdx] = {
  28131. s: new Shape(),
  28132. p: tmpPoints
  28133. };
  28134. newShapes[mainIdx].s.curves = tmpPath.curves;
  28135. if (holesFirst) mainIdx++;
  28136. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  28137. } else {
  28138. newShapeHoles[mainIdx].push({
  28139. h: tmpPath,
  28140. p: tmpPoints[0]
  28141. }); //console.log('ccw', i);
  28142. }
  28143. } // only Holes? -> probably all Shapes with wrong orientation
  28144. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  28145. if (newShapes.length > 1) {
  28146. let ambiguous = false;
  28147. const toChange = [];
  28148. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  28149. betterShapeHoles[sIdx] = [];
  28150. }
  28151. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  28152. const sho = newShapeHoles[sIdx];
  28153. for (let hIdx = 0; hIdx < sho.length; hIdx++) {
  28154. const ho = sho[hIdx];
  28155. let hole_unassigned = true;
  28156. for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  28157. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  28158. if (sIdx !== s2Idx) toChange.push({
  28159. froms: sIdx,
  28160. tos: s2Idx,
  28161. hole: hIdx
  28162. });
  28163. if (hole_unassigned) {
  28164. hole_unassigned = false;
  28165. betterShapeHoles[s2Idx].push(ho);
  28166. } else {
  28167. ambiguous = true;
  28168. }
  28169. }
  28170. }
  28171. if (hole_unassigned) {
  28172. betterShapeHoles[sIdx].push(ho);
  28173. }
  28174. }
  28175. } // console.log("ambiguous: ", ambiguous);
  28176. if (toChange.length > 0) {
  28177. // console.log("to change: ", toChange);
  28178. if (!ambiguous) newShapeHoles = betterShapeHoles;
  28179. }
  28180. }
  28181. let tmpHoles;
  28182. for (let i = 0, il = newShapes.length; i < il; i++) {
  28183. tmpShape = newShapes[i].s;
  28184. shapes.push(tmpShape);
  28185. tmpHoles = newShapeHoles[i];
  28186. for (let j = 0, jl = tmpHoles.length; j < jl; j++) {
  28187. tmpShape.holes.push(tmpHoles[j].h);
  28188. }
  28189. } //console.log("shape", shapes);
  28190. return shapes;
  28191. }
  28192. }
  28193. const _floatView = new Float32Array(1);
  28194. const _int32View = new Int32Array(_floatView.buffer);
  28195. class DataUtils {
  28196. // Converts float32 to float16 (stored as uint16 value).
  28197. static toHalfFloat(val) {
  28198. if (val > 65504) {
  28199. console.warn('THREE.DataUtils.toHalfFloat(): value exceeds 65504.');
  28200. val = 65504; // maximum representable value in float16
  28201. } // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  28202. /* This method is faster than the OpenEXR implementation (very often
  28203. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  28204. * by James Tursa?s half-precision code. */
  28205. _floatView[0] = val;
  28206. const x = _int32View[0];
  28207. let bits = x >> 16 & 0x8000;
  28208. /* Get the sign */
  28209. let m = x >> 12 & 0x07ff;
  28210. /* Keep one extra bit for rounding */
  28211. const e = x >> 23 & 0xff;
  28212. /* Using int is faster here */
  28213. /* If zero, or denormal, or exponent underflows too much for a denormal
  28214. * half, return signed zero. */
  28215. if (e < 103) return bits;
  28216. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  28217. if (e > 142) {
  28218. bits |= 0x7c00;
  28219. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  28220. * not Inf, so make sure we set one mantissa bit too. */
  28221. bits |= (e == 255 ? 0 : 1) && x & 0x007fffff;
  28222. return bits;
  28223. }
  28224. /* If exponent underflows but not too much, return a denormal */
  28225. if (e < 113) {
  28226. m |= 0x0800;
  28227. /* Extra rounding may overflow and set mantissa to 0 and exponent
  28228. * to 1, which is OK. */
  28229. bits |= (m >> 114 - e) + (m >> 113 - e & 1);
  28230. return bits;
  28231. }
  28232. bits |= e - 112 << 10 | m >> 1;
  28233. /* Extra rounding. An overflow will set mantissa to 0 and increment
  28234. * the exponent, which is OK. */
  28235. bits += m & 1;
  28236. return bits;
  28237. }
  28238. }
  28239. const LineStrip = 0;
  28240. const LinePieces = 1;
  28241. const NoColors = 0;
  28242. const FaceColors = 1;
  28243. const VertexColors = 2;
  28244. function MeshFaceMaterial(materials) {
  28245. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  28246. return materials;
  28247. }
  28248. function MultiMaterial(materials = []) {
  28249. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  28250. materials.isMultiMaterial = true;
  28251. materials.materials = materials;
  28252. materials.clone = function () {
  28253. return materials.slice();
  28254. };
  28255. return materials;
  28256. }
  28257. function PointCloud(geometry, material) {
  28258. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  28259. return new Points(geometry, material);
  28260. }
  28261. function Particle(material) {
  28262. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  28263. return new Sprite(material);
  28264. }
  28265. function ParticleSystem(geometry, material) {
  28266. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  28267. return new Points(geometry, material);
  28268. }
  28269. function PointCloudMaterial(parameters) {
  28270. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  28271. return new PointsMaterial(parameters);
  28272. }
  28273. function ParticleBasicMaterial(parameters) {
  28274. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  28275. return new PointsMaterial(parameters);
  28276. }
  28277. function ParticleSystemMaterial(parameters) {
  28278. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  28279. return new PointsMaterial(parameters);
  28280. }
  28281. function Vertex(x, y, z) {
  28282. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  28283. return new Vector3(x, y, z);
  28284. } //
  28285. function DynamicBufferAttribute(array, itemSize) {
  28286. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.');
  28287. return new BufferAttribute(array, itemSize).setUsage(DynamicDrawUsage);
  28288. }
  28289. function Int8Attribute(array, itemSize) {
  28290. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  28291. return new Int8BufferAttribute(array, itemSize);
  28292. }
  28293. function Uint8Attribute(array, itemSize) {
  28294. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  28295. return new Uint8BufferAttribute(array, itemSize);
  28296. }
  28297. function Uint8ClampedAttribute(array, itemSize) {
  28298. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  28299. return new Uint8ClampedBufferAttribute(array, itemSize);
  28300. }
  28301. function Int16Attribute(array, itemSize) {
  28302. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  28303. return new Int16BufferAttribute(array, itemSize);
  28304. }
  28305. function Uint16Attribute(array, itemSize) {
  28306. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  28307. return new Uint16BufferAttribute(array, itemSize);
  28308. }
  28309. function Int32Attribute(array, itemSize) {
  28310. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  28311. return new Int32BufferAttribute(array, itemSize);
  28312. }
  28313. function Uint32Attribute(array, itemSize) {
  28314. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  28315. return new Uint32BufferAttribute(array, itemSize);
  28316. }
  28317. function Float32Attribute(array, itemSize) {
  28318. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  28319. return new Float32BufferAttribute(array, itemSize);
  28320. }
  28321. function Float64Attribute(array, itemSize) {
  28322. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  28323. return new Float64BufferAttribute(array, itemSize);
  28324. } //
  28325. Curve.create = function (construct, getPoint) {
  28326. console.log('THREE.Curve.create() has been deprecated');
  28327. construct.prototype = Object.create(Curve.prototype);
  28328. construct.prototype.constructor = construct;
  28329. construct.prototype.getPoint = getPoint;
  28330. return construct;
  28331. }; //
  28332. Path.prototype.fromPoints = function (points) {
  28333. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  28334. return this.setFromPoints(points);
  28335. }; //
  28336. function AxisHelper(size) {
  28337. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  28338. return new AxesHelper(size);
  28339. }
  28340. function BoundingBoxHelper(object, color) {
  28341. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  28342. return new BoxHelper(object, color);
  28343. }
  28344. function EdgesHelper(object, hex) {
  28345. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  28346. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  28347. color: hex !== undefined ? hex : 0xffffff
  28348. }));
  28349. }
  28350. GridHelper.prototype.setColors = function () {
  28351. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  28352. };
  28353. SkeletonHelper.prototype.update = function () {
  28354. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  28355. };
  28356. function WireframeHelper(object, hex) {
  28357. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  28358. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  28359. color: hex !== undefined ? hex : 0xffffff
  28360. }));
  28361. } //
  28362. Loader.prototype.extractUrlBase = function (url) {
  28363. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  28364. return LoaderUtils.extractUrlBase(url);
  28365. };
  28366. Loader.Handlers = {
  28367. add: function () {
  28368. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  28369. },
  28370. get: function () {
  28371. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  28372. }
  28373. };
  28374. function XHRLoader(manager) {
  28375. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  28376. return new FileLoader(manager);
  28377. }
  28378. function BinaryTextureLoader(manager) {
  28379. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  28380. return new DataTextureLoader(manager);
  28381. } //
  28382. Box2.prototype.center = function (optionalTarget) {
  28383. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  28384. return this.getCenter(optionalTarget);
  28385. };
  28386. Box2.prototype.empty = function () {
  28387. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  28388. return this.isEmpty();
  28389. };
  28390. Box2.prototype.isIntersectionBox = function (box) {
  28391. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  28392. return this.intersectsBox(box);
  28393. };
  28394. Box2.prototype.size = function (optionalTarget) {
  28395. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  28396. return this.getSize(optionalTarget);
  28397. }; //
  28398. Box3.prototype.center = function (optionalTarget) {
  28399. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  28400. return this.getCenter(optionalTarget);
  28401. };
  28402. Box3.prototype.empty = function () {
  28403. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  28404. return this.isEmpty();
  28405. };
  28406. Box3.prototype.isIntersectionBox = function (box) {
  28407. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  28408. return this.intersectsBox(box);
  28409. };
  28410. Box3.prototype.isIntersectionSphere = function (sphere) {
  28411. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  28412. return this.intersectsSphere(sphere);
  28413. };
  28414. Box3.prototype.size = function (optionalTarget) {
  28415. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  28416. return this.getSize(optionalTarget);
  28417. }; //
  28418. Sphere.prototype.empty = function () {
  28419. console.warn('THREE.Sphere: .empty() has been renamed to .isEmpty().');
  28420. return this.isEmpty();
  28421. }; //
  28422. Frustum.prototype.setFromMatrix = function (m) {
  28423. console.warn('THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().');
  28424. return this.setFromProjectionMatrix(m);
  28425. }; //
  28426. Line3.prototype.center = function (optionalTarget) {
  28427. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  28428. return this.getCenter(optionalTarget);
  28429. }; //
  28430. Matrix3.prototype.flattenToArrayOffset = function (array, offset) {
  28431. console.warn('THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  28432. return this.toArray(array, offset);
  28433. };
  28434. Matrix3.prototype.multiplyVector3 = function (vector) {
  28435. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  28436. return vector.applyMatrix3(this);
  28437. };
  28438. Matrix3.prototype.multiplyVector3Array = function () {
  28439. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  28440. };
  28441. Matrix3.prototype.applyToBufferAttribute = function (attribute) {
  28442. console.warn('THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.');
  28443. return attribute.applyMatrix3(this);
  28444. };
  28445. Matrix3.prototype.applyToVector3Array = function () {
  28446. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  28447. };
  28448. Matrix3.prototype.getInverse = function (matrix) {
  28449. console.warn('THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  28450. return this.copy(matrix).invert();
  28451. }; //
  28452. Matrix4.prototype.extractPosition = function (m) {
  28453. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  28454. return this.copyPosition(m);
  28455. };
  28456. Matrix4.prototype.flattenToArrayOffset = function (array, offset) {
  28457. console.warn('THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  28458. return this.toArray(array, offset);
  28459. };
  28460. Matrix4.prototype.getPosition = function () {
  28461. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  28462. return new Vector3().setFromMatrixColumn(this, 3);
  28463. };
  28464. Matrix4.prototype.setRotationFromQuaternion = function (q) {
  28465. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  28466. return this.makeRotationFromQuaternion(q);
  28467. };
  28468. Matrix4.prototype.multiplyToArray = function () {
  28469. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  28470. };
  28471. Matrix4.prototype.multiplyVector3 = function (vector) {
  28472. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28473. return vector.applyMatrix4(this);
  28474. };
  28475. Matrix4.prototype.multiplyVector4 = function (vector) {
  28476. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28477. return vector.applyMatrix4(this);
  28478. };
  28479. Matrix4.prototype.multiplyVector3Array = function () {
  28480. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  28481. };
  28482. Matrix4.prototype.rotateAxis = function (v) {
  28483. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  28484. v.transformDirection(this);
  28485. };
  28486. Matrix4.prototype.crossVector = function (vector) {
  28487. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28488. return vector.applyMatrix4(this);
  28489. };
  28490. Matrix4.prototype.translate = function () {
  28491. console.error('THREE.Matrix4: .translate() has been removed.');
  28492. };
  28493. Matrix4.prototype.rotateX = function () {
  28494. console.error('THREE.Matrix4: .rotateX() has been removed.');
  28495. };
  28496. Matrix4.prototype.rotateY = function () {
  28497. console.error('THREE.Matrix4: .rotateY() has been removed.');
  28498. };
  28499. Matrix4.prototype.rotateZ = function () {
  28500. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  28501. };
  28502. Matrix4.prototype.rotateByAxis = function () {
  28503. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  28504. };
  28505. Matrix4.prototype.applyToBufferAttribute = function (attribute) {
  28506. console.warn('THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.');
  28507. return attribute.applyMatrix4(this);
  28508. };
  28509. Matrix4.prototype.applyToVector3Array = function () {
  28510. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  28511. };
  28512. Matrix4.prototype.makeFrustum = function (left, right, bottom, top, near, far) {
  28513. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  28514. return this.makePerspective(left, right, top, bottom, near, far);
  28515. };
  28516. Matrix4.prototype.getInverse = function (matrix) {
  28517. console.warn('THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  28518. return this.copy(matrix).invert();
  28519. }; //
  28520. Plane.prototype.isIntersectionLine = function (line) {
  28521. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  28522. return this.intersectsLine(line);
  28523. }; //
  28524. Quaternion.prototype.multiplyVector3 = function (vector) {
  28525. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  28526. return vector.applyQuaternion(this);
  28527. };
  28528. Quaternion.prototype.inverse = function () {
  28529. console.warn('THREE.Quaternion: .inverse() has been renamed to invert().');
  28530. return this.invert();
  28531. }; //
  28532. Ray.prototype.isIntersectionBox = function (box) {
  28533. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  28534. return this.intersectsBox(box);
  28535. };
  28536. Ray.prototype.isIntersectionPlane = function (plane) {
  28537. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  28538. return this.intersectsPlane(plane);
  28539. };
  28540. Ray.prototype.isIntersectionSphere = function (sphere) {
  28541. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  28542. return this.intersectsSphere(sphere);
  28543. }; //
  28544. Triangle.prototype.area = function () {
  28545. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  28546. return this.getArea();
  28547. };
  28548. Triangle.prototype.barycoordFromPoint = function (point, target) {
  28549. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28550. return this.getBarycoord(point, target);
  28551. };
  28552. Triangle.prototype.midpoint = function (target) {
  28553. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  28554. return this.getMidpoint(target);
  28555. };
  28556. Triangle.prototypenormal = function (target) {
  28557. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28558. return this.getNormal(target);
  28559. };
  28560. Triangle.prototype.plane = function (target) {
  28561. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  28562. return this.getPlane(target);
  28563. };
  28564. Triangle.barycoordFromPoint = function (point, a, b, c, target) {
  28565. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28566. return Triangle.getBarycoord(point, a, b, c, target);
  28567. };
  28568. Triangle.normal = function (a, b, c, target) {
  28569. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28570. return Triangle.getNormal(a, b, c, target);
  28571. }; //
  28572. Shape.prototype.extractAllPoints = function (divisions) {
  28573. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  28574. return this.extractPoints(divisions);
  28575. };
  28576. Shape.prototype.extrude = function (options) {
  28577. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  28578. return new ExtrudeGeometry(this, options);
  28579. };
  28580. Shape.prototype.makeGeometry = function (options) {
  28581. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  28582. return new ShapeGeometry(this, options);
  28583. }; //
  28584. Vector2.prototype.fromAttribute = function (attribute, index, offset) {
  28585. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28586. return this.fromBufferAttribute(attribute, index, offset);
  28587. };
  28588. Vector2.prototype.distanceToManhattan = function (v) {
  28589. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28590. return this.manhattanDistanceTo(v);
  28591. };
  28592. Vector2.prototype.lengthManhattan = function () {
  28593. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  28594. return this.manhattanLength();
  28595. }; //
  28596. Vector3.prototype.setEulerFromRotationMatrix = function () {
  28597. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  28598. };
  28599. Vector3.prototype.setEulerFromQuaternion = function () {
  28600. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  28601. };
  28602. Vector3.prototype.getPositionFromMatrix = function (m) {
  28603. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  28604. return this.setFromMatrixPosition(m);
  28605. };
  28606. Vector3.prototype.getScaleFromMatrix = function (m) {
  28607. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  28608. return this.setFromMatrixScale(m);
  28609. };
  28610. Vector3.prototype.getColumnFromMatrix = function (index, matrix) {
  28611. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  28612. return this.setFromMatrixColumn(matrix, index);
  28613. };
  28614. Vector3.prototype.applyProjection = function (m) {
  28615. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  28616. return this.applyMatrix4(m);
  28617. };
  28618. Vector3.prototype.fromAttribute = function (attribute, index, offset) {
  28619. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28620. return this.fromBufferAttribute(attribute, index, offset);
  28621. };
  28622. Vector3.prototype.distanceToManhattan = function (v) {
  28623. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28624. return this.manhattanDistanceTo(v);
  28625. };
  28626. Vector3.prototype.lengthManhattan = function () {
  28627. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  28628. return this.manhattanLength();
  28629. }; //
  28630. Vector4.prototype.fromAttribute = function (attribute, index, offset) {
  28631. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28632. return this.fromBufferAttribute(attribute, index, offset);
  28633. };
  28634. Vector4.prototype.lengthManhattan = function () {
  28635. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  28636. return this.manhattanLength();
  28637. }; //
  28638. Object3D.prototype.getChildByName = function (name) {
  28639. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  28640. return this.getObjectByName(name);
  28641. };
  28642. Object3D.prototype.renderDepth = function () {
  28643. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  28644. };
  28645. Object3D.prototype.translate = function (distance, axis) {
  28646. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  28647. return this.translateOnAxis(axis, distance);
  28648. };
  28649. Object3D.prototype.getWorldRotation = function () {
  28650. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  28651. };
  28652. Object3D.prototype.applyMatrix = function (matrix) {
  28653. console.warn('THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().');
  28654. return this.applyMatrix4(matrix);
  28655. };
  28656. Object.defineProperties(Object3D.prototype, {
  28657. eulerOrder: {
  28658. get: function () {
  28659. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28660. return this.rotation.order;
  28661. },
  28662. set: function (value) {
  28663. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28664. this.rotation.order = value;
  28665. }
  28666. },
  28667. useQuaternion: {
  28668. get: function () {
  28669. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28670. },
  28671. set: function () {
  28672. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28673. }
  28674. }
  28675. });
  28676. Mesh.prototype.setDrawMode = function () {
  28677. console.error('THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28678. };
  28679. Object.defineProperties(Mesh.prototype, {
  28680. drawMode: {
  28681. get: function () {
  28682. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.');
  28683. return TrianglesDrawMode;
  28684. },
  28685. set: function () {
  28686. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28687. }
  28688. }
  28689. });
  28690. SkinnedMesh.prototype.initBones = function () {
  28691. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  28692. }; //
  28693. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  28694. console.warn('THREE.PerspectiveCamera.setLens is deprecated. ' + 'Use .setFocalLength and .filmGauge for a photographic setup.');
  28695. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  28696. this.setFocalLength(focalLength);
  28697. }; //
  28698. Object.defineProperties(Light.prototype, {
  28699. onlyShadow: {
  28700. set: function () {
  28701. console.warn('THREE.Light: .onlyShadow has been removed.');
  28702. }
  28703. },
  28704. shadowCameraFov: {
  28705. set: function (value) {
  28706. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  28707. this.shadow.camera.fov = value;
  28708. }
  28709. },
  28710. shadowCameraLeft: {
  28711. set: function (value) {
  28712. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  28713. this.shadow.camera.left = value;
  28714. }
  28715. },
  28716. shadowCameraRight: {
  28717. set: function (value) {
  28718. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  28719. this.shadow.camera.right = value;
  28720. }
  28721. },
  28722. shadowCameraTop: {
  28723. set: function (value) {
  28724. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  28725. this.shadow.camera.top = value;
  28726. }
  28727. },
  28728. shadowCameraBottom: {
  28729. set: function (value) {
  28730. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  28731. this.shadow.camera.bottom = value;
  28732. }
  28733. },
  28734. shadowCameraNear: {
  28735. set: function (value) {
  28736. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  28737. this.shadow.camera.near = value;
  28738. }
  28739. },
  28740. shadowCameraFar: {
  28741. set: function (value) {
  28742. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  28743. this.shadow.camera.far = value;
  28744. }
  28745. },
  28746. shadowCameraVisible: {
  28747. set: function () {
  28748. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  28749. }
  28750. },
  28751. shadowBias: {
  28752. set: function (value) {
  28753. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  28754. this.shadow.bias = value;
  28755. }
  28756. },
  28757. shadowDarkness: {
  28758. set: function () {
  28759. console.warn('THREE.Light: .shadowDarkness has been removed.');
  28760. }
  28761. },
  28762. shadowMapWidth: {
  28763. set: function (value) {
  28764. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  28765. this.shadow.mapSize.width = value;
  28766. }
  28767. },
  28768. shadowMapHeight: {
  28769. set: function (value) {
  28770. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  28771. this.shadow.mapSize.height = value;
  28772. }
  28773. }
  28774. }); //
  28775. Object.defineProperties(BufferAttribute.prototype, {
  28776. length: {
  28777. get: function () {
  28778. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  28779. return this.array.length;
  28780. }
  28781. },
  28782. dynamic: {
  28783. get: function () {
  28784. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28785. return this.usage === DynamicDrawUsage;
  28786. },
  28787. set: function () {
  28788. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28789. this.setUsage(DynamicDrawUsage);
  28790. }
  28791. }
  28792. });
  28793. BufferAttribute.prototype.setDynamic = function (value) {
  28794. console.warn('THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28795. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28796. return this;
  28797. };
  28798. BufferAttribute.prototype.copyIndicesArray = function () {
  28799. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  28800. }, BufferAttribute.prototype.setArray = function () {
  28801. console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28802. }; //
  28803. BufferGeometry.prototype.addIndex = function (index) {
  28804. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  28805. this.setIndex(index);
  28806. };
  28807. BufferGeometry.prototype.addAttribute = function (name, attribute) {
  28808. console.warn('THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().');
  28809. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  28810. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  28811. return this.setAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  28812. }
  28813. if (name === 'index') {
  28814. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  28815. this.setIndex(attribute);
  28816. return this;
  28817. }
  28818. return this.setAttribute(name, attribute);
  28819. };
  28820. BufferGeometry.prototype.addDrawCall = function (start, count, indexOffset) {
  28821. if (indexOffset !== undefined) {
  28822. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  28823. }
  28824. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  28825. this.addGroup(start, count);
  28826. };
  28827. BufferGeometry.prototype.clearDrawCalls = function () {
  28828. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  28829. this.clearGroups();
  28830. };
  28831. BufferGeometry.prototype.computeOffsets = function () {
  28832. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  28833. };
  28834. BufferGeometry.prototype.removeAttribute = function (name) {
  28835. console.warn('THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().');
  28836. return this.deleteAttribute(name);
  28837. };
  28838. BufferGeometry.prototype.applyMatrix = function (matrix) {
  28839. console.warn('THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().');
  28840. return this.applyMatrix4(matrix);
  28841. };
  28842. Object.defineProperties(BufferGeometry.prototype, {
  28843. drawcalls: {
  28844. get: function () {
  28845. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  28846. return this.groups;
  28847. }
  28848. },
  28849. offsets: {
  28850. get: function () {
  28851. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  28852. return this.groups;
  28853. }
  28854. }
  28855. });
  28856. InterleavedBuffer.prototype.setDynamic = function (value) {
  28857. console.warn('THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28858. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28859. return this;
  28860. };
  28861. InterleavedBuffer.prototype.setArray = function () {
  28862. console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28863. }; //
  28864. ExtrudeGeometry.prototype.getArrays = function () {
  28865. console.error('THREE.ExtrudeGeometry: .getArrays() has been removed.');
  28866. };
  28867. ExtrudeGeometry.prototype.addShapeList = function () {
  28868. console.error('THREE.ExtrudeGeometry: .addShapeList() has been removed.');
  28869. };
  28870. ExtrudeGeometry.prototype.addShape = function () {
  28871. console.error('THREE.ExtrudeGeometry: .addShape() has been removed.');
  28872. }; //
  28873. Scene.prototype.dispose = function () {
  28874. console.error('THREE.Scene: .dispose() has been removed.');
  28875. }; //
  28876. Uniform.prototype.onUpdate = function () {
  28877. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  28878. return this;
  28879. }; //
  28880. Object.defineProperties(Material.prototype, {
  28881. wrapAround: {
  28882. get: function () {
  28883. console.warn('THREE.Material: .wrapAround has been removed.');
  28884. },
  28885. set: function () {
  28886. console.warn('THREE.Material: .wrapAround has been removed.');
  28887. }
  28888. },
  28889. overdraw: {
  28890. get: function () {
  28891. console.warn('THREE.Material: .overdraw has been removed.');
  28892. },
  28893. set: function () {
  28894. console.warn('THREE.Material: .overdraw has been removed.');
  28895. }
  28896. },
  28897. wrapRGB: {
  28898. get: function () {
  28899. console.warn('THREE.Material: .wrapRGB has been removed.');
  28900. return new Color();
  28901. }
  28902. },
  28903. shading: {
  28904. get: function () {
  28905. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28906. },
  28907. set: function (value) {
  28908. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28909. this.flatShading = value === FlatShading;
  28910. }
  28911. },
  28912. stencilMask: {
  28913. get: function () {
  28914. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28915. return this.stencilFuncMask;
  28916. },
  28917. set: function (value) {
  28918. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28919. this.stencilFuncMask = value;
  28920. }
  28921. },
  28922. vertexTangents: {
  28923. get: function () {
  28924. console.warn('THREE.' + this.type + ': .vertexTangents has been removed.');
  28925. },
  28926. set: function () {
  28927. console.warn('THREE.' + this.type + ': .vertexTangents has been removed.');
  28928. }
  28929. }
  28930. });
  28931. Object.defineProperties(ShaderMaterial.prototype, {
  28932. derivatives: {
  28933. get: function () {
  28934. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28935. return this.extensions.derivatives;
  28936. },
  28937. set: function (value) {
  28938. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28939. this.extensions.derivatives = value;
  28940. }
  28941. }
  28942. }); //
  28943. WebGLRenderer.prototype.clearTarget = function (renderTarget, color, depth, stencil) {
  28944. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  28945. this.setRenderTarget(renderTarget);
  28946. this.clear(color, depth, stencil);
  28947. };
  28948. WebGLRenderer.prototype.animate = function (callback) {
  28949. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  28950. this.setAnimationLoop(callback);
  28951. };
  28952. WebGLRenderer.prototype.getCurrentRenderTarget = function () {
  28953. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  28954. return this.getRenderTarget();
  28955. };
  28956. WebGLRenderer.prototype.getMaxAnisotropy = function () {
  28957. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  28958. return this.capabilities.getMaxAnisotropy();
  28959. };
  28960. WebGLRenderer.prototype.getPrecision = function () {
  28961. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  28962. return this.capabilities.precision;
  28963. };
  28964. WebGLRenderer.prototype.resetGLState = function () {
  28965. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  28966. return this.state.reset();
  28967. };
  28968. WebGLRenderer.prototype.supportsFloatTextures = function () {
  28969. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  28970. return this.extensions.get('OES_texture_float');
  28971. };
  28972. WebGLRenderer.prototype.supportsHalfFloatTextures = function () {
  28973. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  28974. return this.extensions.get('OES_texture_half_float');
  28975. };
  28976. WebGLRenderer.prototype.supportsStandardDerivatives = function () {
  28977. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  28978. return this.extensions.get('OES_standard_derivatives');
  28979. };
  28980. WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () {
  28981. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  28982. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  28983. };
  28984. WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () {
  28985. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  28986. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  28987. };
  28988. WebGLRenderer.prototype.supportsBlendMinMax = function () {
  28989. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  28990. return this.extensions.get('EXT_blend_minmax');
  28991. };
  28992. WebGLRenderer.prototype.supportsVertexTextures = function () {
  28993. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  28994. return this.capabilities.vertexTextures;
  28995. };
  28996. WebGLRenderer.prototype.supportsInstancedArrays = function () {
  28997. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  28998. return this.extensions.get('ANGLE_instanced_arrays');
  28999. };
  29000. WebGLRenderer.prototype.enableScissorTest = function (boolean) {
  29001. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  29002. this.setScissorTest(boolean);
  29003. };
  29004. WebGLRenderer.prototype.initMaterial = function () {
  29005. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  29006. };
  29007. WebGLRenderer.prototype.addPrePlugin = function () {
  29008. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  29009. };
  29010. WebGLRenderer.prototype.addPostPlugin = function () {
  29011. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  29012. };
  29013. WebGLRenderer.prototype.updateShadowMap = function () {
  29014. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  29015. };
  29016. WebGLRenderer.prototype.setFaceCulling = function () {
  29017. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  29018. };
  29019. WebGLRenderer.prototype.allocTextureUnit = function () {
  29020. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  29021. };
  29022. WebGLRenderer.prototype.setTexture = function () {
  29023. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  29024. };
  29025. WebGLRenderer.prototype.setTexture2D = function () {
  29026. console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
  29027. };
  29028. WebGLRenderer.prototype.setTextureCube = function () {
  29029. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  29030. };
  29031. WebGLRenderer.prototype.getActiveMipMapLevel = function () {
  29032. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  29033. return this.getActiveMipmapLevel();
  29034. };
  29035. Object.defineProperties(WebGLRenderer.prototype, {
  29036. shadowMapEnabled: {
  29037. get: function () {
  29038. return this.shadowMap.enabled;
  29039. },
  29040. set: function (value) {
  29041. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  29042. this.shadowMap.enabled = value;
  29043. }
  29044. },
  29045. shadowMapType: {
  29046. get: function () {
  29047. return this.shadowMap.type;
  29048. },
  29049. set: function (value) {
  29050. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  29051. this.shadowMap.type = value;
  29052. }
  29053. },
  29054. shadowMapCullFace: {
  29055. get: function () {
  29056. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  29057. return undefined;
  29058. },
  29059. set: function () {
  29060. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  29061. }
  29062. },
  29063. context: {
  29064. get: function () {
  29065. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  29066. return this.getContext();
  29067. }
  29068. },
  29069. vr: {
  29070. get: function () {
  29071. console.warn('THREE.WebGLRenderer: .vr has been renamed to .xr');
  29072. return this.xr;
  29073. }
  29074. },
  29075. gammaInput: {
  29076. get: function () {
  29077. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  29078. return false;
  29079. },
  29080. set: function () {
  29081. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  29082. }
  29083. },
  29084. gammaOutput: {
  29085. get: function () {
  29086. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  29087. return false;
  29088. },
  29089. set: function (value) {
  29090. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  29091. this.outputEncoding = value === true ? sRGBEncoding : LinearEncoding;
  29092. }
  29093. },
  29094. toneMappingWhitePoint: {
  29095. get: function () {
  29096. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  29097. return 1.0;
  29098. },
  29099. set: function () {
  29100. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  29101. }
  29102. }
  29103. });
  29104. Object.defineProperties(WebGLShadowMap.prototype, {
  29105. cullFace: {
  29106. get: function () {
  29107. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  29108. return undefined;
  29109. },
  29110. set: function () {
  29111. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  29112. }
  29113. },
  29114. renderReverseSided: {
  29115. get: function () {
  29116. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  29117. return undefined;
  29118. },
  29119. set: function () {
  29120. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  29121. }
  29122. },
  29123. renderSingleSided: {
  29124. get: function () {
  29125. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  29126. return undefined;
  29127. },
  29128. set: function () {
  29129. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  29130. }
  29131. }
  29132. });
  29133. function WebGLRenderTargetCube(width, height, options) {
  29134. console.warn('THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).');
  29135. return new WebGLCubeRenderTarget(width, options);
  29136. } //
  29137. Object.defineProperties(WebGLRenderTarget.prototype, {
  29138. wrapS: {
  29139. get: function () {
  29140. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  29141. return this.texture.wrapS;
  29142. },
  29143. set: function (value) {
  29144. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  29145. this.texture.wrapS = value;
  29146. }
  29147. },
  29148. wrapT: {
  29149. get: function () {
  29150. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  29151. return this.texture.wrapT;
  29152. },
  29153. set: function (value) {
  29154. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  29155. this.texture.wrapT = value;
  29156. }
  29157. },
  29158. magFilter: {
  29159. get: function () {
  29160. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  29161. return this.texture.magFilter;
  29162. },
  29163. set: function (value) {
  29164. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  29165. this.texture.magFilter = value;
  29166. }
  29167. },
  29168. minFilter: {
  29169. get: function () {
  29170. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  29171. return this.texture.minFilter;
  29172. },
  29173. set: function (value) {
  29174. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  29175. this.texture.minFilter = value;
  29176. }
  29177. },
  29178. anisotropy: {
  29179. get: function () {
  29180. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  29181. return this.texture.anisotropy;
  29182. },
  29183. set: function (value) {
  29184. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  29185. this.texture.anisotropy = value;
  29186. }
  29187. },
  29188. offset: {
  29189. get: function () {
  29190. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  29191. return this.texture.offset;
  29192. },
  29193. set: function (value) {
  29194. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  29195. this.texture.offset = value;
  29196. }
  29197. },
  29198. repeat: {
  29199. get: function () {
  29200. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  29201. return this.texture.repeat;
  29202. },
  29203. set: function (value) {
  29204. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  29205. this.texture.repeat = value;
  29206. }
  29207. },
  29208. format: {
  29209. get: function () {
  29210. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  29211. return this.texture.format;
  29212. },
  29213. set: function (value) {
  29214. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  29215. this.texture.format = value;
  29216. }
  29217. },
  29218. type: {
  29219. get: function () {
  29220. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  29221. return this.texture.type;
  29222. },
  29223. set: function (value) {
  29224. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  29225. this.texture.type = value;
  29226. }
  29227. },
  29228. generateMipmaps: {
  29229. get: function () {
  29230. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  29231. return this.texture.generateMipmaps;
  29232. },
  29233. set: function (value) {
  29234. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  29235. this.texture.generateMipmaps = value;
  29236. }
  29237. }
  29238. }); //
  29239. Audio.prototype.load = function (file) {
  29240. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  29241. const scope = this;
  29242. const audioLoader = new AudioLoader();
  29243. audioLoader.load(file, function (buffer) {
  29244. scope.setBuffer(buffer);
  29245. });
  29246. return this;
  29247. };
  29248. AudioAnalyser.prototype.getData = function () {
  29249. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  29250. return this.getFrequencyData();
  29251. }; //
  29252. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  29253. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  29254. return this.update(renderer, scene);
  29255. };
  29256. CubeCamera.prototype.clear = function (renderer, color, depth, stencil) {
  29257. console.warn('THREE.CubeCamera: .clear() is now .renderTarget.clear().');
  29258. return this.renderTarget.clear(renderer, color, depth, stencil);
  29259. };
  29260. ImageUtils.crossOrigin = undefined;
  29261. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  29262. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  29263. const loader = new TextureLoader();
  29264. loader.setCrossOrigin(this.crossOrigin);
  29265. const texture = loader.load(url, onLoad, undefined, onError);
  29266. if (mapping) texture.mapping = mapping;
  29267. return texture;
  29268. };
  29269. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  29270. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  29271. const loader = new CubeTextureLoader();
  29272. loader.setCrossOrigin(this.crossOrigin);
  29273. const texture = loader.load(urls, onLoad, undefined, onError);
  29274. if (mapping) texture.mapping = mapping;
  29275. return texture;
  29276. };
  29277. ImageUtils.loadCompressedTexture = function () {
  29278. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  29279. };
  29280. ImageUtils.loadCompressedTextureCube = function () {
  29281. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  29282. }; //
  29283. function CanvasRenderer() {
  29284. console.error('THREE.CanvasRenderer has been removed');
  29285. } //
  29286. function JSONLoader() {
  29287. console.error('THREE.JSONLoader has been removed.');
  29288. } //
  29289. const SceneUtils = {
  29290. createMultiMaterialObject: function () {
  29291. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  29292. },
  29293. detach: function () {
  29294. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  29295. },
  29296. attach: function () {
  29297. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  29298. }
  29299. }; //
  29300. function LensFlare() {
  29301. console.error('THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js');
  29302. } //
  29303. function ParametricGeometry() {
  29304. console.error('THREE.ParametricGeometry has been moved to /examples/jsm/geometries/ParametricGeometry.js');
  29305. return new BufferGeometry();
  29306. }
  29307. function TextGeometry() {
  29308. console.error('THREE.TextGeometry has been moved to /examples/jsm/geometries/TextGeometry.js');
  29309. return new BufferGeometry();
  29310. }
  29311. function FontLoader() {
  29312. console.error('THREE.FontLoader has been moved to /examples/jsm/loaders/FontLoader.js');
  29313. }
  29314. function Font() {
  29315. console.error('THREE.Font has been moved to /examples/jsm/loaders/FontLoader.js');
  29316. }
  29317. function ImmediateRenderObject() {
  29318. console.error('THREE.ImmediateRenderObject has been removed.');
  29319. }
  29320. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  29321. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  29322. detail: {
  29323. revision: REVISION
  29324. }
  29325. }));
  29326. }
  29327. if (typeof window !== 'undefined') {
  29328. if (window.__THREE__) {
  29329. console.warn('WARNING: Multiple instances of Three.js being imported.');
  29330. } else {
  29331. window.__THREE__ = REVISION;
  29332. }
  29333. }
  29334. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  29335. exports.AddEquation = AddEquation;
  29336. exports.AddOperation = AddOperation;
  29337. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  29338. exports.AdditiveBlending = AdditiveBlending;
  29339. exports.AlphaFormat = AlphaFormat;
  29340. exports.AlwaysDepth = AlwaysDepth;
  29341. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  29342. exports.AmbientLight = AmbientLight;
  29343. exports.AmbientLightProbe = AmbientLightProbe;
  29344. exports.AnimationClip = AnimationClip;
  29345. exports.AnimationLoader = AnimationLoader;
  29346. exports.AnimationMixer = AnimationMixer;
  29347. exports.AnimationObjectGroup = AnimationObjectGroup;
  29348. exports.AnimationUtils = AnimationUtils;
  29349. exports.ArcCurve = ArcCurve;
  29350. exports.ArrayCamera = ArrayCamera;
  29351. exports.ArrowHelper = ArrowHelper;
  29352. exports.Audio = Audio;
  29353. exports.AudioAnalyser = AudioAnalyser;
  29354. exports.AudioContext = AudioContext;
  29355. exports.AudioListener = AudioListener;
  29356. exports.AudioLoader = AudioLoader;
  29357. exports.AxesHelper = AxesHelper;
  29358. exports.AxisHelper = AxisHelper;
  29359. exports.BackSide = BackSide;
  29360. exports.BasicDepthPacking = BasicDepthPacking;
  29361. exports.BasicShadowMap = BasicShadowMap;
  29362. exports.BinaryTextureLoader = BinaryTextureLoader;
  29363. exports.Bone = Bone;
  29364. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  29365. exports.BoundingBoxHelper = BoundingBoxHelper;
  29366. exports.Box2 = Box2;
  29367. exports.Box3 = Box3;
  29368. exports.Box3Helper = Box3Helper;
  29369. exports.BoxBufferGeometry = BoxGeometry;
  29370. exports.BoxGeometry = BoxGeometry;
  29371. exports.BoxHelper = BoxHelper;
  29372. exports.BufferAttribute = BufferAttribute;
  29373. exports.BufferGeometry = BufferGeometry;
  29374. exports.BufferGeometryLoader = BufferGeometryLoader;
  29375. exports.ByteType = ByteType;
  29376. exports.Cache = Cache;
  29377. exports.Camera = Camera;
  29378. exports.CameraHelper = CameraHelper;
  29379. exports.CanvasRenderer = CanvasRenderer;
  29380. exports.CanvasTexture = CanvasTexture;
  29381. exports.CatmullRomCurve3 = CatmullRomCurve3;
  29382. exports.CineonToneMapping = CineonToneMapping;
  29383. exports.CircleBufferGeometry = CircleGeometry;
  29384. exports.CircleGeometry = CircleGeometry;
  29385. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  29386. exports.Clock = Clock;
  29387. exports.Color = Color;
  29388. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  29389. exports.CompressedTexture = CompressedTexture;
  29390. exports.CompressedTextureLoader = CompressedTextureLoader;
  29391. exports.ConeBufferGeometry = ConeGeometry;
  29392. exports.ConeGeometry = ConeGeometry;
  29393. exports.CubeCamera = CubeCamera;
  29394. exports.CubeReflectionMapping = CubeReflectionMapping;
  29395. exports.CubeRefractionMapping = CubeRefractionMapping;
  29396. exports.CubeTexture = CubeTexture;
  29397. exports.CubeTextureLoader = CubeTextureLoader;
  29398. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  29399. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  29400. exports.CubicBezierCurve = CubicBezierCurve;
  29401. exports.CubicBezierCurve3 = CubicBezierCurve3;
  29402. exports.CubicInterpolant = CubicInterpolant;
  29403. exports.CullFaceBack = CullFaceBack;
  29404. exports.CullFaceFront = CullFaceFront;
  29405. exports.CullFaceFrontBack = CullFaceFrontBack;
  29406. exports.CullFaceNone = CullFaceNone;
  29407. exports.Curve = Curve;
  29408. exports.CurvePath = CurvePath;
  29409. exports.CustomBlending = CustomBlending;
  29410. exports.CustomToneMapping = CustomToneMapping;
  29411. exports.CylinderBufferGeometry = CylinderGeometry;
  29412. exports.CylinderGeometry = CylinderGeometry;
  29413. exports.Cylindrical = Cylindrical;
  29414. exports.DataTexture = DataTexture;
  29415. exports.DataTexture2DArray = DataTexture2DArray;
  29416. exports.DataTexture3D = DataTexture3D;
  29417. exports.DataTextureLoader = DataTextureLoader;
  29418. exports.DataUtils = DataUtils;
  29419. exports.DecrementStencilOp = DecrementStencilOp;
  29420. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  29421. exports.DefaultLoadingManager = DefaultLoadingManager;
  29422. exports.DepthFormat = DepthFormat;
  29423. exports.DepthStencilFormat = DepthStencilFormat;
  29424. exports.DepthTexture = DepthTexture;
  29425. exports.DirectionalLight = DirectionalLight;
  29426. exports.DirectionalLightHelper = DirectionalLightHelper;
  29427. exports.DiscreteInterpolant = DiscreteInterpolant;
  29428. exports.DodecahedronBufferGeometry = DodecahedronGeometry;
  29429. exports.DodecahedronGeometry = DodecahedronGeometry;
  29430. exports.DoubleSide = DoubleSide;
  29431. exports.DstAlphaFactor = DstAlphaFactor;
  29432. exports.DstColorFactor = DstColorFactor;
  29433. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  29434. exports.DynamicCopyUsage = DynamicCopyUsage;
  29435. exports.DynamicDrawUsage = DynamicDrawUsage;
  29436. exports.DynamicReadUsage = DynamicReadUsage;
  29437. exports.EdgesGeometry = EdgesGeometry;
  29438. exports.EdgesHelper = EdgesHelper;
  29439. exports.EllipseCurve = EllipseCurve;
  29440. exports.EqualDepth = EqualDepth;
  29441. exports.EqualStencilFunc = EqualStencilFunc;
  29442. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  29443. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  29444. exports.Euler = Euler;
  29445. exports.EventDispatcher = EventDispatcher;
  29446. exports.ExtrudeBufferGeometry = ExtrudeGeometry;
  29447. exports.ExtrudeGeometry = ExtrudeGeometry;
  29448. exports.FaceColors = FaceColors;
  29449. exports.FileLoader = FileLoader;
  29450. exports.FlatShading = FlatShading;
  29451. exports.Float16BufferAttribute = Float16BufferAttribute;
  29452. exports.Float32Attribute = Float32Attribute;
  29453. exports.Float32BufferAttribute = Float32BufferAttribute;
  29454. exports.Float64Attribute = Float64Attribute;
  29455. exports.Float64BufferAttribute = Float64BufferAttribute;
  29456. exports.FloatType = FloatType;
  29457. exports.Fog = Fog;
  29458. exports.FogExp2 = FogExp2;
  29459. exports.Font = Font;
  29460. exports.FontLoader = FontLoader;
  29461. exports.FramebufferTexture = FramebufferTexture;
  29462. exports.FrontSide = FrontSide;
  29463. exports.Frustum = Frustum;
  29464. exports.GLBufferAttribute = GLBufferAttribute;
  29465. exports.GLSL1 = GLSL1;
  29466. exports.GLSL3 = GLSL3;
  29467. exports.GammaEncoding = GammaEncoding;
  29468. exports.GreaterDepth = GreaterDepth;
  29469. exports.GreaterEqualDepth = GreaterEqualDepth;
  29470. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  29471. exports.GreaterStencilFunc = GreaterStencilFunc;
  29472. exports.GridHelper = GridHelper;
  29473. exports.Group = Group;
  29474. exports.HalfFloatType = HalfFloatType;
  29475. exports.HemisphereLight = HemisphereLight;
  29476. exports.HemisphereLightHelper = HemisphereLightHelper;
  29477. exports.HemisphereLightProbe = HemisphereLightProbe;
  29478. exports.IcosahedronBufferGeometry = IcosahedronGeometry;
  29479. exports.IcosahedronGeometry = IcosahedronGeometry;
  29480. exports.ImageBitmapLoader = ImageBitmapLoader;
  29481. exports.ImageLoader = ImageLoader;
  29482. exports.ImageUtils = ImageUtils;
  29483. exports.ImmediateRenderObject = ImmediateRenderObject;
  29484. exports.IncrementStencilOp = IncrementStencilOp;
  29485. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  29486. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  29487. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  29488. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  29489. exports.InstancedMesh = InstancedMesh;
  29490. exports.Int16Attribute = Int16Attribute;
  29491. exports.Int16BufferAttribute = Int16BufferAttribute;
  29492. exports.Int32Attribute = Int32Attribute;
  29493. exports.Int32BufferAttribute = Int32BufferAttribute;
  29494. exports.Int8Attribute = Int8Attribute;
  29495. exports.Int8BufferAttribute = Int8BufferAttribute;
  29496. exports.IntType = IntType;
  29497. exports.InterleavedBuffer = InterleavedBuffer;
  29498. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  29499. exports.Interpolant = Interpolant;
  29500. exports.InterpolateDiscrete = InterpolateDiscrete;
  29501. exports.InterpolateLinear = InterpolateLinear;
  29502. exports.InterpolateSmooth = InterpolateSmooth;
  29503. exports.InvertStencilOp = InvertStencilOp;
  29504. exports.JSONLoader = JSONLoader;
  29505. exports.KeepStencilOp = KeepStencilOp;
  29506. exports.KeyframeTrack = KeyframeTrack;
  29507. exports.LOD = LOD;
  29508. exports.LatheBufferGeometry = LatheGeometry;
  29509. exports.LatheGeometry = LatheGeometry;
  29510. exports.Layers = Layers;
  29511. exports.LensFlare = LensFlare;
  29512. exports.LessDepth = LessDepth;
  29513. exports.LessEqualDepth = LessEqualDepth;
  29514. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  29515. exports.LessStencilFunc = LessStencilFunc;
  29516. exports.Light = Light;
  29517. exports.LightProbe = LightProbe;
  29518. exports.Line = Line;
  29519. exports.Line3 = Line3;
  29520. exports.LineBasicMaterial = LineBasicMaterial;
  29521. exports.LineCurve = LineCurve;
  29522. exports.LineCurve3 = LineCurve3;
  29523. exports.LineDashedMaterial = LineDashedMaterial;
  29524. exports.LineLoop = LineLoop;
  29525. exports.LinePieces = LinePieces;
  29526. exports.LineSegments = LineSegments;
  29527. exports.LineStrip = LineStrip;
  29528. exports.LinearEncoding = LinearEncoding;
  29529. exports.LinearFilter = LinearFilter;
  29530. exports.LinearInterpolant = LinearInterpolant;
  29531. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  29532. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  29533. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  29534. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  29535. exports.LinearToneMapping = LinearToneMapping;
  29536. exports.Loader = Loader;
  29537. exports.LoaderUtils = LoaderUtils;
  29538. exports.LoadingManager = LoadingManager;
  29539. exports.LoopOnce = LoopOnce;
  29540. exports.LoopPingPong = LoopPingPong;
  29541. exports.LoopRepeat = LoopRepeat;
  29542. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  29543. exports.LuminanceFormat = LuminanceFormat;
  29544. exports.MOUSE = MOUSE;
  29545. exports.Material = Material;
  29546. exports.MaterialLoader = MaterialLoader;
  29547. exports.Math = MathUtils;
  29548. exports.MathUtils = MathUtils;
  29549. exports.Matrix3 = Matrix3;
  29550. exports.Matrix4 = Matrix4;
  29551. exports.MaxEquation = MaxEquation;
  29552. exports.Mesh = Mesh;
  29553. exports.MeshBasicMaterial = MeshBasicMaterial;
  29554. exports.MeshDepthMaterial = MeshDepthMaterial;
  29555. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  29556. exports.MeshFaceMaterial = MeshFaceMaterial;
  29557. exports.MeshLambertMaterial = MeshLambertMaterial;
  29558. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  29559. exports.MeshNormalMaterial = MeshNormalMaterial;
  29560. exports.MeshPhongMaterial = MeshPhongMaterial;
  29561. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  29562. exports.MeshStandardMaterial = MeshStandardMaterial;
  29563. exports.MeshToonMaterial = MeshToonMaterial;
  29564. exports.MinEquation = MinEquation;
  29565. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  29566. exports.MixOperation = MixOperation;
  29567. exports.MultiMaterial = MultiMaterial;
  29568. exports.MultiplyBlending = MultiplyBlending;
  29569. exports.MultiplyOperation = MultiplyOperation;
  29570. exports.NearestFilter = NearestFilter;
  29571. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  29572. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  29573. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  29574. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  29575. exports.NeverDepth = NeverDepth;
  29576. exports.NeverStencilFunc = NeverStencilFunc;
  29577. exports.NoBlending = NoBlending;
  29578. exports.NoColors = NoColors;
  29579. exports.NoToneMapping = NoToneMapping;
  29580. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  29581. exports.NormalBlending = NormalBlending;
  29582. exports.NotEqualDepth = NotEqualDepth;
  29583. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  29584. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  29585. exports.Object3D = Object3D;
  29586. exports.ObjectLoader = ObjectLoader;
  29587. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  29588. exports.OctahedronBufferGeometry = OctahedronGeometry;
  29589. exports.OctahedronGeometry = OctahedronGeometry;
  29590. exports.OneFactor = OneFactor;
  29591. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  29592. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  29593. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  29594. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  29595. exports.OrthographicCamera = OrthographicCamera;
  29596. exports.PCFShadowMap = PCFShadowMap;
  29597. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  29598. exports.PMREMGenerator = PMREMGenerator;
  29599. exports.ParametricGeometry = ParametricGeometry;
  29600. exports.Particle = Particle;
  29601. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  29602. exports.ParticleSystem = ParticleSystem;
  29603. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  29604. exports.Path = Path;
  29605. exports.PerspectiveCamera = PerspectiveCamera;
  29606. exports.Plane = Plane;
  29607. exports.PlaneBufferGeometry = PlaneGeometry;
  29608. exports.PlaneGeometry = PlaneGeometry;
  29609. exports.PlaneHelper = PlaneHelper;
  29610. exports.PointCloud = PointCloud;
  29611. exports.PointCloudMaterial = PointCloudMaterial;
  29612. exports.PointLight = PointLight;
  29613. exports.PointLightHelper = PointLightHelper;
  29614. exports.Points = Points;
  29615. exports.PointsMaterial = PointsMaterial;
  29616. exports.PolarGridHelper = PolarGridHelper;
  29617. exports.PolyhedronBufferGeometry = PolyhedronGeometry;
  29618. exports.PolyhedronGeometry = PolyhedronGeometry;
  29619. exports.PositionalAudio = PositionalAudio;
  29620. exports.PropertyBinding = PropertyBinding;
  29621. exports.PropertyMixer = PropertyMixer;
  29622. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  29623. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  29624. exports.Quaternion = Quaternion;
  29625. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  29626. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  29627. exports.REVISION = REVISION;
  29628. exports.RGBADepthPacking = RGBADepthPacking;
  29629. exports.RGBAFormat = RGBAFormat;
  29630. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  29631. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  29632. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  29633. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  29634. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  29635. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  29636. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  29637. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  29638. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  29639. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  29640. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  29641. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  29642. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  29643. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  29644. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  29645. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  29646. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  29647. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  29648. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  29649. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  29650. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  29651. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  29652. exports.RGBDEncoding = RGBDEncoding;
  29653. exports.RGBEEncoding = RGBEEncoding;
  29654. exports.RGBEFormat = RGBEFormat;
  29655. exports.RGBFormat = RGBFormat;
  29656. exports.RGBIntegerFormat = RGBIntegerFormat;
  29657. exports.RGBM16Encoding = RGBM16Encoding;
  29658. exports.RGBM7Encoding = RGBM7Encoding;
  29659. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  29660. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  29661. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  29662. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  29663. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  29664. exports.RGFormat = RGFormat;
  29665. exports.RGIntegerFormat = RGIntegerFormat;
  29666. exports.RawShaderMaterial = RawShaderMaterial;
  29667. exports.Ray = Ray;
  29668. exports.Raycaster = Raycaster;
  29669. exports.RectAreaLight = RectAreaLight;
  29670. exports.RedFormat = RedFormat;
  29671. exports.RedIntegerFormat = RedIntegerFormat;
  29672. exports.ReinhardToneMapping = ReinhardToneMapping;
  29673. exports.RepeatWrapping = RepeatWrapping;
  29674. exports.ReplaceStencilOp = ReplaceStencilOp;
  29675. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  29676. exports.RingBufferGeometry = RingGeometry;
  29677. exports.RingGeometry = RingGeometry;
  29678. exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
  29679. exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
  29680. exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
  29681. exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
  29682. exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
  29683. exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
  29684. exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
  29685. exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
  29686. exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
  29687. exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
  29688. exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
  29689. exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
  29690. exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
  29691. exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
  29692. exports.Scene = Scene;
  29693. exports.SceneUtils = SceneUtils;
  29694. exports.ShaderChunk = ShaderChunk;
  29695. exports.ShaderLib = ShaderLib;
  29696. exports.ShaderMaterial = ShaderMaterial;
  29697. exports.ShadowMaterial = ShadowMaterial;
  29698. exports.Shape = Shape;
  29699. exports.ShapeBufferGeometry = ShapeGeometry;
  29700. exports.ShapeGeometry = ShapeGeometry;
  29701. exports.ShapePath = ShapePath;
  29702. exports.ShapeUtils = ShapeUtils;
  29703. exports.ShortType = ShortType;
  29704. exports.Skeleton = Skeleton;
  29705. exports.SkeletonHelper = SkeletonHelper;
  29706. exports.SkinnedMesh = SkinnedMesh;
  29707. exports.SmoothShading = SmoothShading;
  29708. exports.Sphere = Sphere;
  29709. exports.SphereBufferGeometry = SphereGeometry;
  29710. exports.SphereGeometry = SphereGeometry;
  29711. exports.Spherical = Spherical;
  29712. exports.SphericalHarmonics3 = SphericalHarmonics3;
  29713. exports.SplineCurve = SplineCurve;
  29714. exports.SpotLight = SpotLight;
  29715. exports.SpotLightHelper = SpotLightHelper;
  29716. exports.Sprite = Sprite;
  29717. exports.SpriteMaterial = SpriteMaterial;
  29718. exports.SrcAlphaFactor = SrcAlphaFactor;
  29719. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  29720. exports.SrcColorFactor = SrcColorFactor;
  29721. exports.StaticCopyUsage = StaticCopyUsage;
  29722. exports.StaticDrawUsage = StaticDrawUsage;
  29723. exports.StaticReadUsage = StaticReadUsage;
  29724. exports.StereoCamera = StereoCamera;
  29725. exports.StreamCopyUsage = StreamCopyUsage;
  29726. exports.StreamDrawUsage = StreamDrawUsage;
  29727. exports.StreamReadUsage = StreamReadUsage;
  29728. exports.StringKeyframeTrack = StringKeyframeTrack;
  29729. exports.SubtractEquation = SubtractEquation;
  29730. exports.SubtractiveBlending = SubtractiveBlending;
  29731. exports.TOUCH = TOUCH;
  29732. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  29733. exports.TetrahedronBufferGeometry = TetrahedronGeometry;
  29734. exports.TetrahedronGeometry = TetrahedronGeometry;
  29735. exports.TextGeometry = TextGeometry;
  29736. exports.Texture = Texture;
  29737. exports.TextureLoader = TextureLoader;
  29738. exports.TorusBufferGeometry = TorusGeometry;
  29739. exports.TorusGeometry = TorusGeometry;
  29740. exports.TorusKnotBufferGeometry = TorusKnotGeometry;
  29741. exports.TorusKnotGeometry = TorusKnotGeometry;
  29742. exports.Triangle = Triangle;
  29743. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  29744. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  29745. exports.TrianglesDrawMode = TrianglesDrawMode;
  29746. exports.TubeBufferGeometry = TubeGeometry;
  29747. exports.TubeGeometry = TubeGeometry;
  29748. exports.UVMapping = UVMapping;
  29749. exports.Uint16Attribute = Uint16Attribute;
  29750. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  29751. exports.Uint32Attribute = Uint32Attribute;
  29752. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  29753. exports.Uint8Attribute = Uint8Attribute;
  29754. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  29755. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  29756. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  29757. exports.Uniform = Uniform;
  29758. exports.UniformsLib = UniformsLib;
  29759. exports.UniformsUtils = UniformsUtils;
  29760. exports.UnsignedByteType = UnsignedByteType;
  29761. exports.UnsignedInt248Type = UnsignedInt248Type;
  29762. exports.UnsignedIntType = UnsignedIntType;
  29763. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  29764. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  29765. exports.UnsignedShort565Type = UnsignedShort565Type;
  29766. exports.UnsignedShortType = UnsignedShortType;
  29767. exports.VSMShadowMap = VSMShadowMap;
  29768. exports.Vector2 = Vector2;
  29769. exports.Vector3 = Vector3;
  29770. exports.Vector4 = Vector4;
  29771. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  29772. exports.Vertex = Vertex;
  29773. exports.VertexColors = VertexColors;
  29774. exports.VideoTexture = VideoTexture;
  29775. exports.WebGL1Renderer = WebGL1Renderer;
  29776. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  29777. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  29778. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  29779. exports.WebGLRenderTarget = WebGLRenderTarget;
  29780. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  29781. exports.WebGLRenderer = WebGLRenderer;
  29782. exports.WebGLUtils = WebGLUtils;
  29783. exports.WireframeGeometry = WireframeGeometry;
  29784. exports.WireframeHelper = WireframeHelper;
  29785. exports.WrapAroundEnding = WrapAroundEnding;
  29786. exports.XHRLoader = XHRLoader;
  29787. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  29788. exports.ZeroFactor = ZeroFactor;
  29789. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  29790. exports.ZeroStencilOp = ZeroStencilOp;
  29791. exports.sRGBEncoding = sRGBEncoding;
  29792. Object.defineProperty(exports, '__esModule', { value: true });
  29793. }));
粤ICP备19079148号