three.js 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996
  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 = '128';
  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 LogLuvEncoding = 3003;
  183. const RGBM7Encoding = 3004;
  184. const RGBM16Encoding = 3005;
  185. const RGBDEncoding = 3006;
  186. const BasicDepthPacking = 3200;
  187. const RGBADepthPacking = 3201;
  188. const TangentSpaceNormalMap = 0;
  189. const ObjectSpaceNormalMap = 1;
  190. const ZeroStencilOp = 0;
  191. const KeepStencilOp = 7680;
  192. const ReplaceStencilOp = 7681;
  193. const IncrementStencilOp = 7682;
  194. const DecrementStencilOp = 7683;
  195. const IncrementWrapStencilOp = 34055;
  196. const DecrementWrapStencilOp = 34056;
  197. const InvertStencilOp = 5386;
  198. const NeverStencilFunc = 512;
  199. const LessStencilFunc = 513;
  200. const EqualStencilFunc = 514;
  201. const LessEqualStencilFunc = 515;
  202. const GreaterStencilFunc = 516;
  203. const NotEqualStencilFunc = 517;
  204. const GreaterEqualStencilFunc = 518;
  205. const AlwaysStencilFunc = 519;
  206. const StaticDrawUsage = 35044;
  207. const DynamicDrawUsage = 35048;
  208. const StreamDrawUsage = 35040;
  209. const StaticReadUsage = 35045;
  210. const DynamicReadUsage = 35049;
  211. const StreamReadUsage = 35041;
  212. const StaticCopyUsage = 35046;
  213. const DynamicCopyUsage = 35050;
  214. const StreamCopyUsage = 35042;
  215. const GLSL1 = '100';
  216. const GLSL3 = '300 es';
  217. /**
  218. * https://github.com/mrdoob/eventdispatcher.js/
  219. */
  220. class EventDispatcher {
  221. addEventListener(type, listener) {
  222. if (this._listeners === undefined) this._listeners = {};
  223. const listeners = this._listeners;
  224. if (listeners[type] === undefined) {
  225. listeners[type] = [];
  226. }
  227. if (listeners[type].indexOf(listener) === -1) {
  228. listeners[type].push(listener);
  229. }
  230. }
  231. hasEventListener(type, listener) {
  232. if (this._listeners === undefined) return false;
  233. const listeners = this._listeners;
  234. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  235. }
  236. removeEventListener(type, listener) {
  237. if (this._listeners === undefined) return;
  238. const listeners = this._listeners;
  239. const listenerArray = listeners[type];
  240. if (listenerArray !== undefined) {
  241. const index = listenerArray.indexOf(listener);
  242. if (index !== -1) {
  243. listenerArray.splice(index, 1);
  244. }
  245. }
  246. }
  247. dispatchEvent(event) {
  248. if (this._listeners === undefined) return;
  249. const listeners = this._listeners;
  250. const listenerArray = listeners[event.type];
  251. if (listenerArray !== undefined) {
  252. event.target = this; // Make a copy, in case listeners are removed while iterating.
  253. const array = listenerArray.slice(0);
  254. for (let i = 0, l = array.length; i < l; i++) {
  255. array[i].call(this, event);
  256. }
  257. event.target = null;
  258. }
  259. }
  260. }
  261. const _lut = [];
  262. for (let i = 0; i < 256; i++) {
  263. _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
  264. }
  265. let _seed = 1234567;
  266. const DEG2RAD = Math.PI / 180;
  267. const RAD2DEG = 180 / Math.PI; // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  268. function generateUUID() {
  269. const d0 = Math.random() * 0xffffffff | 0;
  270. const d1 = Math.random() * 0xffffffff | 0;
  271. const d2 = Math.random() * 0xffffffff | 0;
  272. const d3 = Math.random() * 0xffffffff | 0;
  273. 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.
  274. return uuid.toUpperCase();
  275. }
  276. function clamp(value, min, max) {
  277. return Math.max(min, Math.min(max, value));
  278. } // compute euclidian modulo of m % n
  279. // https://en.wikipedia.org/wiki/Modulo_operation
  280. function euclideanModulo(n, m) {
  281. return (n % m + m) % m;
  282. } // Linear mapping from range <a1, a2> to range <b1, b2>
  283. function mapLinear(x, a1, a2, b1, b2) {
  284. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  285. } // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  286. function inverseLerp(x, y, value) {
  287. if (x !== y) {
  288. return (value - x) / (y - x);
  289. } else {
  290. return 0;
  291. }
  292. } // https://en.wikipedia.org/wiki/Linear_interpolation
  293. function lerp(x, y, t) {
  294. return (1 - t) * x + t * y;
  295. } // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  296. function damp(x, y, lambda, dt) {
  297. return lerp(x, y, 1 - Math.exp(-lambda * dt));
  298. } // https://www.desmos.com/calculator/vcsjnyz7x4
  299. function pingpong(x, length = 1) {
  300. return length - Math.abs(euclideanModulo(x, length * 2) - length);
  301. } // http://en.wikipedia.org/wiki/Smoothstep
  302. function smoothstep(x, min, max) {
  303. if (x <= min) return 0;
  304. if (x >= max) return 1;
  305. x = (x - min) / (max - min);
  306. return x * x * (3 - 2 * x);
  307. }
  308. function smootherstep(x, min, max) {
  309. if (x <= min) return 0;
  310. if (x >= max) return 1;
  311. x = (x - min) / (max - min);
  312. return x * x * x * (x * (x * 6 - 15) + 10);
  313. } // Random integer from <low, high> interval
  314. function randInt(low, high) {
  315. return low + Math.floor(Math.random() * (high - low + 1));
  316. } // Random float from <low, high> interval
  317. function randFloat(low, high) {
  318. return low + Math.random() * (high - low);
  319. } // Random float from <-range/2, range/2> interval
  320. function randFloatSpread(range) {
  321. return range * (0.5 - Math.random());
  322. } // Deterministic pseudo-random float in the interval [ 0, 1 ]
  323. function seededRandom(s) {
  324. if (s !== undefined) _seed = s % 2147483647; // Park-Miller algorithm
  325. _seed = _seed * 16807 % 2147483647;
  326. return (_seed - 1) / 2147483646;
  327. }
  328. function degToRad(degrees) {
  329. return degrees * DEG2RAD;
  330. }
  331. function radToDeg(radians) {
  332. return radians * RAD2DEG;
  333. }
  334. function isPowerOfTwo(value) {
  335. return (value & value - 1) === 0 && value !== 0;
  336. }
  337. function ceilPowerOfTwo(value) {
  338. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  339. }
  340. function floorPowerOfTwo(value) {
  341. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  342. }
  343. function setQuaternionFromProperEuler(q, a, b, c, order) {
  344. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  345. // rotations are applied to the axes in the order specified by 'order'
  346. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  347. // angles are in radians
  348. const cos = Math.cos;
  349. const sin = Math.sin;
  350. const c2 = cos(b / 2);
  351. const s2 = sin(b / 2);
  352. const c13 = cos((a + c) / 2);
  353. const s13 = sin((a + c) / 2);
  354. const c1_3 = cos((a - c) / 2);
  355. const s1_3 = sin((a - c) / 2);
  356. const c3_1 = cos((c - a) / 2);
  357. const s3_1 = sin((c - a) / 2);
  358. switch (order) {
  359. case 'XYX':
  360. q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
  361. break;
  362. case 'YZY':
  363. q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
  364. break;
  365. case 'ZXZ':
  366. q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
  367. break;
  368. case 'XZX':
  369. q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
  370. break;
  371. case 'YXY':
  372. q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
  373. break;
  374. case 'ZYZ':
  375. q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
  376. break;
  377. default:
  378. console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order);
  379. }
  380. }
  381. var MathUtils = /*#__PURE__*/Object.freeze({
  382. __proto__: null,
  383. DEG2RAD: DEG2RAD,
  384. RAD2DEG: RAD2DEG,
  385. generateUUID: generateUUID,
  386. clamp: clamp,
  387. euclideanModulo: euclideanModulo,
  388. mapLinear: mapLinear,
  389. inverseLerp: inverseLerp,
  390. lerp: lerp,
  391. damp: damp,
  392. pingpong: pingpong,
  393. smoothstep: smoothstep,
  394. smootherstep: smootherstep,
  395. randInt: randInt,
  396. randFloat: randFloat,
  397. randFloatSpread: randFloatSpread,
  398. seededRandom: seededRandom,
  399. degToRad: degToRad,
  400. radToDeg: radToDeg,
  401. isPowerOfTwo: isPowerOfTwo,
  402. ceilPowerOfTwo: ceilPowerOfTwo,
  403. floorPowerOfTwo: floorPowerOfTwo,
  404. setQuaternionFromProperEuler: setQuaternionFromProperEuler
  405. });
  406. class Vector2 {
  407. constructor(x = 0, y = 0) {
  408. this.x = x;
  409. this.y = y;
  410. }
  411. get width() {
  412. return this.x;
  413. }
  414. set width(value) {
  415. this.x = value;
  416. }
  417. get height() {
  418. return this.y;
  419. }
  420. set height(value) {
  421. this.y = value;
  422. }
  423. set(x, y) {
  424. this.x = x;
  425. this.y = y;
  426. return this;
  427. }
  428. setScalar(scalar) {
  429. this.x = scalar;
  430. this.y = scalar;
  431. return this;
  432. }
  433. setX(x) {
  434. this.x = x;
  435. return this;
  436. }
  437. setY(y) {
  438. this.y = y;
  439. return this;
  440. }
  441. setComponent(index, value) {
  442. switch (index) {
  443. case 0:
  444. this.x = value;
  445. break;
  446. case 1:
  447. this.y = value;
  448. break;
  449. default:
  450. throw new Error('index is out of range: ' + index);
  451. }
  452. return this;
  453. }
  454. getComponent(index) {
  455. switch (index) {
  456. case 0:
  457. return this.x;
  458. case 1:
  459. return this.y;
  460. default:
  461. throw new Error('index is out of range: ' + index);
  462. }
  463. }
  464. clone() {
  465. return new this.constructor(this.x, this.y);
  466. }
  467. copy(v) {
  468. this.x = v.x;
  469. this.y = v.y;
  470. return this;
  471. }
  472. add(v, w) {
  473. if (w !== undefined) {
  474. console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  475. return this.addVectors(v, w);
  476. }
  477. this.x += v.x;
  478. this.y += v.y;
  479. return this;
  480. }
  481. addScalar(s) {
  482. this.x += s;
  483. this.y += s;
  484. return this;
  485. }
  486. addVectors(a, b) {
  487. this.x = a.x + b.x;
  488. this.y = a.y + b.y;
  489. return this;
  490. }
  491. addScaledVector(v, s) {
  492. this.x += v.x * s;
  493. this.y += v.y * s;
  494. return this;
  495. }
  496. sub(v, w) {
  497. if (w !== undefined) {
  498. console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  499. return this.subVectors(v, w);
  500. }
  501. this.x -= v.x;
  502. this.y -= v.y;
  503. return this;
  504. }
  505. subScalar(s) {
  506. this.x -= s;
  507. this.y -= s;
  508. return this;
  509. }
  510. subVectors(a, b) {
  511. this.x = a.x - b.x;
  512. this.y = a.y - b.y;
  513. return this;
  514. }
  515. multiply(v) {
  516. this.x *= v.x;
  517. this.y *= v.y;
  518. return this;
  519. }
  520. multiplyScalar(scalar) {
  521. this.x *= scalar;
  522. this.y *= scalar;
  523. return this;
  524. }
  525. divide(v) {
  526. this.x /= v.x;
  527. this.y /= v.y;
  528. return this;
  529. }
  530. divideScalar(scalar) {
  531. return this.multiplyScalar(1 / scalar);
  532. }
  533. applyMatrix3(m) {
  534. const x = this.x,
  535. y = this.y;
  536. const e = m.elements;
  537. this.x = e[0] * x + e[3] * y + e[6];
  538. this.y = e[1] * x + e[4] * y + e[7];
  539. return this;
  540. }
  541. min(v) {
  542. this.x = Math.min(this.x, v.x);
  543. this.y = Math.min(this.y, v.y);
  544. return this;
  545. }
  546. max(v) {
  547. this.x = Math.max(this.x, v.x);
  548. this.y = Math.max(this.y, v.y);
  549. return this;
  550. }
  551. clamp(min, max) {
  552. // assumes min < max, componentwise
  553. this.x = Math.max(min.x, Math.min(max.x, this.x));
  554. this.y = Math.max(min.y, Math.min(max.y, this.y));
  555. return this;
  556. }
  557. clampScalar(minVal, maxVal) {
  558. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  559. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  560. return this;
  561. }
  562. clampLength(min, max) {
  563. const length = this.length();
  564. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  565. }
  566. floor() {
  567. this.x = Math.floor(this.x);
  568. this.y = Math.floor(this.y);
  569. return this;
  570. }
  571. ceil() {
  572. this.x = Math.ceil(this.x);
  573. this.y = Math.ceil(this.y);
  574. return this;
  575. }
  576. round() {
  577. this.x = Math.round(this.x);
  578. this.y = Math.round(this.y);
  579. return this;
  580. }
  581. roundToZero() {
  582. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  583. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  584. return this;
  585. }
  586. negate() {
  587. this.x = -this.x;
  588. this.y = -this.y;
  589. return this;
  590. }
  591. dot(v) {
  592. return this.x * v.x + this.y * v.y;
  593. }
  594. cross(v) {
  595. return this.x * v.y - this.y * v.x;
  596. }
  597. lengthSq() {
  598. return this.x * this.x + this.y * this.y;
  599. }
  600. length() {
  601. return Math.sqrt(this.x * this.x + this.y * this.y);
  602. }
  603. manhattanLength() {
  604. return Math.abs(this.x) + Math.abs(this.y);
  605. }
  606. normalize() {
  607. return this.divideScalar(this.length() || 1);
  608. }
  609. angle() {
  610. // computes the angle in radians with respect to the positive x-axis
  611. const angle = Math.atan2(-this.y, -this.x) + Math.PI;
  612. return angle;
  613. }
  614. distanceTo(v) {
  615. return Math.sqrt(this.distanceToSquared(v));
  616. }
  617. distanceToSquared(v) {
  618. const dx = this.x - v.x,
  619. dy = this.y - v.y;
  620. return dx * dx + dy * dy;
  621. }
  622. manhattanDistanceTo(v) {
  623. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  624. }
  625. setLength(length) {
  626. return this.normalize().multiplyScalar(length);
  627. }
  628. lerp(v, alpha) {
  629. this.x += (v.x - this.x) * alpha;
  630. this.y += (v.y - this.y) * alpha;
  631. return this;
  632. }
  633. lerpVectors(v1, v2, alpha) {
  634. this.x = v1.x + (v2.x - v1.x) * alpha;
  635. this.y = v1.y + (v2.y - v1.y) * alpha;
  636. return this;
  637. }
  638. equals(v) {
  639. return v.x === this.x && v.y === this.y;
  640. }
  641. fromArray(array, offset = 0) {
  642. this.x = array[offset];
  643. this.y = array[offset + 1];
  644. return this;
  645. }
  646. toArray(array = [], offset = 0) {
  647. array[offset] = this.x;
  648. array[offset + 1] = this.y;
  649. return array;
  650. }
  651. fromBufferAttribute(attribute, index, offset) {
  652. if (offset !== undefined) {
  653. console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
  654. }
  655. this.x = attribute.getX(index);
  656. this.y = attribute.getY(index);
  657. return this;
  658. }
  659. rotateAround(center, angle) {
  660. const c = Math.cos(angle),
  661. s = Math.sin(angle);
  662. const x = this.x - center.x;
  663. const y = this.y - center.y;
  664. this.x = x * c - y * s + center.x;
  665. this.y = x * s + y * c + center.y;
  666. return this;
  667. }
  668. random() {
  669. this.x = Math.random();
  670. this.y = Math.random();
  671. return this;
  672. }
  673. }
  674. Vector2.prototype.isVector2 = true;
  675. class Matrix3 {
  676. constructor() {
  677. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  678. if (arguments.length > 0) {
  679. console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
  680. }
  681. }
  682. set(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  683. const te = this.elements;
  684. te[0] = n11;
  685. te[1] = n21;
  686. te[2] = n31;
  687. te[3] = n12;
  688. te[4] = n22;
  689. te[5] = n32;
  690. te[6] = n13;
  691. te[7] = n23;
  692. te[8] = n33;
  693. return this;
  694. }
  695. identity() {
  696. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  697. return this;
  698. }
  699. copy(m) {
  700. const te = this.elements;
  701. const me = m.elements;
  702. te[0] = me[0];
  703. te[1] = me[1];
  704. te[2] = me[2];
  705. te[3] = me[3];
  706. te[4] = me[4];
  707. te[5] = me[5];
  708. te[6] = me[6];
  709. te[7] = me[7];
  710. te[8] = me[8];
  711. return this;
  712. }
  713. extractBasis(xAxis, yAxis, zAxis) {
  714. xAxis.setFromMatrix3Column(this, 0);
  715. yAxis.setFromMatrix3Column(this, 1);
  716. zAxis.setFromMatrix3Column(this, 2);
  717. return this;
  718. }
  719. setFromMatrix4(m) {
  720. const me = m.elements;
  721. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  722. return this;
  723. }
  724. multiply(m) {
  725. return this.multiplyMatrices(this, m);
  726. }
  727. premultiply(m) {
  728. return this.multiplyMatrices(m, this);
  729. }
  730. multiplyMatrices(a, b) {
  731. const ae = a.elements;
  732. const be = b.elements;
  733. const te = this.elements;
  734. const a11 = ae[0],
  735. a12 = ae[3],
  736. a13 = ae[6];
  737. const a21 = ae[1],
  738. a22 = ae[4],
  739. a23 = ae[7];
  740. const a31 = ae[2],
  741. a32 = ae[5],
  742. a33 = ae[8];
  743. const b11 = be[0],
  744. b12 = be[3],
  745. b13 = be[6];
  746. const b21 = be[1],
  747. b22 = be[4],
  748. b23 = be[7];
  749. const b31 = be[2],
  750. b32 = be[5],
  751. b33 = be[8];
  752. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  753. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  754. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  755. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  756. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  757. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  758. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  759. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  760. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  761. return this;
  762. }
  763. multiplyScalar(s) {
  764. const te = this.elements;
  765. te[0] *= s;
  766. te[3] *= s;
  767. te[6] *= s;
  768. te[1] *= s;
  769. te[4] *= s;
  770. te[7] *= s;
  771. te[2] *= s;
  772. te[5] *= s;
  773. te[8] *= s;
  774. return this;
  775. }
  776. determinant() {
  777. const te = this.elements;
  778. const a = te[0],
  779. b = te[1],
  780. c = te[2],
  781. d = te[3],
  782. e = te[4],
  783. f = te[5],
  784. g = te[6],
  785. h = te[7],
  786. i = te[8];
  787. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  788. }
  789. invert() {
  790. const te = this.elements,
  791. n11 = te[0],
  792. n21 = te[1],
  793. n31 = te[2],
  794. n12 = te[3],
  795. n22 = te[4],
  796. n32 = te[5],
  797. n13 = te[6],
  798. n23 = te[7],
  799. n33 = te[8],
  800. t11 = n33 * n22 - n32 * n23,
  801. t12 = n32 * n13 - n33 * n12,
  802. t13 = n23 * n12 - n22 * n13,
  803. det = n11 * t11 + n21 * t12 + n31 * t13;
  804. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  805. const detInv = 1 / det;
  806. te[0] = t11 * detInv;
  807. te[1] = (n31 * n23 - n33 * n21) * detInv;
  808. te[2] = (n32 * n21 - n31 * n22) * detInv;
  809. te[3] = t12 * detInv;
  810. te[4] = (n33 * n11 - n31 * n13) * detInv;
  811. te[5] = (n31 * n12 - n32 * n11) * detInv;
  812. te[6] = t13 * detInv;
  813. te[7] = (n21 * n13 - n23 * n11) * detInv;
  814. te[8] = (n22 * n11 - n21 * n12) * detInv;
  815. return this;
  816. }
  817. transpose() {
  818. let tmp;
  819. const m = this.elements;
  820. tmp = m[1];
  821. m[1] = m[3];
  822. m[3] = tmp;
  823. tmp = m[2];
  824. m[2] = m[6];
  825. m[6] = tmp;
  826. tmp = m[5];
  827. m[5] = m[7];
  828. m[7] = tmp;
  829. return this;
  830. }
  831. getNormalMatrix(matrix4) {
  832. return this.setFromMatrix4(matrix4).invert().transpose();
  833. }
  834. transposeIntoArray(r) {
  835. const m = this.elements;
  836. r[0] = m[0];
  837. r[1] = m[3];
  838. r[2] = m[6];
  839. r[3] = m[1];
  840. r[4] = m[4];
  841. r[5] = m[7];
  842. r[6] = m[2];
  843. r[7] = m[5];
  844. r[8] = m[8];
  845. return this;
  846. }
  847. setUvTransform(tx, ty, sx, sy, rotation, cx, cy) {
  848. const c = Math.cos(rotation);
  849. const s = Math.sin(rotation);
  850. 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);
  851. return this;
  852. }
  853. scale(sx, sy) {
  854. const te = this.elements;
  855. te[0] *= sx;
  856. te[3] *= sx;
  857. te[6] *= sx;
  858. te[1] *= sy;
  859. te[4] *= sy;
  860. te[7] *= sy;
  861. return this;
  862. }
  863. rotate(theta) {
  864. const c = Math.cos(theta);
  865. const s = Math.sin(theta);
  866. const te = this.elements;
  867. const a11 = te[0],
  868. a12 = te[3],
  869. a13 = te[6];
  870. const a21 = te[1],
  871. a22 = te[4],
  872. a23 = te[7];
  873. te[0] = c * a11 + s * a21;
  874. te[3] = c * a12 + s * a22;
  875. te[6] = c * a13 + s * a23;
  876. te[1] = -s * a11 + c * a21;
  877. te[4] = -s * a12 + c * a22;
  878. te[7] = -s * a13 + c * a23;
  879. return this;
  880. }
  881. translate(tx, ty) {
  882. const te = this.elements;
  883. te[0] += tx * te[2];
  884. te[3] += tx * te[5];
  885. te[6] += tx * te[8];
  886. te[1] += ty * te[2];
  887. te[4] += ty * te[5];
  888. te[7] += ty * te[8];
  889. return this;
  890. }
  891. equals(matrix) {
  892. const te = this.elements;
  893. const me = matrix.elements;
  894. for (let i = 0; i < 9; i++) {
  895. if (te[i] !== me[i]) return false;
  896. }
  897. return true;
  898. }
  899. fromArray(array, offset = 0) {
  900. for (let i = 0; i < 9; i++) {
  901. this.elements[i] = array[i + offset];
  902. }
  903. return this;
  904. }
  905. toArray(array = [], offset = 0) {
  906. const te = this.elements;
  907. array[offset] = te[0];
  908. array[offset + 1] = te[1];
  909. array[offset + 2] = te[2];
  910. array[offset + 3] = te[3];
  911. array[offset + 4] = te[4];
  912. array[offset + 5] = te[5];
  913. array[offset + 6] = te[6];
  914. array[offset + 7] = te[7];
  915. array[offset + 8] = te[8];
  916. return array;
  917. }
  918. clone() {
  919. return new this.constructor().fromArray(this.elements);
  920. }
  921. }
  922. Matrix3.prototype.isMatrix3 = true;
  923. let _canvas;
  924. class ImageUtils {
  925. static getDataURL(image) {
  926. if (/^data:/i.test(image.src)) {
  927. return image.src;
  928. }
  929. if (typeof HTMLCanvasElement == 'undefined') {
  930. return image.src;
  931. }
  932. let canvas;
  933. if (image instanceof HTMLCanvasElement) {
  934. canvas = image;
  935. } else {
  936. if (_canvas === undefined) _canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  937. _canvas.width = image.width;
  938. _canvas.height = image.height;
  939. const context = _canvas.getContext('2d');
  940. if (image instanceof ImageData) {
  941. context.putImageData(image, 0, 0);
  942. } else {
  943. context.drawImage(image, 0, 0, image.width, image.height);
  944. }
  945. canvas = _canvas;
  946. }
  947. if (canvas.width > 2048 || canvas.height > 2048) {
  948. console.warn('THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image);
  949. return canvas.toDataURL('image/jpeg', 0.6);
  950. } else {
  951. return canvas.toDataURL('image/png');
  952. }
  953. }
  954. }
  955. let textureId = 0;
  956. class Texture extends EventDispatcher {
  957. 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) {
  958. super();
  959. Object.defineProperty(this, 'id', {
  960. value: textureId++
  961. });
  962. this.uuid = generateUUID();
  963. this.name = '';
  964. this.image = image;
  965. this.mipmaps = [];
  966. this.mapping = mapping;
  967. this.wrapS = wrapS;
  968. this.wrapT = wrapT;
  969. this.magFilter = magFilter;
  970. this.minFilter = minFilter;
  971. this.anisotropy = anisotropy;
  972. this.format = format;
  973. this.internalFormat = null;
  974. this.type = type;
  975. this.offset = new Vector2(0, 0);
  976. this.repeat = new Vector2(1, 1);
  977. this.center = new Vector2(0, 0);
  978. this.rotation = 0;
  979. this.matrixAutoUpdate = true;
  980. this.matrix = new Matrix3();
  981. this.generateMipmaps = true;
  982. this.premultiplyAlpha = false;
  983. this.flipY = true;
  984. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  985. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  986. //
  987. // Also changing the encoding after already used by a Material will not automatically make the Material
  988. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  989. this.encoding = encoding;
  990. this.version = 0;
  991. this.onUpdate = null;
  992. }
  993. updateMatrix() {
  994. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  995. }
  996. clone() {
  997. return new this.constructor().copy(this);
  998. }
  999. copy(source) {
  1000. this.name = source.name;
  1001. this.image = source.image;
  1002. this.mipmaps = source.mipmaps.slice(0);
  1003. this.mapping = source.mapping;
  1004. this.wrapS = source.wrapS;
  1005. this.wrapT = source.wrapT;
  1006. this.magFilter = source.magFilter;
  1007. this.minFilter = source.minFilter;
  1008. this.anisotropy = source.anisotropy;
  1009. this.format = source.format;
  1010. this.internalFormat = source.internalFormat;
  1011. this.type = source.type;
  1012. this.offset.copy(source.offset);
  1013. this.repeat.copy(source.repeat);
  1014. this.center.copy(source.center);
  1015. this.rotation = source.rotation;
  1016. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1017. this.matrix.copy(source.matrix);
  1018. this.generateMipmaps = source.generateMipmaps;
  1019. this.premultiplyAlpha = source.premultiplyAlpha;
  1020. this.flipY = source.flipY;
  1021. this.unpackAlignment = source.unpackAlignment;
  1022. this.encoding = source.encoding;
  1023. return this;
  1024. }
  1025. toJSON(meta) {
  1026. const isRootObject = meta === undefined || typeof meta === 'string';
  1027. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  1028. return meta.textures[this.uuid];
  1029. }
  1030. const output = {
  1031. metadata: {
  1032. version: 4.5,
  1033. type: 'Texture',
  1034. generator: 'Texture.toJSON'
  1035. },
  1036. uuid: this.uuid,
  1037. name: this.name,
  1038. mapping: this.mapping,
  1039. repeat: [this.repeat.x, this.repeat.y],
  1040. offset: [this.offset.x, this.offset.y],
  1041. center: [this.center.x, this.center.y],
  1042. rotation: this.rotation,
  1043. wrap: [this.wrapS, this.wrapT],
  1044. format: this.format,
  1045. type: this.type,
  1046. encoding: this.encoding,
  1047. minFilter: this.minFilter,
  1048. magFilter: this.magFilter,
  1049. anisotropy: this.anisotropy,
  1050. flipY: this.flipY,
  1051. premultiplyAlpha: this.premultiplyAlpha,
  1052. unpackAlignment: this.unpackAlignment
  1053. };
  1054. if (this.image !== undefined) {
  1055. // TODO: Move to THREE.Image
  1056. const image = this.image;
  1057. if (image.uuid === undefined) {
  1058. image.uuid = generateUUID(); // UGH
  1059. }
  1060. if (!isRootObject && meta.images[image.uuid] === undefined) {
  1061. let url;
  1062. if (Array.isArray(image)) {
  1063. // process array of images e.g. CubeTexture
  1064. url = [];
  1065. for (let i = 0, l = image.length; i < l; i++) {
  1066. // check cube texture with data textures
  1067. if (image[i].isDataTexture) {
  1068. url.push(serializeImage(image[i].image));
  1069. } else {
  1070. url.push(serializeImage(image[i]));
  1071. }
  1072. }
  1073. } else {
  1074. // process single image
  1075. url = serializeImage(image);
  1076. }
  1077. meta.images[image.uuid] = {
  1078. uuid: image.uuid,
  1079. url: url
  1080. };
  1081. }
  1082. output.image = image.uuid;
  1083. }
  1084. if (!isRootObject) {
  1085. meta.textures[this.uuid] = output;
  1086. }
  1087. return output;
  1088. }
  1089. dispose() {
  1090. this.dispatchEvent({
  1091. type: 'dispose'
  1092. });
  1093. }
  1094. transformUv(uv) {
  1095. if (this.mapping !== UVMapping) return uv;
  1096. uv.applyMatrix3(this.matrix);
  1097. if (uv.x < 0 || uv.x > 1) {
  1098. switch (this.wrapS) {
  1099. case RepeatWrapping:
  1100. uv.x = uv.x - Math.floor(uv.x);
  1101. break;
  1102. case ClampToEdgeWrapping:
  1103. uv.x = uv.x < 0 ? 0 : 1;
  1104. break;
  1105. case MirroredRepeatWrapping:
  1106. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  1107. uv.x = Math.ceil(uv.x) - uv.x;
  1108. } else {
  1109. uv.x = uv.x - Math.floor(uv.x);
  1110. }
  1111. break;
  1112. }
  1113. }
  1114. if (uv.y < 0 || uv.y > 1) {
  1115. switch (this.wrapT) {
  1116. case RepeatWrapping:
  1117. uv.y = uv.y - Math.floor(uv.y);
  1118. break;
  1119. case ClampToEdgeWrapping:
  1120. uv.y = uv.y < 0 ? 0 : 1;
  1121. break;
  1122. case MirroredRepeatWrapping:
  1123. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  1124. uv.y = Math.ceil(uv.y) - uv.y;
  1125. } else {
  1126. uv.y = uv.y - Math.floor(uv.y);
  1127. }
  1128. break;
  1129. }
  1130. }
  1131. if (this.flipY) {
  1132. uv.y = 1 - uv.y;
  1133. }
  1134. return uv;
  1135. }
  1136. set needsUpdate(value) {
  1137. if (value === true) this.version++;
  1138. }
  1139. }
  1140. Texture.DEFAULT_IMAGE = undefined;
  1141. Texture.DEFAULT_MAPPING = UVMapping;
  1142. Texture.prototype.isTexture = true;
  1143. function serializeImage(image) {
  1144. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  1145. // default images
  1146. return ImageUtils.getDataURL(image);
  1147. } else {
  1148. if (image.data) {
  1149. // images of DataTexture
  1150. return {
  1151. data: Array.prototype.slice.call(image.data),
  1152. width: image.width,
  1153. height: image.height,
  1154. type: image.data.constructor.name
  1155. };
  1156. } else {
  1157. console.warn('THREE.Texture: Unable to serialize Texture.');
  1158. return {};
  1159. }
  1160. }
  1161. }
  1162. class Vector4 {
  1163. constructor(x = 0, y = 0, z = 0, w = 1) {
  1164. this.x = x;
  1165. this.y = y;
  1166. this.z = z;
  1167. this.w = w;
  1168. }
  1169. get width() {
  1170. return this.z;
  1171. }
  1172. set width(value) {
  1173. this.z = value;
  1174. }
  1175. get height() {
  1176. return this.w;
  1177. }
  1178. set height(value) {
  1179. this.w = value;
  1180. }
  1181. set(x, y, z, w) {
  1182. this.x = x;
  1183. this.y = y;
  1184. this.z = z;
  1185. this.w = w;
  1186. return this;
  1187. }
  1188. setScalar(scalar) {
  1189. this.x = scalar;
  1190. this.y = scalar;
  1191. this.z = scalar;
  1192. this.w = scalar;
  1193. return this;
  1194. }
  1195. setX(x) {
  1196. this.x = x;
  1197. return this;
  1198. }
  1199. setY(y) {
  1200. this.y = y;
  1201. return this;
  1202. }
  1203. setZ(z) {
  1204. this.z = z;
  1205. return this;
  1206. }
  1207. setW(w) {
  1208. this.w = w;
  1209. return this;
  1210. }
  1211. setComponent(index, value) {
  1212. switch (index) {
  1213. case 0:
  1214. this.x = value;
  1215. break;
  1216. case 1:
  1217. this.y = value;
  1218. break;
  1219. case 2:
  1220. this.z = value;
  1221. break;
  1222. case 3:
  1223. this.w = value;
  1224. break;
  1225. default:
  1226. throw new Error('index is out of range: ' + index);
  1227. }
  1228. return this;
  1229. }
  1230. getComponent(index) {
  1231. switch (index) {
  1232. case 0:
  1233. return this.x;
  1234. case 1:
  1235. return this.y;
  1236. case 2:
  1237. return this.z;
  1238. case 3:
  1239. return this.w;
  1240. default:
  1241. throw new Error('index is out of range: ' + index);
  1242. }
  1243. }
  1244. clone() {
  1245. return new this.constructor(this.x, this.y, this.z, this.w);
  1246. }
  1247. copy(v) {
  1248. this.x = v.x;
  1249. this.y = v.y;
  1250. this.z = v.z;
  1251. this.w = v.w !== undefined ? v.w : 1;
  1252. return this;
  1253. }
  1254. add(v, w) {
  1255. if (w !== undefined) {
  1256. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  1257. return this.addVectors(v, w);
  1258. }
  1259. this.x += v.x;
  1260. this.y += v.y;
  1261. this.z += v.z;
  1262. this.w += v.w;
  1263. return this;
  1264. }
  1265. addScalar(s) {
  1266. this.x += s;
  1267. this.y += s;
  1268. this.z += s;
  1269. this.w += s;
  1270. return this;
  1271. }
  1272. addVectors(a, b) {
  1273. this.x = a.x + b.x;
  1274. this.y = a.y + b.y;
  1275. this.z = a.z + b.z;
  1276. this.w = a.w + b.w;
  1277. return this;
  1278. }
  1279. addScaledVector(v, s) {
  1280. this.x += v.x * s;
  1281. this.y += v.y * s;
  1282. this.z += v.z * s;
  1283. this.w += v.w * s;
  1284. return this;
  1285. }
  1286. sub(v, w) {
  1287. if (w !== undefined) {
  1288. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  1289. return this.subVectors(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. subScalar(s) {
  1298. this.x -= s;
  1299. this.y -= s;
  1300. this.z -= s;
  1301. this.w -= s;
  1302. return this;
  1303. }
  1304. subVectors(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. multiply(v) {
  1312. this.x *= v.x;
  1313. this.y *= v.y;
  1314. this.z *= v.z;
  1315. this.w *= v.w;
  1316. return this;
  1317. }
  1318. multiplyScalar(scalar) {
  1319. this.x *= scalar;
  1320. this.y *= scalar;
  1321. this.z *= scalar;
  1322. this.w *= scalar;
  1323. return this;
  1324. }
  1325. applyMatrix4(m) {
  1326. const x = this.x,
  1327. y = this.y,
  1328. z = this.z,
  1329. w = this.w;
  1330. const e = m.elements;
  1331. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1332. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1333. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1334. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1335. return this;
  1336. }
  1337. divideScalar(scalar) {
  1338. return this.multiplyScalar(1 / scalar);
  1339. }
  1340. setAxisAngleFromQuaternion(q) {
  1341. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1342. // q is assumed to be normalized
  1343. this.w = 2 * Math.acos(q.w);
  1344. const s = Math.sqrt(1 - q.w * q.w);
  1345. if (s < 0.0001) {
  1346. this.x = 1;
  1347. this.y = 0;
  1348. this.z = 0;
  1349. } else {
  1350. this.x = q.x / s;
  1351. this.y = q.y / s;
  1352. this.z = q.z / s;
  1353. }
  1354. return this;
  1355. }
  1356. setAxisAngleFromRotationMatrix(m) {
  1357. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1358. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1359. let angle, x, y, z; // variables for result
  1360. const epsilon = 0.01,
  1361. // margin to allow for rounding errors
  1362. epsilon2 = 0.1,
  1363. // margin to distinguish between 0 and 180 degrees
  1364. te = m.elements,
  1365. m11 = te[0],
  1366. m12 = te[4],
  1367. m13 = te[8],
  1368. m21 = te[1],
  1369. m22 = te[5],
  1370. m23 = te[9],
  1371. m31 = te[2],
  1372. m32 = te[6],
  1373. m33 = te[10];
  1374. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  1375. // singularity found
  1376. // first check for identity matrix which must have +1 for all terms
  1377. // in leading diagonal and zero in other terms
  1378. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  1379. // this singularity is identity matrix so angle = 0
  1380. this.set(1, 0, 0, 0);
  1381. return this; // zero angle, arbitrary axis
  1382. } // otherwise this singularity is angle = 180
  1383. angle = Math.PI;
  1384. const xx = (m11 + 1) / 2;
  1385. const yy = (m22 + 1) / 2;
  1386. const zz = (m33 + 1) / 2;
  1387. const xy = (m12 + m21) / 4;
  1388. const xz = (m13 + m31) / 4;
  1389. const yz = (m23 + m32) / 4;
  1390. if (xx > yy && xx > zz) {
  1391. // m11 is the largest diagonal term
  1392. if (xx < epsilon) {
  1393. x = 0;
  1394. y = 0.707106781;
  1395. z = 0.707106781;
  1396. } else {
  1397. x = Math.sqrt(xx);
  1398. y = xy / x;
  1399. z = xz / x;
  1400. }
  1401. } else if (yy > zz) {
  1402. // m22 is the largest diagonal term
  1403. if (yy < epsilon) {
  1404. x = 0.707106781;
  1405. y = 0;
  1406. z = 0.707106781;
  1407. } else {
  1408. y = Math.sqrt(yy);
  1409. x = xy / y;
  1410. z = yz / y;
  1411. }
  1412. } else {
  1413. // m33 is the largest diagonal term so base result on this
  1414. if (zz < epsilon) {
  1415. x = 0.707106781;
  1416. y = 0.707106781;
  1417. z = 0;
  1418. } else {
  1419. z = Math.sqrt(zz);
  1420. x = xz / z;
  1421. y = yz / z;
  1422. }
  1423. }
  1424. this.set(x, y, z, angle);
  1425. return this; // return 180 deg rotation
  1426. } // as we have reached here there are no singularities so we can handle normally
  1427. let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  1428. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1429. // caught by singularity test above, but I've left it in just in case
  1430. this.x = (m32 - m23) / s;
  1431. this.y = (m13 - m31) / s;
  1432. this.z = (m21 - m12) / s;
  1433. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  1434. return this;
  1435. }
  1436. min(v) {
  1437. this.x = Math.min(this.x, v.x);
  1438. this.y = Math.min(this.y, v.y);
  1439. this.z = Math.min(this.z, v.z);
  1440. this.w = Math.min(this.w, v.w);
  1441. return this;
  1442. }
  1443. max(v) {
  1444. this.x = Math.max(this.x, v.x);
  1445. this.y = Math.max(this.y, v.y);
  1446. this.z = Math.max(this.z, v.z);
  1447. this.w = Math.max(this.w, v.w);
  1448. return this;
  1449. }
  1450. clamp(min, max) {
  1451. // assumes min < max, componentwise
  1452. this.x = Math.max(min.x, Math.min(max.x, this.x));
  1453. this.y = Math.max(min.y, Math.min(max.y, this.y));
  1454. this.z = Math.max(min.z, Math.min(max.z, this.z));
  1455. this.w = Math.max(min.w, Math.min(max.w, this.w));
  1456. return this;
  1457. }
  1458. clampScalar(minVal, maxVal) {
  1459. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  1460. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  1461. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  1462. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  1463. return this;
  1464. }
  1465. clampLength(min, max) {
  1466. const length = this.length();
  1467. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  1468. }
  1469. floor() {
  1470. this.x = Math.floor(this.x);
  1471. this.y = Math.floor(this.y);
  1472. this.z = Math.floor(this.z);
  1473. this.w = Math.floor(this.w);
  1474. return this;
  1475. }
  1476. ceil() {
  1477. this.x = Math.ceil(this.x);
  1478. this.y = Math.ceil(this.y);
  1479. this.z = Math.ceil(this.z);
  1480. this.w = Math.ceil(this.w);
  1481. return this;
  1482. }
  1483. round() {
  1484. this.x = Math.round(this.x);
  1485. this.y = Math.round(this.y);
  1486. this.z = Math.round(this.z);
  1487. this.w = Math.round(this.w);
  1488. return this;
  1489. }
  1490. roundToZero() {
  1491. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  1492. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  1493. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  1494. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  1495. return this;
  1496. }
  1497. negate() {
  1498. this.x = -this.x;
  1499. this.y = -this.y;
  1500. this.z = -this.z;
  1501. this.w = -this.w;
  1502. return this;
  1503. }
  1504. dot(v) {
  1505. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1506. }
  1507. lengthSq() {
  1508. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1509. }
  1510. length() {
  1511. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1512. }
  1513. manhattanLength() {
  1514. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  1515. }
  1516. normalize() {
  1517. return this.divideScalar(this.length() || 1);
  1518. }
  1519. setLength(length) {
  1520. return this.normalize().multiplyScalar(length);
  1521. }
  1522. lerp(v, alpha) {
  1523. this.x += (v.x - this.x) * alpha;
  1524. this.y += (v.y - this.y) * alpha;
  1525. this.z += (v.z - this.z) * alpha;
  1526. this.w += (v.w - this.w) * alpha;
  1527. return this;
  1528. }
  1529. lerpVectors(v1, v2, alpha) {
  1530. this.x = v1.x + (v2.x - v1.x) * alpha;
  1531. this.y = v1.y + (v2.y - v1.y) * alpha;
  1532. this.z = v1.z + (v2.z - v1.z) * alpha;
  1533. this.w = v1.w + (v2.w - v1.w) * alpha;
  1534. return this;
  1535. }
  1536. equals(v) {
  1537. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  1538. }
  1539. fromArray(array, offset = 0) {
  1540. this.x = array[offset];
  1541. this.y = array[offset + 1];
  1542. this.z = array[offset + 2];
  1543. this.w = array[offset + 3];
  1544. return this;
  1545. }
  1546. toArray(array = [], offset = 0) {
  1547. array[offset] = this.x;
  1548. array[offset + 1] = this.y;
  1549. array[offset + 2] = this.z;
  1550. array[offset + 3] = this.w;
  1551. return array;
  1552. }
  1553. fromBufferAttribute(attribute, index, offset) {
  1554. if (offset !== undefined) {
  1555. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  1556. }
  1557. this.x = attribute.getX(index);
  1558. this.y = attribute.getY(index);
  1559. this.z = attribute.getZ(index);
  1560. this.w = attribute.getW(index);
  1561. return this;
  1562. }
  1563. random() {
  1564. this.x = Math.random();
  1565. this.y = Math.random();
  1566. this.z = Math.random();
  1567. this.w = Math.random();
  1568. return this;
  1569. }
  1570. }
  1571. Vector4.prototype.isVector4 = true;
  1572. /*
  1573. In options, we can specify:
  1574. * Texture parameters for an auto-generated target texture
  1575. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1576. */
  1577. class WebGLRenderTarget extends EventDispatcher {
  1578. constructor(width, height, options) {
  1579. super();
  1580. this.width = width;
  1581. this.height = height;
  1582. this.depth = 1;
  1583. this.scissor = new Vector4(0, 0, width, height);
  1584. this.scissorTest = false;
  1585. this.viewport = new Vector4(0, 0, width, height);
  1586. options = options || {};
  1587. this.texture = new Texture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  1588. this.texture.image = {};
  1589. this.texture.image.width = width;
  1590. this.texture.image.height = height;
  1591. this.texture.image.depth = 1;
  1592. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  1593. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  1594. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1595. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  1596. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1597. }
  1598. setTexture(texture) {
  1599. texture.image = {
  1600. width: this.width,
  1601. height: this.height,
  1602. depth: this.depth
  1603. };
  1604. this.texture = texture;
  1605. }
  1606. setSize(width, height, depth = 1) {
  1607. if (this.width !== width || this.height !== height || this.depth !== depth) {
  1608. this.width = width;
  1609. this.height = height;
  1610. this.depth = depth;
  1611. this.texture.image.width = width;
  1612. this.texture.image.height = height;
  1613. this.texture.image.depth = depth;
  1614. this.dispose();
  1615. }
  1616. this.viewport.set(0, 0, width, height);
  1617. this.scissor.set(0, 0, width, height);
  1618. }
  1619. clone() {
  1620. return new this.constructor().copy(this);
  1621. }
  1622. copy(source) {
  1623. this.width = source.width;
  1624. this.height = source.height;
  1625. this.depth = source.depth;
  1626. this.viewport.copy(source.viewport);
  1627. this.texture = source.texture.clone();
  1628. this.depthBuffer = source.depthBuffer;
  1629. this.stencilBuffer = source.stencilBuffer;
  1630. this.depthTexture = source.depthTexture;
  1631. return this;
  1632. }
  1633. dispose() {
  1634. this.dispatchEvent({
  1635. type: 'dispose'
  1636. });
  1637. }
  1638. }
  1639. WebGLRenderTarget.prototype.isWebGLRenderTarget = true;
  1640. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  1641. constructor(width, height, options) {
  1642. super(width, height, options);
  1643. this.samples = 4;
  1644. }
  1645. copy(source) {
  1646. super.copy.call(this, source);
  1647. this.samples = source.samples;
  1648. return this;
  1649. }
  1650. }
  1651. WebGLMultisampleRenderTarget.prototype.isWebGLMultisampleRenderTarget = true;
  1652. class Quaternion {
  1653. constructor(x = 0, y = 0, z = 0, w = 1) {
  1654. this._x = x;
  1655. this._y = y;
  1656. this._z = z;
  1657. this._w = w;
  1658. }
  1659. static slerp(qa, qb, qm, t) {
  1660. console.warn('THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead.');
  1661. return qm.slerpQuaternions(qa, qb, t);
  1662. }
  1663. static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  1664. // fuzz-free, array-based Quaternion SLERP operation
  1665. let x0 = src0[srcOffset0 + 0],
  1666. y0 = src0[srcOffset0 + 1],
  1667. z0 = src0[srcOffset0 + 2],
  1668. w0 = src0[srcOffset0 + 3];
  1669. const x1 = src1[srcOffset1 + 0],
  1670. y1 = src1[srcOffset1 + 1],
  1671. z1 = src1[srcOffset1 + 2],
  1672. w1 = src1[srcOffset1 + 3];
  1673. if (t === 0) {
  1674. dst[dstOffset + 0] = x0;
  1675. dst[dstOffset + 1] = y0;
  1676. dst[dstOffset + 2] = z0;
  1677. dst[dstOffset + 3] = w0;
  1678. return;
  1679. }
  1680. if (t === 1) {
  1681. dst[dstOffset + 0] = x1;
  1682. dst[dstOffset + 1] = y1;
  1683. dst[dstOffset + 2] = z1;
  1684. dst[dstOffset + 3] = w1;
  1685. return;
  1686. }
  1687. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  1688. let s = 1 - t;
  1689. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1690. dir = cos >= 0 ? 1 : -1,
  1691. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  1692. if (sqrSin > Number.EPSILON) {
  1693. const sin = Math.sqrt(sqrSin),
  1694. len = Math.atan2(sin, cos * dir);
  1695. s = Math.sin(s * len) / sin;
  1696. t = Math.sin(t * len) / sin;
  1697. }
  1698. const tDir = t * dir;
  1699. x0 = x0 * s + x1 * tDir;
  1700. y0 = y0 * s + y1 * tDir;
  1701. z0 = z0 * s + z1 * tDir;
  1702. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  1703. if (s === 1 - t) {
  1704. const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  1705. x0 *= f;
  1706. y0 *= f;
  1707. z0 *= f;
  1708. w0 *= f;
  1709. }
  1710. }
  1711. dst[dstOffset] = x0;
  1712. dst[dstOffset + 1] = y0;
  1713. dst[dstOffset + 2] = z0;
  1714. dst[dstOffset + 3] = w0;
  1715. }
  1716. static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
  1717. const x0 = src0[srcOffset0];
  1718. const y0 = src0[srcOffset0 + 1];
  1719. const z0 = src0[srcOffset0 + 2];
  1720. const w0 = src0[srcOffset0 + 3];
  1721. const x1 = src1[srcOffset1];
  1722. const y1 = src1[srcOffset1 + 1];
  1723. const z1 = src1[srcOffset1 + 2];
  1724. const w1 = src1[srcOffset1 + 3];
  1725. dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  1726. dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  1727. dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  1728. dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  1729. return dst;
  1730. }
  1731. get x() {
  1732. return this._x;
  1733. }
  1734. set x(value) {
  1735. this._x = value;
  1736. this._onChangeCallback();
  1737. }
  1738. get y() {
  1739. return this._y;
  1740. }
  1741. set y(value) {
  1742. this._y = value;
  1743. this._onChangeCallback();
  1744. }
  1745. get z() {
  1746. return this._z;
  1747. }
  1748. set z(value) {
  1749. this._z = value;
  1750. this._onChangeCallback();
  1751. }
  1752. get w() {
  1753. return this._w;
  1754. }
  1755. set w(value) {
  1756. this._w = value;
  1757. this._onChangeCallback();
  1758. }
  1759. set(x, y, z, w) {
  1760. this._x = x;
  1761. this._y = y;
  1762. this._z = z;
  1763. this._w = w;
  1764. this._onChangeCallback();
  1765. return this;
  1766. }
  1767. clone() {
  1768. return new this.constructor(this._x, this._y, this._z, this._w);
  1769. }
  1770. copy(quaternion) {
  1771. this._x = quaternion.x;
  1772. this._y = quaternion.y;
  1773. this._z = quaternion.z;
  1774. this._w = quaternion.w;
  1775. this._onChangeCallback();
  1776. return this;
  1777. }
  1778. setFromEuler(euler, update) {
  1779. if (!(euler && euler.isEuler)) {
  1780. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  1781. }
  1782. const x = euler._x,
  1783. y = euler._y,
  1784. z = euler._z,
  1785. order = euler._order; // http://www.mathworks.com/matlabcentral/fileexchange/
  1786. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1787. // content/SpinCalc.m
  1788. const cos = Math.cos;
  1789. const sin = Math.sin;
  1790. const c1 = cos(x / 2);
  1791. const c2 = cos(y / 2);
  1792. const c3 = cos(z / 2);
  1793. const s1 = sin(x / 2);
  1794. const s2 = sin(y / 2);
  1795. const s3 = sin(z / 2);
  1796. switch (order) {
  1797. case 'XYZ':
  1798. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1799. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1800. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1801. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1802. break;
  1803. case 'YXZ':
  1804. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1805. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1806. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1807. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1808. break;
  1809. case 'ZXY':
  1810. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1811. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1812. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1813. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1814. break;
  1815. case 'ZYX':
  1816. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1817. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1818. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1819. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1820. break;
  1821. case 'YZX':
  1822. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1823. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1824. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1825. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1826. break;
  1827. case 'XZY':
  1828. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1829. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1830. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1831. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1832. break;
  1833. default:
  1834. console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
  1835. }
  1836. if (update !== false) this._onChangeCallback();
  1837. return this;
  1838. }
  1839. setFromAxisAngle(axis, angle) {
  1840. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1841. // assumes axis is normalized
  1842. const halfAngle = angle / 2,
  1843. s = Math.sin(halfAngle);
  1844. this._x = axis.x * s;
  1845. this._y = axis.y * s;
  1846. this._z = axis.z * s;
  1847. this._w = Math.cos(halfAngle);
  1848. this._onChangeCallback();
  1849. return this;
  1850. }
  1851. setFromRotationMatrix(m) {
  1852. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1853. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1854. const te = m.elements,
  1855. m11 = te[0],
  1856. m12 = te[4],
  1857. m13 = te[8],
  1858. m21 = te[1],
  1859. m22 = te[5],
  1860. m23 = te[9],
  1861. m31 = te[2],
  1862. m32 = te[6],
  1863. m33 = te[10],
  1864. trace = m11 + m22 + m33;
  1865. if (trace > 0) {
  1866. const s = 0.5 / Math.sqrt(trace + 1.0);
  1867. this._w = 0.25 / s;
  1868. this._x = (m32 - m23) * s;
  1869. this._y = (m13 - m31) * s;
  1870. this._z = (m21 - m12) * s;
  1871. } else if (m11 > m22 && m11 > m33) {
  1872. const s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1873. this._w = (m32 - m23) / s;
  1874. this._x = 0.25 * s;
  1875. this._y = (m12 + m21) / s;
  1876. this._z = (m13 + m31) / s;
  1877. } else if (m22 > m33) {
  1878. const s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1879. this._w = (m13 - m31) / s;
  1880. this._x = (m12 + m21) / s;
  1881. this._y = 0.25 * s;
  1882. this._z = (m23 + m32) / s;
  1883. } else {
  1884. const s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1885. this._w = (m21 - m12) / s;
  1886. this._x = (m13 + m31) / s;
  1887. this._y = (m23 + m32) / s;
  1888. this._z = 0.25 * s;
  1889. }
  1890. this._onChangeCallback();
  1891. return this;
  1892. }
  1893. setFromUnitVectors(vFrom, vTo) {
  1894. // assumes direction vectors vFrom and vTo are normalized
  1895. let r = vFrom.dot(vTo) + 1;
  1896. if (r < Number.EPSILON) {
  1897. // vFrom and vTo point in opposite directions
  1898. r = 0;
  1899. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  1900. this._x = -vFrom.y;
  1901. this._y = vFrom.x;
  1902. this._z = 0;
  1903. this._w = r;
  1904. } else {
  1905. this._x = 0;
  1906. this._y = -vFrom.z;
  1907. this._z = vFrom.y;
  1908. this._w = r;
  1909. }
  1910. } else {
  1911. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  1912. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  1913. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  1914. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  1915. this._w = r;
  1916. }
  1917. return this.normalize();
  1918. }
  1919. angleTo(q) {
  1920. return 2 * Math.acos(Math.abs(clamp(this.dot(q), -1, 1)));
  1921. }
  1922. rotateTowards(q, step) {
  1923. const angle = this.angleTo(q);
  1924. if (angle === 0) return this;
  1925. const t = Math.min(1, step / angle);
  1926. this.slerp(q, t);
  1927. return this;
  1928. }
  1929. identity() {
  1930. return this.set(0, 0, 0, 1);
  1931. }
  1932. invert() {
  1933. // quaternion is assumed to have unit length
  1934. return this.conjugate();
  1935. }
  1936. conjugate() {
  1937. this._x *= -1;
  1938. this._y *= -1;
  1939. this._z *= -1;
  1940. this._onChangeCallback();
  1941. return this;
  1942. }
  1943. dot(v) {
  1944. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1945. }
  1946. lengthSq() {
  1947. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1948. }
  1949. length() {
  1950. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  1951. }
  1952. normalize() {
  1953. let l = this.length();
  1954. if (l === 0) {
  1955. this._x = 0;
  1956. this._y = 0;
  1957. this._z = 0;
  1958. this._w = 1;
  1959. } else {
  1960. l = 1 / l;
  1961. this._x = this._x * l;
  1962. this._y = this._y * l;
  1963. this._z = this._z * l;
  1964. this._w = this._w * l;
  1965. }
  1966. this._onChangeCallback();
  1967. return this;
  1968. }
  1969. multiply(q, p) {
  1970. if (p !== undefined) {
  1971. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  1972. return this.multiplyQuaternions(q, p);
  1973. }
  1974. return this.multiplyQuaternions(this, q);
  1975. }
  1976. premultiply(q) {
  1977. return this.multiplyQuaternions(q, this);
  1978. }
  1979. multiplyQuaternions(a, b) {
  1980. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  1981. const qax = a._x,
  1982. qay = a._y,
  1983. qaz = a._z,
  1984. qaw = a._w;
  1985. const qbx = b._x,
  1986. qby = b._y,
  1987. qbz = b._z,
  1988. qbw = b._w;
  1989. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  1990. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  1991. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  1992. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  1993. this._onChangeCallback();
  1994. return this;
  1995. }
  1996. slerp(qb, t) {
  1997. if (t === 0) return this;
  1998. if (t === 1) return this.copy(qb);
  1999. const x = this._x,
  2000. y = this._y,
  2001. z = this._z,
  2002. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2003. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2004. if (cosHalfTheta < 0) {
  2005. this._w = -qb._w;
  2006. this._x = -qb._x;
  2007. this._y = -qb._y;
  2008. this._z = -qb._z;
  2009. cosHalfTheta = -cosHalfTheta;
  2010. } else {
  2011. this.copy(qb);
  2012. }
  2013. if (cosHalfTheta >= 1.0) {
  2014. this._w = w;
  2015. this._x = x;
  2016. this._y = y;
  2017. this._z = z;
  2018. return this;
  2019. }
  2020. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2021. if (sqrSinHalfTheta <= Number.EPSILON) {
  2022. const s = 1 - t;
  2023. this._w = s * w + t * this._w;
  2024. this._x = s * x + t * this._x;
  2025. this._y = s * y + t * this._y;
  2026. this._z = s * z + t * this._z;
  2027. this.normalize();
  2028. this._onChangeCallback();
  2029. return this;
  2030. }
  2031. const sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2032. const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2033. const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2034. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2035. this._w = w * ratioA + this._w * ratioB;
  2036. this._x = x * ratioA + this._x * ratioB;
  2037. this._y = y * ratioA + this._y * ratioB;
  2038. this._z = z * ratioA + this._z * ratioB;
  2039. this._onChangeCallback();
  2040. return this;
  2041. }
  2042. slerpQuaternions(qa, qb, t) {
  2043. this.copy(qa).slerp(qb, t);
  2044. }
  2045. equals(quaternion) {
  2046. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2047. }
  2048. fromArray(array, offset = 0) {
  2049. this._x = array[offset];
  2050. this._y = array[offset + 1];
  2051. this._z = array[offset + 2];
  2052. this._w = array[offset + 3];
  2053. this._onChangeCallback();
  2054. return this;
  2055. }
  2056. toArray(array = [], offset = 0) {
  2057. array[offset] = this._x;
  2058. array[offset + 1] = this._y;
  2059. array[offset + 2] = this._z;
  2060. array[offset + 3] = this._w;
  2061. return array;
  2062. }
  2063. fromBufferAttribute(attribute, index) {
  2064. this._x = attribute.getX(index);
  2065. this._y = attribute.getY(index);
  2066. this._z = attribute.getZ(index);
  2067. this._w = attribute.getW(index);
  2068. return this;
  2069. }
  2070. _onChange(callback) {
  2071. this._onChangeCallback = callback;
  2072. return this;
  2073. }
  2074. _onChangeCallback() {}
  2075. }
  2076. Quaternion.prototype.isQuaternion = true;
  2077. class Vector3 {
  2078. constructor(x = 0, y = 0, z = 0) {
  2079. this.x = x;
  2080. this.y = y;
  2081. this.z = z;
  2082. }
  2083. set(x, y, z) {
  2084. if (z === undefined) z = this.z; // sprite.scale.set(x,y)
  2085. this.x = x;
  2086. this.y = y;
  2087. this.z = z;
  2088. return this;
  2089. }
  2090. setScalar(scalar) {
  2091. this.x = scalar;
  2092. this.y = scalar;
  2093. this.z = scalar;
  2094. return this;
  2095. }
  2096. setX(x) {
  2097. this.x = x;
  2098. return this;
  2099. }
  2100. setY(y) {
  2101. this.y = y;
  2102. return this;
  2103. }
  2104. setZ(z) {
  2105. this.z = z;
  2106. return this;
  2107. }
  2108. setComponent(index, value) {
  2109. switch (index) {
  2110. case 0:
  2111. this.x = value;
  2112. break;
  2113. case 1:
  2114. this.y = value;
  2115. break;
  2116. case 2:
  2117. this.z = value;
  2118. break;
  2119. default:
  2120. throw new Error('index is out of range: ' + index);
  2121. }
  2122. return this;
  2123. }
  2124. getComponent(index) {
  2125. switch (index) {
  2126. case 0:
  2127. return this.x;
  2128. case 1:
  2129. return this.y;
  2130. case 2:
  2131. return this.z;
  2132. default:
  2133. throw new Error('index is out of range: ' + index);
  2134. }
  2135. }
  2136. clone() {
  2137. return new this.constructor(this.x, this.y, this.z);
  2138. }
  2139. copy(v) {
  2140. this.x = v.x;
  2141. this.y = v.y;
  2142. this.z = v.z;
  2143. return this;
  2144. }
  2145. add(v, w) {
  2146. if (w !== undefined) {
  2147. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2148. return this.addVectors(v, w);
  2149. }
  2150. this.x += v.x;
  2151. this.y += v.y;
  2152. this.z += v.z;
  2153. return this;
  2154. }
  2155. addScalar(s) {
  2156. this.x += s;
  2157. this.y += s;
  2158. this.z += s;
  2159. return this;
  2160. }
  2161. addVectors(a, b) {
  2162. this.x = a.x + b.x;
  2163. this.y = a.y + b.y;
  2164. this.z = a.z + b.z;
  2165. return this;
  2166. }
  2167. addScaledVector(v, s) {
  2168. this.x += v.x * s;
  2169. this.y += v.y * s;
  2170. this.z += v.z * s;
  2171. return this;
  2172. }
  2173. sub(v, w) {
  2174. if (w !== undefined) {
  2175. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2176. return this.subVectors(v, w);
  2177. }
  2178. this.x -= v.x;
  2179. this.y -= v.y;
  2180. this.z -= v.z;
  2181. return this;
  2182. }
  2183. subScalar(s) {
  2184. this.x -= s;
  2185. this.y -= s;
  2186. this.z -= s;
  2187. return this;
  2188. }
  2189. subVectors(a, b) {
  2190. this.x = a.x - b.x;
  2191. this.y = a.y - b.y;
  2192. this.z = a.z - b.z;
  2193. return this;
  2194. }
  2195. multiply(v, w) {
  2196. if (w !== undefined) {
  2197. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  2198. return this.multiplyVectors(v, w);
  2199. }
  2200. this.x *= v.x;
  2201. this.y *= v.y;
  2202. this.z *= v.z;
  2203. return this;
  2204. }
  2205. multiplyScalar(scalar) {
  2206. this.x *= scalar;
  2207. this.y *= scalar;
  2208. this.z *= scalar;
  2209. return this;
  2210. }
  2211. multiplyVectors(a, b) {
  2212. this.x = a.x * b.x;
  2213. this.y = a.y * b.y;
  2214. this.z = a.z * b.z;
  2215. return this;
  2216. }
  2217. applyEuler(euler) {
  2218. if (!(euler && euler.isEuler)) {
  2219. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2220. }
  2221. return this.applyQuaternion(_quaternion$4.setFromEuler(euler));
  2222. }
  2223. applyAxisAngle(axis, angle) {
  2224. return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle));
  2225. }
  2226. applyMatrix3(m) {
  2227. const x = this.x,
  2228. y = this.y,
  2229. z = this.z;
  2230. const e = m.elements;
  2231. this.x = e[0] * x + e[3] * y + e[6] * z;
  2232. this.y = e[1] * x + e[4] * y + e[7] * z;
  2233. this.z = e[2] * x + e[5] * y + e[8] * z;
  2234. return this;
  2235. }
  2236. applyNormalMatrix(m) {
  2237. return this.applyMatrix3(m).normalize();
  2238. }
  2239. applyMatrix4(m) {
  2240. const x = this.x,
  2241. y = this.y,
  2242. z = this.z;
  2243. const e = m.elements;
  2244. const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2245. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2246. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2247. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2248. return this;
  2249. }
  2250. applyQuaternion(q) {
  2251. const x = this.x,
  2252. y = this.y,
  2253. z = this.z;
  2254. const qx = q.x,
  2255. qy = q.y,
  2256. qz = q.z,
  2257. qw = q.w; // calculate quat * vector
  2258. const ix = qw * x + qy * z - qz * y;
  2259. const iy = qw * y + qz * x - qx * z;
  2260. const iz = qw * z + qx * y - qy * x;
  2261. const iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  2262. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2263. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2264. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2265. return this;
  2266. }
  2267. project(camera) {
  2268. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  2269. }
  2270. unproject(camera) {
  2271. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  2272. }
  2273. transformDirection(m) {
  2274. // input: THREE.Matrix4 affine matrix
  2275. // vector interpreted as a direction
  2276. const x = this.x,
  2277. y = this.y,
  2278. z = this.z;
  2279. const e = m.elements;
  2280. this.x = e[0] * x + e[4] * y + e[8] * z;
  2281. this.y = e[1] * x + e[5] * y + e[9] * z;
  2282. this.z = e[2] * x + e[6] * y + e[10] * z;
  2283. return this.normalize();
  2284. }
  2285. divide(v) {
  2286. this.x /= v.x;
  2287. this.y /= v.y;
  2288. this.z /= v.z;
  2289. return this;
  2290. }
  2291. divideScalar(scalar) {
  2292. return this.multiplyScalar(1 / scalar);
  2293. }
  2294. min(v) {
  2295. this.x = Math.min(this.x, v.x);
  2296. this.y = Math.min(this.y, v.y);
  2297. this.z = Math.min(this.z, v.z);
  2298. return this;
  2299. }
  2300. max(v) {
  2301. this.x = Math.max(this.x, v.x);
  2302. this.y = Math.max(this.y, v.y);
  2303. this.z = Math.max(this.z, v.z);
  2304. return this;
  2305. }
  2306. clamp(min, max) {
  2307. // assumes min < max, componentwise
  2308. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2309. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2310. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2311. return this;
  2312. }
  2313. clampScalar(minVal, maxVal) {
  2314. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2315. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2316. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2317. return this;
  2318. }
  2319. clampLength(min, max) {
  2320. const length = this.length();
  2321. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2322. }
  2323. floor() {
  2324. this.x = Math.floor(this.x);
  2325. this.y = Math.floor(this.y);
  2326. this.z = Math.floor(this.z);
  2327. return this;
  2328. }
  2329. ceil() {
  2330. this.x = Math.ceil(this.x);
  2331. this.y = Math.ceil(this.y);
  2332. this.z = Math.ceil(this.z);
  2333. return this;
  2334. }
  2335. round() {
  2336. this.x = Math.round(this.x);
  2337. this.y = Math.round(this.y);
  2338. this.z = Math.round(this.z);
  2339. return this;
  2340. }
  2341. roundToZero() {
  2342. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2343. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2344. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2345. return this;
  2346. }
  2347. negate() {
  2348. this.x = -this.x;
  2349. this.y = -this.y;
  2350. this.z = -this.z;
  2351. return this;
  2352. }
  2353. dot(v) {
  2354. return this.x * v.x + this.y * v.y + this.z * v.z;
  2355. } // TODO lengthSquared?
  2356. lengthSq() {
  2357. return this.x * this.x + this.y * this.y + this.z * this.z;
  2358. }
  2359. length() {
  2360. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2361. }
  2362. manhattanLength() {
  2363. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  2364. }
  2365. normalize() {
  2366. return this.divideScalar(this.length() || 1);
  2367. }
  2368. setLength(length) {
  2369. return this.normalize().multiplyScalar(length);
  2370. }
  2371. lerp(v, alpha) {
  2372. this.x += (v.x - this.x) * alpha;
  2373. this.y += (v.y - this.y) * alpha;
  2374. this.z += (v.z - this.z) * alpha;
  2375. return this;
  2376. }
  2377. lerpVectors(v1, v2, alpha) {
  2378. this.x = v1.x + (v2.x - v1.x) * alpha;
  2379. this.y = v1.y + (v2.y - v1.y) * alpha;
  2380. this.z = v1.z + (v2.z - v1.z) * alpha;
  2381. return this;
  2382. }
  2383. cross(v, w) {
  2384. if (w !== undefined) {
  2385. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  2386. return this.crossVectors(v, w);
  2387. }
  2388. return this.crossVectors(this, v);
  2389. }
  2390. crossVectors(a, b) {
  2391. const ax = a.x,
  2392. ay = a.y,
  2393. az = a.z;
  2394. const bx = b.x,
  2395. by = b.y,
  2396. bz = b.z;
  2397. this.x = ay * bz - az * by;
  2398. this.y = az * bx - ax * bz;
  2399. this.z = ax * by - ay * bx;
  2400. return this;
  2401. }
  2402. projectOnVector(v) {
  2403. const denominator = v.lengthSq();
  2404. if (denominator === 0) return this.set(0, 0, 0);
  2405. const scalar = v.dot(this) / denominator;
  2406. return this.copy(v).multiplyScalar(scalar);
  2407. }
  2408. projectOnPlane(planeNormal) {
  2409. _vector$c.copy(this).projectOnVector(planeNormal);
  2410. return this.sub(_vector$c);
  2411. }
  2412. reflect(normal) {
  2413. // reflect incident vector off plane orthogonal to normal
  2414. // normal is assumed to have unit length
  2415. return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal)));
  2416. }
  2417. angleTo(v) {
  2418. const denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  2419. if (denominator === 0) return Math.PI / 2;
  2420. const theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  2421. return Math.acos(clamp(theta, -1, 1));
  2422. }
  2423. distanceTo(v) {
  2424. return Math.sqrt(this.distanceToSquared(v));
  2425. }
  2426. distanceToSquared(v) {
  2427. const dx = this.x - v.x,
  2428. dy = this.y - v.y,
  2429. dz = this.z - v.z;
  2430. return dx * dx + dy * dy + dz * dz;
  2431. }
  2432. manhattanDistanceTo(v) {
  2433. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  2434. }
  2435. setFromSpherical(s) {
  2436. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  2437. }
  2438. setFromSphericalCoords(radius, phi, theta) {
  2439. const sinPhiRadius = Math.sin(phi) * radius;
  2440. this.x = sinPhiRadius * Math.sin(theta);
  2441. this.y = Math.cos(phi) * radius;
  2442. this.z = sinPhiRadius * Math.cos(theta);
  2443. return this;
  2444. }
  2445. setFromCylindrical(c) {
  2446. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  2447. }
  2448. setFromCylindricalCoords(radius, theta, y) {
  2449. this.x = radius * Math.sin(theta);
  2450. this.y = y;
  2451. this.z = radius * Math.cos(theta);
  2452. return this;
  2453. }
  2454. setFromMatrixPosition(m) {
  2455. const e = m.elements;
  2456. this.x = e[12];
  2457. this.y = e[13];
  2458. this.z = e[14];
  2459. return this;
  2460. }
  2461. setFromMatrixScale(m) {
  2462. const sx = this.setFromMatrixColumn(m, 0).length();
  2463. const sy = this.setFromMatrixColumn(m, 1).length();
  2464. const sz = this.setFromMatrixColumn(m, 2).length();
  2465. this.x = sx;
  2466. this.y = sy;
  2467. this.z = sz;
  2468. return this;
  2469. }
  2470. setFromMatrixColumn(m, index) {
  2471. return this.fromArray(m.elements, index * 4);
  2472. }
  2473. setFromMatrix3Column(m, index) {
  2474. return this.fromArray(m.elements, index * 3);
  2475. }
  2476. equals(v) {
  2477. return v.x === this.x && v.y === this.y && v.z === this.z;
  2478. }
  2479. fromArray(array, offset = 0) {
  2480. this.x = array[offset];
  2481. this.y = array[offset + 1];
  2482. this.z = array[offset + 2];
  2483. return this;
  2484. }
  2485. toArray(array = [], offset = 0) {
  2486. array[offset] = this.x;
  2487. array[offset + 1] = this.y;
  2488. array[offset + 2] = this.z;
  2489. return array;
  2490. }
  2491. fromBufferAttribute(attribute, index, offset) {
  2492. if (offset !== undefined) {
  2493. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  2494. }
  2495. this.x = attribute.getX(index);
  2496. this.y = attribute.getY(index);
  2497. this.z = attribute.getZ(index);
  2498. return this;
  2499. }
  2500. random() {
  2501. this.x = Math.random();
  2502. this.y = Math.random();
  2503. this.z = Math.random();
  2504. return this;
  2505. }
  2506. }
  2507. Vector3.prototype.isVector3 = true;
  2508. const _vector$c = /*@__PURE__*/new Vector3();
  2509. const _quaternion$4 = /*@__PURE__*/new Quaternion();
  2510. class Box3 {
  2511. constructor(min = new Vector3(+Infinity, +Infinity, +Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity)) {
  2512. this.min = min;
  2513. this.max = max;
  2514. }
  2515. set(min, max) {
  2516. this.min.copy(min);
  2517. this.max.copy(max);
  2518. return this;
  2519. }
  2520. setFromArray(array) {
  2521. let minX = +Infinity;
  2522. let minY = +Infinity;
  2523. let minZ = +Infinity;
  2524. let maxX = -Infinity;
  2525. let maxY = -Infinity;
  2526. let maxZ = -Infinity;
  2527. for (let i = 0, l = array.length; i < l; i += 3) {
  2528. const x = array[i];
  2529. const y = array[i + 1];
  2530. const z = array[i + 2];
  2531. if (x < minX) minX = x;
  2532. if (y < minY) minY = y;
  2533. if (z < minZ) minZ = z;
  2534. if (x > maxX) maxX = x;
  2535. if (y > maxY) maxY = y;
  2536. if (z > maxZ) maxZ = z;
  2537. }
  2538. this.min.set(minX, minY, minZ);
  2539. this.max.set(maxX, maxY, maxZ);
  2540. return this;
  2541. }
  2542. setFromBufferAttribute(attribute) {
  2543. let minX = +Infinity;
  2544. let minY = +Infinity;
  2545. let minZ = +Infinity;
  2546. let maxX = -Infinity;
  2547. let maxY = -Infinity;
  2548. let maxZ = -Infinity;
  2549. for (let i = 0, l = attribute.count; i < l; i++) {
  2550. const x = attribute.getX(i);
  2551. const y = attribute.getY(i);
  2552. const z = attribute.getZ(i);
  2553. if (x < minX) minX = x;
  2554. if (y < minY) minY = y;
  2555. if (z < minZ) minZ = z;
  2556. if (x > maxX) maxX = x;
  2557. if (y > maxY) maxY = y;
  2558. if (z > maxZ) maxZ = z;
  2559. }
  2560. this.min.set(minX, minY, minZ);
  2561. this.max.set(maxX, maxY, maxZ);
  2562. return this;
  2563. }
  2564. setFromPoints(points) {
  2565. this.makeEmpty();
  2566. for (let i = 0, il = points.length; i < il; i++) {
  2567. this.expandByPoint(points[i]);
  2568. }
  2569. return this;
  2570. }
  2571. setFromCenterAndSize(center, size) {
  2572. const halfSize = _vector$b.copy(size).multiplyScalar(0.5);
  2573. this.min.copy(center).sub(halfSize);
  2574. this.max.copy(center).add(halfSize);
  2575. return this;
  2576. }
  2577. setFromObject(object) {
  2578. this.makeEmpty();
  2579. return this.expandByObject(object);
  2580. }
  2581. clone() {
  2582. return new this.constructor().copy(this);
  2583. }
  2584. copy(box) {
  2585. this.min.copy(box.min);
  2586. this.max.copy(box.max);
  2587. return this;
  2588. }
  2589. makeEmpty() {
  2590. this.min.x = this.min.y = this.min.z = +Infinity;
  2591. this.max.x = this.max.y = this.max.z = -Infinity;
  2592. return this;
  2593. }
  2594. isEmpty() {
  2595. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2596. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  2597. }
  2598. getCenter(target) {
  2599. if (target === undefined) {
  2600. console.warn('THREE.Box3: .getCenter() target is now required');
  2601. target = new Vector3();
  2602. }
  2603. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  2604. }
  2605. getSize(target) {
  2606. if (target === undefined) {
  2607. console.warn('THREE.Box3: .getSize() target is now required');
  2608. target = new Vector3();
  2609. }
  2610. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  2611. }
  2612. expandByPoint(point) {
  2613. this.min.min(point);
  2614. this.max.max(point);
  2615. return this;
  2616. }
  2617. expandByVector(vector) {
  2618. this.min.sub(vector);
  2619. this.max.add(vector);
  2620. return this;
  2621. }
  2622. expandByScalar(scalar) {
  2623. this.min.addScalar(-scalar);
  2624. this.max.addScalar(scalar);
  2625. return this;
  2626. }
  2627. expandByObject(object) {
  2628. // Computes the world-axis-aligned bounding box of an object (including its children),
  2629. // accounting for both the object's, and children's, world transforms
  2630. object.updateWorldMatrix(false, false);
  2631. const geometry = object.geometry;
  2632. if (geometry !== undefined) {
  2633. if (geometry.boundingBox === null) {
  2634. geometry.computeBoundingBox();
  2635. }
  2636. _box$3.copy(geometry.boundingBox);
  2637. _box$3.applyMatrix4(object.matrixWorld);
  2638. this.union(_box$3);
  2639. }
  2640. const children = object.children;
  2641. for (let i = 0, l = children.length; i < l; i++) {
  2642. this.expandByObject(children[i]);
  2643. }
  2644. return this;
  2645. }
  2646. containsPoint(point) {
  2647. 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;
  2648. }
  2649. containsBox(box) {
  2650. 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;
  2651. }
  2652. getParameter(point, target) {
  2653. // This can potentially have a divide by zero if the box
  2654. // has a size dimension of 0.
  2655. if (target === undefined) {
  2656. console.warn('THREE.Box3: .getParameter() target is now required');
  2657. target = new Vector3();
  2658. }
  2659. 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));
  2660. }
  2661. intersectsBox(box) {
  2662. // using 6 splitting planes to rule out intersections.
  2663. 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;
  2664. }
  2665. intersectsSphere(sphere) {
  2666. // Find the point on the AABB closest to the sphere center.
  2667. this.clampPoint(sphere.center, _vector$b); // If that point is inside the sphere, the AABB and sphere intersect.
  2668. return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  2669. }
  2670. intersectsPlane(plane) {
  2671. // We compute the minimum and maximum dot product values. If those values
  2672. // are on the same side (back or front) of the plane, then there is no intersection.
  2673. let min, max;
  2674. if (plane.normal.x > 0) {
  2675. min = plane.normal.x * this.min.x;
  2676. max = plane.normal.x * this.max.x;
  2677. } else {
  2678. min = plane.normal.x * this.max.x;
  2679. max = plane.normal.x * this.min.x;
  2680. }
  2681. if (plane.normal.y > 0) {
  2682. min += plane.normal.y * this.min.y;
  2683. max += plane.normal.y * this.max.y;
  2684. } else {
  2685. min += plane.normal.y * this.max.y;
  2686. max += plane.normal.y * this.min.y;
  2687. }
  2688. if (plane.normal.z > 0) {
  2689. min += plane.normal.z * this.min.z;
  2690. max += plane.normal.z * this.max.z;
  2691. } else {
  2692. min += plane.normal.z * this.max.z;
  2693. max += plane.normal.z * this.min.z;
  2694. }
  2695. return min <= -plane.constant && max >= -plane.constant;
  2696. }
  2697. intersectsTriangle(triangle) {
  2698. if (this.isEmpty()) {
  2699. return false;
  2700. } // compute box center and extents
  2701. this.getCenter(_center);
  2702. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  2703. _v0$2.subVectors(triangle.a, _center);
  2704. _v1$7.subVectors(triangle.b, _center);
  2705. _v2$3.subVectors(triangle.c, _center); // compute edge vectors for triangle
  2706. _f0.subVectors(_v1$7, _v0$2);
  2707. _f1.subVectors(_v2$3, _v1$7);
  2708. _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
  2709. // 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
  2710. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2711. 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];
  2712. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  2713. return false;
  2714. } // test 3 face normals from the aabb
  2715. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  2716. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  2717. return false;
  2718. } // finally testing the face normal of the triangle
  2719. // use already existing triangle edge vectors here
  2720. _triangleNormal.crossVectors(_f0, _f1);
  2721. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  2722. return satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents);
  2723. }
  2724. clampPoint(point, target) {
  2725. if (target === undefined) {
  2726. console.warn('THREE.Box3: .clampPoint() target is now required');
  2727. target = new Vector3();
  2728. }
  2729. return target.copy(point).clamp(this.min, this.max);
  2730. }
  2731. distanceToPoint(point) {
  2732. const clampedPoint = _vector$b.copy(point).clamp(this.min, this.max);
  2733. return clampedPoint.sub(point).length();
  2734. }
  2735. getBoundingSphere(target) {
  2736. if (target === undefined) {
  2737. console.error('THREE.Box3: .getBoundingSphere() target is now required'); //target = new Sphere(); // removed to avoid cyclic dependency
  2738. }
  2739. this.getCenter(target.center);
  2740. target.radius = this.getSize(_vector$b).length() * 0.5;
  2741. return target;
  2742. }
  2743. intersect(box) {
  2744. this.min.max(box.min);
  2745. 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.
  2746. if (this.isEmpty()) this.makeEmpty();
  2747. return this;
  2748. }
  2749. union(box) {
  2750. this.min.min(box.min);
  2751. this.max.max(box.max);
  2752. return this;
  2753. }
  2754. applyMatrix4(matrix) {
  2755. // transform of empty box is an empty box.
  2756. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2757. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  2758. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  2759. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  2760. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  2761. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  2762. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  2763. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  2764. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  2765. this.setFromPoints(_points);
  2766. return this;
  2767. }
  2768. translate(offset) {
  2769. this.min.add(offset);
  2770. this.max.add(offset);
  2771. return this;
  2772. }
  2773. equals(box) {
  2774. return box.min.equals(this.min) && box.max.equals(this.max);
  2775. }
  2776. }
  2777. Box3.prototype.isBox3 = true;
  2778. 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()];
  2779. const _vector$b = /*@__PURE__*/new Vector3();
  2780. const _box$3 = /*@__PURE__*/new Box3(); // triangle centered vertices
  2781. const _v0$2 = /*@__PURE__*/new Vector3();
  2782. const _v1$7 = /*@__PURE__*/new Vector3();
  2783. const _v2$3 = /*@__PURE__*/new Vector3(); // triangle edge vectors
  2784. const _f0 = /*@__PURE__*/new Vector3();
  2785. const _f1 = /*@__PURE__*/new Vector3();
  2786. const _f2 = /*@__PURE__*/new Vector3();
  2787. const _center = /*@__PURE__*/new Vector3();
  2788. const _extents = /*@__PURE__*/new Vector3();
  2789. const _triangleNormal = /*@__PURE__*/new Vector3();
  2790. const _testAxis = /*@__PURE__*/new Vector3();
  2791. function satForAxes(axes, v0, v1, v2, extents) {
  2792. for (let i = 0, j = axes.length - 3; i <= j; i += 3) {
  2793. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  2794. 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
  2795. const p0 = v0.dot(_testAxis);
  2796. const p1 = v1.dot(_testAxis);
  2797. const p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  2798. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  2799. // points of the projected triangle are outside the projected half-length of the aabb
  2800. // the axis is seperating and we can exit
  2801. return false;
  2802. }
  2803. }
  2804. return true;
  2805. }
  2806. const _box$2 = /*@__PURE__*/new Box3();
  2807. const _v1$6 = /*@__PURE__*/new Vector3();
  2808. const _toFarthestPoint = /*@__PURE__*/new Vector3();
  2809. const _toPoint = /*@__PURE__*/new Vector3();
  2810. class Sphere {
  2811. constructor(center = new Vector3(), radius = -1) {
  2812. this.center = center;
  2813. this.radius = radius;
  2814. }
  2815. set(center, radius) {
  2816. this.center.copy(center);
  2817. this.radius = radius;
  2818. return this;
  2819. }
  2820. setFromPoints(points, optionalCenter) {
  2821. const center = this.center;
  2822. if (optionalCenter !== undefined) {
  2823. center.copy(optionalCenter);
  2824. } else {
  2825. _box$2.setFromPoints(points).getCenter(center);
  2826. }
  2827. let maxRadiusSq = 0;
  2828. for (let i = 0, il = points.length; i < il; i++) {
  2829. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  2830. }
  2831. this.radius = Math.sqrt(maxRadiusSq);
  2832. return this;
  2833. }
  2834. copy(sphere) {
  2835. this.center.copy(sphere.center);
  2836. this.radius = sphere.radius;
  2837. return this;
  2838. }
  2839. isEmpty() {
  2840. return this.radius < 0;
  2841. }
  2842. makeEmpty() {
  2843. this.center.set(0, 0, 0);
  2844. this.radius = -1;
  2845. return this;
  2846. }
  2847. containsPoint(point) {
  2848. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  2849. }
  2850. distanceToPoint(point) {
  2851. return point.distanceTo(this.center) - this.radius;
  2852. }
  2853. intersectsSphere(sphere) {
  2854. const radiusSum = this.radius + sphere.radius;
  2855. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  2856. }
  2857. intersectsBox(box) {
  2858. return box.intersectsSphere(this);
  2859. }
  2860. intersectsPlane(plane) {
  2861. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  2862. }
  2863. clampPoint(point, target) {
  2864. const deltaLengthSq = this.center.distanceToSquared(point);
  2865. if (target === undefined) {
  2866. console.warn('THREE.Sphere: .clampPoint() target is now required');
  2867. target = new Vector3();
  2868. }
  2869. target.copy(point);
  2870. if (deltaLengthSq > this.radius * this.radius) {
  2871. target.sub(this.center).normalize();
  2872. target.multiplyScalar(this.radius).add(this.center);
  2873. }
  2874. return target;
  2875. }
  2876. getBoundingBox(target) {
  2877. if (target === undefined) {
  2878. console.warn('THREE.Sphere: .getBoundingBox() target is now required');
  2879. target = new Box3();
  2880. }
  2881. if (this.isEmpty()) {
  2882. // Empty sphere produces empty bounding box
  2883. target.makeEmpty();
  2884. return target;
  2885. }
  2886. target.set(this.center, this.center);
  2887. target.expandByScalar(this.radius);
  2888. return target;
  2889. }
  2890. applyMatrix4(matrix) {
  2891. this.center.applyMatrix4(matrix);
  2892. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2893. return this;
  2894. }
  2895. translate(offset) {
  2896. this.center.add(offset);
  2897. return this;
  2898. }
  2899. expandByPoint(point) {
  2900. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  2901. _toPoint.subVectors(point, this.center);
  2902. const lengthSq = _toPoint.lengthSq();
  2903. if (lengthSq > this.radius * this.radius) {
  2904. const length = Math.sqrt(lengthSq);
  2905. const missingRadiusHalf = (length - this.radius) * 0.5; // Nudge this sphere towards the target point. Add half the missing distance to radius,
  2906. // and the other half to position. This gives a tighter enclosure, instead of if
  2907. // the whole missing distance were just added to radius.
  2908. this.center.add(_toPoint.multiplyScalar(missingRadiusHalf / length));
  2909. this.radius += missingRadiusHalf;
  2910. }
  2911. return this;
  2912. }
  2913. union(sphere) {
  2914. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  2915. // To enclose another sphere into this sphere, we only need to enclose two points:
  2916. // 1) Enclose the farthest point on the other sphere into this sphere.
  2917. // 2) Enclose the opposite point of the farthest point into this sphere.
  2918. _toFarthestPoint.subVectors(sphere.center, this.center).normalize().multiplyScalar(sphere.radius);
  2919. this.expandByPoint(_v1$6.copy(sphere.center).add(_toFarthestPoint));
  2920. this.expandByPoint(_v1$6.copy(sphere.center).sub(_toFarthestPoint));
  2921. return this;
  2922. }
  2923. equals(sphere) {
  2924. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  2925. }
  2926. clone() {
  2927. return new this.constructor().copy(this);
  2928. }
  2929. }
  2930. const _vector$a = /*@__PURE__*/new Vector3();
  2931. const _segCenter = /*@__PURE__*/new Vector3();
  2932. const _segDir = /*@__PURE__*/new Vector3();
  2933. const _diff = /*@__PURE__*/new Vector3();
  2934. const _edge1 = /*@__PURE__*/new Vector3();
  2935. const _edge2 = /*@__PURE__*/new Vector3();
  2936. const _normal$1 = /*@__PURE__*/new Vector3();
  2937. class Ray {
  2938. constructor(origin = new Vector3(), direction = new Vector3(0, 0, -1)) {
  2939. this.origin = origin;
  2940. this.direction = direction;
  2941. }
  2942. set(origin, direction) {
  2943. this.origin.copy(origin);
  2944. this.direction.copy(direction);
  2945. return this;
  2946. }
  2947. copy(ray) {
  2948. this.origin.copy(ray.origin);
  2949. this.direction.copy(ray.direction);
  2950. return this;
  2951. }
  2952. at(t, target) {
  2953. if (target === undefined) {
  2954. console.warn('THREE.Ray: .at() target is now required');
  2955. target = new Vector3();
  2956. }
  2957. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  2958. }
  2959. lookAt(v) {
  2960. this.direction.copy(v).sub(this.origin).normalize();
  2961. return this;
  2962. }
  2963. recast(t) {
  2964. this.origin.copy(this.at(t, _vector$a));
  2965. return this;
  2966. }
  2967. closestPointToPoint(point, target) {
  2968. if (target === undefined) {
  2969. console.warn('THREE.Ray: .closestPointToPoint() target is now required');
  2970. target = new Vector3();
  2971. }
  2972. target.subVectors(point, this.origin);
  2973. const directionDistance = target.dot(this.direction);
  2974. if (directionDistance < 0) {
  2975. return target.copy(this.origin);
  2976. }
  2977. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  2978. }
  2979. distanceToPoint(point) {
  2980. return Math.sqrt(this.distanceSqToPoint(point));
  2981. }
  2982. distanceSqToPoint(point) {
  2983. const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  2984. if (directionDistance < 0) {
  2985. return this.origin.distanceToSquared(point);
  2986. }
  2987. _vector$a.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  2988. return _vector$a.distanceToSquared(point);
  2989. }
  2990. distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  2991. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  2992. // It returns the min distance between the ray and the segment
  2993. // defined by v0 and v1
  2994. // It can also set two optional targets :
  2995. // - The closest point on the ray
  2996. // - The closest point on the segment
  2997. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  2998. _segDir.copy(v1).sub(v0).normalize();
  2999. _diff.copy(this.origin).sub(_segCenter);
  3000. const segExtent = v0.distanceTo(v1) * 0.5;
  3001. const a01 = -this.direction.dot(_segDir);
  3002. const b0 = _diff.dot(this.direction);
  3003. const b1 = -_diff.dot(_segDir);
  3004. const c = _diff.lengthSq();
  3005. const det = Math.abs(1 - a01 * a01);
  3006. let s0, s1, sqrDist, extDet;
  3007. if (det > 0) {
  3008. // The ray and segment are not parallel.
  3009. s0 = a01 * b1 - b0;
  3010. s1 = a01 * b0 - b1;
  3011. extDet = segExtent * det;
  3012. if (s0 >= 0) {
  3013. if (s1 >= -extDet) {
  3014. if (s1 <= extDet) {
  3015. // region 0
  3016. // Minimum at interior points of ray and segment.
  3017. const invDet = 1 / det;
  3018. s0 *= invDet;
  3019. s1 *= invDet;
  3020. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  3021. } else {
  3022. // region 1
  3023. s1 = segExtent;
  3024. s0 = Math.max(0, -(a01 * s1 + b0));
  3025. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3026. }
  3027. } else {
  3028. // region 5
  3029. s1 = -segExtent;
  3030. s0 = Math.max(0, -(a01 * s1 + b0));
  3031. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3032. }
  3033. } else {
  3034. if (s1 <= -extDet) {
  3035. // region 4
  3036. s0 = Math.max(0, -(-a01 * segExtent + b0));
  3037. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3038. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3039. } else if (s1 <= extDet) {
  3040. // region 3
  3041. s0 = 0;
  3042. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  3043. sqrDist = s1 * (s1 + 2 * b1) + c;
  3044. } else {
  3045. // region 2
  3046. s0 = Math.max(0, -(a01 * segExtent + b0));
  3047. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3048. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3049. }
  3050. }
  3051. } else {
  3052. // Ray and segment are parallel.
  3053. s1 = a01 > 0 ? -segExtent : segExtent;
  3054. s0 = Math.max(0, -(a01 * s1 + b0));
  3055. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3056. }
  3057. if (optionalPointOnRay) {
  3058. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  3059. }
  3060. if (optionalPointOnSegment) {
  3061. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  3062. }
  3063. return sqrDist;
  3064. }
  3065. intersectSphere(sphere, target) {
  3066. _vector$a.subVectors(sphere.center, this.origin);
  3067. const tca = _vector$a.dot(this.direction);
  3068. const d2 = _vector$a.dot(_vector$a) - tca * tca;
  3069. const radius2 = sphere.radius * sphere.radius;
  3070. if (d2 > radius2) return null;
  3071. const thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  3072. const t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  3073. const t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  3074. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  3075. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3076. // in order to always return an intersect point that is in front of the ray.
  3077. 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
  3078. return this.at(t0, target);
  3079. }
  3080. intersectsSphere(sphere) {
  3081. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  3082. }
  3083. distanceToPlane(plane) {
  3084. const denominator = plane.normal.dot(this.direction);
  3085. if (denominator === 0) {
  3086. // line is coplanar, return origin
  3087. if (plane.distanceToPoint(this.origin) === 0) {
  3088. return 0;
  3089. } // Null is preferable to undefined since undefined means.... it is undefined
  3090. return null;
  3091. }
  3092. const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  3093. return t >= 0 ? t : null;
  3094. }
  3095. intersectPlane(plane, target) {
  3096. const t = this.distanceToPlane(plane);
  3097. if (t === null) {
  3098. return null;
  3099. }
  3100. return this.at(t, target);
  3101. }
  3102. intersectsPlane(plane) {
  3103. // check if the ray lies on the plane first
  3104. const distToPoint = plane.distanceToPoint(this.origin);
  3105. if (distToPoint === 0) {
  3106. return true;
  3107. }
  3108. const denominator = plane.normal.dot(this.direction);
  3109. if (denominator * distToPoint < 0) {
  3110. return true;
  3111. } // ray origin is behind the plane (and is pointing behind it)
  3112. return false;
  3113. }
  3114. intersectBox(box, target) {
  3115. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3116. const invdirx = 1 / this.direction.x,
  3117. invdiry = 1 / this.direction.y,
  3118. invdirz = 1 / this.direction.z;
  3119. const origin = this.origin;
  3120. if (invdirx >= 0) {
  3121. tmin = (box.min.x - origin.x) * invdirx;
  3122. tmax = (box.max.x - origin.x) * invdirx;
  3123. } else {
  3124. tmin = (box.max.x - origin.x) * invdirx;
  3125. tmax = (box.min.x - origin.x) * invdirx;
  3126. }
  3127. if (invdiry >= 0) {
  3128. tymin = (box.min.y - origin.y) * invdiry;
  3129. tymax = (box.max.y - origin.y) * invdiry;
  3130. } else {
  3131. tymin = (box.max.y - origin.y) * invdiry;
  3132. tymax = (box.min.y - origin.y) * invdiry;
  3133. }
  3134. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  3135. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3136. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  3137. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  3138. if (invdirz >= 0) {
  3139. tzmin = (box.min.z - origin.z) * invdirz;
  3140. tzmax = (box.max.z - origin.z) * invdirz;
  3141. } else {
  3142. tzmin = (box.max.z - origin.z) * invdirz;
  3143. tzmax = (box.min.z - origin.z) * invdirz;
  3144. }
  3145. if (tmin > tzmax || tzmin > tmax) return null;
  3146. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  3147. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  3148. if (tmax < 0) return null;
  3149. return this.at(tmin >= 0 ? tmin : tmax, target);
  3150. }
  3151. intersectsBox(box) {
  3152. return this.intersectBox(box, _vector$a) !== null;
  3153. }
  3154. intersectTriangle(a, b, c, backfaceCulling, target) {
  3155. // Compute the offset origin, edges, and normal.
  3156. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3157. _edge1.subVectors(b, a);
  3158. _edge2.subVectors(c, a);
  3159. _normal$1.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3160. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3161. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3162. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3163. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3164. let DdN = this.direction.dot(_normal$1);
  3165. let sign;
  3166. if (DdN > 0) {
  3167. if (backfaceCulling) return null;
  3168. sign = 1;
  3169. } else if (DdN < 0) {
  3170. sign = -1;
  3171. DdN = -DdN;
  3172. } else {
  3173. return null;
  3174. }
  3175. _diff.subVectors(this.origin, a);
  3176. const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  3177. if (DdQxE2 < 0) {
  3178. return null;
  3179. }
  3180. const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  3181. if (DdE1xQ < 0) {
  3182. return null;
  3183. } // b1+b2 > 1, no intersection
  3184. if (DdQxE2 + DdE1xQ > DdN) {
  3185. return null;
  3186. } // Line intersects triangle, check if ray does.
  3187. const QdN = -sign * _diff.dot(_normal$1); // t < 0, no intersection
  3188. if (QdN < 0) {
  3189. return null;
  3190. } // Ray intersects triangle.
  3191. return this.at(QdN / DdN, target);
  3192. }
  3193. applyMatrix4(matrix4) {
  3194. this.origin.applyMatrix4(matrix4);
  3195. this.direction.transformDirection(matrix4);
  3196. return this;
  3197. }
  3198. equals(ray) {
  3199. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  3200. }
  3201. clone() {
  3202. return new this.constructor().copy(this);
  3203. }
  3204. }
  3205. class Matrix4 {
  3206. constructor() {
  3207. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  3208. if (arguments.length > 0) {
  3209. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  3210. }
  3211. }
  3212. set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  3213. const te = this.elements;
  3214. te[0] = n11;
  3215. te[4] = n12;
  3216. te[8] = n13;
  3217. te[12] = n14;
  3218. te[1] = n21;
  3219. te[5] = n22;
  3220. te[9] = n23;
  3221. te[13] = n24;
  3222. te[2] = n31;
  3223. te[6] = n32;
  3224. te[10] = n33;
  3225. te[14] = n34;
  3226. te[3] = n41;
  3227. te[7] = n42;
  3228. te[11] = n43;
  3229. te[15] = n44;
  3230. return this;
  3231. }
  3232. identity() {
  3233. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3234. return this;
  3235. }
  3236. clone() {
  3237. return new Matrix4().fromArray(this.elements);
  3238. }
  3239. copy(m) {
  3240. const te = this.elements;
  3241. const me = m.elements;
  3242. te[0] = me[0];
  3243. te[1] = me[1];
  3244. te[2] = me[2];
  3245. te[3] = me[3];
  3246. te[4] = me[4];
  3247. te[5] = me[5];
  3248. te[6] = me[6];
  3249. te[7] = me[7];
  3250. te[8] = me[8];
  3251. te[9] = me[9];
  3252. te[10] = me[10];
  3253. te[11] = me[11];
  3254. te[12] = me[12];
  3255. te[13] = me[13];
  3256. te[14] = me[14];
  3257. te[15] = me[15];
  3258. return this;
  3259. }
  3260. copyPosition(m) {
  3261. const te = this.elements,
  3262. me = m.elements;
  3263. te[12] = me[12];
  3264. te[13] = me[13];
  3265. te[14] = me[14];
  3266. return this;
  3267. }
  3268. setFromMatrix3(m) {
  3269. const me = m.elements;
  3270. 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);
  3271. return this;
  3272. }
  3273. extractBasis(xAxis, yAxis, zAxis) {
  3274. xAxis.setFromMatrixColumn(this, 0);
  3275. yAxis.setFromMatrixColumn(this, 1);
  3276. zAxis.setFromMatrixColumn(this, 2);
  3277. return this;
  3278. }
  3279. makeBasis(xAxis, yAxis, zAxis) {
  3280. 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);
  3281. return this;
  3282. }
  3283. extractRotation(m) {
  3284. // this method does not support reflection matrices
  3285. const te = this.elements;
  3286. const me = m.elements;
  3287. const scaleX = 1 / _v1$5.setFromMatrixColumn(m, 0).length();
  3288. const scaleY = 1 / _v1$5.setFromMatrixColumn(m, 1).length();
  3289. const scaleZ = 1 / _v1$5.setFromMatrixColumn(m, 2).length();
  3290. te[0] = me[0] * scaleX;
  3291. te[1] = me[1] * scaleX;
  3292. te[2] = me[2] * scaleX;
  3293. te[3] = 0;
  3294. te[4] = me[4] * scaleY;
  3295. te[5] = me[5] * scaleY;
  3296. te[6] = me[6] * scaleY;
  3297. te[7] = 0;
  3298. te[8] = me[8] * scaleZ;
  3299. te[9] = me[9] * scaleZ;
  3300. te[10] = me[10] * scaleZ;
  3301. te[11] = 0;
  3302. te[12] = 0;
  3303. te[13] = 0;
  3304. te[14] = 0;
  3305. te[15] = 1;
  3306. return this;
  3307. }
  3308. makeRotationFromEuler(euler) {
  3309. if (!(euler && euler.isEuler)) {
  3310. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  3311. }
  3312. const te = this.elements;
  3313. const x = euler.x,
  3314. y = euler.y,
  3315. z = euler.z;
  3316. const a = Math.cos(x),
  3317. b = Math.sin(x);
  3318. const c = Math.cos(y),
  3319. d = Math.sin(y);
  3320. const e = Math.cos(z),
  3321. f = Math.sin(z);
  3322. if (euler.order === 'XYZ') {
  3323. const ae = a * e,
  3324. af = a * f,
  3325. be = b * e,
  3326. bf = b * f;
  3327. te[0] = c * e;
  3328. te[4] = -c * f;
  3329. te[8] = d;
  3330. te[1] = af + be * d;
  3331. te[5] = ae - bf * d;
  3332. te[9] = -b * c;
  3333. te[2] = bf - ae * d;
  3334. te[6] = be + af * d;
  3335. te[10] = a * c;
  3336. } else if (euler.order === 'YXZ') {
  3337. const ce = c * e,
  3338. cf = c * f,
  3339. de = d * e,
  3340. df = d * f;
  3341. te[0] = ce + df * b;
  3342. te[4] = de * b - cf;
  3343. te[8] = a * d;
  3344. te[1] = a * f;
  3345. te[5] = a * e;
  3346. te[9] = -b;
  3347. te[2] = cf * b - de;
  3348. te[6] = df + ce * b;
  3349. te[10] = a * c;
  3350. } else if (euler.order === 'ZXY') {
  3351. const ce = c * e,
  3352. cf = c * f,
  3353. de = d * e,
  3354. df = d * f;
  3355. te[0] = ce - df * b;
  3356. te[4] = -a * f;
  3357. te[8] = de + cf * b;
  3358. te[1] = cf + de * b;
  3359. te[5] = a * e;
  3360. te[9] = df - ce * b;
  3361. te[2] = -a * d;
  3362. te[6] = b;
  3363. te[10] = a * c;
  3364. } else if (euler.order === 'ZYX') {
  3365. const ae = a * e,
  3366. af = a * f,
  3367. be = b * e,
  3368. bf = b * f;
  3369. te[0] = c * e;
  3370. te[4] = be * d - af;
  3371. te[8] = ae * d + bf;
  3372. te[1] = c * f;
  3373. te[5] = bf * d + ae;
  3374. te[9] = af * d - be;
  3375. te[2] = -d;
  3376. te[6] = b * c;
  3377. te[10] = a * c;
  3378. } else if (euler.order === 'YZX') {
  3379. const ac = a * c,
  3380. ad = a * d,
  3381. bc = b * c,
  3382. bd = b * d;
  3383. te[0] = c * e;
  3384. te[4] = bd - ac * f;
  3385. te[8] = bc * f + ad;
  3386. te[1] = f;
  3387. te[5] = a * e;
  3388. te[9] = -b * e;
  3389. te[2] = -d * e;
  3390. te[6] = ad * f + bc;
  3391. te[10] = ac - bd * f;
  3392. } else if (euler.order === 'XZY') {
  3393. const ac = a * c,
  3394. ad = a * d,
  3395. bc = b * c,
  3396. bd = b * d;
  3397. te[0] = c * e;
  3398. te[4] = -f;
  3399. te[8] = d * e;
  3400. te[1] = ac * f + bd;
  3401. te[5] = a * e;
  3402. te[9] = ad * f - bc;
  3403. te[2] = bc * f - ad;
  3404. te[6] = b * e;
  3405. te[10] = bd * f + ac;
  3406. } // bottom row
  3407. te[3] = 0;
  3408. te[7] = 0;
  3409. te[11] = 0; // last column
  3410. te[12] = 0;
  3411. te[13] = 0;
  3412. te[14] = 0;
  3413. te[15] = 1;
  3414. return this;
  3415. }
  3416. makeRotationFromQuaternion(q) {
  3417. return this.compose(_zero, q, _one);
  3418. }
  3419. lookAt(eye, target, up) {
  3420. const te = this.elements;
  3421. _z.subVectors(eye, target);
  3422. if (_z.lengthSq() === 0) {
  3423. // eye and target are in the same position
  3424. _z.z = 1;
  3425. }
  3426. _z.normalize();
  3427. _x.crossVectors(up, _z);
  3428. if (_x.lengthSq() === 0) {
  3429. // up and z are parallel
  3430. if (Math.abs(up.z) === 1) {
  3431. _z.x += 0.0001;
  3432. } else {
  3433. _z.z += 0.0001;
  3434. }
  3435. _z.normalize();
  3436. _x.crossVectors(up, _z);
  3437. }
  3438. _x.normalize();
  3439. _y.crossVectors(_z, _x);
  3440. te[0] = _x.x;
  3441. te[4] = _y.x;
  3442. te[8] = _z.x;
  3443. te[1] = _x.y;
  3444. te[5] = _y.y;
  3445. te[9] = _z.y;
  3446. te[2] = _x.z;
  3447. te[6] = _y.z;
  3448. te[10] = _z.z;
  3449. return this;
  3450. }
  3451. multiply(m, n) {
  3452. if (n !== undefined) {
  3453. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  3454. return this.multiplyMatrices(m, n);
  3455. }
  3456. return this.multiplyMatrices(this, m);
  3457. }
  3458. premultiply(m) {
  3459. return this.multiplyMatrices(m, this);
  3460. }
  3461. multiplyMatrices(a, b) {
  3462. const ae = a.elements;
  3463. const be = b.elements;
  3464. const te = this.elements;
  3465. const a11 = ae[0],
  3466. a12 = ae[4],
  3467. a13 = ae[8],
  3468. a14 = ae[12];
  3469. const a21 = ae[1],
  3470. a22 = ae[5],
  3471. a23 = ae[9],
  3472. a24 = ae[13];
  3473. const a31 = ae[2],
  3474. a32 = ae[6],
  3475. a33 = ae[10],
  3476. a34 = ae[14];
  3477. const a41 = ae[3],
  3478. a42 = ae[7],
  3479. a43 = ae[11],
  3480. a44 = ae[15];
  3481. const b11 = be[0],
  3482. b12 = be[4],
  3483. b13 = be[8],
  3484. b14 = be[12];
  3485. const b21 = be[1],
  3486. b22 = be[5],
  3487. b23 = be[9],
  3488. b24 = be[13];
  3489. const b31 = be[2],
  3490. b32 = be[6],
  3491. b33 = be[10],
  3492. b34 = be[14];
  3493. const b41 = be[3],
  3494. b42 = be[7],
  3495. b43 = be[11],
  3496. b44 = be[15];
  3497. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3498. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3499. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3500. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3501. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3502. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3503. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3504. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3505. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3506. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3507. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3508. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3509. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3510. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3511. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3512. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3513. return this;
  3514. }
  3515. multiplyScalar(s) {
  3516. const te = this.elements;
  3517. te[0] *= s;
  3518. te[4] *= s;
  3519. te[8] *= s;
  3520. te[12] *= s;
  3521. te[1] *= s;
  3522. te[5] *= s;
  3523. te[9] *= s;
  3524. te[13] *= s;
  3525. te[2] *= s;
  3526. te[6] *= s;
  3527. te[10] *= s;
  3528. te[14] *= s;
  3529. te[3] *= s;
  3530. te[7] *= s;
  3531. te[11] *= s;
  3532. te[15] *= s;
  3533. return this;
  3534. }
  3535. determinant() {
  3536. const te = this.elements;
  3537. const n11 = te[0],
  3538. n12 = te[4],
  3539. n13 = te[8],
  3540. n14 = te[12];
  3541. const n21 = te[1],
  3542. n22 = te[5],
  3543. n23 = te[9],
  3544. n24 = te[13];
  3545. const n31 = te[2],
  3546. n32 = te[6],
  3547. n33 = te[10],
  3548. n34 = te[14];
  3549. const n41 = te[3],
  3550. n42 = te[7],
  3551. n43 = te[11],
  3552. n44 = te[15]; //TODO: make this more efficient
  3553. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3554. 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);
  3555. }
  3556. transpose() {
  3557. const te = this.elements;
  3558. let tmp;
  3559. tmp = te[1];
  3560. te[1] = te[4];
  3561. te[4] = tmp;
  3562. tmp = te[2];
  3563. te[2] = te[8];
  3564. te[8] = tmp;
  3565. tmp = te[6];
  3566. te[6] = te[9];
  3567. te[9] = tmp;
  3568. tmp = te[3];
  3569. te[3] = te[12];
  3570. te[12] = tmp;
  3571. tmp = te[7];
  3572. te[7] = te[13];
  3573. te[13] = tmp;
  3574. tmp = te[11];
  3575. te[11] = te[14];
  3576. te[14] = tmp;
  3577. return this;
  3578. }
  3579. setPosition(x, y, z) {
  3580. const te = this.elements;
  3581. if (x.isVector3) {
  3582. te[12] = x.x;
  3583. te[13] = x.y;
  3584. te[14] = x.z;
  3585. } else {
  3586. te[12] = x;
  3587. te[13] = y;
  3588. te[14] = z;
  3589. }
  3590. return this;
  3591. }
  3592. invert() {
  3593. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3594. const te = this.elements,
  3595. n11 = te[0],
  3596. n21 = te[1],
  3597. n31 = te[2],
  3598. n41 = te[3],
  3599. n12 = te[4],
  3600. n22 = te[5],
  3601. n32 = te[6],
  3602. n42 = te[7],
  3603. n13 = te[8],
  3604. n23 = te[9],
  3605. n33 = te[10],
  3606. n43 = te[11],
  3607. n14 = te[12],
  3608. n24 = te[13],
  3609. n34 = te[14],
  3610. n44 = te[15],
  3611. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3612. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3613. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3614. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3615. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3616. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  3617. const detInv = 1 / det;
  3618. te[0] = t11 * detInv;
  3619. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  3620. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  3621. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  3622. te[4] = t12 * detInv;
  3623. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  3624. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  3625. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  3626. te[8] = t13 * detInv;
  3627. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  3628. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  3629. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  3630. te[12] = t14 * detInv;
  3631. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  3632. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  3633. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  3634. return this;
  3635. }
  3636. scale(v) {
  3637. const te = this.elements;
  3638. const x = v.x,
  3639. y = v.y,
  3640. z = v.z;
  3641. te[0] *= x;
  3642. te[4] *= y;
  3643. te[8] *= z;
  3644. te[1] *= x;
  3645. te[5] *= y;
  3646. te[9] *= z;
  3647. te[2] *= x;
  3648. te[6] *= y;
  3649. te[10] *= z;
  3650. te[3] *= x;
  3651. te[7] *= y;
  3652. te[11] *= z;
  3653. return this;
  3654. }
  3655. getMaxScaleOnAxis() {
  3656. const te = this.elements;
  3657. const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  3658. const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  3659. const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  3660. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  3661. }
  3662. makeTranslation(x, y, z) {
  3663. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  3664. return this;
  3665. }
  3666. makeRotationX(theta) {
  3667. const c = Math.cos(theta),
  3668. s = Math.sin(theta);
  3669. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  3670. return this;
  3671. }
  3672. makeRotationY(theta) {
  3673. const c = Math.cos(theta),
  3674. s = Math.sin(theta);
  3675. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  3676. return this;
  3677. }
  3678. makeRotationZ(theta) {
  3679. const c = Math.cos(theta),
  3680. s = Math.sin(theta);
  3681. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3682. return this;
  3683. }
  3684. makeRotationAxis(axis, angle) {
  3685. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3686. const c = Math.cos(angle);
  3687. const s = Math.sin(angle);
  3688. const t = 1 - c;
  3689. const x = axis.x,
  3690. y = axis.y,
  3691. z = axis.z;
  3692. const tx = t * x,
  3693. ty = t * y;
  3694. 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);
  3695. return this;
  3696. }
  3697. makeScale(x, y, z) {
  3698. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  3699. return this;
  3700. }
  3701. makeShear(x, y, z) {
  3702. this.set(1, y, z, 0, x, 1, z, 0, x, y, 1, 0, 0, 0, 0, 1);
  3703. return this;
  3704. }
  3705. compose(position, quaternion, scale) {
  3706. const te = this.elements;
  3707. const x = quaternion._x,
  3708. y = quaternion._y,
  3709. z = quaternion._z,
  3710. w = quaternion._w;
  3711. const x2 = x + x,
  3712. y2 = y + y,
  3713. z2 = z + z;
  3714. const xx = x * x2,
  3715. xy = x * y2,
  3716. xz = x * z2;
  3717. const yy = y * y2,
  3718. yz = y * z2,
  3719. zz = z * z2;
  3720. const wx = w * x2,
  3721. wy = w * y2,
  3722. wz = w * z2;
  3723. const sx = scale.x,
  3724. sy = scale.y,
  3725. sz = scale.z;
  3726. te[0] = (1 - (yy + zz)) * sx;
  3727. te[1] = (xy + wz) * sx;
  3728. te[2] = (xz - wy) * sx;
  3729. te[3] = 0;
  3730. te[4] = (xy - wz) * sy;
  3731. te[5] = (1 - (xx + zz)) * sy;
  3732. te[6] = (yz + wx) * sy;
  3733. te[7] = 0;
  3734. te[8] = (xz + wy) * sz;
  3735. te[9] = (yz - wx) * sz;
  3736. te[10] = (1 - (xx + yy)) * sz;
  3737. te[11] = 0;
  3738. te[12] = position.x;
  3739. te[13] = position.y;
  3740. te[14] = position.z;
  3741. te[15] = 1;
  3742. return this;
  3743. }
  3744. decompose(position, quaternion, scale) {
  3745. const te = this.elements;
  3746. let sx = _v1$5.set(te[0], te[1], te[2]).length();
  3747. const sy = _v1$5.set(te[4], te[5], te[6]).length();
  3748. const sz = _v1$5.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  3749. const det = this.determinant();
  3750. if (det < 0) sx = -sx;
  3751. position.x = te[12];
  3752. position.y = te[13];
  3753. position.z = te[14]; // scale the rotation part
  3754. _m1$2.copy(this);
  3755. const invSX = 1 / sx;
  3756. const invSY = 1 / sy;
  3757. const invSZ = 1 / sz;
  3758. _m1$2.elements[0] *= invSX;
  3759. _m1$2.elements[1] *= invSX;
  3760. _m1$2.elements[2] *= invSX;
  3761. _m1$2.elements[4] *= invSY;
  3762. _m1$2.elements[5] *= invSY;
  3763. _m1$2.elements[6] *= invSY;
  3764. _m1$2.elements[8] *= invSZ;
  3765. _m1$2.elements[9] *= invSZ;
  3766. _m1$2.elements[10] *= invSZ;
  3767. quaternion.setFromRotationMatrix(_m1$2);
  3768. scale.x = sx;
  3769. scale.y = sy;
  3770. scale.z = sz;
  3771. return this;
  3772. }
  3773. makePerspective(left, right, top, bottom, near, far) {
  3774. if (far === undefined) {
  3775. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  3776. }
  3777. const te = this.elements;
  3778. const x = 2 * near / (right - left);
  3779. const y = 2 * near / (top - bottom);
  3780. const a = (right + left) / (right - left);
  3781. const b = (top + bottom) / (top - bottom);
  3782. const c = -(far + near) / (far - near);
  3783. const d = -2 * far * near / (far - near);
  3784. te[0] = x;
  3785. te[4] = 0;
  3786. te[8] = a;
  3787. te[12] = 0;
  3788. te[1] = 0;
  3789. te[5] = y;
  3790. te[9] = b;
  3791. te[13] = 0;
  3792. te[2] = 0;
  3793. te[6] = 0;
  3794. te[10] = c;
  3795. te[14] = d;
  3796. te[3] = 0;
  3797. te[7] = 0;
  3798. te[11] = -1;
  3799. te[15] = 0;
  3800. return this;
  3801. }
  3802. makeOrthographic(left, right, top, bottom, near, far) {
  3803. const te = this.elements;
  3804. const w = 1.0 / (right - left);
  3805. const h = 1.0 / (top - bottom);
  3806. const p = 1.0 / (far - near);
  3807. const x = (right + left) * w;
  3808. const y = (top + bottom) * h;
  3809. const z = (far + near) * p;
  3810. te[0] = 2 * w;
  3811. te[4] = 0;
  3812. te[8] = 0;
  3813. te[12] = -x;
  3814. te[1] = 0;
  3815. te[5] = 2 * h;
  3816. te[9] = 0;
  3817. te[13] = -y;
  3818. te[2] = 0;
  3819. te[6] = 0;
  3820. te[10] = -2 * p;
  3821. te[14] = -z;
  3822. te[3] = 0;
  3823. te[7] = 0;
  3824. te[11] = 0;
  3825. te[15] = 1;
  3826. return this;
  3827. }
  3828. equals(matrix) {
  3829. const te = this.elements;
  3830. const me = matrix.elements;
  3831. for (let i = 0; i < 16; i++) {
  3832. if (te[i] !== me[i]) return false;
  3833. }
  3834. return true;
  3835. }
  3836. fromArray(array, offset = 0) {
  3837. for (let i = 0; i < 16; i++) {
  3838. this.elements[i] = array[i + offset];
  3839. }
  3840. return this;
  3841. }
  3842. toArray(array = [], offset = 0) {
  3843. const te = this.elements;
  3844. array[offset] = te[0];
  3845. array[offset + 1] = te[1];
  3846. array[offset + 2] = te[2];
  3847. array[offset + 3] = te[3];
  3848. array[offset + 4] = te[4];
  3849. array[offset + 5] = te[5];
  3850. array[offset + 6] = te[6];
  3851. array[offset + 7] = te[7];
  3852. array[offset + 8] = te[8];
  3853. array[offset + 9] = te[9];
  3854. array[offset + 10] = te[10];
  3855. array[offset + 11] = te[11];
  3856. array[offset + 12] = te[12];
  3857. array[offset + 13] = te[13];
  3858. array[offset + 14] = te[14];
  3859. array[offset + 15] = te[15];
  3860. return array;
  3861. }
  3862. }
  3863. Matrix4.prototype.isMatrix4 = true;
  3864. const _v1$5 = /*@__PURE__*/new Vector3();
  3865. const _m1$2 = /*@__PURE__*/new Matrix4();
  3866. const _zero = /*@__PURE__*/new Vector3(0, 0, 0);
  3867. const _one = /*@__PURE__*/new Vector3(1, 1, 1);
  3868. const _x = /*@__PURE__*/new Vector3();
  3869. const _y = /*@__PURE__*/new Vector3();
  3870. const _z = /*@__PURE__*/new Vector3();
  3871. const _matrix$1 = /*@__PURE__*/new Matrix4();
  3872. const _quaternion$3 = /*@__PURE__*/new Quaternion();
  3873. class Euler {
  3874. constructor(x = 0, y = 0, z = 0, order = Euler.DefaultOrder) {
  3875. this._x = x;
  3876. this._y = y;
  3877. this._z = z;
  3878. this._order = order;
  3879. }
  3880. get x() {
  3881. return this._x;
  3882. }
  3883. set x(value) {
  3884. this._x = value;
  3885. this._onChangeCallback();
  3886. }
  3887. get y() {
  3888. return this._y;
  3889. }
  3890. set y(value) {
  3891. this._y = value;
  3892. this._onChangeCallback();
  3893. }
  3894. get z() {
  3895. return this._z;
  3896. }
  3897. set z(value) {
  3898. this._z = value;
  3899. this._onChangeCallback();
  3900. }
  3901. get order() {
  3902. return this._order;
  3903. }
  3904. set order(value) {
  3905. this._order = value;
  3906. this._onChangeCallback();
  3907. }
  3908. set(x, y, z, order) {
  3909. this._x = x;
  3910. this._y = y;
  3911. this._z = z;
  3912. this._order = order || this._order;
  3913. this._onChangeCallback();
  3914. return this;
  3915. }
  3916. clone() {
  3917. return new this.constructor(this._x, this._y, this._z, this._order);
  3918. }
  3919. copy(euler) {
  3920. this._x = euler._x;
  3921. this._y = euler._y;
  3922. this._z = euler._z;
  3923. this._order = euler._order;
  3924. this._onChangeCallback();
  3925. return this;
  3926. }
  3927. setFromRotationMatrix(m, order, update) {
  3928. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3929. const te = m.elements;
  3930. const m11 = te[0],
  3931. m12 = te[4],
  3932. m13 = te[8];
  3933. const m21 = te[1],
  3934. m22 = te[5],
  3935. m23 = te[9];
  3936. const m31 = te[2],
  3937. m32 = te[6],
  3938. m33 = te[10];
  3939. order = order || this._order;
  3940. switch (order) {
  3941. case 'XYZ':
  3942. this._y = Math.asin(clamp(m13, -1, 1));
  3943. if (Math.abs(m13) < 0.9999999) {
  3944. this._x = Math.atan2(-m23, m33);
  3945. this._z = Math.atan2(-m12, m11);
  3946. } else {
  3947. this._x = Math.atan2(m32, m22);
  3948. this._z = 0;
  3949. }
  3950. break;
  3951. case 'YXZ':
  3952. this._x = Math.asin(-clamp(m23, -1, 1));
  3953. if (Math.abs(m23) < 0.9999999) {
  3954. this._y = Math.atan2(m13, m33);
  3955. this._z = Math.atan2(m21, m22);
  3956. } else {
  3957. this._y = Math.atan2(-m31, m11);
  3958. this._z = 0;
  3959. }
  3960. break;
  3961. case 'ZXY':
  3962. this._x = Math.asin(clamp(m32, -1, 1));
  3963. if (Math.abs(m32) < 0.9999999) {
  3964. this._y = Math.atan2(-m31, m33);
  3965. this._z = Math.atan2(-m12, m22);
  3966. } else {
  3967. this._y = 0;
  3968. this._z = Math.atan2(m21, m11);
  3969. }
  3970. break;
  3971. case 'ZYX':
  3972. this._y = Math.asin(-clamp(m31, -1, 1));
  3973. if (Math.abs(m31) < 0.9999999) {
  3974. this._x = Math.atan2(m32, m33);
  3975. this._z = Math.atan2(m21, m11);
  3976. } else {
  3977. this._x = 0;
  3978. this._z = Math.atan2(-m12, m22);
  3979. }
  3980. break;
  3981. case 'YZX':
  3982. this._z = Math.asin(clamp(m21, -1, 1));
  3983. if (Math.abs(m21) < 0.9999999) {
  3984. this._x = Math.atan2(-m23, m22);
  3985. this._y = Math.atan2(-m31, m11);
  3986. } else {
  3987. this._x = 0;
  3988. this._y = Math.atan2(m13, m33);
  3989. }
  3990. break;
  3991. case 'XZY':
  3992. this._z = Math.asin(-clamp(m12, -1, 1));
  3993. if (Math.abs(m12) < 0.9999999) {
  3994. this._x = Math.atan2(m32, m22);
  3995. this._y = Math.atan2(m13, m11);
  3996. } else {
  3997. this._x = Math.atan2(-m23, m33);
  3998. this._y = 0;
  3999. }
  4000. break;
  4001. default:
  4002. console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
  4003. }
  4004. this._order = order;
  4005. if (update !== false) this._onChangeCallback();
  4006. return this;
  4007. }
  4008. setFromQuaternion(q, order, update) {
  4009. _matrix$1.makeRotationFromQuaternion(q);
  4010. return this.setFromRotationMatrix(_matrix$1, order, update);
  4011. }
  4012. setFromVector3(v, order) {
  4013. return this.set(v.x, v.y, v.z, order || this._order);
  4014. }
  4015. reorder(newOrder) {
  4016. // WARNING: this discards revolution information -bhouston
  4017. _quaternion$3.setFromEuler(this);
  4018. return this.setFromQuaternion(_quaternion$3, newOrder);
  4019. }
  4020. equals(euler) {
  4021. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4022. }
  4023. fromArray(array) {
  4024. this._x = array[0];
  4025. this._y = array[1];
  4026. this._z = array[2];
  4027. if (array[3] !== undefined) this._order = array[3];
  4028. this._onChangeCallback();
  4029. return this;
  4030. }
  4031. toArray(array = [], offset = 0) {
  4032. array[offset] = this._x;
  4033. array[offset + 1] = this._y;
  4034. array[offset + 2] = this._z;
  4035. array[offset + 3] = this._order;
  4036. return array;
  4037. }
  4038. toVector3(optionalResult) {
  4039. if (optionalResult) {
  4040. return optionalResult.set(this._x, this._y, this._z);
  4041. } else {
  4042. return new Vector3(this._x, this._y, this._z);
  4043. }
  4044. }
  4045. _onChange(callback) {
  4046. this._onChangeCallback = callback;
  4047. return this;
  4048. }
  4049. _onChangeCallback() {}
  4050. }
  4051. Euler.prototype.isEuler = true;
  4052. Euler.DefaultOrder = 'XYZ';
  4053. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4054. class Layers {
  4055. constructor() {
  4056. this.mask = 1 | 0;
  4057. }
  4058. set(channel) {
  4059. this.mask = 1 << channel | 0;
  4060. }
  4061. enable(channel) {
  4062. this.mask |= 1 << channel | 0;
  4063. }
  4064. enableAll() {
  4065. this.mask = 0xffffffff | 0;
  4066. }
  4067. toggle(channel) {
  4068. this.mask ^= 1 << channel | 0;
  4069. }
  4070. disable(channel) {
  4071. this.mask &= ~(1 << channel | 0);
  4072. }
  4073. disableAll() {
  4074. this.mask = 0;
  4075. }
  4076. test(layers) {
  4077. return (this.mask & layers.mask) !== 0;
  4078. }
  4079. }
  4080. let _object3DId = 0;
  4081. const _v1$4 = new /*@__PURE__*/Vector3();
  4082. const _q1 = new /*@__PURE__*/Quaternion();
  4083. const _m1$1 = new /*@__PURE__*/Matrix4();
  4084. const _target = new /*@__PURE__*/Vector3();
  4085. const _position$3 = new /*@__PURE__*/Vector3();
  4086. const _scale$2 = new /*@__PURE__*/Vector3();
  4087. const _quaternion$2 = new /*@__PURE__*/Quaternion();
  4088. const _xAxis = new /*@__PURE__*/Vector3(1, 0, 0);
  4089. const _yAxis = new /*@__PURE__*/Vector3(0, 1, 0);
  4090. const _zAxis = new /*@__PURE__*/Vector3(0, 0, 1);
  4091. const _addedEvent = {
  4092. type: 'added'
  4093. };
  4094. const _removedEvent = {
  4095. type: 'removed'
  4096. };
  4097. class Object3D extends EventDispatcher {
  4098. constructor() {
  4099. super();
  4100. Object.defineProperty(this, 'id', {
  4101. value: _object3DId++
  4102. });
  4103. this.uuid = generateUUID();
  4104. this.name = '';
  4105. this.type = 'Object3D';
  4106. this.parent = null;
  4107. this.children = [];
  4108. this.up = Object3D.DefaultUp.clone();
  4109. const position = new Vector3();
  4110. const rotation = new Euler();
  4111. const quaternion = new Quaternion();
  4112. const scale = new Vector3(1, 1, 1);
  4113. function onRotationChange() {
  4114. quaternion.setFromEuler(rotation, false);
  4115. }
  4116. function onQuaternionChange() {
  4117. rotation.setFromQuaternion(quaternion, undefined, false);
  4118. }
  4119. rotation._onChange(onRotationChange);
  4120. quaternion._onChange(onQuaternionChange);
  4121. Object.defineProperties(this, {
  4122. position: {
  4123. configurable: true,
  4124. enumerable: true,
  4125. value: position
  4126. },
  4127. rotation: {
  4128. configurable: true,
  4129. enumerable: true,
  4130. value: rotation
  4131. },
  4132. quaternion: {
  4133. configurable: true,
  4134. enumerable: true,
  4135. value: quaternion
  4136. },
  4137. scale: {
  4138. configurable: true,
  4139. enumerable: true,
  4140. value: scale
  4141. },
  4142. modelViewMatrix: {
  4143. value: new Matrix4()
  4144. },
  4145. normalMatrix: {
  4146. value: new Matrix3()
  4147. }
  4148. });
  4149. this.matrix = new Matrix4();
  4150. this.matrixWorld = new Matrix4();
  4151. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4152. this.matrixWorldNeedsUpdate = false;
  4153. this.layers = new Layers();
  4154. this.visible = true;
  4155. this.castShadow = false;
  4156. this.receiveShadow = false;
  4157. this.frustumCulled = true;
  4158. this.renderOrder = 0;
  4159. this.animations = [];
  4160. this.userData = {};
  4161. }
  4162. onBeforeRender() {}
  4163. onAfterRender() {}
  4164. applyMatrix4(matrix) {
  4165. if (this.matrixAutoUpdate) this.updateMatrix();
  4166. this.matrix.premultiply(matrix);
  4167. this.matrix.decompose(this.position, this.quaternion, this.scale);
  4168. }
  4169. applyQuaternion(q) {
  4170. this.quaternion.premultiply(q);
  4171. return this;
  4172. }
  4173. setRotationFromAxisAngle(axis, angle) {
  4174. // assumes axis is normalized
  4175. this.quaternion.setFromAxisAngle(axis, angle);
  4176. }
  4177. setRotationFromEuler(euler) {
  4178. this.quaternion.setFromEuler(euler, true);
  4179. }
  4180. setRotationFromMatrix(m) {
  4181. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4182. this.quaternion.setFromRotationMatrix(m);
  4183. }
  4184. setRotationFromQuaternion(q) {
  4185. // assumes q is normalized
  4186. this.quaternion.copy(q);
  4187. }
  4188. rotateOnAxis(axis, angle) {
  4189. // rotate object on axis in object space
  4190. // axis is assumed to be normalized
  4191. _q1.setFromAxisAngle(axis, angle);
  4192. this.quaternion.multiply(_q1);
  4193. return this;
  4194. }
  4195. rotateOnWorldAxis(axis, angle) {
  4196. // rotate object on axis in world space
  4197. // axis is assumed to be normalized
  4198. // method assumes no rotated parent
  4199. _q1.setFromAxisAngle(axis, angle);
  4200. this.quaternion.premultiply(_q1);
  4201. return this;
  4202. }
  4203. rotateX(angle) {
  4204. return this.rotateOnAxis(_xAxis, angle);
  4205. }
  4206. rotateY(angle) {
  4207. return this.rotateOnAxis(_yAxis, angle);
  4208. }
  4209. rotateZ(angle) {
  4210. return this.rotateOnAxis(_zAxis, angle);
  4211. }
  4212. translateOnAxis(axis, distance) {
  4213. // translate object by distance along axis in object space
  4214. // axis is assumed to be normalized
  4215. _v1$4.copy(axis).applyQuaternion(this.quaternion);
  4216. this.position.add(_v1$4.multiplyScalar(distance));
  4217. return this;
  4218. }
  4219. translateX(distance) {
  4220. return this.translateOnAxis(_xAxis, distance);
  4221. }
  4222. translateY(distance) {
  4223. return this.translateOnAxis(_yAxis, distance);
  4224. }
  4225. translateZ(distance) {
  4226. return this.translateOnAxis(_zAxis, distance);
  4227. }
  4228. localToWorld(vector) {
  4229. return vector.applyMatrix4(this.matrixWorld);
  4230. }
  4231. worldToLocal(vector) {
  4232. return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
  4233. }
  4234. lookAt(x, y, z) {
  4235. // This method does not support objects having non-uniformly-scaled parent(s)
  4236. if (x.isVector3) {
  4237. _target.copy(x);
  4238. } else {
  4239. _target.set(x, y, z);
  4240. }
  4241. const parent = this.parent;
  4242. this.updateWorldMatrix(true, false);
  4243. _position$3.setFromMatrixPosition(this.matrixWorld);
  4244. if (this.isCamera || this.isLight) {
  4245. _m1$1.lookAt(_position$3, _target, this.up);
  4246. } else {
  4247. _m1$1.lookAt(_target, _position$3, this.up);
  4248. }
  4249. this.quaternion.setFromRotationMatrix(_m1$1);
  4250. if (parent) {
  4251. _m1$1.extractRotation(parent.matrixWorld);
  4252. _q1.setFromRotationMatrix(_m1$1);
  4253. this.quaternion.premultiply(_q1.invert());
  4254. }
  4255. }
  4256. add(object) {
  4257. if (arguments.length > 1) {
  4258. for (let i = 0; i < arguments.length; i++) {
  4259. this.add(arguments[i]);
  4260. }
  4261. return this;
  4262. }
  4263. if (object === this) {
  4264. console.error('THREE.Object3D.add: object can\'t be added as a child of itself.', object);
  4265. return this;
  4266. }
  4267. if (object && object.isObject3D) {
  4268. if (object.parent !== null) {
  4269. object.parent.remove(object);
  4270. }
  4271. object.parent = this;
  4272. this.children.push(object);
  4273. object.dispatchEvent(_addedEvent);
  4274. } else {
  4275. console.error('THREE.Object3D.add: object not an instance of THREE.Object3D.', object);
  4276. }
  4277. return this;
  4278. }
  4279. remove(object) {
  4280. if (arguments.length > 1) {
  4281. for (let i = 0; i < arguments.length; i++) {
  4282. this.remove(arguments[i]);
  4283. }
  4284. return this;
  4285. }
  4286. const index = this.children.indexOf(object);
  4287. if (index !== -1) {
  4288. object.parent = null;
  4289. this.children.splice(index, 1);
  4290. object.dispatchEvent(_removedEvent);
  4291. }
  4292. return this;
  4293. }
  4294. clear() {
  4295. for (let i = 0; i < this.children.length; i++) {
  4296. const object = this.children[i];
  4297. object.parent = null;
  4298. object.dispatchEvent(_removedEvent);
  4299. }
  4300. this.children.length = 0;
  4301. return this;
  4302. }
  4303. attach(object) {
  4304. // adds object as a child of this, while maintaining the object's world transform
  4305. this.updateWorldMatrix(true, false);
  4306. _m1$1.copy(this.matrixWorld).invert();
  4307. if (object.parent !== null) {
  4308. object.parent.updateWorldMatrix(true, false);
  4309. _m1$1.multiply(object.parent.matrixWorld);
  4310. }
  4311. object.applyMatrix4(_m1$1);
  4312. this.add(object);
  4313. object.updateWorldMatrix(false, true);
  4314. return this;
  4315. }
  4316. getObjectById(id) {
  4317. return this.getObjectByProperty('id', id);
  4318. }
  4319. getObjectByName(name) {
  4320. return this.getObjectByProperty('name', name);
  4321. }
  4322. getObjectByProperty(name, value) {
  4323. if (this[name] === value) return this;
  4324. for (let i = 0, l = this.children.length; i < l; i++) {
  4325. const child = this.children[i];
  4326. const object = child.getObjectByProperty(name, value);
  4327. if (object !== undefined) {
  4328. return object;
  4329. }
  4330. }
  4331. return undefined;
  4332. }
  4333. getWorldPosition(target) {
  4334. if (target === undefined) {
  4335. console.warn('THREE.Object3D: .getWorldPosition() target is now required');
  4336. target = new Vector3();
  4337. }
  4338. this.updateWorldMatrix(true, false);
  4339. return target.setFromMatrixPosition(this.matrixWorld);
  4340. }
  4341. getWorldQuaternion(target) {
  4342. if (target === undefined) {
  4343. console.warn('THREE.Object3D: .getWorldQuaternion() target is now required');
  4344. target = new Quaternion();
  4345. }
  4346. this.updateWorldMatrix(true, false);
  4347. this.matrixWorld.decompose(_position$3, target, _scale$2);
  4348. return target;
  4349. }
  4350. getWorldScale(target) {
  4351. if (target === undefined) {
  4352. console.warn('THREE.Object3D: .getWorldScale() target is now required');
  4353. target = new Vector3();
  4354. }
  4355. this.updateWorldMatrix(true, false);
  4356. this.matrixWorld.decompose(_position$3, _quaternion$2, target);
  4357. return target;
  4358. }
  4359. getWorldDirection(target) {
  4360. if (target === undefined) {
  4361. console.warn('THREE.Object3D: .getWorldDirection() target is now required');
  4362. target = new Vector3();
  4363. }
  4364. this.updateWorldMatrix(true, false);
  4365. const e = this.matrixWorld.elements;
  4366. return target.set(e[8], e[9], e[10]).normalize();
  4367. }
  4368. raycast() {}
  4369. traverse(callback) {
  4370. callback(this);
  4371. const children = this.children;
  4372. for (let i = 0, l = children.length; i < l; i++) {
  4373. children[i].traverse(callback);
  4374. }
  4375. }
  4376. traverseVisible(callback) {
  4377. if (this.visible === false) return;
  4378. callback(this);
  4379. const children = this.children;
  4380. for (let i = 0, l = children.length; i < l; i++) {
  4381. children[i].traverseVisible(callback);
  4382. }
  4383. }
  4384. traverseAncestors(callback) {
  4385. const parent = this.parent;
  4386. if (parent !== null) {
  4387. callback(parent);
  4388. parent.traverseAncestors(callback);
  4389. }
  4390. }
  4391. updateMatrix() {
  4392. this.matrix.compose(this.position, this.quaternion, this.scale);
  4393. this.matrixWorldNeedsUpdate = true;
  4394. }
  4395. updateMatrixWorld(force) {
  4396. if (this.matrixAutoUpdate) this.updateMatrix();
  4397. if (this.matrixWorldNeedsUpdate || force) {
  4398. if (this.parent === null) {
  4399. this.matrixWorld.copy(this.matrix);
  4400. } else {
  4401. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4402. }
  4403. this.matrixWorldNeedsUpdate = false;
  4404. force = true;
  4405. } // update children
  4406. const children = this.children;
  4407. for (let i = 0, l = children.length; i < l; i++) {
  4408. children[i].updateMatrixWorld(force);
  4409. }
  4410. }
  4411. updateWorldMatrix(updateParents, updateChildren) {
  4412. const parent = this.parent;
  4413. if (updateParents === true && parent !== null) {
  4414. parent.updateWorldMatrix(true, false);
  4415. }
  4416. if (this.matrixAutoUpdate) this.updateMatrix();
  4417. if (this.parent === null) {
  4418. this.matrixWorld.copy(this.matrix);
  4419. } else {
  4420. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4421. } // update children
  4422. if (updateChildren === true) {
  4423. const children = this.children;
  4424. for (let i = 0, l = children.length; i < l; i++) {
  4425. children[i].updateWorldMatrix(false, true);
  4426. }
  4427. }
  4428. }
  4429. toJSON(meta) {
  4430. // meta is a string when called from JSON.stringify
  4431. const isRootObject = meta === undefined || typeof meta === 'string';
  4432. const output = {}; // meta is a hash used to collect geometries, materials.
  4433. // not providing it implies that this is the root object
  4434. // being serialized.
  4435. if (isRootObject) {
  4436. // initialize meta obj
  4437. meta = {
  4438. geometries: {},
  4439. materials: {},
  4440. textures: {},
  4441. images: {},
  4442. shapes: {},
  4443. skeletons: {},
  4444. animations: {}
  4445. };
  4446. output.metadata = {
  4447. version: 4.5,
  4448. type: 'Object',
  4449. generator: 'Object3D.toJSON'
  4450. };
  4451. } // standard Object3D serialization
  4452. const object = {};
  4453. object.uuid = this.uuid;
  4454. object.type = this.type;
  4455. if (this.name !== '') object.name = this.name;
  4456. if (this.castShadow === true) object.castShadow = true;
  4457. if (this.receiveShadow === true) object.receiveShadow = true;
  4458. if (this.visible === false) object.visible = false;
  4459. if (this.frustumCulled === false) object.frustumCulled = false;
  4460. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  4461. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  4462. object.layers = this.layers.mask;
  4463. object.matrix = this.matrix.toArray();
  4464. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  4465. if (this.isInstancedMesh) {
  4466. object.type = 'InstancedMesh';
  4467. object.count = this.count;
  4468. object.instanceMatrix = this.instanceMatrix.toJSON();
  4469. if (this.instanceColor !== null) object.instanceColor = this.instanceColor.toJSON();
  4470. } //
  4471. function serialize(library, element) {
  4472. if (library[element.uuid] === undefined) {
  4473. library[element.uuid] = element.toJSON(meta);
  4474. }
  4475. return element.uuid;
  4476. }
  4477. if (this.isMesh || this.isLine || this.isPoints) {
  4478. object.geometry = serialize(meta.geometries, this.geometry);
  4479. const parameters = this.geometry.parameters;
  4480. if (parameters !== undefined && parameters.shapes !== undefined) {
  4481. const shapes = parameters.shapes;
  4482. if (Array.isArray(shapes)) {
  4483. for (let i = 0, l = shapes.length; i < l; i++) {
  4484. const shape = shapes[i];
  4485. serialize(meta.shapes, shape);
  4486. }
  4487. } else {
  4488. serialize(meta.shapes, shapes);
  4489. }
  4490. }
  4491. }
  4492. if (this.isSkinnedMesh) {
  4493. object.bindMode = this.bindMode;
  4494. object.bindMatrix = this.bindMatrix.toArray();
  4495. if (this.skeleton !== undefined) {
  4496. serialize(meta.skeletons, this.skeleton);
  4497. object.skeleton = this.skeleton.uuid;
  4498. }
  4499. }
  4500. if (this.material !== undefined) {
  4501. if (Array.isArray(this.material)) {
  4502. const uuids = [];
  4503. for (let i = 0, l = this.material.length; i < l; i++) {
  4504. uuids.push(serialize(meta.materials, this.material[i]));
  4505. }
  4506. object.material = uuids;
  4507. } else {
  4508. object.material = serialize(meta.materials, this.material);
  4509. }
  4510. } //
  4511. if (this.children.length > 0) {
  4512. object.children = [];
  4513. for (let i = 0; i < this.children.length; i++) {
  4514. object.children.push(this.children[i].toJSON(meta).object);
  4515. }
  4516. } //
  4517. if (this.animations.length > 0) {
  4518. object.animations = [];
  4519. for (let i = 0; i < this.animations.length; i++) {
  4520. const animation = this.animations[i];
  4521. object.animations.push(serialize(meta.animations, animation));
  4522. }
  4523. }
  4524. if (isRootObject) {
  4525. const geometries = extractFromCache(meta.geometries);
  4526. const materials = extractFromCache(meta.materials);
  4527. const textures = extractFromCache(meta.textures);
  4528. const images = extractFromCache(meta.images);
  4529. const shapes = extractFromCache(meta.shapes);
  4530. const skeletons = extractFromCache(meta.skeletons);
  4531. const animations = extractFromCache(meta.animations);
  4532. if (geometries.length > 0) output.geometries = geometries;
  4533. if (materials.length > 0) output.materials = materials;
  4534. if (textures.length > 0) output.textures = textures;
  4535. if (images.length > 0) output.images = images;
  4536. if (shapes.length > 0) output.shapes = shapes;
  4537. if (skeletons.length > 0) output.skeletons = skeletons;
  4538. if (animations.length > 0) output.animations = animations;
  4539. }
  4540. output.object = object;
  4541. return output; // extract data from the cache hash
  4542. // remove metadata on each item
  4543. // and return as array
  4544. function extractFromCache(cache) {
  4545. const values = [];
  4546. for (const key in cache) {
  4547. const data = cache[key];
  4548. delete data.metadata;
  4549. values.push(data);
  4550. }
  4551. return values;
  4552. }
  4553. }
  4554. clone(recursive) {
  4555. return new this.constructor().copy(this, recursive);
  4556. }
  4557. copy(source, recursive = true) {
  4558. this.name = source.name;
  4559. this.up.copy(source.up);
  4560. this.position.copy(source.position);
  4561. this.rotation.order = source.rotation.order;
  4562. this.quaternion.copy(source.quaternion);
  4563. this.scale.copy(source.scale);
  4564. this.matrix.copy(source.matrix);
  4565. this.matrixWorld.copy(source.matrixWorld);
  4566. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4567. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4568. this.layers.mask = source.layers.mask;
  4569. this.visible = source.visible;
  4570. this.castShadow = source.castShadow;
  4571. this.receiveShadow = source.receiveShadow;
  4572. this.frustumCulled = source.frustumCulled;
  4573. this.renderOrder = source.renderOrder;
  4574. this.userData = JSON.parse(JSON.stringify(source.userData));
  4575. if (recursive === true) {
  4576. for (let i = 0; i < source.children.length; i++) {
  4577. const child = source.children[i];
  4578. this.add(child.clone());
  4579. }
  4580. }
  4581. return this;
  4582. }
  4583. }
  4584. Object3D.DefaultUp = new Vector3(0, 1, 0);
  4585. Object3D.DefaultMatrixAutoUpdate = true;
  4586. Object3D.prototype.isObject3D = true;
  4587. const _vector1 = /*@__PURE__*/new Vector3();
  4588. const _vector2$1 = /*@__PURE__*/new Vector3();
  4589. const _normalMatrix = /*@__PURE__*/new Matrix3();
  4590. class Plane {
  4591. constructor(normal = new Vector3(1, 0, 0), constant = 0) {
  4592. // normal is assumed to be normalized
  4593. this.normal = normal;
  4594. this.constant = constant;
  4595. }
  4596. set(normal, constant) {
  4597. this.normal.copy(normal);
  4598. this.constant = constant;
  4599. return this;
  4600. }
  4601. setComponents(x, y, z, w) {
  4602. this.normal.set(x, y, z);
  4603. this.constant = w;
  4604. return this;
  4605. }
  4606. setFromNormalAndCoplanarPoint(normal, point) {
  4607. this.normal.copy(normal);
  4608. this.constant = -point.dot(this.normal);
  4609. return this;
  4610. }
  4611. setFromCoplanarPoints(a, b, c) {
  4612. const normal = _vector1.subVectors(c, b).cross(_vector2$1.subVectors(a, b)).normalize(); // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  4613. this.setFromNormalAndCoplanarPoint(normal, a);
  4614. return this;
  4615. }
  4616. copy(plane) {
  4617. this.normal.copy(plane.normal);
  4618. this.constant = plane.constant;
  4619. return this;
  4620. }
  4621. normalize() {
  4622. // Note: will lead to a divide by zero if the plane is invalid.
  4623. const inverseNormalLength = 1.0 / this.normal.length();
  4624. this.normal.multiplyScalar(inverseNormalLength);
  4625. this.constant *= inverseNormalLength;
  4626. return this;
  4627. }
  4628. negate() {
  4629. this.constant *= -1;
  4630. this.normal.negate();
  4631. return this;
  4632. }
  4633. distanceToPoint(point) {
  4634. return this.normal.dot(point) + this.constant;
  4635. }
  4636. distanceToSphere(sphere) {
  4637. return this.distanceToPoint(sphere.center) - sphere.radius;
  4638. }
  4639. projectPoint(point, target) {
  4640. if (target === undefined) {
  4641. console.warn('THREE.Plane: .projectPoint() target is now required');
  4642. target = new Vector3();
  4643. }
  4644. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  4645. }
  4646. intersectLine(line, target) {
  4647. if (target === undefined) {
  4648. console.warn('THREE.Plane: .intersectLine() target is now required');
  4649. target = new Vector3();
  4650. }
  4651. const direction = line.delta(_vector1);
  4652. const denominator = this.normal.dot(direction);
  4653. if (denominator === 0) {
  4654. // line is coplanar, return origin
  4655. if (this.distanceToPoint(line.start) === 0) {
  4656. return target.copy(line.start);
  4657. } // Unsure if this is the correct method to handle this case.
  4658. return null;
  4659. }
  4660. const t = -(line.start.dot(this.normal) + this.constant) / denominator;
  4661. if (t < 0 || t > 1) {
  4662. return null;
  4663. }
  4664. return target.copy(direction).multiplyScalar(t).add(line.start);
  4665. }
  4666. intersectsLine(line) {
  4667. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  4668. const startSign = this.distanceToPoint(line.start);
  4669. const endSign = this.distanceToPoint(line.end);
  4670. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  4671. }
  4672. intersectsBox(box) {
  4673. return box.intersectsPlane(this);
  4674. }
  4675. intersectsSphere(sphere) {
  4676. return sphere.intersectsPlane(this);
  4677. }
  4678. coplanarPoint(target) {
  4679. if (target === undefined) {
  4680. console.warn('THREE.Plane: .coplanarPoint() target is now required');
  4681. target = new Vector3();
  4682. }
  4683. return target.copy(this.normal).multiplyScalar(-this.constant);
  4684. }
  4685. applyMatrix4(matrix, optionalNormalMatrix) {
  4686. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  4687. const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  4688. const normal = this.normal.applyMatrix3(normalMatrix).normalize();
  4689. this.constant = -referencePoint.dot(normal);
  4690. return this;
  4691. }
  4692. translate(offset) {
  4693. this.constant -= offset.dot(this.normal);
  4694. return this;
  4695. }
  4696. equals(plane) {
  4697. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  4698. }
  4699. clone() {
  4700. return new this.constructor().copy(this);
  4701. }
  4702. }
  4703. Plane.prototype.isPlane = true;
  4704. const _v0$1 = /*@__PURE__*/new Vector3();
  4705. const _v1$3 = /*@__PURE__*/new Vector3();
  4706. const _v2$2 = /*@__PURE__*/new Vector3();
  4707. const _v3$1 = /*@__PURE__*/new Vector3();
  4708. const _vab = /*@__PURE__*/new Vector3();
  4709. const _vac = /*@__PURE__*/new Vector3();
  4710. const _vbc = /*@__PURE__*/new Vector3();
  4711. const _vap = /*@__PURE__*/new Vector3();
  4712. const _vbp = /*@__PURE__*/new Vector3();
  4713. const _vcp = /*@__PURE__*/new Vector3();
  4714. class Triangle {
  4715. constructor(a = new Vector3(), b = new Vector3(), c = new Vector3()) {
  4716. this.a = a;
  4717. this.b = b;
  4718. this.c = c;
  4719. }
  4720. static getNormal(a, b, c, target) {
  4721. if (target === undefined) {
  4722. console.warn('THREE.Triangle: .getNormal() target is now required');
  4723. target = new Vector3();
  4724. }
  4725. target.subVectors(c, b);
  4726. _v0$1.subVectors(a, b);
  4727. target.cross(_v0$1);
  4728. const targetLengthSq = target.lengthSq();
  4729. if (targetLengthSq > 0) {
  4730. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  4731. }
  4732. return target.set(0, 0, 0);
  4733. } // static/instance method to calculate barycentric coordinates
  4734. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4735. static getBarycoord(point, a, b, c, target) {
  4736. _v0$1.subVectors(c, a);
  4737. _v1$3.subVectors(b, a);
  4738. _v2$2.subVectors(point, a);
  4739. const dot00 = _v0$1.dot(_v0$1);
  4740. const dot01 = _v0$1.dot(_v1$3);
  4741. const dot02 = _v0$1.dot(_v2$2);
  4742. const dot11 = _v1$3.dot(_v1$3);
  4743. const dot12 = _v1$3.dot(_v2$2);
  4744. const denom = dot00 * dot11 - dot01 * dot01;
  4745. if (target === undefined) {
  4746. console.warn('THREE.Triangle: .getBarycoord() target is now required');
  4747. target = new Vector3();
  4748. } // collinear or singular triangle
  4749. if (denom === 0) {
  4750. // arbitrary location outside of triangle?
  4751. // not sure if this is the best idea, maybe should be returning undefined
  4752. return target.set(-2, -1, -1);
  4753. }
  4754. const invDenom = 1 / denom;
  4755. const u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  4756. const v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  4757. return target.set(1 - u - v, v, u);
  4758. }
  4759. static containsPoint(point, a, b, c) {
  4760. this.getBarycoord(point, a, b, c, _v3$1);
  4761. return _v3$1.x >= 0 && _v3$1.y >= 0 && _v3$1.x + _v3$1.y <= 1;
  4762. }
  4763. static getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
  4764. this.getBarycoord(point, p1, p2, p3, _v3$1);
  4765. target.set(0, 0);
  4766. target.addScaledVector(uv1, _v3$1.x);
  4767. target.addScaledVector(uv2, _v3$1.y);
  4768. target.addScaledVector(uv3, _v3$1.z);
  4769. return target;
  4770. }
  4771. static isFrontFacing(a, b, c, direction) {
  4772. _v0$1.subVectors(c, b);
  4773. _v1$3.subVectors(a, b); // strictly front facing
  4774. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  4775. }
  4776. set(a, b, c) {
  4777. this.a.copy(a);
  4778. this.b.copy(b);
  4779. this.c.copy(c);
  4780. return this;
  4781. }
  4782. setFromPointsAndIndices(points, i0, i1, i2) {
  4783. this.a.copy(points[i0]);
  4784. this.b.copy(points[i1]);
  4785. this.c.copy(points[i2]);
  4786. return this;
  4787. }
  4788. clone() {
  4789. return new this.constructor().copy(this);
  4790. }
  4791. copy(triangle) {
  4792. this.a.copy(triangle.a);
  4793. this.b.copy(triangle.b);
  4794. this.c.copy(triangle.c);
  4795. return this;
  4796. }
  4797. getArea() {
  4798. _v0$1.subVectors(this.c, this.b);
  4799. _v1$3.subVectors(this.a, this.b);
  4800. return _v0$1.cross(_v1$3).length() * 0.5;
  4801. }
  4802. getMidpoint(target) {
  4803. if (target === undefined) {
  4804. console.warn('THREE.Triangle: .getMidpoint() target is now required');
  4805. target = new Vector3();
  4806. }
  4807. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  4808. }
  4809. getNormal(target) {
  4810. return Triangle.getNormal(this.a, this.b, this.c, target);
  4811. }
  4812. getPlane(target) {
  4813. if (target === undefined) {
  4814. console.warn('THREE.Triangle: .getPlane() target is now required');
  4815. target = new Plane();
  4816. }
  4817. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  4818. }
  4819. getBarycoord(point, target) {
  4820. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  4821. }
  4822. getUV(point, uv1, uv2, uv3, target) {
  4823. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  4824. }
  4825. containsPoint(point) {
  4826. return Triangle.containsPoint(point, this.a, this.b, this.c);
  4827. }
  4828. isFrontFacing(direction) {
  4829. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  4830. }
  4831. intersectsBox(box) {
  4832. return box.intersectsTriangle(this);
  4833. }
  4834. closestPointToPoint(p, target) {
  4835. if (target === undefined) {
  4836. console.warn('THREE.Triangle: .closestPointToPoint() target is now required');
  4837. target = new Vector3();
  4838. }
  4839. const a = this.a,
  4840. b = this.b,
  4841. c = this.c;
  4842. let v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4843. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4844. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4845. // basically, we're distinguishing which of the voronoi regions of the triangle
  4846. // the point lies in with the minimum amount of redundant computation.
  4847. _vab.subVectors(b, a);
  4848. _vac.subVectors(c, a);
  4849. _vap.subVectors(p, a);
  4850. const d1 = _vab.dot(_vap);
  4851. const d2 = _vac.dot(_vap);
  4852. if (d1 <= 0 && d2 <= 0) {
  4853. // vertex region of A; barycentric coords (1, 0, 0)
  4854. return target.copy(a);
  4855. }
  4856. _vbp.subVectors(p, b);
  4857. const d3 = _vab.dot(_vbp);
  4858. const d4 = _vac.dot(_vbp);
  4859. if (d3 >= 0 && d4 <= d3) {
  4860. // vertex region of B; barycentric coords (0, 1, 0)
  4861. return target.copy(b);
  4862. }
  4863. const vc = d1 * d4 - d3 * d2;
  4864. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  4865. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  4866. return target.copy(a).addScaledVector(_vab, v);
  4867. }
  4868. _vcp.subVectors(p, c);
  4869. const d5 = _vab.dot(_vcp);
  4870. const d6 = _vac.dot(_vcp);
  4871. if (d6 >= 0 && d5 <= d6) {
  4872. // vertex region of C; barycentric coords (0, 0, 1)
  4873. return target.copy(c);
  4874. }
  4875. const vb = d5 * d2 - d1 * d6;
  4876. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  4877. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  4878. return target.copy(a).addScaledVector(_vac, w);
  4879. }
  4880. const va = d3 * d6 - d5 * d4;
  4881. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  4882. _vbc.subVectors(c, b);
  4883. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  4884. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  4885. } // face region
  4886. const denom = 1 / (va + vb + vc); // u = va * denom
  4887. v = vb * denom;
  4888. w = vc * denom;
  4889. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  4890. }
  4891. equals(triangle) {
  4892. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  4893. }
  4894. }
  4895. let materialId = 0;
  4896. function Material() {
  4897. Object.defineProperty(this, 'id', {
  4898. value: materialId++
  4899. });
  4900. this.uuid = generateUUID();
  4901. this.name = '';
  4902. this.type = 'Material';
  4903. this.fog = true;
  4904. this.blending = NormalBlending;
  4905. this.side = FrontSide;
  4906. this.vertexColors = false;
  4907. this.opacity = 1;
  4908. this.transparent = false;
  4909. this.blendSrc = SrcAlphaFactor;
  4910. this.blendDst = OneMinusSrcAlphaFactor;
  4911. this.blendEquation = AddEquation;
  4912. this.blendSrcAlpha = null;
  4913. this.blendDstAlpha = null;
  4914. this.blendEquationAlpha = null;
  4915. this.depthFunc = LessEqualDepth;
  4916. this.depthTest = true;
  4917. this.depthWrite = true;
  4918. this.stencilWriteMask = 0xff;
  4919. this.stencilFunc = AlwaysStencilFunc;
  4920. this.stencilRef = 0;
  4921. this.stencilFuncMask = 0xff;
  4922. this.stencilFail = KeepStencilOp;
  4923. this.stencilZFail = KeepStencilOp;
  4924. this.stencilZPass = KeepStencilOp;
  4925. this.stencilWrite = false;
  4926. this.clippingPlanes = null;
  4927. this.clipIntersection = false;
  4928. this.clipShadows = false;
  4929. this.shadowSide = null;
  4930. this.colorWrite = true;
  4931. this.precision = null; // override the renderer's default precision for this material
  4932. this.polygonOffset = false;
  4933. this.polygonOffsetFactor = 0;
  4934. this.polygonOffsetUnits = 0;
  4935. this.dithering = false;
  4936. this.alphaTest = 0;
  4937. this.alphaToCoverage = false;
  4938. this.premultipliedAlpha = false;
  4939. this.visible = true;
  4940. this.toneMapped = true;
  4941. this.userData = {};
  4942. this.version = 0;
  4943. }
  4944. Material.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  4945. constructor: Material,
  4946. isMaterial: true,
  4947. onBuild: function ()
  4948. /* shaderobject, renderer */
  4949. {},
  4950. onBeforeCompile: function ()
  4951. /* shaderobject, renderer */
  4952. {},
  4953. customProgramCacheKey: function () {
  4954. return this.onBeforeCompile.toString();
  4955. },
  4956. setValues: function (values) {
  4957. if (values === undefined) return;
  4958. for (const key in values) {
  4959. const newValue = values[key];
  4960. if (newValue === undefined) {
  4961. console.warn('THREE.Material: \'' + key + '\' parameter is undefined.');
  4962. continue;
  4963. } // for backward compatability if shading is set in the constructor
  4964. if (key === 'shading') {
  4965. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  4966. this.flatShading = newValue === FlatShading ? true : false;
  4967. continue;
  4968. }
  4969. const currentValue = this[key];
  4970. if (currentValue === undefined) {
  4971. console.warn('THREE.' + this.type + ': \'' + key + '\' is not a property of this material.');
  4972. continue;
  4973. }
  4974. if (currentValue && currentValue.isColor) {
  4975. currentValue.set(newValue);
  4976. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  4977. currentValue.copy(newValue);
  4978. } else {
  4979. this[key] = newValue;
  4980. }
  4981. }
  4982. },
  4983. toJSON: function (meta) {
  4984. const isRoot = meta === undefined || typeof meta === 'string';
  4985. if (isRoot) {
  4986. meta = {
  4987. textures: {},
  4988. images: {}
  4989. };
  4990. }
  4991. const data = {
  4992. metadata: {
  4993. version: 4.5,
  4994. type: 'Material',
  4995. generator: 'Material.toJSON'
  4996. }
  4997. }; // standard Material serialization
  4998. data.uuid = this.uuid;
  4999. data.type = this.type;
  5000. if (this.name !== '') data.name = this.name;
  5001. if (this.color && this.color.isColor) data.color = this.color.getHex();
  5002. if (this.roughness !== undefined) data.roughness = this.roughness;
  5003. if (this.metalness !== undefined) data.metalness = this.metalness;
  5004. if (this.sheen && this.sheen.isColor) data.sheen = this.sheen.getHex();
  5005. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  5006. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  5007. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  5008. if (this.shininess !== undefined) data.shininess = this.shininess;
  5009. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  5010. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  5011. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  5012. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  5013. }
  5014. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  5015. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  5016. }
  5017. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  5018. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  5019. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5020. }
  5021. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  5022. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  5023. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  5024. if (this.lightMap && this.lightMap.isTexture) {
  5025. data.lightMap = this.lightMap.toJSON(meta).uuid;
  5026. data.lightMapIntensity = this.lightMapIntensity;
  5027. }
  5028. if (this.aoMap && this.aoMap.isTexture) {
  5029. data.aoMap = this.aoMap.toJSON(meta).uuid;
  5030. data.aoMapIntensity = this.aoMapIntensity;
  5031. }
  5032. if (this.bumpMap && this.bumpMap.isTexture) {
  5033. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  5034. data.bumpScale = this.bumpScale;
  5035. }
  5036. if (this.normalMap && this.normalMap.isTexture) {
  5037. data.normalMap = this.normalMap.toJSON(meta).uuid;
  5038. data.normalMapType = this.normalMapType;
  5039. data.normalScale = this.normalScale.toArray();
  5040. }
  5041. if (this.displacementMap && this.displacementMap.isTexture) {
  5042. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  5043. data.displacementScale = this.displacementScale;
  5044. data.displacementBias = this.displacementBias;
  5045. }
  5046. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  5047. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  5048. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  5049. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  5050. if (this.envMap && this.envMap.isTexture) {
  5051. data.envMap = this.envMap.toJSON(meta).uuid;
  5052. if (this.combine !== undefined) data.combine = this.combine;
  5053. }
  5054. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  5055. if (this.reflectivity !== undefined) data.reflectivity = this.reflectivity;
  5056. if (this.refractionRatio !== undefined) data.refractionRatio = this.refractionRatio;
  5057. if (this.gradientMap && this.gradientMap.isTexture) {
  5058. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  5059. }
  5060. if (this.size !== undefined) data.size = this.size;
  5061. if (this.shadowSide !== null) data.shadowSide = this.shadowSide;
  5062. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  5063. if (this.blending !== NormalBlending) data.blending = this.blending;
  5064. if (this.side !== FrontSide) data.side = this.side;
  5065. if (this.vertexColors) data.vertexColors = true;
  5066. if (this.opacity < 1) data.opacity = this.opacity;
  5067. if (this.transparent === true) data.transparent = this.transparent;
  5068. data.depthFunc = this.depthFunc;
  5069. data.depthTest = this.depthTest;
  5070. data.depthWrite = this.depthWrite;
  5071. data.colorWrite = this.colorWrite;
  5072. data.stencilWrite = this.stencilWrite;
  5073. data.stencilWriteMask = this.stencilWriteMask;
  5074. data.stencilFunc = this.stencilFunc;
  5075. data.stencilRef = this.stencilRef;
  5076. data.stencilFuncMask = this.stencilFuncMask;
  5077. data.stencilFail = this.stencilFail;
  5078. data.stencilZFail = this.stencilZFail;
  5079. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  5080. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  5081. if (this.polygonOffset === true) data.polygonOffset = true;
  5082. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5083. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5084. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  5085. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  5086. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  5087. if (this.scale !== undefined) data.scale = this.scale;
  5088. if (this.dithering === true) data.dithering = true;
  5089. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  5090. if (this.alphaToCoverage === true) data.alphaToCoverage = this.alphaToCoverage;
  5091. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  5092. if (this.wireframe === true) data.wireframe = this.wireframe;
  5093. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  5094. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  5095. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  5096. if (this.morphTargets === true) data.morphTargets = true;
  5097. if (this.morphNormals === true) data.morphNormals = true;
  5098. if (this.skinning === true) data.skinning = true;
  5099. if (this.flatShading === true) data.flatShading = this.flatShading;
  5100. if (this.visible === false) data.visible = false;
  5101. if (this.toneMapped === false) data.toneMapped = false;
  5102. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  5103. function extractFromCache(cache) {
  5104. const values = [];
  5105. for (const key in cache) {
  5106. const data = cache[key];
  5107. delete data.metadata;
  5108. values.push(data);
  5109. }
  5110. return values;
  5111. }
  5112. if (isRoot) {
  5113. const textures = extractFromCache(meta.textures);
  5114. const images = extractFromCache(meta.images);
  5115. if (textures.length > 0) data.textures = textures;
  5116. if (images.length > 0) data.images = images;
  5117. }
  5118. return data;
  5119. },
  5120. clone: function () {
  5121. return new this.constructor().copy(this);
  5122. },
  5123. copy: function (source) {
  5124. this.name = source.name;
  5125. this.fog = source.fog;
  5126. this.blending = source.blending;
  5127. this.side = source.side;
  5128. this.vertexColors = source.vertexColors;
  5129. this.opacity = source.opacity;
  5130. this.transparent = source.transparent;
  5131. this.blendSrc = source.blendSrc;
  5132. this.blendDst = source.blendDst;
  5133. this.blendEquation = source.blendEquation;
  5134. this.blendSrcAlpha = source.blendSrcAlpha;
  5135. this.blendDstAlpha = source.blendDstAlpha;
  5136. this.blendEquationAlpha = source.blendEquationAlpha;
  5137. this.depthFunc = source.depthFunc;
  5138. this.depthTest = source.depthTest;
  5139. this.depthWrite = source.depthWrite;
  5140. this.stencilWriteMask = source.stencilWriteMask;
  5141. this.stencilFunc = source.stencilFunc;
  5142. this.stencilRef = source.stencilRef;
  5143. this.stencilFuncMask = source.stencilFuncMask;
  5144. this.stencilFail = source.stencilFail;
  5145. this.stencilZFail = source.stencilZFail;
  5146. this.stencilZPass = source.stencilZPass;
  5147. this.stencilWrite = source.stencilWrite;
  5148. const srcPlanes = source.clippingPlanes;
  5149. let dstPlanes = null;
  5150. if (srcPlanes !== null) {
  5151. const n = srcPlanes.length;
  5152. dstPlanes = new Array(n);
  5153. for (let i = 0; i !== n; ++i) {
  5154. dstPlanes[i] = srcPlanes[i].clone();
  5155. }
  5156. }
  5157. this.clippingPlanes = dstPlanes;
  5158. this.clipIntersection = source.clipIntersection;
  5159. this.clipShadows = source.clipShadows;
  5160. this.shadowSide = source.shadowSide;
  5161. this.colorWrite = source.colorWrite;
  5162. this.precision = source.precision;
  5163. this.polygonOffset = source.polygonOffset;
  5164. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5165. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5166. this.dithering = source.dithering;
  5167. this.alphaTest = source.alphaTest;
  5168. this.alphaToCoverage = source.alphaToCoverage;
  5169. this.premultipliedAlpha = source.premultipliedAlpha;
  5170. this.visible = source.visible;
  5171. this.toneMapped = source.toneMapped;
  5172. this.userData = JSON.parse(JSON.stringify(source.userData));
  5173. return this;
  5174. },
  5175. dispose: function () {
  5176. this.dispatchEvent({
  5177. type: 'dispose'
  5178. });
  5179. }
  5180. });
  5181. Object.defineProperty(Material.prototype, 'needsUpdate', {
  5182. set: function (value) {
  5183. if (value === true) this.version++;
  5184. }
  5185. });
  5186. const _colorKeywords = {
  5187. 'aliceblue': 0xF0F8FF,
  5188. 'antiquewhite': 0xFAEBD7,
  5189. 'aqua': 0x00FFFF,
  5190. 'aquamarine': 0x7FFFD4,
  5191. 'azure': 0xF0FFFF,
  5192. 'beige': 0xF5F5DC,
  5193. 'bisque': 0xFFE4C4,
  5194. 'black': 0x000000,
  5195. 'blanchedalmond': 0xFFEBCD,
  5196. 'blue': 0x0000FF,
  5197. 'blueviolet': 0x8A2BE2,
  5198. 'brown': 0xA52A2A,
  5199. 'burlywood': 0xDEB887,
  5200. 'cadetblue': 0x5F9EA0,
  5201. 'chartreuse': 0x7FFF00,
  5202. 'chocolate': 0xD2691E,
  5203. 'coral': 0xFF7F50,
  5204. 'cornflowerblue': 0x6495ED,
  5205. 'cornsilk': 0xFFF8DC,
  5206. 'crimson': 0xDC143C,
  5207. 'cyan': 0x00FFFF,
  5208. 'darkblue': 0x00008B,
  5209. 'darkcyan': 0x008B8B,
  5210. 'darkgoldenrod': 0xB8860B,
  5211. 'darkgray': 0xA9A9A9,
  5212. 'darkgreen': 0x006400,
  5213. 'darkgrey': 0xA9A9A9,
  5214. 'darkkhaki': 0xBDB76B,
  5215. 'darkmagenta': 0x8B008B,
  5216. 'darkolivegreen': 0x556B2F,
  5217. 'darkorange': 0xFF8C00,
  5218. 'darkorchid': 0x9932CC,
  5219. 'darkred': 0x8B0000,
  5220. 'darksalmon': 0xE9967A,
  5221. 'darkseagreen': 0x8FBC8F,
  5222. 'darkslateblue': 0x483D8B,
  5223. 'darkslategray': 0x2F4F4F,
  5224. 'darkslategrey': 0x2F4F4F,
  5225. 'darkturquoise': 0x00CED1,
  5226. 'darkviolet': 0x9400D3,
  5227. 'deeppink': 0xFF1493,
  5228. 'deepskyblue': 0x00BFFF,
  5229. 'dimgray': 0x696969,
  5230. 'dimgrey': 0x696969,
  5231. 'dodgerblue': 0x1E90FF,
  5232. 'firebrick': 0xB22222,
  5233. 'floralwhite': 0xFFFAF0,
  5234. 'forestgreen': 0x228B22,
  5235. 'fuchsia': 0xFF00FF,
  5236. 'gainsboro': 0xDCDCDC,
  5237. 'ghostwhite': 0xF8F8FF,
  5238. 'gold': 0xFFD700,
  5239. 'goldenrod': 0xDAA520,
  5240. 'gray': 0x808080,
  5241. 'green': 0x008000,
  5242. 'greenyellow': 0xADFF2F,
  5243. 'grey': 0x808080,
  5244. 'honeydew': 0xF0FFF0,
  5245. 'hotpink': 0xFF69B4,
  5246. 'indianred': 0xCD5C5C,
  5247. 'indigo': 0x4B0082,
  5248. 'ivory': 0xFFFFF0,
  5249. 'khaki': 0xF0E68C,
  5250. 'lavender': 0xE6E6FA,
  5251. 'lavenderblush': 0xFFF0F5,
  5252. 'lawngreen': 0x7CFC00,
  5253. 'lemonchiffon': 0xFFFACD,
  5254. 'lightblue': 0xADD8E6,
  5255. 'lightcoral': 0xF08080,
  5256. 'lightcyan': 0xE0FFFF,
  5257. 'lightgoldenrodyellow': 0xFAFAD2,
  5258. 'lightgray': 0xD3D3D3,
  5259. 'lightgreen': 0x90EE90,
  5260. 'lightgrey': 0xD3D3D3,
  5261. 'lightpink': 0xFFB6C1,
  5262. 'lightsalmon': 0xFFA07A,
  5263. 'lightseagreen': 0x20B2AA,
  5264. 'lightskyblue': 0x87CEFA,
  5265. 'lightslategray': 0x778899,
  5266. 'lightslategrey': 0x778899,
  5267. 'lightsteelblue': 0xB0C4DE,
  5268. 'lightyellow': 0xFFFFE0,
  5269. 'lime': 0x00FF00,
  5270. 'limegreen': 0x32CD32,
  5271. 'linen': 0xFAF0E6,
  5272. 'magenta': 0xFF00FF,
  5273. 'maroon': 0x800000,
  5274. 'mediumaquamarine': 0x66CDAA,
  5275. 'mediumblue': 0x0000CD,
  5276. 'mediumorchid': 0xBA55D3,
  5277. 'mediumpurple': 0x9370DB,
  5278. 'mediumseagreen': 0x3CB371,
  5279. 'mediumslateblue': 0x7B68EE,
  5280. 'mediumspringgreen': 0x00FA9A,
  5281. 'mediumturquoise': 0x48D1CC,
  5282. 'mediumvioletred': 0xC71585,
  5283. 'midnightblue': 0x191970,
  5284. 'mintcream': 0xF5FFFA,
  5285. 'mistyrose': 0xFFE4E1,
  5286. 'moccasin': 0xFFE4B5,
  5287. 'navajowhite': 0xFFDEAD,
  5288. 'navy': 0x000080,
  5289. 'oldlace': 0xFDF5E6,
  5290. 'olive': 0x808000,
  5291. 'olivedrab': 0x6B8E23,
  5292. 'orange': 0xFFA500,
  5293. 'orangered': 0xFF4500,
  5294. 'orchid': 0xDA70D6,
  5295. 'palegoldenrod': 0xEEE8AA,
  5296. 'palegreen': 0x98FB98,
  5297. 'paleturquoise': 0xAFEEEE,
  5298. 'palevioletred': 0xDB7093,
  5299. 'papayawhip': 0xFFEFD5,
  5300. 'peachpuff': 0xFFDAB9,
  5301. 'peru': 0xCD853F,
  5302. 'pink': 0xFFC0CB,
  5303. 'plum': 0xDDA0DD,
  5304. 'powderblue': 0xB0E0E6,
  5305. 'purple': 0x800080,
  5306. 'rebeccapurple': 0x663399,
  5307. 'red': 0xFF0000,
  5308. 'rosybrown': 0xBC8F8F,
  5309. 'royalblue': 0x4169E1,
  5310. 'saddlebrown': 0x8B4513,
  5311. 'salmon': 0xFA8072,
  5312. 'sandybrown': 0xF4A460,
  5313. 'seagreen': 0x2E8B57,
  5314. 'seashell': 0xFFF5EE,
  5315. 'sienna': 0xA0522D,
  5316. 'silver': 0xC0C0C0,
  5317. 'skyblue': 0x87CEEB,
  5318. 'slateblue': 0x6A5ACD,
  5319. 'slategray': 0x708090,
  5320. 'slategrey': 0x708090,
  5321. 'snow': 0xFFFAFA,
  5322. 'springgreen': 0x00FF7F,
  5323. 'steelblue': 0x4682B4,
  5324. 'tan': 0xD2B48C,
  5325. 'teal': 0x008080,
  5326. 'thistle': 0xD8BFD8,
  5327. 'tomato': 0xFF6347,
  5328. 'turquoise': 0x40E0D0,
  5329. 'violet': 0xEE82EE,
  5330. 'wheat': 0xF5DEB3,
  5331. 'white': 0xFFFFFF,
  5332. 'whitesmoke': 0xF5F5F5,
  5333. 'yellow': 0xFFFF00,
  5334. 'yellowgreen': 0x9ACD32
  5335. };
  5336. const _hslA = {
  5337. h: 0,
  5338. s: 0,
  5339. l: 0
  5340. };
  5341. const _hslB = {
  5342. h: 0,
  5343. s: 0,
  5344. l: 0
  5345. };
  5346. function hue2rgb(p, q, t) {
  5347. if (t < 0) t += 1;
  5348. if (t > 1) t -= 1;
  5349. if (t < 1 / 6) return p + (q - p) * 6 * t;
  5350. if (t < 1 / 2) return q;
  5351. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  5352. return p;
  5353. }
  5354. function SRGBToLinear(c) {
  5355. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  5356. }
  5357. function LinearToSRGB(c) {
  5358. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  5359. }
  5360. class Color {
  5361. constructor(r, g, b) {
  5362. if (g === undefined && b === undefined) {
  5363. // r is THREE.Color, hex or string
  5364. return this.set(r);
  5365. }
  5366. return this.setRGB(r, g, b);
  5367. }
  5368. set(value) {
  5369. if (value && value.isColor) {
  5370. this.copy(value);
  5371. } else if (typeof value === 'number') {
  5372. this.setHex(value);
  5373. } else if (typeof value === 'string') {
  5374. this.setStyle(value);
  5375. }
  5376. return this;
  5377. }
  5378. setScalar(scalar) {
  5379. this.r = scalar;
  5380. this.g = scalar;
  5381. this.b = scalar;
  5382. return this;
  5383. }
  5384. setHex(hex) {
  5385. hex = Math.floor(hex);
  5386. this.r = (hex >> 16 & 255) / 255;
  5387. this.g = (hex >> 8 & 255) / 255;
  5388. this.b = (hex & 255) / 255;
  5389. return this;
  5390. }
  5391. setRGB(r, g, b) {
  5392. this.r = r;
  5393. this.g = g;
  5394. this.b = b;
  5395. return this;
  5396. }
  5397. setHSL(h, s, l) {
  5398. // h,s,l ranges are in 0.0 - 1.0
  5399. h = euclideanModulo(h, 1);
  5400. s = clamp(s, 0, 1);
  5401. l = clamp(l, 0, 1);
  5402. if (s === 0) {
  5403. this.r = this.g = this.b = l;
  5404. } else {
  5405. const p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  5406. const q = 2 * l - p;
  5407. this.r = hue2rgb(q, p, h + 1 / 3);
  5408. this.g = hue2rgb(q, p, h);
  5409. this.b = hue2rgb(q, p, h - 1 / 3);
  5410. }
  5411. return this;
  5412. }
  5413. setStyle(style) {
  5414. function handleAlpha(string) {
  5415. if (string === undefined) return;
  5416. if (parseFloat(string) < 1) {
  5417. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  5418. }
  5419. }
  5420. let m;
  5421. if (m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style)) {
  5422. // rgb / hsl
  5423. let color;
  5424. const name = m[1];
  5425. const components = m[2];
  5426. switch (name) {
  5427. case 'rgb':
  5428. case 'rgba':
  5429. if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5430. // rgb(255,0,0) rgba(255,0,0,0.5)
  5431. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  5432. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  5433. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  5434. handleAlpha(color[4]);
  5435. return this;
  5436. }
  5437. if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5438. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5439. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  5440. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  5441. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  5442. handleAlpha(color[4]);
  5443. return this;
  5444. }
  5445. break;
  5446. case 'hsl':
  5447. case 'hsla':
  5448. if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5449. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5450. const h = parseFloat(color[1]) / 360;
  5451. const s = parseInt(color[2], 10) / 100;
  5452. const l = parseInt(color[3], 10) / 100;
  5453. handleAlpha(color[4]);
  5454. return this.setHSL(h, s, l);
  5455. }
  5456. break;
  5457. }
  5458. } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) {
  5459. // hex color
  5460. const hex = m[1];
  5461. const size = hex.length;
  5462. if (size === 3) {
  5463. // #ff0
  5464. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  5465. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  5466. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  5467. return this;
  5468. } else if (size === 6) {
  5469. // #ff0000
  5470. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  5471. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  5472. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  5473. return this;
  5474. }
  5475. }
  5476. if (style && style.length > 0) {
  5477. return this.setColorName(style);
  5478. }
  5479. return this;
  5480. }
  5481. setColorName(style) {
  5482. // color keywords
  5483. const hex = _colorKeywords[style.toLowerCase()];
  5484. if (hex !== undefined) {
  5485. // red
  5486. this.setHex(hex);
  5487. } else {
  5488. // unknown color
  5489. console.warn('THREE.Color: Unknown color ' + style);
  5490. }
  5491. return this;
  5492. }
  5493. clone() {
  5494. return new this.constructor(this.r, this.g, this.b);
  5495. }
  5496. copy(color) {
  5497. this.r = color.r;
  5498. this.g = color.g;
  5499. this.b = color.b;
  5500. return this;
  5501. }
  5502. copyGammaToLinear(color, gammaFactor = 2.0) {
  5503. this.r = Math.pow(color.r, gammaFactor);
  5504. this.g = Math.pow(color.g, gammaFactor);
  5505. this.b = Math.pow(color.b, gammaFactor);
  5506. return this;
  5507. }
  5508. copyLinearToGamma(color, gammaFactor = 2.0) {
  5509. const safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  5510. this.r = Math.pow(color.r, safeInverse);
  5511. this.g = Math.pow(color.g, safeInverse);
  5512. this.b = Math.pow(color.b, safeInverse);
  5513. return this;
  5514. }
  5515. convertGammaToLinear(gammaFactor) {
  5516. this.copyGammaToLinear(this, gammaFactor);
  5517. return this;
  5518. }
  5519. convertLinearToGamma(gammaFactor) {
  5520. this.copyLinearToGamma(this, gammaFactor);
  5521. return this;
  5522. }
  5523. copySRGBToLinear(color) {
  5524. this.r = SRGBToLinear(color.r);
  5525. this.g = SRGBToLinear(color.g);
  5526. this.b = SRGBToLinear(color.b);
  5527. return this;
  5528. }
  5529. copyLinearToSRGB(color) {
  5530. this.r = LinearToSRGB(color.r);
  5531. this.g = LinearToSRGB(color.g);
  5532. this.b = LinearToSRGB(color.b);
  5533. return this;
  5534. }
  5535. convertSRGBToLinear() {
  5536. this.copySRGBToLinear(this);
  5537. return this;
  5538. }
  5539. convertLinearToSRGB() {
  5540. this.copyLinearToSRGB(this);
  5541. return this;
  5542. }
  5543. getHex() {
  5544. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  5545. }
  5546. getHexString() {
  5547. return ('000000' + this.getHex().toString(16)).slice(-6);
  5548. }
  5549. getHSL(target) {
  5550. // h,s,l ranges are in 0.0 - 1.0
  5551. if (target === undefined) {
  5552. console.warn('THREE.Color: .getHSL() target is now required');
  5553. target = {
  5554. h: 0,
  5555. s: 0,
  5556. l: 0
  5557. };
  5558. }
  5559. const r = this.r,
  5560. g = this.g,
  5561. b = this.b;
  5562. const max = Math.max(r, g, b);
  5563. const min = Math.min(r, g, b);
  5564. let hue, saturation;
  5565. const lightness = (min + max) / 2.0;
  5566. if (min === max) {
  5567. hue = 0;
  5568. saturation = 0;
  5569. } else {
  5570. const delta = max - min;
  5571. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  5572. switch (max) {
  5573. case r:
  5574. hue = (g - b) / delta + (g < b ? 6 : 0);
  5575. break;
  5576. case g:
  5577. hue = (b - r) / delta + 2;
  5578. break;
  5579. case b:
  5580. hue = (r - g) / delta + 4;
  5581. break;
  5582. }
  5583. hue /= 6;
  5584. }
  5585. target.h = hue;
  5586. target.s = saturation;
  5587. target.l = lightness;
  5588. return target;
  5589. }
  5590. getStyle() {
  5591. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  5592. }
  5593. offsetHSL(h, s, l) {
  5594. this.getHSL(_hslA);
  5595. _hslA.h += h;
  5596. _hslA.s += s;
  5597. _hslA.l += l;
  5598. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  5599. return this;
  5600. }
  5601. add(color) {
  5602. this.r += color.r;
  5603. this.g += color.g;
  5604. this.b += color.b;
  5605. return this;
  5606. }
  5607. addColors(color1, color2) {
  5608. this.r = color1.r + color2.r;
  5609. this.g = color1.g + color2.g;
  5610. this.b = color1.b + color2.b;
  5611. return this;
  5612. }
  5613. addScalar(s) {
  5614. this.r += s;
  5615. this.g += s;
  5616. this.b += s;
  5617. return this;
  5618. }
  5619. sub(color) {
  5620. this.r = Math.max(0, this.r - color.r);
  5621. this.g = Math.max(0, this.g - color.g);
  5622. this.b = Math.max(0, this.b - color.b);
  5623. return this;
  5624. }
  5625. multiply(color) {
  5626. this.r *= color.r;
  5627. this.g *= color.g;
  5628. this.b *= color.b;
  5629. return this;
  5630. }
  5631. multiplyScalar(s) {
  5632. this.r *= s;
  5633. this.g *= s;
  5634. this.b *= s;
  5635. return this;
  5636. }
  5637. lerp(color, alpha) {
  5638. this.r += (color.r - this.r) * alpha;
  5639. this.g += (color.g - this.g) * alpha;
  5640. this.b += (color.b - this.b) * alpha;
  5641. return this;
  5642. }
  5643. lerpColors(color1, color2, alpha) {
  5644. this.r = color1.r + (color2.r - color1.r) * alpha;
  5645. this.g = color1.g + (color2.g - color1.g) * alpha;
  5646. this.b = color1.b + (color2.b - color1.b) * alpha;
  5647. return this;
  5648. }
  5649. lerpHSL(color, alpha) {
  5650. this.getHSL(_hslA);
  5651. color.getHSL(_hslB);
  5652. const h = lerp(_hslA.h, _hslB.h, alpha);
  5653. const s = lerp(_hslA.s, _hslB.s, alpha);
  5654. const l = lerp(_hslA.l, _hslB.l, alpha);
  5655. this.setHSL(h, s, l);
  5656. return this;
  5657. }
  5658. equals(c) {
  5659. return c.r === this.r && c.g === this.g && c.b === this.b;
  5660. }
  5661. fromArray(array, offset = 0) {
  5662. this.r = array[offset];
  5663. this.g = array[offset + 1];
  5664. this.b = array[offset + 2];
  5665. return this;
  5666. }
  5667. toArray(array = [], offset = 0) {
  5668. array[offset] = this.r;
  5669. array[offset + 1] = this.g;
  5670. array[offset + 2] = this.b;
  5671. return array;
  5672. }
  5673. fromBufferAttribute(attribute, index) {
  5674. this.r = attribute.getX(index);
  5675. this.g = attribute.getY(index);
  5676. this.b = attribute.getZ(index);
  5677. if (attribute.normalized === true) {
  5678. // assuming Uint8Array
  5679. this.r /= 255;
  5680. this.g /= 255;
  5681. this.b /= 255;
  5682. }
  5683. return this;
  5684. }
  5685. toJSON() {
  5686. return this.getHex();
  5687. }
  5688. }
  5689. Color.NAMES = _colorKeywords;
  5690. Color.prototype.isColor = true;
  5691. Color.prototype.r = 1;
  5692. Color.prototype.g = 1;
  5693. Color.prototype.b = 1;
  5694. /**
  5695. * parameters = {
  5696. * color: <hex>,
  5697. * opacity: <float>,
  5698. * map: new THREE.Texture( <Image> ),
  5699. *
  5700. * lightMap: new THREE.Texture( <Image> ),
  5701. * lightMapIntensity: <float>
  5702. *
  5703. * aoMap: new THREE.Texture( <Image> ),
  5704. * aoMapIntensity: <float>
  5705. *
  5706. * specularMap: new THREE.Texture( <Image> ),
  5707. *
  5708. * alphaMap: new THREE.Texture( <Image> ),
  5709. *
  5710. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  5711. * combine: THREE.Multiply,
  5712. * reflectivity: <float>,
  5713. * refractionRatio: <float>,
  5714. *
  5715. * depthTest: <bool>,
  5716. * depthWrite: <bool>,
  5717. *
  5718. * wireframe: <boolean>,
  5719. * wireframeLinewidth: <float>,
  5720. *
  5721. * skinning: <bool>,
  5722. * morphTargets: <bool>
  5723. * }
  5724. */
  5725. class MeshBasicMaterial extends Material {
  5726. constructor(parameters) {
  5727. super();
  5728. this.type = 'MeshBasicMaterial';
  5729. this.color = new Color(0xffffff); // emissive
  5730. this.map = null;
  5731. this.lightMap = null;
  5732. this.lightMapIntensity = 1.0;
  5733. this.aoMap = null;
  5734. this.aoMapIntensity = 1.0;
  5735. this.specularMap = null;
  5736. this.alphaMap = null;
  5737. this.envMap = null;
  5738. this.combine = MultiplyOperation;
  5739. this.reflectivity = 1;
  5740. this.refractionRatio = 0.98;
  5741. this.wireframe = false;
  5742. this.wireframeLinewidth = 1;
  5743. this.wireframeLinecap = 'round';
  5744. this.wireframeLinejoin = 'round';
  5745. this.skinning = false;
  5746. this.morphTargets = false;
  5747. this.setValues(parameters);
  5748. }
  5749. copy(source) {
  5750. super.copy(source);
  5751. this.color.copy(source.color);
  5752. this.map = source.map;
  5753. this.lightMap = source.lightMap;
  5754. this.lightMapIntensity = source.lightMapIntensity;
  5755. this.aoMap = source.aoMap;
  5756. this.aoMapIntensity = source.aoMapIntensity;
  5757. this.specularMap = source.specularMap;
  5758. this.alphaMap = source.alphaMap;
  5759. this.envMap = source.envMap;
  5760. this.combine = source.combine;
  5761. this.reflectivity = source.reflectivity;
  5762. this.refractionRatio = source.refractionRatio;
  5763. this.wireframe = source.wireframe;
  5764. this.wireframeLinewidth = source.wireframeLinewidth;
  5765. this.wireframeLinecap = source.wireframeLinecap;
  5766. this.wireframeLinejoin = source.wireframeLinejoin;
  5767. this.skinning = source.skinning;
  5768. this.morphTargets = source.morphTargets;
  5769. return this;
  5770. }
  5771. }
  5772. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  5773. const _vector$9 = new /*@__PURE__*/Vector3();
  5774. const _vector2 = new /*@__PURE__*/Vector2();
  5775. class BufferAttribute {
  5776. constructor(array, itemSize, normalized) {
  5777. if (Array.isArray(array)) {
  5778. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  5779. }
  5780. this.name = '';
  5781. this.array = array;
  5782. this.itemSize = itemSize;
  5783. this.count = array !== undefined ? array.length / itemSize : 0;
  5784. this.normalized = normalized === true;
  5785. this.usage = StaticDrawUsage;
  5786. this.updateRange = {
  5787. offset: 0,
  5788. count: -1
  5789. };
  5790. this.version = 0;
  5791. this.onUploadCallback = function () {};
  5792. }
  5793. set needsUpdate(value) {
  5794. if (value === true) this.version++;
  5795. }
  5796. setUsage(value) {
  5797. this.usage = value;
  5798. return this;
  5799. }
  5800. copy(source) {
  5801. this.name = source.name;
  5802. this.array = new source.array.constructor(source.array);
  5803. this.itemSize = source.itemSize;
  5804. this.count = source.count;
  5805. this.normalized = source.normalized;
  5806. this.usage = source.usage;
  5807. return this;
  5808. }
  5809. copyAt(index1, attribute, index2) {
  5810. index1 *= this.itemSize;
  5811. index2 *= attribute.itemSize;
  5812. for (let i = 0, l = this.itemSize; i < l; i++) {
  5813. this.array[index1 + i] = attribute.array[index2 + i];
  5814. }
  5815. return this;
  5816. }
  5817. copyArray(array) {
  5818. this.array.set(array);
  5819. return this;
  5820. }
  5821. copyColorsArray(colors) {
  5822. const array = this.array;
  5823. let offset = 0;
  5824. for (let i = 0, l = colors.length; i < l; i++) {
  5825. let color = colors[i];
  5826. if (color === undefined) {
  5827. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  5828. color = new Color();
  5829. }
  5830. array[offset++] = color.r;
  5831. array[offset++] = color.g;
  5832. array[offset++] = color.b;
  5833. }
  5834. return this;
  5835. }
  5836. copyVector2sArray(vectors) {
  5837. const array = this.array;
  5838. let offset = 0;
  5839. for (let i = 0, l = vectors.length; i < l; i++) {
  5840. let vector = vectors[i];
  5841. if (vector === undefined) {
  5842. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  5843. vector = new Vector2();
  5844. }
  5845. array[offset++] = vector.x;
  5846. array[offset++] = vector.y;
  5847. }
  5848. return this;
  5849. }
  5850. copyVector3sArray(vectors) {
  5851. const array = this.array;
  5852. let offset = 0;
  5853. for (let i = 0, l = vectors.length; i < l; i++) {
  5854. let vector = vectors[i];
  5855. if (vector === undefined) {
  5856. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  5857. vector = new Vector3();
  5858. }
  5859. array[offset++] = vector.x;
  5860. array[offset++] = vector.y;
  5861. array[offset++] = vector.z;
  5862. }
  5863. return this;
  5864. }
  5865. copyVector4sArray(vectors) {
  5866. const array = this.array;
  5867. let offset = 0;
  5868. for (let i = 0, l = vectors.length; i < l; i++) {
  5869. let vector = vectors[i];
  5870. if (vector === undefined) {
  5871. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  5872. vector = new Vector4();
  5873. }
  5874. array[offset++] = vector.x;
  5875. array[offset++] = vector.y;
  5876. array[offset++] = vector.z;
  5877. array[offset++] = vector.w;
  5878. }
  5879. return this;
  5880. }
  5881. applyMatrix3(m) {
  5882. if (this.itemSize === 2) {
  5883. for (let i = 0, l = this.count; i < l; i++) {
  5884. _vector2.fromBufferAttribute(this, i);
  5885. _vector2.applyMatrix3(m);
  5886. this.setXY(i, _vector2.x, _vector2.y);
  5887. }
  5888. } else if (this.itemSize === 3) {
  5889. for (let i = 0, l = this.count; i < l; i++) {
  5890. _vector$9.fromBufferAttribute(this, i);
  5891. _vector$9.applyMatrix3(m);
  5892. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5893. }
  5894. }
  5895. return this;
  5896. }
  5897. applyMatrix4(m) {
  5898. for (let i = 0, l = this.count; i < l; i++) {
  5899. _vector$9.x = this.getX(i);
  5900. _vector$9.y = this.getY(i);
  5901. _vector$9.z = this.getZ(i);
  5902. _vector$9.applyMatrix4(m);
  5903. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5904. }
  5905. return this;
  5906. }
  5907. applyNormalMatrix(m) {
  5908. for (let i = 0, l = this.count; i < l; i++) {
  5909. _vector$9.x = this.getX(i);
  5910. _vector$9.y = this.getY(i);
  5911. _vector$9.z = this.getZ(i);
  5912. _vector$9.applyNormalMatrix(m);
  5913. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5914. }
  5915. return this;
  5916. }
  5917. transformDirection(m) {
  5918. for (let i = 0, l = this.count; i < l; i++) {
  5919. _vector$9.x = this.getX(i);
  5920. _vector$9.y = this.getY(i);
  5921. _vector$9.z = this.getZ(i);
  5922. _vector$9.transformDirection(m);
  5923. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5924. }
  5925. return this;
  5926. }
  5927. set(value, offset = 0) {
  5928. this.array.set(value, offset);
  5929. return this;
  5930. }
  5931. getX(index) {
  5932. return this.array[index * this.itemSize];
  5933. }
  5934. setX(index, x) {
  5935. this.array[index * this.itemSize] = x;
  5936. return this;
  5937. }
  5938. getY(index) {
  5939. return this.array[index * this.itemSize + 1];
  5940. }
  5941. setY(index, y) {
  5942. this.array[index * this.itemSize + 1] = y;
  5943. return this;
  5944. }
  5945. getZ(index) {
  5946. return this.array[index * this.itemSize + 2];
  5947. }
  5948. setZ(index, z) {
  5949. this.array[index * this.itemSize + 2] = z;
  5950. return this;
  5951. }
  5952. getW(index) {
  5953. return this.array[index * this.itemSize + 3];
  5954. }
  5955. setW(index, w) {
  5956. this.array[index * this.itemSize + 3] = w;
  5957. return this;
  5958. }
  5959. setXY(index, x, y) {
  5960. index *= this.itemSize;
  5961. this.array[index + 0] = x;
  5962. this.array[index + 1] = y;
  5963. return this;
  5964. }
  5965. setXYZ(index, x, y, z) {
  5966. index *= this.itemSize;
  5967. this.array[index + 0] = x;
  5968. this.array[index + 1] = y;
  5969. this.array[index + 2] = z;
  5970. return this;
  5971. }
  5972. setXYZW(index, x, y, z, w) {
  5973. index *= this.itemSize;
  5974. this.array[index + 0] = x;
  5975. this.array[index + 1] = y;
  5976. this.array[index + 2] = z;
  5977. this.array[index + 3] = w;
  5978. return this;
  5979. }
  5980. onUpload(callback) {
  5981. this.onUploadCallback = callback;
  5982. return this;
  5983. }
  5984. clone() {
  5985. return new this.constructor(this.array, this.itemSize).copy(this);
  5986. }
  5987. toJSON() {
  5988. const data = {
  5989. itemSize: this.itemSize,
  5990. type: this.array.constructor.name,
  5991. array: Array.prototype.slice.call(this.array),
  5992. normalized: this.normalized
  5993. };
  5994. if (this.name !== '') data.name = this.name;
  5995. if (this.usage !== StaticDrawUsage) data.usage = this.usage;
  5996. if (this.updateRange.offset !== 0 || this.updateRange.count !== -1) data.updateRange = this.updateRange;
  5997. return data;
  5998. }
  5999. }
  6000. BufferAttribute.prototype.isBufferAttribute = true; //
  6001. class Int8BufferAttribute extends BufferAttribute {
  6002. constructor(array, itemSize, normalized) {
  6003. super(new Int8Array(array), itemSize, normalized);
  6004. }
  6005. }
  6006. class Uint8BufferAttribute extends BufferAttribute {
  6007. constructor(array, itemSize, normalized) {
  6008. super(new Uint8Array(array), itemSize, normalized);
  6009. }
  6010. }
  6011. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6012. constructor(array, itemSize, normalized) {
  6013. super(new Uint8ClampedArray(array), itemSize, normalized);
  6014. }
  6015. }
  6016. class Int16BufferAttribute extends BufferAttribute {
  6017. constructor(array, itemSize, normalized) {
  6018. super(new Int16Array(array), itemSize, normalized);
  6019. }
  6020. }
  6021. class Uint16BufferAttribute extends BufferAttribute {
  6022. constructor(array, itemSize, normalized) {
  6023. super(new Uint16Array(array), itemSize, normalized);
  6024. }
  6025. }
  6026. class Int32BufferAttribute extends BufferAttribute {
  6027. constructor(array, itemSize, normalized) {
  6028. super(new Int32Array(array), itemSize, normalized);
  6029. }
  6030. }
  6031. class Uint32BufferAttribute extends BufferAttribute {
  6032. constructor(array, itemSize, normalized) {
  6033. super(new Uint32Array(array), itemSize, normalized);
  6034. }
  6035. }
  6036. class Float16BufferAttribute extends BufferAttribute {
  6037. constructor(array, itemSize, normalized) {
  6038. super(new Uint16Array(array), itemSize, normalized);
  6039. }
  6040. }
  6041. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  6042. class Float32BufferAttribute extends BufferAttribute {
  6043. constructor(array, itemSize, normalized) {
  6044. super(new Float32Array(array), itemSize, normalized);
  6045. }
  6046. }
  6047. class Float64BufferAttribute extends BufferAttribute {
  6048. constructor(array, itemSize, normalized) {
  6049. super(new Float64Array(array), itemSize, normalized);
  6050. }
  6051. } //
  6052. function arrayMax(array) {
  6053. if (array.length === 0) return -Infinity;
  6054. let max = array[0];
  6055. for (let i = 1, l = array.length; i < l; ++i) {
  6056. if (array[i] > max) max = array[i];
  6057. }
  6058. return max;
  6059. }
  6060. const TYPED_ARRAYS = {
  6061. Int8Array: Int8Array,
  6062. Uint8Array: Uint8Array,
  6063. Uint8ClampedArray: Uint8ClampedArray,
  6064. Int16Array: Int16Array,
  6065. Uint16Array: Uint16Array,
  6066. Int32Array: Int32Array,
  6067. Uint32Array: Uint32Array,
  6068. Float32Array: Float32Array,
  6069. Float64Array: Float64Array
  6070. };
  6071. function getTypedArray(type, buffer) {
  6072. return new TYPED_ARRAYS[type](buffer);
  6073. }
  6074. let _id = 0;
  6075. const _m1 = new /*@__PURE__*/Matrix4();
  6076. const _obj = new /*@__PURE__*/Object3D();
  6077. const _offset = new /*@__PURE__*/Vector3();
  6078. const _box$1 = new /*@__PURE__*/Box3();
  6079. const _boxMorphTargets = new /*@__PURE__*/Box3();
  6080. const _vector$8 = new /*@__PURE__*/Vector3();
  6081. class BufferGeometry extends EventDispatcher {
  6082. constructor() {
  6083. super();
  6084. Object.defineProperty(this, 'id', {
  6085. value: _id++
  6086. });
  6087. this.uuid = generateUUID();
  6088. this.name = '';
  6089. this.type = 'BufferGeometry';
  6090. this.index = null;
  6091. this.attributes = {};
  6092. this.morphAttributes = {};
  6093. this.morphTargetsRelative = false;
  6094. this.groups = [];
  6095. this.boundingBox = null;
  6096. this.boundingSphere = null;
  6097. this.drawRange = {
  6098. start: 0,
  6099. count: Infinity
  6100. };
  6101. this.userData = {};
  6102. }
  6103. getIndex() {
  6104. return this.index;
  6105. }
  6106. setIndex(index) {
  6107. if (Array.isArray(index)) {
  6108. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  6109. } else {
  6110. this.index = index;
  6111. }
  6112. return this;
  6113. }
  6114. getAttribute(name) {
  6115. return this.attributes[name];
  6116. }
  6117. setAttribute(name, attribute) {
  6118. this.attributes[name] = attribute;
  6119. return this;
  6120. }
  6121. deleteAttribute(name) {
  6122. delete this.attributes[name];
  6123. return this;
  6124. }
  6125. hasAttribute(name) {
  6126. return this.attributes[name] !== undefined;
  6127. }
  6128. addGroup(start, count, materialIndex = 0) {
  6129. this.groups.push({
  6130. start: start,
  6131. count: count,
  6132. materialIndex: materialIndex
  6133. });
  6134. }
  6135. clearGroups() {
  6136. this.groups = [];
  6137. }
  6138. setDrawRange(start, count) {
  6139. this.drawRange.start = start;
  6140. this.drawRange.count = count;
  6141. }
  6142. applyMatrix4(matrix) {
  6143. const position = this.attributes.position;
  6144. if (position !== undefined) {
  6145. position.applyMatrix4(matrix);
  6146. position.needsUpdate = true;
  6147. }
  6148. const normal = this.attributes.normal;
  6149. if (normal !== undefined) {
  6150. const normalMatrix = new Matrix3().getNormalMatrix(matrix);
  6151. normal.applyNormalMatrix(normalMatrix);
  6152. normal.needsUpdate = true;
  6153. }
  6154. const tangent = this.attributes.tangent;
  6155. if (tangent !== undefined) {
  6156. tangent.transformDirection(matrix);
  6157. tangent.needsUpdate = true;
  6158. }
  6159. if (this.boundingBox !== null) {
  6160. this.computeBoundingBox();
  6161. }
  6162. if (this.boundingSphere !== null) {
  6163. this.computeBoundingSphere();
  6164. }
  6165. return this;
  6166. }
  6167. rotateX(angle) {
  6168. // rotate geometry around world x-axis
  6169. _m1.makeRotationX(angle);
  6170. this.applyMatrix4(_m1);
  6171. return this;
  6172. }
  6173. rotateY(angle) {
  6174. // rotate geometry around world y-axis
  6175. _m1.makeRotationY(angle);
  6176. this.applyMatrix4(_m1);
  6177. return this;
  6178. }
  6179. rotateZ(angle) {
  6180. // rotate geometry around world z-axis
  6181. _m1.makeRotationZ(angle);
  6182. this.applyMatrix4(_m1);
  6183. return this;
  6184. }
  6185. translate(x, y, z) {
  6186. // translate geometry
  6187. _m1.makeTranslation(x, y, z);
  6188. this.applyMatrix4(_m1);
  6189. return this;
  6190. }
  6191. scale(x, y, z) {
  6192. // scale geometry
  6193. _m1.makeScale(x, y, z);
  6194. this.applyMatrix4(_m1);
  6195. return this;
  6196. }
  6197. lookAt(vector) {
  6198. _obj.lookAt(vector);
  6199. _obj.updateMatrix();
  6200. this.applyMatrix4(_obj.matrix);
  6201. return this;
  6202. }
  6203. center() {
  6204. this.computeBoundingBox();
  6205. this.boundingBox.getCenter(_offset).negate();
  6206. this.translate(_offset.x, _offset.y, _offset.z);
  6207. return this;
  6208. }
  6209. setFromPoints(points) {
  6210. const position = [];
  6211. for (let i = 0, l = points.length; i < l; i++) {
  6212. const point = points[i];
  6213. position.push(point.x, point.y, point.z || 0);
  6214. }
  6215. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  6216. return this;
  6217. }
  6218. computeBoundingBox() {
  6219. if (this.boundingBox === null) {
  6220. this.boundingBox = new Box3();
  6221. }
  6222. const position = this.attributes.position;
  6223. const morphAttributesPosition = this.morphAttributes.position;
  6224. if (position && position.isGLBufferAttribute) {
  6225. console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
  6226. this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
  6227. return;
  6228. }
  6229. if (position !== undefined) {
  6230. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  6231. if (morphAttributesPosition) {
  6232. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6233. const morphAttribute = morphAttributesPosition[i];
  6234. _box$1.setFromBufferAttribute(morphAttribute);
  6235. if (this.morphTargetsRelative) {
  6236. _vector$8.addVectors(this.boundingBox.min, _box$1.min);
  6237. this.boundingBox.expandByPoint(_vector$8);
  6238. _vector$8.addVectors(this.boundingBox.max, _box$1.max);
  6239. this.boundingBox.expandByPoint(_vector$8);
  6240. } else {
  6241. this.boundingBox.expandByPoint(_box$1.min);
  6242. this.boundingBox.expandByPoint(_box$1.max);
  6243. }
  6244. }
  6245. }
  6246. } else {
  6247. this.boundingBox.makeEmpty();
  6248. }
  6249. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  6250. console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  6251. }
  6252. }
  6253. computeBoundingSphere() {
  6254. if (this.boundingSphere === null) {
  6255. this.boundingSphere = new Sphere();
  6256. }
  6257. const position = this.attributes.position;
  6258. const morphAttributesPosition = this.morphAttributes.position;
  6259. if (position && position.isGLBufferAttribute) {
  6260. console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
  6261. this.boundingSphere.set(new Vector3(), Infinity);
  6262. return;
  6263. }
  6264. if (position) {
  6265. // first, find the center of the bounding sphere
  6266. const center = this.boundingSphere.center;
  6267. _box$1.setFromBufferAttribute(position); // process morph attributes if present
  6268. if (morphAttributesPosition) {
  6269. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6270. const morphAttribute = morphAttributesPosition[i];
  6271. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  6272. if (this.morphTargetsRelative) {
  6273. _vector$8.addVectors(_box$1.min, _boxMorphTargets.min);
  6274. _box$1.expandByPoint(_vector$8);
  6275. _vector$8.addVectors(_box$1.max, _boxMorphTargets.max);
  6276. _box$1.expandByPoint(_vector$8);
  6277. } else {
  6278. _box$1.expandByPoint(_boxMorphTargets.min);
  6279. _box$1.expandByPoint(_boxMorphTargets.max);
  6280. }
  6281. }
  6282. }
  6283. _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  6284. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6285. let maxRadiusSq = 0;
  6286. for (let i = 0, il = position.count; i < il; i++) {
  6287. _vector$8.fromBufferAttribute(position, i);
  6288. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6289. } // process morph attributes if present
  6290. if (morphAttributesPosition) {
  6291. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6292. const morphAttribute = morphAttributesPosition[i];
  6293. const morphTargetsRelative = this.morphTargetsRelative;
  6294. for (let j = 0, jl = morphAttribute.count; j < jl; j++) {
  6295. _vector$8.fromBufferAttribute(morphAttribute, j);
  6296. if (morphTargetsRelative) {
  6297. _offset.fromBufferAttribute(position, j);
  6298. _vector$8.add(_offset);
  6299. }
  6300. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6301. }
  6302. }
  6303. }
  6304. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  6305. if (isNaN(this.boundingSphere.radius)) {
  6306. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  6307. }
  6308. }
  6309. }
  6310. computeFaceNormals() {// backwards compatibility
  6311. }
  6312. computeTangents() {
  6313. const index = this.index;
  6314. const attributes = this.attributes; // based on http://www.terathon.com/code/tangent.html
  6315. // (per vertex tangents)
  6316. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  6317. console.error('THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)');
  6318. return;
  6319. }
  6320. const indices = index.array;
  6321. const positions = attributes.position.array;
  6322. const normals = attributes.normal.array;
  6323. const uvs = attributes.uv.array;
  6324. const nVertices = positions.length / 3;
  6325. if (attributes.tangent === undefined) {
  6326. this.setAttribute('tangent', new BufferAttribute(new Float32Array(4 * nVertices), 4));
  6327. }
  6328. const tangents = attributes.tangent.array;
  6329. const tan1 = [],
  6330. tan2 = [];
  6331. for (let i = 0; i < nVertices; i++) {
  6332. tan1[i] = new Vector3();
  6333. tan2[i] = new Vector3();
  6334. }
  6335. const vA = new Vector3(),
  6336. vB = new Vector3(),
  6337. vC = new Vector3(),
  6338. uvA = new Vector2(),
  6339. uvB = new Vector2(),
  6340. uvC = new Vector2(),
  6341. sdir = new Vector3(),
  6342. tdir = new Vector3();
  6343. function handleTriangle(a, b, c) {
  6344. vA.fromArray(positions, a * 3);
  6345. vB.fromArray(positions, b * 3);
  6346. vC.fromArray(positions, c * 3);
  6347. uvA.fromArray(uvs, a * 2);
  6348. uvB.fromArray(uvs, b * 2);
  6349. uvC.fromArray(uvs, c * 2);
  6350. vB.sub(vA);
  6351. vC.sub(vA);
  6352. uvB.sub(uvA);
  6353. uvC.sub(uvA);
  6354. const r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y); // silently ignore degenerate uv triangles having coincident or colinear vertices
  6355. if (!isFinite(r)) return;
  6356. sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
  6357. tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
  6358. tan1[a].add(sdir);
  6359. tan1[b].add(sdir);
  6360. tan1[c].add(sdir);
  6361. tan2[a].add(tdir);
  6362. tan2[b].add(tdir);
  6363. tan2[c].add(tdir);
  6364. }
  6365. let groups = this.groups;
  6366. if (groups.length === 0) {
  6367. groups = [{
  6368. start: 0,
  6369. count: indices.length
  6370. }];
  6371. }
  6372. for (let i = 0, il = groups.length; i < il; ++i) {
  6373. const group = groups[i];
  6374. const start = group.start;
  6375. const count = group.count;
  6376. for (let j = start, jl = start + count; j < jl; j += 3) {
  6377. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  6378. }
  6379. }
  6380. const tmp = new Vector3(),
  6381. tmp2 = new Vector3();
  6382. const n = new Vector3(),
  6383. n2 = new Vector3();
  6384. function handleVertex(v) {
  6385. n.fromArray(normals, v * 3);
  6386. n2.copy(n);
  6387. const t = tan1[v]; // Gram-Schmidt orthogonalize
  6388. tmp.copy(t);
  6389. tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
  6390. tmp2.crossVectors(n2, t);
  6391. const test = tmp2.dot(tan2[v]);
  6392. const w = test < 0.0 ? -1.0 : 1.0;
  6393. tangents[v * 4] = tmp.x;
  6394. tangents[v * 4 + 1] = tmp.y;
  6395. tangents[v * 4 + 2] = tmp.z;
  6396. tangents[v * 4 + 3] = w;
  6397. }
  6398. for (let i = 0, il = groups.length; i < il; ++i) {
  6399. const group = groups[i];
  6400. const start = group.start;
  6401. const count = group.count;
  6402. for (let j = start, jl = start + count; j < jl; j += 3) {
  6403. handleVertex(indices[j + 0]);
  6404. handleVertex(indices[j + 1]);
  6405. handleVertex(indices[j + 2]);
  6406. }
  6407. }
  6408. }
  6409. computeVertexNormals() {
  6410. const index = this.index;
  6411. const positionAttribute = this.getAttribute('position');
  6412. if (positionAttribute !== undefined) {
  6413. let normalAttribute = this.getAttribute('normal');
  6414. if (normalAttribute === undefined) {
  6415. normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
  6416. this.setAttribute('normal', normalAttribute);
  6417. } else {
  6418. // reset existing normals to zero
  6419. for (let i = 0, il = normalAttribute.count; i < il; i++) {
  6420. normalAttribute.setXYZ(i, 0, 0, 0);
  6421. }
  6422. }
  6423. const pA = new Vector3(),
  6424. pB = new Vector3(),
  6425. pC = new Vector3();
  6426. const nA = new Vector3(),
  6427. nB = new Vector3(),
  6428. nC = new Vector3();
  6429. const cb = new Vector3(),
  6430. ab = new Vector3(); // indexed elements
  6431. if (index) {
  6432. for (let i = 0, il = index.count; i < il; i += 3) {
  6433. const vA = index.getX(i + 0);
  6434. const vB = index.getX(i + 1);
  6435. const vC = index.getX(i + 2);
  6436. pA.fromBufferAttribute(positionAttribute, vA);
  6437. pB.fromBufferAttribute(positionAttribute, vB);
  6438. pC.fromBufferAttribute(positionAttribute, vC);
  6439. cb.subVectors(pC, pB);
  6440. ab.subVectors(pA, pB);
  6441. cb.cross(ab);
  6442. nA.fromBufferAttribute(normalAttribute, vA);
  6443. nB.fromBufferAttribute(normalAttribute, vB);
  6444. nC.fromBufferAttribute(normalAttribute, vC);
  6445. nA.add(cb);
  6446. nB.add(cb);
  6447. nC.add(cb);
  6448. normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
  6449. normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
  6450. normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
  6451. }
  6452. } else {
  6453. // non-indexed elements (unconnected triangle soup)
  6454. for (let i = 0, il = positionAttribute.count; i < il; i += 3) {
  6455. pA.fromBufferAttribute(positionAttribute, i + 0);
  6456. pB.fromBufferAttribute(positionAttribute, i + 1);
  6457. pC.fromBufferAttribute(positionAttribute, i + 2);
  6458. cb.subVectors(pC, pB);
  6459. ab.subVectors(pA, pB);
  6460. cb.cross(ab);
  6461. normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z);
  6462. normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z);
  6463. normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z);
  6464. }
  6465. }
  6466. this.normalizeNormals();
  6467. normalAttribute.needsUpdate = true;
  6468. }
  6469. }
  6470. merge(geometry, offset) {
  6471. if (!(geometry && geometry.isBufferGeometry)) {
  6472. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  6473. return;
  6474. }
  6475. if (offset === undefined) {
  6476. offset = 0;
  6477. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  6478. }
  6479. const attributes = this.attributes;
  6480. for (const key in attributes) {
  6481. if (geometry.attributes[key] === undefined) continue;
  6482. const attribute1 = attributes[key];
  6483. const attributeArray1 = attribute1.array;
  6484. const attribute2 = geometry.attributes[key];
  6485. const attributeArray2 = attribute2.array;
  6486. const attributeOffset = attribute2.itemSize * offset;
  6487. const length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  6488. for (let i = 0, j = attributeOffset; i < length; i++, j++) {
  6489. attributeArray1[j] = attributeArray2[i];
  6490. }
  6491. }
  6492. return this;
  6493. }
  6494. normalizeNormals() {
  6495. const normals = this.attributes.normal;
  6496. for (let i = 0, il = normals.count; i < il; i++) {
  6497. _vector$8.fromBufferAttribute(normals, i);
  6498. _vector$8.normalize();
  6499. normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z);
  6500. }
  6501. }
  6502. toNonIndexed() {
  6503. function convertBufferAttribute(attribute, indices) {
  6504. const array = attribute.array;
  6505. const itemSize = attribute.itemSize;
  6506. const normalized = attribute.normalized;
  6507. const array2 = new array.constructor(indices.length * itemSize);
  6508. let index = 0,
  6509. index2 = 0;
  6510. for (let i = 0, l = indices.length; i < l; i++) {
  6511. index = indices[i] * itemSize;
  6512. for (let j = 0; j < itemSize; j++) {
  6513. array2[index2++] = array[index++];
  6514. }
  6515. }
  6516. return new BufferAttribute(array2, itemSize, normalized);
  6517. } //
  6518. if (this.index === null) {
  6519. console.warn('THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.');
  6520. return this;
  6521. }
  6522. const geometry2 = new BufferGeometry();
  6523. const indices = this.index.array;
  6524. const attributes = this.attributes; // attributes
  6525. for (const name in attributes) {
  6526. const attribute = attributes[name];
  6527. const newAttribute = convertBufferAttribute(attribute, indices);
  6528. geometry2.setAttribute(name, newAttribute);
  6529. } // morph attributes
  6530. const morphAttributes = this.morphAttributes;
  6531. for (const name in morphAttributes) {
  6532. const morphArray = [];
  6533. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6534. for (let i = 0, il = morphAttribute.length; i < il; i++) {
  6535. const attribute = morphAttribute[i];
  6536. const newAttribute = convertBufferAttribute(attribute, indices);
  6537. morphArray.push(newAttribute);
  6538. }
  6539. geometry2.morphAttributes[name] = morphArray;
  6540. }
  6541. geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
  6542. const groups = this.groups;
  6543. for (let i = 0, l = groups.length; i < l; i++) {
  6544. const group = groups[i];
  6545. geometry2.addGroup(group.start, group.count, group.materialIndex);
  6546. }
  6547. return geometry2;
  6548. }
  6549. toJSON() {
  6550. const data = {
  6551. metadata: {
  6552. version: 4.5,
  6553. type: 'BufferGeometry',
  6554. generator: 'BufferGeometry.toJSON'
  6555. }
  6556. }; // standard BufferGeometry serialization
  6557. data.uuid = this.uuid;
  6558. data.type = this.type;
  6559. if (this.name !== '') data.name = this.name;
  6560. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  6561. if (this.parameters !== undefined) {
  6562. const parameters = this.parameters;
  6563. for (const key in parameters) {
  6564. if (parameters[key] !== undefined) data[key] = parameters[key];
  6565. }
  6566. return data;
  6567. } // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6568. data.data = {
  6569. attributes: {}
  6570. };
  6571. const index = this.index;
  6572. if (index !== null) {
  6573. data.data.index = {
  6574. type: index.array.constructor.name,
  6575. array: Array.prototype.slice.call(index.array)
  6576. };
  6577. }
  6578. const attributes = this.attributes;
  6579. for (const key in attributes) {
  6580. const attribute = attributes[key];
  6581. data.data.attributes[key] = attribute.toJSON(data.data);
  6582. }
  6583. const morphAttributes = {};
  6584. let hasMorphAttributes = false;
  6585. for (const key in this.morphAttributes) {
  6586. const attributeArray = this.morphAttributes[key];
  6587. const array = [];
  6588. for (let i = 0, il = attributeArray.length; i < il; i++) {
  6589. const attribute = attributeArray[i];
  6590. array.push(attribute.toJSON(data.data));
  6591. }
  6592. if (array.length > 0) {
  6593. morphAttributes[key] = array;
  6594. hasMorphAttributes = true;
  6595. }
  6596. }
  6597. if (hasMorphAttributes) {
  6598. data.data.morphAttributes = morphAttributes;
  6599. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6600. }
  6601. const groups = this.groups;
  6602. if (groups.length > 0) {
  6603. data.data.groups = JSON.parse(JSON.stringify(groups));
  6604. }
  6605. const boundingSphere = this.boundingSphere;
  6606. if (boundingSphere !== null) {
  6607. data.data.boundingSphere = {
  6608. center: boundingSphere.center.toArray(),
  6609. radius: boundingSphere.radius
  6610. };
  6611. }
  6612. return data;
  6613. }
  6614. clone() {
  6615. /*
  6616. // Handle primitives
  6617. const parameters = this.parameters;
  6618. if ( parameters !== undefined ) {
  6619. const values = [];
  6620. for ( const key in parameters ) {
  6621. values.push( parameters[ key ] );
  6622. }
  6623. const geometry = Object.create( this.constructor.prototype );
  6624. this.constructor.apply( geometry, values );
  6625. return geometry;
  6626. }
  6627. return new this.constructor().copy( this );
  6628. */
  6629. return new BufferGeometry().copy(this);
  6630. }
  6631. copy(source) {
  6632. // reset
  6633. this.index = null;
  6634. this.attributes = {};
  6635. this.morphAttributes = {};
  6636. this.groups = [];
  6637. this.boundingBox = null;
  6638. this.boundingSphere = null; // used for storing cloned, shared data
  6639. const data = {}; // name
  6640. this.name = source.name; // index
  6641. const index = source.index;
  6642. if (index !== null) {
  6643. this.setIndex(index.clone(data));
  6644. } // attributes
  6645. const attributes = source.attributes;
  6646. for (const name in attributes) {
  6647. const attribute = attributes[name];
  6648. this.setAttribute(name, attribute.clone(data));
  6649. } // morph attributes
  6650. const morphAttributes = source.morphAttributes;
  6651. for (const name in morphAttributes) {
  6652. const array = [];
  6653. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6654. for (let i = 0, l = morphAttribute.length; i < l; i++) {
  6655. array.push(morphAttribute[i].clone(data));
  6656. }
  6657. this.morphAttributes[name] = array;
  6658. }
  6659. this.morphTargetsRelative = source.morphTargetsRelative; // groups
  6660. const groups = source.groups;
  6661. for (let i = 0, l = groups.length; i < l; i++) {
  6662. const group = groups[i];
  6663. this.addGroup(group.start, group.count, group.materialIndex);
  6664. } // bounding box
  6665. const boundingBox = source.boundingBox;
  6666. if (boundingBox !== null) {
  6667. this.boundingBox = boundingBox.clone();
  6668. } // bounding sphere
  6669. const boundingSphere = source.boundingSphere;
  6670. if (boundingSphere !== null) {
  6671. this.boundingSphere = boundingSphere.clone();
  6672. } // draw range
  6673. this.drawRange.start = source.drawRange.start;
  6674. this.drawRange.count = source.drawRange.count; // user data
  6675. this.userData = source.userData;
  6676. return this;
  6677. }
  6678. dispose() {
  6679. this.dispatchEvent({
  6680. type: 'dispose'
  6681. });
  6682. }
  6683. }
  6684. BufferGeometry.prototype.isBufferGeometry = true;
  6685. const _inverseMatrix$2 = /*@__PURE__*/new Matrix4();
  6686. const _ray$2 = /*@__PURE__*/new Ray();
  6687. const _sphere$3 = /*@__PURE__*/new Sphere();
  6688. const _vA$1 = /*@__PURE__*/new Vector3();
  6689. const _vB$1 = /*@__PURE__*/new Vector3();
  6690. const _vC$1 = /*@__PURE__*/new Vector3();
  6691. const _tempA = /*@__PURE__*/new Vector3();
  6692. const _tempB = /*@__PURE__*/new Vector3();
  6693. const _tempC = /*@__PURE__*/new Vector3();
  6694. const _morphA = /*@__PURE__*/new Vector3();
  6695. const _morphB = /*@__PURE__*/new Vector3();
  6696. const _morphC = /*@__PURE__*/new Vector3();
  6697. const _uvA$1 = /*@__PURE__*/new Vector2();
  6698. const _uvB$1 = /*@__PURE__*/new Vector2();
  6699. const _uvC$1 = /*@__PURE__*/new Vector2();
  6700. const _intersectionPoint = /*@__PURE__*/new Vector3();
  6701. const _intersectionPointWorld = /*@__PURE__*/new Vector3();
  6702. class Mesh extends Object3D {
  6703. constructor(geometry = new BufferGeometry(), material = new MeshBasicMaterial()) {
  6704. super();
  6705. this.type = 'Mesh';
  6706. this.geometry = geometry;
  6707. this.material = material;
  6708. this.updateMorphTargets();
  6709. }
  6710. copy(source) {
  6711. super.copy(source);
  6712. if (source.morphTargetInfluences !== undefined) {
  6713. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6714. }
  6715. if (source.morphTargetDictionary !== undefined) {
  6716. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  6717. }
  6718. this.material = source.material;
  6719. this.geometry = source.geometry;
  6720. return this;
  6721. }
  6722. updateMorphTargets() {
  6723. const geometry = this.geometry;
  6724. if (geometry.isBufferGeometry) {
  6725. const morphAttributes = geometry.morphAttributes;
  6726. const keys = Object.keys(morphAttributes);
  6727. if (keys.length > 0) {
  6728. const morphAttribute = morphAttributes[keys[0]];
  6729. if (morphAttribute !== undefined) {
  6730. this.morphTargetInfluences = [];
  6731. this.morphTargetDictionary = {};
  6732. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  6733. const name = morphAttribute[m].name || String(m);
  6734. this.morphTargetInfluences.push(0);
  6735. this.morphTargetDictionary[name] = m;
  6736. }
  6737. }
  6738. }
  6739. } else {
  6740. const morphTargets = geometry.morphTargets;
  6741. if (morphTargets !== undefined && morphTargets.length > 0) {
  6742. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6743. }
  6744. }
  6745. }
  6746. raycast(raycaster, intersects) {
  6747. const geometry = this.geometry;
  6748. const material = this.material;
  6749. const matrixWorld = this.matrixWorld;
  6750. if (material === undefined) return; // Checking boundingSphere distance to ray
  6751. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  6752. _sphere$3.copy(geometry.boundingSphere);
  6753. _sphere$3.applyMatrix4(matrixWorld);
  6754. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  6755. _inverseMatrix$2.copy(matrixWorld).invert();
  6756. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2); // Check boundingBox before continuing
  6757. if (geometry.boundingBox !== null) {
  6758. if (_ray$2.intersectsBox(geometry.boundingBox) === false) return;
  6759. }
  6760. let intersection;
  6761. if (geometry.isBufferGeometry) {
  6762. const index = geometry.index;
  6763. const position = geometry.attributes.position;
  6764. const morphPosition = geometry.morphAttributes.position;
  6765. const morphTargetsRelative = geometry.morphTargetsRelative;
  6766. const uv = geometry.attributes.uv;
  6767. const uv2 = geometry.attributes.uv2;
  6768. const groups = geometry.groups;
  6769. const drawRange = geometry.drawRange;
  6770. if (index !== null) {
  6771. // indexed buffer geometry
  6772. if (Array.isArray(material)) {
  6773. for (let i = 0, il = groups.length; i < il; i++) {
  6774. const group = groups[i];
  6775. const groupMaterial = material[group.materialIndex];
  6776. const start = Math.max(group.start, drawRange.start);
  6777. const end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  6778. for (let j = start, jl = end; j < jl; j += 3) {
  6779. const a = index.getX(j);
  6780. const b = index.getX(j + 1);
  6781. const c = index.getX(j + 2);
  6782. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6783. if (intersection) {
  6784. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  6785. intersection.face.materialIndex = group.materialIndex;
  6786. intersects.push(intersection);
  6787. }
  6788. }
  6789. }
  6790. } else {
  6791. const start = Math.max(0, drawRange.start);
  6792. const end = Math.min(index.count, drawRange.start + drawRange.count);
  6793. for (let i = start, il = end; i < il; i += 3) {
  6794. const a = index.getX(i);
  6795. const b = index.getX(i + 1);
  6796. const c = index.getX(i + 2);
  6797. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6798. if (intersection) {
  6799. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  6800. intersects.push(intersection);
  6801. }
  6802. }
  6803. }
  6804. } else if (position !== undefined) {
  6805. // non-indexed buffer geometry
  6806. if (Array.isArray(material)) {
  6807. for (let i = 0, il = groups.length; i < il; i++) {
  6808. const group = groups[i];
  6809. const groupMaterial = material[group.materialIndex];
  6810. const start = Math.max(group.start, drawRange.start);
  6811. const end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  6812. for (let j = start, jl = end; j < jl; j += 3) {
  6813. const a = j;
  6814. const b = j + 1;
  6815. const c = j + 2;
  6816. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6817. if (intersection) {
  6818. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  6819. intersection.face.materialIndex = group.materialIndex;
  6820. intersects.push(intersection);
  6821. }
  6822. }
  6823. }
  6824. } else {
  6825. const start = Math.max(0, drawRange.start);
  6826. const end = Math.min(position.count, drawRange.start + drawRange.count);
  6827. for (let i = start, il = end; i < il; i += 3) {
  6828. const a = i;
  6829. const b = i + 1;
  6830. const c = i + 2;
  6831. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6832. if (intersection) {
  6833. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  6834. intersects.push(intersection);
  6835. }
  6836. }
  6837. }
  6838. }
  6839. } else if (geometry.isGeometry) {
  6840. console.error('THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6841. }
  6842. }
  6843. }
  6844. Mesh.prototype.isMesh = true;
  6845. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  6846. let intersect;
  6847. if (material.side === BackSide) {
  6848. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  6849. } else {
  6850. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  6851. }
  6852. if (intersect === null) return null;
  6853. _intersectionPointWorld.copy(point);
  6854. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  6855. const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  6856. if (distance < raycaster.near || distance > raycaster.far) return null;
  6857. return {
  6858. distance: distance,
  6859. point: _intersectionPointWorld.clone(),
  6860. object: object
  6861. };
  6862. }
  6863. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  6864. _vA$1.fromBufferAttribute(position, a);
  6865. _vB$1.fromBufferAttribute(position, b);
  6866. _vC$1.fromBufferAttribute(position, c);
  6867. const morphInfluences = object.morphTargetInfluences;
  6868. if (material.morphTargets && morphPosition && morphInfluences) {
  6869. _morphA.set(0, 0, 0);
  6870. _morphB.set(0, 0, 0);
  6871. _morphC.set(0, 0, 0);
  6872. for (let i = 0, il = morphPosition.length; i < il; i++) {
  6873. const influence = morphInfluences[i];
  6874. const morphAttribute = morphPosition[i];
  6875. if (influence === 0) continue;
  6876. _tempA.fromBufferAttribute(morphAttribute, a);
  6877. _tempB.fromBufferAttribute(morphAttribute, b);
  6878. _tempC.fromBufferAttribute(morphAttribute, c);
  6879. if (morphTargetsRelative) {
  6880. _morphA.addScaledVector(_tempA, influence);
  6881. _morphB.addScaledVector(_tempB, influence);
  6882. _morphC.addScaledVector(_tempC, influence);
  6883. } else {
  6884. _morphA.addScaledVector(_tempA.sub(_vA$1), influence);
  6885. _morphB.addScaledVector(_tempB.sub(_vB$1), influence);
  6886. _morphC.addScaledVector(_tempC.sub(_vC$1), influence);
  6887. }
  6888. }
  6889. _vA$1.add(_morphA);
  6890. _vB$1.add(_morphB);
  6891. _vC$1.add(_morphC);
  6892. }
  6893. if (object.isSkinnedMesh && material.skinning) {
  6894. object.boneTransform(a, _vA$1);
  6895. object.boneTransform(b, _vB$1);
  6896. object.boneTransform(c, _vC$1);
  6897. }
  6898. const intersection = checkIntersection(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint);
  6899. if (intersection) {
  6900. if (uv) {
  6901. _uvA$1.fromBufferAttribute(uv, a);
  6902. _uvB$1.fromBufferAttribute(uv, b);
  6903. _uvC$1.fromBufferAttribute(uv, c);
  6904. intersection.uv = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6905. }
  6906. if (uv2) {
  6907. _uvA$1.fromBufferAttribute(uv2, a);
  6908. _uvB$1.fromBufferAttribute(uv2, b);
  6909. _uvC$1.fromBufferAttribute(uv2, c);
  6910. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6911. }
  6912. const face = {
  6913. a: a,
  6914. b: b,
  6915. c: c,
  6916. normal: new Vector3(),
  6917. materialIndex: 0
  6918. };
  6919. Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal);
  6920. intersection.face = face;
  6921. }
  6922. return intersection;
  6923. }
  6924. class BoxGeometry extends BufferGeometry {
  6925. constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
  6926. super();
  6927. this.type = 'BoxGeometry';
  6928. this.parameters = {
  6929. width: width,
  6930. height: height,
  6931. depth: depth,
  6932. widthSegments: widthSegments,
  6933. heightSegments: heightSegments,
  6934. depthSegments: depthSegments
  6935. };
  6936. const scope = this; // segments
  6937. widthSegments = Math.floor(widthSegments);
  6938. heightSegments = Math.floor(heightSegments);
  6939. depthSegments = Math.floor(depthSegments); // buffers
  6940. const indices = [];
  6941. const vertices = [];
  6942. const normals = [];
  6943. const uvs = []; // helper variables
  6944. let numberOfVertices = 0;
  6945. let groupStart = 0; // build each side of the box geometry
  6946. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  6947. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  6948. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  6949. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  6950. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  6951. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  6952. // build geometry
  6953. this.setIndex(indices);
  6954. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  6955. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  6956. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  6957. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  6958. const segmentWidth = width / gridX;
  6959. const segmentHeight = height / gridY;
  6960. const widthHalf = width / 2;
  6961. const heightHalf = height / 2;
  6962. const depthHalf = depth / 2;
  6963. const gridX1 = gridX + 1;
  6964. const gridY1 = gridY + 1;
  6965. let vertexCounter = 0;
  6966. let groupCount = 0;
  6967. const vector = new Vector3(); // generate vertices, normals and uvs
  6968. for (let iy = 0; iy < gridY1; iy++) {
  6969. const y = iy * segmentHeight - heightHalf;
  6970. for (let ix = 0; ix < gridX1; ix++) {
  6971. const x = ix * segmentWidth - widthHalf; // set values to correct vector component
  6972. vector[u] = x * udir;
  6973. vector[v] = y * vdir;
  6974. vector[w] = depthHalf; // now apply vector to vertex buffer
  6975. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  6976. vector[u] = 0;
  6977. vector[v] = 0;
  6978. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  6979. normals.push(vector.x, vector.y, vector.z); // uvs
  6980. uvs.push(ix / gridX);
  6981. uvs.push(1 - iy / gridY); // counters
  6982. vertexCounter += 1;
  6983. }
  6984. } // indices
  6985. // 1. you need three indices to draw a single face
  6986. // 2. a single segment consists of two faces
  6987. // 3. so we need to generate six (2*3) indices per segment
  6988. for (let iy = 0; iy < gridY; iy++) {
  6989. for (let ix = 0; ix < gridX; ix++) {
  6990. const a = numberOfVertices + ix + gridX1 * iy;
  6991. const b = numberOfVertices + ix + gridX1 * (iy + 1);
  6992. const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  6993. const d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  6994. indices.push(a, b, d);
  6995. indices.push(b, c, d); // increase counter
  6996. groupCount += 6;
  6997. }
  6998. } // add a group to the geometry. this will ensure multi material support
  6999. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  7000. groupStart += groupCount; // update total number of vertices
  7001. numberOfVertices += vertexCounter;
  7002. }
  7003. }
  7004. }
  7005. /**
  7006. * Uniform Utilities
  7007. */
  7008. function cloneUniforms(src) {
  7009. const dst = {};
  7010. for (const u in src) {
  7011. dst[u] = {};
  7012. for (const p in src[u]) {
  7013. const property = src[u][p];
  7014. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion)) {
  7015. dst[u][p] = property.clone();
  7016. } else if (Array.isArray(property)) {
  7017. dst[u][p] = property.slice();
  7018. } else {
  7019. dst[u][p] = property;
  7020. }
  7021. }
  7022. }
  7023. return dst;
  7024. }
  7025. function mergeUniforms(uniforms) {
  7026. const merged = {};
  7027. for (let u = 0; u < uniforms.length; u++) {
  7028. const tmp = cloneUniforms(uniforms[u]);
  7029. for (const p in tmp) {
  7030. merged[p] = tmp[p];
  7031. }
  7032. }
  7033. return merged;
  7034. } // Legacy
  7035. const UniformsUtils = {
  7036. clone: cloneUniforms,
  7037. merge: mergeUniforms
  7038. };
  7039. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7040. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7041. /**
  7042. * parameters = {
  7043. * defines: { "label" : "value" },
  7044. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  7045. *
  7046. * fragmentShader: <string>,
  7047. * vertexShader: <string>,
  7048. *
  7049. * wireframe: <boolean>,
  7050. * wireframeLinewidth: <float>,
  7051. *
  7052. * lights: <bool>,
  7053. *
  7054. * skinning: <bool>,
  7055. * morphTargets: <bool>,
  7056. * morphNormals: <bool>
  7057. * }
  7058. */
  7059. class ShaderMaterial extends Material {
  7060. constructor(parameters) {
  7061. super();
  7062. this.type = 'ShaderMaterial';
  7063. this.defines = {};
  7064. this.uniforms = {};
  7065. this.vertexShader = default_vertex;
  7066. this.fragmentShader = default_fragment;
  7067. this.linewidth = 1;
  7068. this.wireframe = false;
  7069. this.wireframeLinewidth = 1;
  7070. this.fog = false; // set to use scene fog
  7071. this.lights = false; // set to use scene lights
  7072. this.clipping = false; // set to use user-defined clipping planes
  7073. this.skinning = false; // set to use skinning attribute streams
  7074. this.morphTargets = false; // set to use morph targets
  7075. this.morphNormals = false; // set to use morph normals
  7076. this.extensions = {
  7077. derivatives: false,
  7078. // set to use derivatives
  7079. fragDepth: false,
  7080. // set to use fragment depth values
  7081. drawBuffers: false,
  7082. // set to use draw buffers
  7083. shaderTextureLOD: false // set to use shader texture LOD
  7084. }; // When rendered geometry doesn't include these attributes but the material does,
  7085. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7086. this.defaultAttributeValues = {
  7087. 'color': [1, 1, 1],
  7088. 'uv': [0, 0],
  7089. 'uv2': [0, 0]
  7090. };
  7091. this.index0AttributeName = undefined;
  7092. this.uniformsNeedUpdate = false;
  7093. this.glslVersion = null;
  7094. if (parameters !== undefined) {
  7095. if (parameters.attributes !== undefined) {
  7096. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  7097. }
  7098. this.setValues(parameters);
  7099. }
  7100. }
  7101. copy(source) {
  7102. super.copy(source);
  7103. this.fragmentShader = source.fragmentShader;
  7104. this.vertexShader = source.vertexShader;
  7105. this.uniforms = cloneUniforms(source.uniforms);
  7106. this.defines = Object.assign({}, source.defines);
  7107. this.wireframe = source.wireframe;
  7108. this.wireframeLinewidth = source.wireframeLinewidth;
  7109. this.lights = source.lights;
  7110. this.clipping = source.clipping;
  7111. this.skinning = source.skinning;
  7112. this.morphTargets = source.morphTargets;
  7113. this.morphNormals = source.morphNormals;
  7114. this.extensions = Object.assign({}, source.extensions);
  7115. this.glslVersion = source.glslVersion;
  7116. return this;
  7117. }
  7118. toJSON(meta) {
  7119. const data = super.toJSON(meta);
  7120. data.glslVersion = this.glslVersion;
  7121. data.uniforms = {};
  7122. for (const name in this.uniforms) {
  7123. const uniform = this.uniforms[name];
  7124. const value = uniform.value;
  7125. if (value && value.isTexture) {
  7126. data.uniforms[name] = {
  7127. type: 't',
  7128. value: value.toJSON(meta).uuid
  7129. };
  7130. } else if (value && value.isColor) {
  7131. data.uniforms[name] = {
  7132. type: 'c',
  7133. value: value.getHex()
  7134. };
  7135. } else if (value && value.isVector2) {
  7136. data.uniforms[name] = {
  7137. type: 'v2',
  7138. value: value.toArray()
  7139. };
  7140. } else if (value && value.isVector3) {
  7141. data.uniforms[name] = {
  7142. type: 'v3',
  7143. value: value.toArray()
  7144. };
  7145. } else if (value && value.isVector4) {
  7146. data.uniforms[name] = {
  7147. type: 'v4',
  7148. value: value.toArray()
  7149. };
  7150. } else if (value && value.isMatrix3) {
  7151. data.uniforms[name] = {
  7152. type: 'm3',
  7153. value: value.toArray()
  7154. };
  7155. } else if (value && value.isMatrix4) {
  7156. data.uniforms[name] = {
  7157. type: 'm4',
  7158. value: value.toArray()
  7159. };
  7160. } else {
  7161. data.uniforms[name] = {
  7162. value: value
  7163. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7164. }
  7165. }
  7166. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  7167. data.vertexShader = this.vertexShader;
  7168. data.fragmentShader = this.fragmentShader;
  7169. const extensions = {};
  7170. for (const key in this.extensions) {
  7171. if (this.extensions[key] === true) extensions[key] = true;
  7172. }
  7173. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  7174. return data;
  7175. }
  7176. }
  7177. ShaderMaterial.prototype.isShaderMaterial = true;
  7178. class Camera extends Object3D {
  7179. constructor() {
  7180. super();
  7181. this.type = 'Camera';
  7182. this.matrixWorldInverse = new Matrix4();
  7183. this.projectionMatrix = new Matrix4();
  7184. this.projectionMatrixInverse = new Matrix4();
  7185. }
  7186. copy(source, recursive) {
  7187. super.copy(source, recursive);
  7188. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  7189. this.projectionMatrix.copy(source.projectionMatrix);
  7190. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  7191. return this;
  7192. }
  7193. getWorldDirection(target) {
  7194. if (target === undefined) {
  7195. console.warn('THREE.Camera: .getWorldDirection() target is now required');
  7196. target = new Vector3();
  7197. }
  7198. this.updateWorldMatrix(true, false);
  7199. const e = this.matrixWorld.elements;
  7200. return target.set(-e[8], -e[9], -e[10]).normalize();
  7201. }
  7202. updateMatrixWorld(force) {
  7203. super.updateMatrixWorld(force);
  7204. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7205. }
  7206. updateWorldMatrix(updateParents, updateChildren) {
  7207. super.updateWorldMatrix(updateParents, updateChildren);
  7208. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7209. }
  7210. clone() {
  7211. return new this.constructor().copy(this);
  7212. }
  7213. }
  7214. Camera.prototype.isCamera = true;
  7215. class PerspectiveCamera extends Camera {
  7216. constructor(fov = 50, aspect = 1, near = 0.1, far = 2000) {
  7217. super();
  7218. this.type = 'PerspectiveCamera';
  7219. this.fov = fov;
  7220. this.zoom = 1;
  7221. this.near = near;
  7222. this.far = far;
  7223. this.focus = 10;
  7224. this.aspect = aspect;
  7225. this.view = null;
  7226. this.filmGauge = 35; // width of the film (default in millimeters)
  7227. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7228. this.updateProjectionMatrix();
  7229. }
  7230. copy(source, recursive) {
  7231. super.copy(source, recursive);
  7232. this.fov = source.fov;
  7233. this.zoom = source.zoom;
  7234. this.near = source.near;
  7235. this.far = source.far;
  7236. this.focus = source.focus;
  7237. this.aspect = source.aspect;
  7238. this.view = source.view === null ? null : Object.assign({}, source.view);
  7239. this.filmGauge = source.filmGauge;
  7240. this.filmOffset = source.filmOffset;
  7241. return this;
  7242. }
  7243. /**
  7244. * Sets the FOV by focal length in respect to the current .filmGauge.
  7245. *
  7246. * The default film gauge is 35, so that the focal length can be specified for
  7247. * a 35mm (full frame) camera.
  7248. *
  7249. * Values for focal length and film gauge must have the same unit.
  7250. */
  7251. setFocalLength(focalLength) {
  7252. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7253. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7254. this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope);
  7255. this.updateProjectionMatrix();
  7256. }
  7257. /**
  7258. * Calculates the focal length from the current .fov and .filmGauge.
  7259. */
  7260. getFocalLength() {
  7261. const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov);
  7262. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7263. }
  7264. getEffectiveFOV() {
  7265. return RAD2DEG * 2 * Math.atan(Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom);
  7266. }
  7267. getFilmWidth() {
  7268. // film not completely covered in portrait format (aspect < 1)
  7269. return this.filmGauge * Math.min(this.aspect, 1);
  7270. }
  7271. getFilmHeight() {
  7272. // film not completely covered in landscape format (aspect > 1)
  7273. return this.filmGauge / Math.max(this.aspect, 1);
  7274. }
  7275. /**
  7276. * Sets an offset in a larger frustum. This is useful for multi-window or
  7277. * multi-monitor/multi-machine setups.
  7278. *
  7279. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7280. * the monitors are in grid like this
  7281. *
  7282. * +---+---+---+
  7283. * | A | B | C |
  7284. * +---+---+---+
  7285. * | D | E | F |
  7286. * +---+---+---+
  7287. *
  7288. * then for each monitor you would call it like this
  7289. *
  7290. * const w = 1920;
  7291. * const h = 1080;
  7292. * const fullWidth = w * 3;
  7293. * const fullHeight = h * 2;
  7294. *
  7295. * --A--
  7296. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7297. * --B--
  7298. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7299. * --C--
  7300. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7301. * --D--
  7302. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7303. * --E--
  7304. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7305. * --F--
  7306. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7307. *
  7308. * Note there is no reason monitors have to be the same size or in a grid.
  7309. */
  7310. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  7311. this.aspect = fullWidth / fullHeight;
  7312. if (this.view === null) {
  7313. this.view = {
  7314. enabled: true,
  7315. fullWidth: 1,
  7316. fullHeight: 1,
  7317. offsetX: 0,
  7318. offsetY: 0,
  7319. width: 1,
  7320. height: 1
  7321. };
  7322. }
  7323. this.view.enabled = true;
  7324. this.view.fullWidth = fullWidth;
  7325. this.view.fullHeight = fullHeight;
  7326. this.view.offsetX = x;
  7327. this.view.offsetY = y;
  7328. this.view.width = width;
  7329. this.view.height = height;
  7330. this.updateProjectionMatrix();
  7331. }
  7332. clearViewOffset() {
  7333. if (this.view !== null) {
  7334. this.view.enabled = false;
  7335. }
  7336. this.updateProjectionMatrix();
  7337. }
  7338. updateProjectionMatrix() {
  7339. const near = this.near;
  7340. let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom;
  7341. let height = 2 * top;
  7342. let width = this.aspect * height;
  7343. let left = -0.5 * width;
  7344. const view = this.view;
  7345. if (this.view !== null && this.view.enabled) {
  7346. const fullWidth = view.fullWidth,
  7347. fullHeight = view.fullHeight;
  7348. left += view.offsetX * width / fullWidth;
  7349. top -= view.offsetY * height / fullHeight;
  7350. width *= view.width / fullWidth;
  7351. height *= view.height / fullHeight;
  7352. }
  7353. const skew = this.filmOffset;
  7354. if (skew !== 0) left += near * skew / this.getFilmWidth();
  7355. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  7356. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  7357. }
  7358. toJSON(meta) {
  7359. const data = super.toJSON(meta);
  7360. data.object.fov = this.fov;
  7361. data.object.zoom = this.zoom;
  7362. data.object.near = this.near;
  7363. data.object.far = this.far;
  7364. data.object.focus = this.focus;
  7365. data.object.aspect = this.aspect;
  7366. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  7367. data.object.filmGauge = this.filmGauge;
  7368. data.object.filmOffset = this.filmOffset;
  7369. return data;
  7370. }
  7371. }
  7372. PerspectiveCamera.prototype.isPerspectiveCamera = true;
  7373. const fov = 90,
  7374. aspect = 1;
  7375. class CubeCamera extends Object3D {
  7376. constructor(near, far, renderTarget) {
  7377. super();
  7378. this.type = 'CubeCamera';
  7379. if (renderTarget.isWebGLCubeRenderTarget !== true) {
  7380. console.error('THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.');
  7381. return;
  7382. }
  7383. this.renderTarget = renderTarget;
  7384. const cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  7385. cameraPX.layers = this.layers;
  7386. cameraPX.up.set(0, -1, 0);
  7387. cameraPX.lookAt(new Vector3(1, 0, 0));
  7388. this.add(cameraPX);
  7389. const cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  7390. cameraNX.layers = this.layers;
  7391. cameraNX.up.set(0, -1, 0);
  7392. cameraNX.lookAt(new Vector3(-1, 0, 0));
  7393. this.add(cameraNX);
  7394. const cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  7395. cameraPY.layers = this.layers;
  7396. cameraPY.up.set(0, 0, 1);
  7397. cameraPY.lookAt(new Vector3(0, 1, 0));
  7398. this.add(cameraPY);
  7399. const cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  7400. cameraNY.layers = this.layers;
  7401. cameraNY.up.set(0, 0, -1);
  7402. cameraNY.lookAt(new Vector3(0, -1, 0));
  7403. this.add(cameraNY);
  7404. const cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  7405. cameraPZ.layers = this.layers;
  7406. cameraPZ.up.set(0, -1, 0);
  7407. cameraPZ.lookAt(new Vector3(0, 0, 1));
  7408. this.add(cameraPZ);
  7409. const cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  7410. cameraNZ.layers = this.layers;
  7411. cameraNZ.up.set(0, -1, 0);
  7412. cameraNZ.lookAt(new Vector3(0, 0, -1));
  7413. this.add(cameraNZ);
  7414. }
  7415. update(renderer, scene) {
  7416. if (this.parent === null) this.updateMatrixWorld();
  7417. const renderTarget = this.renderTarget;
  7418. const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children;
  7419. const currentXrEnabled = renderer.xr.enabled;
  7420. const currentRenderTarget = renderer.getRenderTarget();
  7421. renderer.xr.enabled = false;
  7422. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7423. renderTarget.texture.generateMipmaps = false;
  7424. renderer.setRenderTarget(renderTarget, 0);
  7425. renderer.render(scene, cameraPX);
  7426. renderer.setRenderTarget(renderTarget, 1);
  7427. renderer.render(scene, cameraNX);
  7428. renderer.setRenderTarget(renderTarget, 2);
  7429. renderer.render(scene, cameraPY);
  7430. renderer.setRenderTarget(renderTarget, 3);
  7431. renderer.render(scene, cameraNY);
  7432. renderer.setRenderTarget(renderTarget, 4);
  7433. renderer.render(scene, cameraPZ);
  7434. renderTarget.texture.generateMipmaps = generateMipmaps;
  7435. renderer.setRenderTarget(renderTarget, 5);
  7436. renderer.render(scene, cameraNZ);
  7437. renderer.setRenderTarget(currentRenderTarget);
  7438. renderer.xr.enabled = currentXrEnabled;
  7439. }
  7440. }
  7441. class CubeTexture extends Texture {
  7442. constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  7443. images = images !== undefined ? images : [];
  7444. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7445. format = format !== undefined ? format : RGBFormat;
  7446. super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding); // Why CubeTexture._needsFlipEnvMap is necessary:
  7447. //
  7448. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7449. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7450. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7451. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7452. // and the flag _needsFlipEnvMap controls this conversion. The flip is not required (and thus _needsFlipEnvMap is set to false)
  7453. // when using WebGLCubeRenderTarget.texture as a cube texture.
  7454. this._needsFlipEnvMap = true;
  7455. this.flipY = false;
  7456. }
  7457. get images() {
  7458. return this.image;
  7459. }
  7460. set images(value) {
  7461. this.image = value;
  7462. }
  7463. }
  7464. CubeTexture.prototype.isCubeTexture = true;
  7465. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7466. constructor(size, options, dummy) {
  7467. if (Number.isInteger(options)) {
  7468. console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');
  7469. options = dummy;
  7470. }
  7471. super(size, size, options);
  7472. options = options || {};
  7473. this.texture = new CubeTexture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  7474. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7475. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7476. this.texture._needsFlipEnvMap = false;
  7477. }
  7478. fromEquirectangularTexture(renderer, texture) {
  7479. this.texture.type = texture.type;
  7480. this.texture.format = RGBAFormat; // see #18859
  7481. this.texture.encoding = texture.encoding;
  7482. this.texture.generateMipmaps = texture.generateMipmaps;
  7483. this.texture.minFilter = texture.minFilter;
  7484. this.texture.magFilter = texture.magFilter;
  7485. const shader = {
  7486. uniforms: {
  7487. tEquirect: {
  7488. value: null
  7489. }
  7490. },
  7491. vertexShader:
  7492. /* glsl */
  7493. `
  7494. varying vec3 vWorldDirection;
  7495. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7496. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7497. }
  7498. void main() {
  7499. vWorldDirection = transformDirection( position, modelMatrix );
  7500. #include <begin_vertex>
  7501. #include <project_vertex>
  7502. }
  7503. `,
  7504. fragmentShader:
  7505. /* glsl */
  7506. `
  7507. uniform sampler2D tEquirect;
  7508. varying vec3 vWorldDirection;
  7509. #include <common>
  7510. void main() {
  7511. vec3 direction = normalize( vWorldDirection );
  7512. vec2 sampleUV = equirectUv( direction );
  7513. gl_FragColor = texture2D( tEquirect, sampleUV );
  7514. }
  7515. `
  7516. };
  7517. const geometry = new BoxGeometry(5, 5, 5);
  7518. const material = new ShaderMaterial({
  7519. name: 'CubemapFromEquirect',
  7520. uniforms: cloneUniforms(shader.uniforms),
  7521. vertexShader: shader.vertexShader,
  7522. fragmentShader: shader.fragmentShader,
  7523. side: BackSide,
  7524. blending: NoBlending
  7525. });
  7526. material.uniforms.tEquirect.value = texture;
  7527. const mesh = new Mesh(geometry, material);
  7528. const currentMinFilter = texture.minFilter; // Avoid blurred poles
  7529. if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
  7530. const camera = new CubeCamera(1, 10, this);
  7531. camera.update(renderer, mesh);
  7532. texture.minFilter = currentMinFilter;
  7533. mesh.geometry.dispose();
  7534. mesh.material.dispose();
  7535. return this;
  7536. }
  7537. clear(renderer, color, depth, stencil) {
  7538. const currentRenderTarget = renderer.getRenderTarget();
  7539. for (let i = 0; i < 6; i++) {
  7540. renderer.setRenderTarget(this, i);
  7541. renderer.clear(color, depth, stencil);
  7542. }
  7543. renderer.setRenderTarget(currentRenderTarget);
  7544. }
  7545. }
  7546. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  7547. class DataTexture extends Texture {
  7548. constructor(data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  7549. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  7550. this.image = {
  7551. data: data || null,
  7552. width: width || 1,
  7553. height: height || 1
  7554. };
  7555. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  7556. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  7557. this.generateMipmaps = false;
  7558. this.flipY = false;
  7559. this.unpackAlignment = 1;
  7560. this.needsUpdate = true;
  7561. }
  7562. }
  7563. DataTexture.prototype.isDataTexture = true;
  7564. const _sphere$2 = /*@__PURE__*/new Sphere();
  7565. const _vector$7 = /*@__PURE__*/new Vector3();
  7566. class Frustum {
  7567. constructor(p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane()) {
  7568. this.planes = [p0, p1, p2, p3, p4, p5];
  7569. }
  7570. set(p0, p1, p2, p3, p4, p5) {
  7571. const planes = this.planes;
  7572. planes[0].copy(p0);
  7573. planes[1].copy(p1);
  7574. planes[2].copy(p2);
  7575. planes[3].copy(p3);
  7576. planes[4].copy(p4);
  7577. planes[5].copy(p5);
  7578. return this;
  7579. }
  7580. copy(frustum) {
  7581. const planes = this.planes;
  7582. for (let i = 0; i < 6; i++) {
  7583. planes[i].copy(frustum.planes[i]);
  7584. }
  7585. return this;
  7586. }
  7587. setFromProjectionMatrix(m) {
  7588. const planes = this.planes;
  7589. const me = m.elements;
  7590. const me0 = me[0],
  7591. me1 = me[1],
  7592. me2 = me[2],
  7593. me3 = me[3];
  7594. const me4 = me[4],
  7595. me5 = me[5],
  7596. me6 = me[6],
  7597. me7 = me[7];
  7598. const me8 = me[8],
  7599. me9 = me[9],
  7600. me10 = me[10],
  7601. me11 = me[11];
  7602. const me12 = me[12],
  7603. me13 = me[13],
  7604. me14 = me[14],
  7605. me15 = me[15];
  7606. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  7607. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  7608. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  7609. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  7610. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  7611. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  7612. return this;
  7613. }
  7614. intersectsObject(object) {
  7615. const geometry = object.geometry;
  7616. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  7617. _sphere$2.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  7618. return this.intersectsSphere(_sphere$2);
  7619. }
  7620. intersectsSprite(sprite) {
  7621. _sphere$2.center.set(0, 0, 0);
  7622. _sphere$2.radius = 0.7071067811865476;
  7623. _sphere$2.applyMatrix4(sprite.matrixWorld);
  7624. return this.intersectsSphere(_sphere$2);
  7625. }
  7626. intersectsSphere(sphere) {
  7627. const planes = this.planes;
  7628. const center = sphere.center;
  7629. const negRadius = -sphere.radius;
  7630. for (let i = 0; i < 6; i++) {
  7631. const distance = planes[i].distanceToPoint(center);
  7632. if (distance < negRadius) {
  7633. return false;
  7634. }
  7635. }
  7636. return true;
  7637. }
  7638. intersectsBox(box) {
  7639. const planes = this.planes;
  7640. for (let i = 0; i < 6; i++) {
  7641. const plane = planes[i]; // corner at max distance
  7642. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7643. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7644. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7645. if (plane.distanceToPoint(_vector$7) < 0) {
  7646. return false;
  7647. }
  7648. }
  7649. return true;
  7650. }
  7651. containsPoint(point) {
  7652. const planes = this.planes;
  7653. for (let i = 0; i < 6; i++) {
  7654. if (planes[i].distanceToPoint(point) < 0) {
  7655. return false;
  7656. }
  7657. }
  7658. return true;
  7659. }
  7660. clone() {
  7661. return new this.constructor().copy(this);
  7662. }
  7663. }
  7664. function WebGLAnimation() {
  7665. let context = null;
  7666. let isAnimating = false;
  7667. let animationLoop = null;
  7668. let requestId = null;
  7669. function onAnimationFrame(time, frame) {
  7670. animationLoop(time, frame);
  7671. requestId = context.requestAnimationFrame(onAnimationFrame);
  7672. }
  7673. return {
  7674. start: function () {
  7675. if (isAnimating === true) return;
  7676. if (animationLoop === null) return;
  7677. requestId = context.requestAnimationFrame(onAnimationFrame);
  7678. isAnimating = true;
  7679. },
  7680. stop: function () {
  7681. context.cancelAnimationFrame(requestId);
  7682. isAnimating = false;
  7683. },
  7684. setAnimationLoop: function (callback) {
  7685. animationLoop = callback;
  7686. },
  7687. setContext: function (value) {
  7688. context = value;
  7689. }
  7690. };
  7691. }
  7692. function WebGLAttributes(gl, capabilities) {
  7693. const isWebGL2 = capabilities.isWebGL2;
  7694. const buffers = new WeakMap();
  7695. function createBuffer(attribute, bufferType) {
  7696. const array = attribute.array;
  7697. const usage = attribute.usage;
  7698. const buffer = gl.createBuffer();
  7699. gl.bindBuffer(bufferType, buffer);
  7700. gl.bufferData(bufferType, array, usage);
  7701. attribute.onUploadCallback();
  7702. let type = gl.FLOAT;
  7703. if (array instanceof Float32Array) {
  7704. type = gl.FLOAT;
  7705. } else if (array instanceof Float64Array) {
  7706. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  7707. } else if (array instanceof Uint16Array) {
  7708. if (attribute.isFloat16BufferAttribute) {
  7709. if (isWebGL2) {
  7710. type = gl.HALF_FLOAT;
  7711. } else {
  7712. console.warn('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
  7713. }
  7714. } else {
  7715. type = gl.UNSIGNED_SHORT;
  7716. }
  7717. } else if (array instanceof Int16Array) {
  7718. type = gl.SHORT;
  7719. } else if (array instanceof Uint32Array) {
  7720. type = gl.UNSIGNED_INT;
  7721. } else if (array instanceof Int32Array) {
  7722. type = gl.INT;
  7723. } else if (array instanceof Int8Array) {
  7724. type = gl.BYTE;
  7725. } else if (array instanceof Uint8Array) {
  7726. type = gl.UNSIGNED_BYTE;
  7727. }
  7728. return {
  7729. buffer: buffer,
  7730. type: type,
  7731. bytesPerElement: array.BYTES_PER_ELEMENT,
  7732. version: attribute.version
  7733. };
  7734. }
  7735. function updateBuffer(buffer, attribute, bufferType) {
  7736. const array = attribute.array;
  7737. const updateRange = attribute.updateRange;
  7738. gl.bindBuffer(bufferType, buffer);
  7739. if (updateRange.count === -1) {
  7740. // Not using update ranges
  7741. gl.bufferSubData(bufferType, 0, array);
  7742. } else {
  7743. if (isWebGL2) {
  7744. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  7745. } else {
  7746. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  7747. }
  7748. updateRange.count = -1; // reset range
  7749. }
  7750. } //
  7751. function get(attribute) {
  7752. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7753. return buffers.get(attribute);
  7754. }
  7755. function remove(attribute) {
  7756. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7757. const data = buffers.get(attribute);
  7758. if (data) {
  7759. gl.deleteBuffer(data.buffer);
  7760. buffers.delete(attribute);
  7761. }
  7762. }
  7763. function update(attribute, bufferType) {
  7764. if (attribute.isGLBufferAttribute) {
  7765. const cached = buffers.get(attribute);
  7766. if (!cached || cached.version < attribute.version) {
  7767. buffers.set(attribute, {
  7768. buffer: attribute.buffer,
  7769. type: attribute.type,
  7770. bytesPerElement: attribute.elementSize,
  7771. version: attribute.version
  7772. });
  7773. }
  7774. return;
  7775. }
  7776. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7777. const data = buffers.get(attribute);
  7778. if (data === undefined) {
  7779. buffers.set(attribute, createBuffer(attribute, bufferType));
  7780. } else if (data.version < attribute.version) {
  7781. updateBuffer(data.buffer, attribute, bufferType);
  7782. data.version = attribute.version;
  7783. }
  7784. }
  7785. return {
  7786. get: get,
  7787. remove: remove,
  7788. update: update
  7789. };
  7790. }
  7791. class PlaneGeometry extends BufferGeometry {
  7792. constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) {
  7793. super();
  7794. this.type = 'PlaneGeometry';
  7795. this.parameters = {
  7796. width: width,
  7797. height: height,
  7798. widthSegments: widthSegments,
  7799. heightSegments: heightSegments
  7800. };
  7801. const width_half = width / 2;
  7802. const height_half = height / 2;
  7803. const gridX = Math.floor(widthSegments);
  7804. const gridY = Math.floor(heightSegments);
  7805. const gridX1 = gridX + 1;
  7806. const gridY1 = gridY + 1;
  7807. const segment_width = width / gridX;
  7808. const segment_height = height / gridY; //
  7809. const indices = [];
  7810. const vertices = [];
  7811. const normals = [];
  7812. const uvs = [];
  7813. for (let iy = 0; iy < gridY1; iy++) {
  7814. const y = iy * segment_height - height_half;
  7815. for (let ix = 0; ix < gridX1; ix++) {
  7816. const x = ix * segment_width - width_half;
  7817. vertices.push(x, -y, 0);
  7818. normals.push(0, 0, 1);
  7819. uvs.push(ix / gridX);
  7820. uvs.push(1 - iy / gridY);
  7821. }
  7822. }
  7823. for (let iy = 0; iy < gridY; iy++) {
  7824. for (let ix = 0; ix < gridX; ix++) {
  7825. const a = ix + gridX1 * iy;
  7826. const b = ix + gridX1 * (iy + 1);
  7827. const c = ix + 1 + gridX1 * (iy + 1);
  7828. const d = ix + 1 + gridX1 * iy;
  7829. indices.push(a, b, d);
  7830. indices.push(b, c, d);
  7831. }
  7832. }
  7833. this.setIndex(indices);
  7834. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  7835. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  7836. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  7837. }
  7838. }
  7839. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7840. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7841. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  7842. 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.specularRoughness );\n\t#endif\n#endif";
  7843. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7844. var begin_vertex = "vec3 transformed = vec3( position );";
  7845. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7846. var bsdfs = "vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\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\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_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_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * 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}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.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}\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_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif";
  7847. 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";
  7848. 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";
  7849. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7850. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7851. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7852. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7853. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7854. 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";
  7855. 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";
  7856. 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 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 max3( vec3 v ) { return max( max( v.x, v.y ), v.z ); }\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 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}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\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}";
  7857. 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 );\n\t\tvec2 f = fract( uv );\n\t\tuv += 0.5 - f;\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\tvec3 tl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x += texelSize;\n\t\tvec3 tr = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.y += texelSize;\n\t\tvec3 br = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x -= texelSize;\n\t\tvec3 bl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tvec3 tm = mix( tl, tr, f.x );\n\t\tvec3 bm = mix( bl, br, f.x );\n\t\treturn mix( tm, bm, f.y );\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";
  7858. 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";
  7859. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7860. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7861. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7862. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7863. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7864. 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}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}";
  7865. 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#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#ifndef ENVMAP_TYPE_CUBE_UV\n\t\tenvColor = envMapTexelToLinear( envColor );\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";
  7866. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\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";
  7867. 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";
  7868. 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";
  7869. 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";
  7870. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = - mvPosition.z;\n#endif";
  7871. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  7872. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * fogDepth * fogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
  7873. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\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";
  7874. 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 texture2D( gradientMap, coord ).rgb;\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";
  7875. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";
  7876. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7877. 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 );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry );\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\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * 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\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * 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\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * 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 );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";
  7878. 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 GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\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 getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.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 getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.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 getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.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 GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif";
  7879. 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 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif";
  7880. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7881. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\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\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_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_Diffuse_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)";
  7882. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7883. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\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\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, 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_Diffuse_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)";
  7884. 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.specularRoughness = max( roughnessFactor, 0.0525 );material.specularRoughness += geometryRoughness;\nmaterial.specularRoughness = min( material.specularRoughness, 1.0 );\n#ifdef REFLECTIVITY\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\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 = sheen;\n#endif";
  7885. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat specularRoughness;\n\tvec3 specularColor;\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\n#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearcoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\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.specularRoughness;\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#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tccIrradiance *= PI;\n\t\t#endif\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(\n\t\t\tmaterial.specularRoughness,\n\t\t\tdirectLight.direction,\n\t\t\tgeometry,\n\t\t\tmaterial.sheenColor\n\t\t);\n\t#else\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularRoughness);\n\t#endif\n\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_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_Diffuse_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 CLEARCOAT\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += clearcoatInv * 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}";
  7886. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef 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\tgetPointDirectLightIrradiance( 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\tgetSpotDirectLightIrradiance( 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\tgetDirectionalDirectLightIrradiance( 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 );\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 );\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";
  7887. 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 += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\t#ifdef CLEARCOAT\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\t#endif\n#endif";
  7888. 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";
  7889. 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";
  7890. 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";
  7891. 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";
  7892. 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";
  7893. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  7894. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7895. 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";
  7896. 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";
  7897. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7898. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7899. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n#endif";
  7900. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifndef USE_MORPHNORMALS\n\t\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\t\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
  7901. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t#endif\n#endif";
  7902. 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;";
  7903. 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";
  7904. 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";
  7905. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7906. 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";
  7907. 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";
  7908. 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}";
  7909. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7910. 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;";
  7911. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7912. 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";
  7913. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7914. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7915. 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";
  7916. 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";
  7917. 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";
  7918. 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}";
  7919. 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";
  7920. 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";
  7921. 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";
  7922. 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";
  7923. 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";
  7924. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7925. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7926. 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; }";
  7927. var transmissionmap_fragment = "#ifdef USE_TRANSMISSIONMAP\n\ttotalTransmission *= texture2D( transmissionMap, vUv ).r;\n#endif";
  7928. var transmissionmap_pars_fragment = "#ifdef USE_TRANSMISSIONMAP\n\tuniform sampler2D transmissionMap;\n#endif";
  7929. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7930. 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";
  7931. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7932. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7933. 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";
  7934. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7935. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\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";
  7936. var background_frag = "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}";
  7937. var background_vert = "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}";
  7938. var cube_frag = "#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}";
  7939. var cube_vert = "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}";
  7940. var depth_frag = "#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 <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}";
  7941. var depth_vert = "#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}";
  7942. var distanceRGBA_frag = "#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 <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}";
  7943. var distanceRGBA_vert = "#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}";
  7944. var equirect_frag = "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}";
  7945. var equirect_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
  7946. var linedashed_frag = "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\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7947. var linedashed_vert = "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}";
  7948. var meshbasic_frag = "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 <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\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\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\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}";
  7949. var meshbasic_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\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 <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  7950. var meshlambert_frag = "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 <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_Diffuse_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_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\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}";
  7951. var meshlambert_vert = "#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}";
  7952. var meshmatcap_frag = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\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 <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_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\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\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}";
  7953. var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\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 <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#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\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\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  7954. var meshtoon_frag = "#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 <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 <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\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\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}";
  7955. var meshtoon_vert = "#define TOON\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\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 <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#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#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\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7956. var meshphong_frag = "#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 <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 <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\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\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}";
  7957. var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\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 <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#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#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\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7958. var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSMISSION\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef TRANSMISSION\n\tuniform float transmission;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#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\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 <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <transmissionmap_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 <lights_physical_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#ifdef TRANSMISSION\n\t\tfloat totalTransmission = transmission;\n\t#endif\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 <transmissionmap_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 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#ifdef TRANSMISSION\n\t\tdiffuseColor.a *= mix( saturate( 1. - totalTransmission + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) ), 1.0, metalness );\n\t#endif\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\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}";
  7959. var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#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\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 <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#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\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}";
  7960. var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#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\n#include <packing>\n#include <uv_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}";
  7961. var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#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\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 <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#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\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}";
  7962. var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_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\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7963. var points_vert = "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}";
  7964. var shadow_frag = "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}";
  7965. var shadow_vert = "#include <common>\n#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_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 <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7966. var sprite_frag = "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 <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\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  7967. var sprite_vert = "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}";
  7968. const ShaderChunk = {
  7969. alphamap_fragment: alphamap_fragment,
  7970. alphamap_pars_fragment: alphamap_pars_fragment,
  7971. alphatest_fragment: alphatest_fragment,
  7972. aomap_fragment: aomap_fragment,
  7973. aomap_pars_fragment: aomap_pars_fragment,
  7974. begin_vertex: begin_vertex,
  7975. beginnormal_vertex: beginnormal_vertex,
  7976. bsdfs: bsdfs,
  7977. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7978. clipping_planes_fragment: clipping_planes_fragment,
  7979. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7980. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7981. clipping_planes_vertex: clipping_planes_vertex,
  7982. color_fragment: color_fragment,
  7983. color_pars_fragment: color_pars_fragment,
  7984. color_pars_vertex: color_pars_vertex,
  7985. color_vertex: color_vertex,
  7986. common: common,
  7987. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7988. defaultnormal_vertex: defaultnormal_vertex,
  7989. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7990. displacementmap_vertex: displacementmap_vertex,
  7991. emissivemap_fragment: emissivemap_fragment,
  7992. emissivemap_pars_fragment: emissivemap_pars_fragment,
  7993. encodings_fragment: encodings_fragment,
  7994. encodings_pars_fragment: encodings_pars_fragment,
  7995. envmap_fragment: envmap_fragment,
  7996. envmap_common_pars_fragment: envmap_common_pars_fragment,
  7997. envmap_pars_fragment: envmap_pars_fragment,
  7998. envmap_pars_vertex: envmap_pars_vertex,
  7999. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8000. envmap_vertex: envmap_vertex,
  8001. fog_vertex: fog_vertex,
  8002. fog_pars_vertex: fog_pars_vertex,
  8003. fog_fragment: fog_fragment,
  8004. fog_pars_fragment: fog_pars_fragment,
  8005. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8006. lightmap_fragment: lightmap_fragment,
  8007. lightmap_pars_fragment: lightmap_pars_fragment,
  8008. lights_lambert_vertex: lights_lambert_vertex,
  8009. lights_pars_begin: lights_pars_begin,
  8010. lights_toon_fragment: lights_toon_fragment,
  8011. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8012. lights_phong_fragment: lights_phong_fragment,
  8013. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8014. lights_physical_fragment: lights_physical_fragment,
  8015. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8016. lights_fragment_begin: lights_fragment_begin,
  8017. lights_fragment_maps: lights_fragment_maps,
  8018. lights_fragment_end: lights_fragment_end,
  8019. logdepthbuf_fragment: logdepthbuf_fragment,
  8020. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8021. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8022. logdepthbuf_vertex: logdepthbuf_vertex,
  8023. map_fragment: map_fragment,
  8024. map_pars_fragment: map_pars_fragment,
  8025. map_particle_fragment: map_particle_fragment,
  8026. map_particle_pars_fragment: map_particle_pars_fragment,
  8027. metalnessmap_fragment: metalnessmap_fragment,
  8028. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8029. morphnormal_vertex: morphnormal_vertex,
  8030. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8031. morphtarget_vertex: morphtarget_vertex,
  8032. normal_fragment_begin: normal_fragment_begin,
  8033. normal_fragment_maps: normal_fragment_maps,
  8034. normalmap_pars_fragment: normalmap_pars_fragment,
  8035. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8036. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8037. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8038. packing: packing,
  8039. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8040. project_vertex: project_vertex,
  8041. dithering_fragment: dithering_fragment,
  8042. dithering_pars_fragment: dithering_pars_fragment,
  8043. roughnessmap_fragment: roughnessmap_fragment,
  8044. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8045. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8046. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8047. shadowmap_vertex: shadowmap_vertex,
  8048. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8049. skinbase_vertex: skinbase_vertex,
  8050. skinning_pars_vertex: skinning_pars_vertex,
  8051. skinning_vertex: skinning_vertex,
  8052. skinnormal_vertex: skinnormal_vertex,
  8053. specularmap_fragment: specularmap_fragment,
  8054. specularmap_pars_fragment: specularmap_pars_fragment,
  8055. tonemapping_fragment: tonemapping_fragment,
  8056. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8057. transmissionmap_fragment: transmissionmap_fragment,
  8058. transmissionmap_pars_fragment: transmissionmap_pars_fragment,
  8059. uv_pars_fragment: uv_pars_fragment,
  8060. uv_pars_vertex: uv_pars_vertex,
  8061. uv_vertex: uv_vertex,
  8062. uv2_pars_fragment: uv2_pars_fragment,
  8063. uv2_pars_vertex: uv2_pars_vertex,
  8064. uv2_vertex: uv2_vertex,
  8065. worldpos_vertex: worldpos_vertex,
  8066. background_frag: background_frag,
  8067. background_vert: background_vert,
  8068. cube_frag: cube_frag,
  8069. cube_vert: cube_vert,
  8070. depth_frag: depth_frag,
  8071. depth_vert: depth_vert,
  8072. distanceRGBA_frag: distanceRGBA_frag,
  8073. distanceRGBA_vert: distanceRGBA_vert,
  8074. equirect_frag: equirect_frag,
  8075. equirect_vert: equirect_vert,
  8076. linedashed_frag: linedashed_frag,
  8077. linedashed_vert: linedashed_vert,
  8078. meshbasic_frag: meshbasic_frag,
  8079. meshbasic_vert: meshbasic_vert,
  8080. meshlambert_frag: meshlambert_frag,
  8081. meshlambert_vert: meshlambert_vert,
  8082. meshmatcap_frag: meshmatcap_frag,
  8083. meshmatcap_vert: meshmatcap_vert,
  8084. meshtoon_frag: meshtoon_frag,
  8085. meshtoon_vert: meshtoon_vert,
  8086. meshphong_frag: meshphong_frag,
  8087. meshphong_vert: meshphong_vert,
  8088. meshphysical_frag: meshphysical_frag,
  8089. meshphysical_vert: meshphysical_vert,
  8090. normal_frag: normal_frag,
  8091. normal_vert: normal_vert,
  8092. points_frag: points_frag,
  8093. points_vert: points_vert,
  8094. shadow_frag: shadow_frag,
  8095. shadow_vert: shadow_vert,
  8096. sprite_frag: sprite_frag,
  8097. sprite_vert: sprite_vert
  8098. };
  8099. /**
  8100. * Uniforms library for shared webgl shaders
  8101. */
  8102. const UniformsLib = {
  8103. common: {
  8104. diffuse: {
  8105. value: new Color(0xeeeeee)
  8106. },
  8107. opacity: {
  8108. value: 1.0
  8109. },
  8110. map: {
  8111. value: null
  8112. },
  8113. uvTransform: {
  8114. value: new Matrix3()
  8115. },
  8116. uv2Transform: {
  8117. value: new Matrix3()
  8118. },
  8119. alphaMap: {
  8120. value: null
  8121. }
  8122. },
  8123. specularmap: {
  8124. specularMap: {
  8125. value: null
  8126. }
  8127. },
  8128. envmap: {
  8129. envMap: {
  8130. value: null
  8131. },
  8132. flipEnvMap: {
  8133. value: -1
  8134. },
  8135. reflectivity: {
  8136. value: 1.0
  8137. },
  8138. refractionRatio: {
  8139. value: 0.98
  8140. },
  8141. maxMipLevel: {
  8142. value: 0
  8143. }
  8144. },
  8145. aomap: {
  8146. aoMap: {
  8147. value: null
  8148. },
  8149. aoMapIntensity: {
  8150. value: 1
  8151. }
  8152. },
  8153. lightmap: {
  8154. lightMap: {
  8155. value: null
  8156. },
  8157. lightMapIntensity: {
  8158. value: 1
  8159. }
  8160. },
  8161. emissivemap: {
  8162. emissiveMap: {
  8163. value: null
  8164. }
  8165. },
  8166. bumpmap: {
  8167. bumpMap: {
  8168. value: null
  8169. },
  8170. bumpScale: {
  8171. value: 1
  8172. }
  8173. },
  8174. normalmap: {
  8175. normalMap: {
  8176. value: null
  8177. },
  8178. normalScale: {
  8179. value: new Vector2(1, 1)
  8180. }
  8181. },
  8182. displacementmap: {
  8183. displacementMap: {
  8184. value: null
  8185. },
  8186. displacementScale: {
  8187. value: 1
  8188. },
  8189. displacementBias: {
  8190. value: 0
  8191. }
  8192. },
  8193. roughnessmap: {
  8194. roughnessMap: {
  8195. value: null
  8196. }
  8197. },
  8198. metalnessmap: {
  8199. metalnessMap: {
  8200. value: null
  8201. }
  8202. },
  8203. gradientmap: {
  8204. gradientMap: {
  8205. value: null
  8206. }
  8207. },
  8208. fog: {
  8209. fogDensity: {
  8210. value: 0.00025
  8211. },
  8212. fogNear: {
  8213. value: 1
  8214. },
  8215. fogFar: {
  8216. value: 2000
  8217. },
  8218. fogColor: {
  8219. value: new Color(0xffffff)
  8220. }
  8221. },
  8222. lights: {
  8223. ambientLightColor: {
  8224. value: []
  8225. },
  8226. lightProbe: {
  8227. value: []
  8228. },
  8229. directionalLights: {
  8230. value: [],
  8231. properties: {
  8232. direction: {},
  8233. color: {}
  8234. }
  8235. },
  8236. directionalLightShadows: {
  8237. value: [],
  8238. properties: {
  8239. shadowBias: {},
  8240. shadowNormalBias: {},
  8241. shadowRadius: {},
  8242. shadowMapSize: {}
  8243. }
  8244. },
  8245. directionalShadowMap: {
  8246. value: []
  8247. },
  8248. directionalShadowMatrix: {
  8249. value: []
  8250. },
  8251. spotLights: {
  8252. value: [],
  8253. properties: {
  8254. color: {},
  8255. position: {},
  8256. direction: {},
  8257. distance: {},
  8258. coneCos: {},
  8259. penumbraCos: {},
  8260. decay: {}
  8261. }
  8262. },
  8263. spotLightShadows: {
  8264. value: [],
  8265. properties: {
  8266. shadowBias: {},
  8267. shadowNormalBias: {},
  8268. shadowRadius: {},
  8269. shadowMapSize: {}
  8270. }
  8271. },
  8272. spotShadowMap: {
  8273. value: []
  8274. },
  8275. spotShadowMatrix: {
  8276. value: []
  8277. },
  8278. pointLights: {
  8279. value: [],
  8280. properties: {
  8281. color: {},
  8282. position: {},
  8283. decay: {},
  8284. distance: {}
  8285. }
  8286. },
  8287. pointLightShadows: {
  8288. value: [],
  8289. properties: {
  8290. shadowBias: {},
  8291. shadowNormalBias: {},
  8292. shadowRadius: {},
  8293. shadowMapSize: {},
  8294. shadowCameraNear: {},
  8295. shadowCameraFar: {}
  8296. }
  8297. },
  8298. pointShadowMap: {
  8299. value: []
  8300. },
  8301. pointShadowMatrix: {
  8302. value: []
  8303. },
  8304. hemisphereLights: {
  8305. value: [],
  8306. properties: {
  8307. direction: {},
  8308. skyColor: {},
  8309. groundColor: {}
  8310. }
  8311. },
  8312. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8313. rectAreaLights: {
  8314. value: [],
  8315. properties: {
  8316. color: {},
  8317. position: {},
  8318. width: {},
  8319. height: {}
  8320. }
  8321. },
  8322. ltc_1: {
  8323. value: null
  8324. },
  8325. ltc_2: {
  8326. value: null
  8327. }
  8328. },
  8329. points: {
  8330. diffuse: {
  8331. value: new Color(0xeeeeee)
  8332. },
  8333. opacity: {
  8334. value: 1.0
  8335. },
  8336. size: {
  8337. value: 1.0
  8338. },
  8339. scale: {
  8340. value: 1.0
  8341. },
  8342. map: {
  8343. value: null
  8344. },
  8345. alphaMap: {
  8346. value: null
  8347. },
  8348. uvTransform: {
  8349. value: new Matrix3()
  8350. }
  8351. },
  8352. sprite: {
  8353. diffuse: {
  8354. value: new Color(0xeeeeee)
  8355. },
  8356. opacity: {
  8357. value: 1.0
  8358. },
  8359. center: {
  8360. value: new Vector2(0.5, 0.5)
  8361. },
  8362. rotation: {
  8363. value: 0.0
  8364. },
  8365. map: {
  8366. value: null
  8367. },
  8368. alphaMap: {
  8369. value: null
  8370. },
  8371. uvTransform: {
  8372. value: new Matrix3()
  8373. }
  8374. }
  8375. };
  8376. const ShaderLib = {
  8377. basic: {
  8378. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  8379. vertexShader: ShaderChunk.meshbasic_vert,
  8380. fragmentShader: ShaderChunk.meshbasic_frag
  8381. },
  8382. lambert: {
  8383. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  8384. emissive: {
  8385. value: new Color(0x000000)
  8386. }
  8387. }]),
  8388. vertexShader: ShaderChunk.meshlambert_vert,
  8389. fragmentShader: ShaderChunk.meshlambert_frag
  8390. },
  8391. phong: {
  8392. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  8393. emissive: {
  8394. value: new Color(0x000000)
  8395. },
  8396. specular: {
  8397. value: new Color(0x111111)
  8398. },
  8399. shininess: {
  8400. value: 30
  8401. }
  8402. }]),
  8403. vertexShader: ShaderChunk.meshphong_vert,
  8404. fragmentShader: ShaderChunk.meshphong_frag
  8405. },
  8406. standard: {
  8407. 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, {
  8408. emissive: {
  8409. value: new Color(0x000000)
  8410. },
  8411. roughness: {
  8412. value: 1.0
  8413. },
  8414. metalness: {
  8415. value: 0.0
  8416. },
  8417. envMapIntensity: {
  8418. value: 1
  8419. } // temporary
  8420. }]),
  8421. vertexShader: ShaderChunk.meshphysical_vert,
  8422. fragmentShader: ShaderChunk.meshphysical_frag
  8423. },
  8424. toon: {
  8425. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  8426. emissive: {
  8427. value: new Color(0x000000)
  8428. }
  8429. }]),
  8430. vertexShader: ShaderChunk.meshtoon_vert,
  8431. fragmentShader: ShaderChunk.meshtoon_frag
  8432. },
  8433. matcap: {
  8434. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  8435. matcap: {
  8436. value: null
  8437. }
  8438. }]),
  8439. vertexShader: ShaderChunk.meshmatcap_vert,
  8440. fragmentShader: ShaderChunk.meshmatcap_frag
  8441. },
  8442. points: {
  8443. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  8444. vertexShader: ShaderChunk.points_vert,
  8445. fragmentShader: ShaderChunk.points_frag
  8446. },
  8447. dashed: {
  8448. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  8449. scale: {
  8450. value: 1
  8451. },
  8452. dashSize: {
  8453. value: 1
  8454. },
  8455. totalSize: {
  8456. value: 2
  8457. }
  8458. }]),
  8459. vertexShader: ShaderChunk.linedashed_vert,
  8460. fragmentShader: ShaderChunk.linedashed_frag
  8461. },
  8462. depth: {
  8463. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  8464. vertexShader: ShaderChunk.depth_vert,
  8465. fragmentShader: ShaderChunk.depth_frag
  8466. },
  8467. normal: {
  8468. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  8469. opacity: {
  8470. value: 1.0
  8471. }
  8472. }]),
  8473. vertexShader: ShaderChunk.normal_vert,
  8474. fragmentShader: ShaderChunk.normal_frag
  8475. },
  8476. sprite: {
  8477. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  8478. vertexShader: ShaderChunk.sprite_vert,
  8479. fragmentShader: ShaderChunk.sprite_frag
  8480. },
  8481. background: {
  8482. uniforms: {
  8483. uvTransform: {
  8484. value: new Matrix3()
  8485. },
  8486. t2D: {
  8487. value: null
  8488. }
  8489. },
  8490. vertexShader: ShaderChunk.background_vert,
  8491. fragmentShader: ShaderChunk.background_frag
  8492. },
  8493. /* -------------------------------------------------------------------------
  8494. // Cube map shader
  8495. ------------------------------------------------------------------------- */
  8496. cube: {
  8497. uniforms: mergeUniforms([UniformsLib.envmap, {
  8498. opacity: {
  8499. value: 1.0
  8500. }
  8501. }]),
  8502. vertexShader: ShaderChunk.cube_vert,
  8503. fragmentShader: ShaderChunk.cube_frag
  8504. },
  8505. equirect: {
  8506. uniforms: {
  8507. tEquirect: {
  8508. value: null
  8509. }
  8510. },
  8511. vertexShader: ShaderChunk.equirect_vert,
  8512. fragmentShader: ShaderChunk.equirect_frag
  8513. },
  8514. distanceRGBA: {
  8515. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  8516. referencePosition: {
  8517. value: new Vector3()
  8518. },
  8519. nearDistance: {
  8520. value: 1
  8521. },
  8522. farDistance: {
  8523. value: 1000
  8524. }
  8525. }]),
  8526. vertexShader: ShaderChunk.distanceRGBA_vert,
  8527. fragmentShader: ShaderChunk.distanceRGBA_frag
  8528. },
  8529. shadow: {
  8530. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  8531. color: {
  8532. value: new Color(0x00000)
  8533. },
  8534. opacity: {
  8535. value: 1.0
  8536. }
  8537. }]),
  8538. vertexShader: ShaderChunk.shadow_vert,
  8539. fragmentShader: ShaderChunk.shadow_frag
  8540. }
  8541. };
  8542. ShaderLib.physical = {
  8543. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  8544. clearcoat: {
  8545. value: 0
  8546. },
  8547. clearcoatMap: {
  8548. value: null
  8549. },
  8550. clearcoatRoughness: {
  8551. value: 0
  8552. },
  8553. clearcoatRoughnessMap: {
  8554. value: null
  8555. },
  8556. clearcoatNormalScale: {
  8557. value: new Vector2(1, 1)
  8558. },
  8559. clearcoatNormalMap: {
  8560. value: null
  8561. },
  8562. sheen: {
  8563. value: new Color(0x000000)
  8564. },
  8565. transmission: {
  8566. value: 0
  8567. },
  8568. transmissionMap: {
  8569. value: null
  8570. }
  8571. }]),
  8572. vertexShader: ShaderChunk.meshphysical_vert,
  8573. fragmentShader: ShaderChunk.meshphysical_frag
  8574. };
  8575. function WebGLBackground(renderer, cubemaps, state, objects, premultipliedAlpha) {
  8576. const clearColor = new Color(0x000000);
  8577. let clearAlpha = 0;
  8578. let planeMesh;
  8579. let boxMesh;
  8580. let currentBackground = null;
  8581. let currentBackgroundVersion = 0;
  8582. let currentTonemapping = null;
  8583. function render(renderList, scene, camera, forceClear) {
  8584. let background = scene.isScene === true ? scene.background : null;
  8585. if (background && background.isTexture) {
  8586. background = cubemaps.get(background);
  8587. } // Ignore background in AR
  8588. // TODO: Reconsider this.
  8589. const xr = renderer.xr;
  8590. const session = xr.getSession && xr.getSession();
  8591. if (session && session.environmentBlendMode === 'additive') {
  8592. background = null;
  8593. }
  8594. if (background === null) {
  8595. setClear(clearColor, clearAlpha);
  8596. } else if (background && background.isColor) {
  8597. setClear(background, 1);
  8598. forceClear = true;
  8599. }
  8600. if (renderer.autoClear || forceClear) {
  8601. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  8602. }
  8603. if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) {
  8604. if (boxMesh === undefined) {
  8605. boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({
  8606. name: 'BackgroundCubeMaterial',
  8607. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  8608. vertexShader: ShaderLib.cube.vertexShader,
  8609. fragmentShader: ShaderLib.cube.fragmentShader,
  8610. side: BackSide,
  8611. depthTest: false,
  8612. depthWrite: false,
  8613. fog: false
  8614. }));
  8615. boxMesh.geometry.deleteAttribute('normal');
  8616. boxMesh.geometry.deleteAttribute('uv');
  8617. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  8618. this.matrixWorld.copyPosition(camera.matrixWorld);
  8619. }; // enable code injection for non-built-in material
  8620. Object.defineProperty(boxMesh.material, 'envMap', {
  8621. get: function () {
  8622. return this.uniforms.envMap.value;
  8623. }
  8624. });
  8625. objects.update(boxMesh);
  8626. }
  8627. boxMesh.material.uniforms.envMap.value = background;
  8628. boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background._needsFlipEnvMap ? -1 : 1;
  8629. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8630. boxMesh.material.needsUpdate = true;
  8631. currentBackground = background;
  8632. currentBackgroundVersion = background.version;
  8633. currentTonemapping = renderer.toneMapping;
  8634. } // push to the pre-sorted opaque render list
  8635. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  8636. } else if (background && background.isTexture) {
  8637. if (planeMesh === undefined) {
  8638. planeMesh = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({
  8639. name: 'BackgroundMaterial',
  8640. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  8641. vertexShader: ShaderLib.background.vertexShader,
  8642. fragmentShader: ShaderLib.background.fragmentShader,
  8643. side: FrontSide,
  8644. depthTest: false,
  8645. depthWrite: false,
  8646. fog: false
  8647. }));
  8648. planeMesh.geometry.deleteAttribute('normal'); // enable code injection for non-built-in material
  8649. Object.defineProperty(planeMesh.material, 'map', {
  8650. get: function () {
  8651. return this.uniforms.t2D.value;
  8652. }
  8653. });
  8654. objects.update(planeMesh);
  8655. }
  8656. planeMesh.material.uniforms.t2D.value = background;
  8657. if (background.matrixAutoUpdate === true) {
  8658. background.updateMatrix();
  8659. }
  8660. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  8661. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8662. planeMesh.material.needsUpdate = true;
  8663. currentBackground = background;
  8664. currentBackgroundVersion = background.version;
  8665. currentTonemapping = renderer.toneMapping;
  8666. } // push to the pre-sorted opaque render list
  8667. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  8668. }
  8669. }
  8670. function setClear(color, alpha) {
  8671. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  8672. }
  8673. return {
  8674. getClearColor: function () {
  8675. return clearColor;
  8676. },
  8677. setClearColor: function (color, alpha = 1) {
  8678. clearColor.set(color);
  8679. clearAlpha = alpha;
  8680. setClear(clearColor, clearAlpha);
  8681. },
  8682. getClearAlpha: function () {
  8683. return clearAlpha;
  8684. },
  8685. setClearAlpha: function (alpha) {
  8686. clearAlpha = alpha;
  8687. setClear(clearColor, clearAlpha);
  8688. },
  8689. render: render
  8690. };
  8691. }
  8692. function WebGLBindingStates(gl, extensions, attributes, capabilities) {
  8693. const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  8694. const extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
  8695. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8696. const bindingStates = {};
  8697. const defaultState = createBindingState(null);
  8698. let currentState = defaultState;
  8699. function setup(object, material, program, geometry, index) {
  8700. let updateBuffers = false;
  8701. if (vaoAvailable) {
  8702. const state = getBindingState(geometry, program, material);
  8703. if (currentState !== state) {
  8704. currentState = state;
  8705. bindVertexArrayObject(currentState.object);
  8706. }
  8707. updateBuffers = needsUpdate(geometry, index);
  8708. if (updateBuffers) saveCache(geometry, index);
  8709. } else {
  8710. const wireframe = material.wireframe === true;
  8711. if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
  8712. currentState.geometry = geometry.id;
  8713. currentState.program = program.id;
  8714. currentState.wireframe = wireframe;
  8715. updateBuffers = true;
  8716. }
  8717. }
  8718. if (object.isInstancedMesh === true) {
  8719. updateBuffers = true;
  8720. }
  8721. if (index !== null) {
  8722. attributes.update(index, gl.ELEMENT_ARRAY_BUFFER);
  8723. }
  8724. if (updateBuffers) {
  8725. setupVertexAttributes(object, material, program, geometry);
  8726. if (index !== null) {
  8727. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index).buffer);
  8728. }
  8729. }
  8730. }
  8731. function createVertexArrayObject() {
  8732. if (capabilities.isWebGL2) return gl.createVertexArray();
  8733. return extension.createVertexArrayOES();
  8734. }
  8735. function bindVertexArrayObject(vao) {
  8736. if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
  8737. return extension.bindVertexArrayOES(vao);
  8738. }
  8739. function deleteVertexArrayObject(vao) {
  8740. if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
  8741. return extension.deleteVertexArrayOES(vao);
  8742. }
  8743. function getBindingState(geometry, program, material) {
  8744. const wireframe = material.wireframe === true;
  8745. let programMap = bindingStates[geometry.id];
  8746. if (programMap === undefined) {
  8747. programMap = {};
  8748. bindingStates[geometry.id] = programMap;
  8749. }
  8750. let stateMap = programMap[program.id];
  8751. if (stateMap === undefined) {
  8752. stateMap = {};
  8753. programMap[program.id] = stateMap;
  8754. }
  8755. let state = stateMap[wireframe];
  8756. if (state === undefined) {
  8757. state = createBindingState(createVertexArrayObject());
  8758. stateMap[wireframe] = state;
  8759. }
  8760. return state;
  8761. }
  8762. function createBindingState(vao) {
  8763. const newAttributes = [];
  8764. const enabledAttributes = [];
  8765. const attributeDivisors = [];
  8766. for (let i = 0; i < maxVertexAttributes; i++) {
  8767. newAttributes[i] = 0;
  8768. enabledAttributes[i] = 0;
  8769. attributeDivisors[i] = 0;
  8770. }
  8771. return {
  8772. // for backward compatibility on non-VAO support browser
  8773. geometry: null,
  8774. program: null,
  8775. wireframe: false,
  8776. newAttributes: newAttributes,
  8777. enabledAttributes: enabledAttributes,
  8778. attributeDivisors: attributeDivisors,
  8779. object: vao,
  8780. attributes: {},
  8781. index: null
  8782. };
  8783. }
  8784. function needsUpdate(geometry, index) {
  8785. const cachedAttributes = currentState.attributes;
  8786. const geometryAttributes = geometry.attributes;
  8787. let attributesNum = 0;
  8788. for (const key in geometryAttributes) {
  8789. const cachedAttribute = cachedAttributes[key];
  8790. const geometryAttribute = geometryAttributes[key];
  8791. if (cachedAttribute === undefined) return true;
  8792. if (cachedAttribute.attribute !== geometryAttribute) return true;
  8793. if (cachedAttribute.data !== geometryAttribute.data) return true;
  8794. attributesNum++;
  8795. }
  8796. if (currentState.attributesNum !== attributesNum) return true;
  8797. if (currentState.index !== index) return true;
  8798. return false;
  8799. }
  8800. function saveCache(geometry, index) {
  8801. const cache = {};
  8802. const attributes = geometry.attributes;
  8803. let attributesNum = 0;
  8804. for (const key in attributes) {
  8805. const attribute = attributes[key];
  8806. const data = {};
  8807. data.attribute = attribute;
  8808. if (attribute.data) {
  8809. data.data = attribute.data;
  8810. }
  8811. cache[key] = data;
  8812. attributesNum++;
  8813. }
  8814. currentState.attributes = cache;
  8815. currentState.attributesNum = attributesNum;
  8816. currentState.index = index;
  8817. }
  8818. function initAttributes() {
  8819. const newAttributes = currentState.newAttributes;
  8820. for (let i = 0, il = newAttributes.length; i < il; i++) {
  8821. newAttributes[i] = 0;
  8822. }
  8823. }
  8824. function enableAttribute(attribute) {
  8825. enableAttributeAndDivisor(attribute, 0);
  8826. }
  8827. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  8828. const newAttributes = currentState.newAttributes;
  8829. const enabledAttributes = currentState.enabledAttributes;
  8830. const attributeDivisors = currentState.attributeDivisors;
  8831. newAttributes[attribute] = 1;
  8832. if (enabledAttributes[attribute] === 0) {
  8833. gl.enableVertexAttribArray(attribute);
  8834. enabledAttributes[attribute] = 1;
  8835. }
  8836. if (attributeDivisors[attribute] !== meshPerAttribute) {
  8837. const extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  8838. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  8839. attributeDivisors[attribute] = meshPerAttribute;
  8840. }
  8841. }
  8842. function disableUnusedAttributes() {
  8843. const newAttributes = currentState.newAttributes;
  8844. const enabledAttributes = currentState.enabledAttributes;
  8845. for (let i = 0, il = enabledAttributes.length; i < il; i++) {
  8846. if (enabledAttributes[i] !== newAttributes[i]) {
  8847. gl.disableVertexAttribArray(i);
  8848. enabledAttributes[i] = 0;
  8849. }
  8850. }
  8851. }
  8852. function vertexAttribPointer(index, size, type, normalized, stride, offset) {
  8853. if (capabilities.isWebGL2 === true && (type === gl.INT || type === gl.UNSIGNED_INT)) {
  8854. gl.vertexAttribIPointer(index, size, type, stride, offset);
  8855. } else {
  8856. gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
  8857. }
  8858. }
  8859. function setupVertexAttributes(object, material, program, geometry) {
  8860. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  8861. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  8862. }
  8863. initAttributes();
  8864. const geometryAttributes = geometry.attributes;
  8865. const programAttributes = program.getAttributes();
  8866. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8867. for (const name in programAttributes) {
  8868. const programAttribute = programAttributes[name];
  8869. if (programAttribute >= 0) {
  8870. const geometryAttribute = geometryAttributes[name];
  8871. if (geometryAttribute !== undefined) {
  8872. const normalized = geometryAttribute.normalized;
  8873. const size = geometryAttribute.itemSize;
  8874. const attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  8875. if (attribute === undefined) continue;
  8876. const buffer = attribute.buffer;
  8877. const type = attribute.type;
  8878. const bytesPerElement = attribute.bytesPerElement;
  8879. if (geometryAttribute.isInterleavedBufferAttribute) {
  8880. const data = geometryAttribute.data;
  8881. const stride = data.stride;
  8882. const offset = geometryAttribute.offset;
  8883. if (data && data.isInstancedInterleavedBuffer) {
  8884. enableAttributeAndDivisor(programAttribute, data.meshPerAttribute);
  8885. if (geometry._maxInstanceCount === undefined) {
  8886. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8887. }
  8888. } else {
  8889. enableAttribute(programAttribute);
  8890. }
  8891. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8892. vertexAttribPointer(programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement);
  8893. } else {
  8894. if (geometryAttribute.isInstancedBufferAttribute) {
  8895. enableAttributeAndDivisor(programAttribute, geometryAttribute.meshPerAttribute);
  8896. if (geometry._maxInstanceCount === undefined) {
  8897. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8898. }
  8899. } else {
  8900. enableAttribute(programAttribute);
  8901. }
  8902. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8903. vertexAttribPointer(programAttribute, size, type, normalized, 0, 0);
  8904. }
  8905. } else if (name === 'instanceMatrix') {
  8906. const attribute = attributes.get(object.instanceMatrix); // TODO Attribute may not be available on context restore
  8907. if (attribute === undefined) continue;
  8908. const buffer = attribute.buffer;
  8909. const type = attribute.type;
  8910. enableAttributeAndDivisor(programAttribute + 0, 1);
  8911. enableAttributeAndDivisor(programAttribute + 1, 1);
  8912. enableAttributeAndDivisor(programAttribute + 2, 1);
  8913. enableAttributeAndDivisor(programAttribute + 3, 1);
  8914. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8915. gl.vertexAttribPointer(programAttribute + 0, 4, type, false, 64, 0);
  8916. gl.vertexAttribPointer(programAttribute + 1, 4, type, false, 64, 16);
  8917. gl.vertexAttribPointer(programAttribute + 2, 4, type, false, 64, 32);
  8918. gl.vertexAttribPointer(programAttribute + 3, 4, type, false, 64, 48);
  8919. } else if (name === 'instanceColor') {
  8920. const attribute = attributes.get(object.instanceColor); // TODO Attribute may not be available on context restore
  8921. if (attribute === undefined) continue;
  8922. const buffer = attribute.buffer;
  8923. const type = attribute.type;
  8924. enableAttributeAndDivisor(programAttribute, 1);
  8925. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8926. gl.vertexAttribPointer(programAttribute, 3, type, false, 12, 0);
  8927. } else if (materialDefaultAttributeValues !== undefined) {
  8928. const value = materialDefaultAttributeValues[name];
  8929. if (value !== undefined) {
  8930. switch (value.length) {
  8931. case 2:
  8932. gl.vertexAttrib2fv(programAttribute, value);
  8933. break;
  8934. case 3:
  8935. gl.vertexAttrib3fv(programAttribute, value);
  8936. break;
  8937. case 4:
  8938. gl.vertexAttrib4fv(programAttribute, value);
  8939. break;
  8940. default:
  8941. gl.vertexAttrib1fv(programAttribute, value);
  8942. }
  8943. }
  8944. }
  8945. }
  8946. }
  8947. disableUnusedAttributes();
  8948. }
  8949. function dispose() {
  8950. reset();
  8951. for (const geometryId in bindingStates) {
  8952. const programMap = bindingStates[geometryId];
  8953. for (const programId in programMap) {
  8954. const stateMap = programMap[programId];
  8955. for (const wireframe in stateMap) {
  8956. deleteVertexArrayObject(stateMap[wireframe].object);
  8957. delete stateMap[wireframe];
  8958. }
  8959. delete programMap[programId];
  8960. }
  8961. delete bindingStates[geometryId];
  8962. }
  8963. }
  8964. function releaseStatesOfGeometry(geometry) {
  8965. if (bindingStates[geometry.id] === undefined) return;
  8966. const programMap = bindingStates[geometry.id];
  8967. for (const programId in programMap) {
  8968. const stateMap = programMap[programId];
  8969. for (const wireframe in stateMap) {
  8970. deleteVertexArrayObject(stateMap[wireframe].object);
  8971. delete stateMap[wireframe];
  8972. }
  8973. delete programMap[programId];
  8974. }
  8975. delete bindingStates[geometry.id];
  8976. }
  8977. function releaseStatesOfProgram(program) {
  8978. for (const geometryId in bindingStates) {
  8979. const programMap = bindingStates[geometryId];
  8980. if (programMap[program.id] === undefined) continue;
  8981. const stateMap = programMap[program.id];
  8982. for (const wireframe in stateMap) {
  8983. deleteVertexArrayObject(stateMap[wireframe].object);
  8984. delete stateMap[wireframe];
  8985. }
  8986. delete programMap[program.id];
  8987. }
  8988. }
  8989. function reset() {
  8990. resetDefaultState();
  8991. if (currentState === defaultState) return;
  8992. currentState = defaultState;
  8993. bindVertexArrayObject(currentState.object);
  8994. } // for backward-compatilibity
  8995. function resetDefaultState() {
  8996. defaultState.geometry = null;
  8997. defaultState.program = null;
  8998. defaultState.wireframe = false;
  8999. }
  9000. return {
  9001. setup: setup,
  9002. reset: reset,
  9003. resetDefaultState: resetDefaultState,
  9004. dispose: dispose,
  9005. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9006. releaseStatesOfProgram: releaseStatesOfProgram,
  9007. initAttributes: initAttributes,
  9008. enableAttribute: enableAttribute,
  9009. disableUnusedAttributes: disableUnusedAttributes
  9010. };
  9011. }
  9012. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  9013. const isWebGL2 = capabilities.isWebGL2;
  9014. let mode;
  9015. function setMode(value) {
  9016. mode = value;
  9017. }
  9018. function render(start, count) {
  9019. gl.drawArrays(mode, start, count);
  9020. info.update(count, mode, 1);
  9021. }
  9022. function renderInstances(start, count, primcount) {
  9023. if (primcount === 0) return;
  9024. let extension, methodName;
  9025. if (isWebGL2) {
  9026. extension = gl;
  9027. methodName = 'drawArraysInstanced';
  9028. } else {
  9029. extension = extensions.get('ANGLE_instanced_arrays');
  9030. methodName = 'drawArraysInstancedANGLE';
  9031. if (extension === null) {
  9032. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9033. return;
  9034. }
  9035. }
  9036. extension[methodName](mode, start, count, primcount);
  9037. info.update(count, mode, primcount);
  9038. } //
  9039. this.setMode = setMode;
  9040. this.render = render;
  9041. this.renderInstances = renderInstances;
  9042. }
  9043. function WebGLCapabilities(gl, extensions, parameters) {
  9044. let maxAnisotropy;
  9045. function getMaxAnisotropy() {
  9046. if (maxAnisotropy !== undefined) return maxAnisotropy;
  9047. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  9048. const extension = extensions.get('EXT_texture_filter_anisotropic');
  9049. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  9050. } else {
  9051. maxAnisotropy = 0;
  9052. }
  9053. return maxAnisotropy;
  9054. }
  9055. function getMaxPrecision(precision) {
  9056. if (precision === 'highp') {
  9057. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) {
  9058. return 'highp';
  9059. }
  9060. precision = 'mediump';
  9061. }
  9062. if (precision === 'mediump') {
  9063. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) {
  9064. return 'mediump';
  9065. }
  9066. }
  9067. return 'lowp';
  9068. }
  9069. /* eslint-disable no-undef */
  9070. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  9071. /* eslint-enable no-undef */
  9072. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9073. const maxPrecision = getMaxPrecision(precision);
  9074. if (maxPrecision !== precision) {
  9075. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  9076. precision = maxPrecision;
  9077. }
  9078. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9079. const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
  9080. const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9081. const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
  9082. const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9083. const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  9084. const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
  9085. const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS);
  9086. const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9087. const vertexTextures = maxVertexTextures > 0;
  9088. const floatFragmentTextures = isWebGL2 || extensions.has('OES_texture_float');
  9089. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9090. const maxSamples = isWebGL2 ? gl.getParameter(gl.MAX_SAMPLES) : 0;
  9091. return {
  9092. isWebGL2: isWebGL2,
  9093. getMaxAnisotropy: getMaxAnisotropy,
  9094. getMaxPrecision: getMaxPrecision,
  9095. precision: precision,
  9096. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9097. maxTextures: maxTextures,
  9098. maxVertexTextures: maxVertexTextures,
  9099. maxTextureSize: maxTextureSize,
  9100. maxCubemapSize: maxCubemapSize,
  9101. maxAttributes: maxAttributes,
  9102. maxVertexUniforms: maxVertexUniforms,
  9103. maxVaryings: maxVaryings,
  9104. maxFragmentUniforms: maxFragmentUniforms,
  9105. vertexTextures: vertexTextures,
  9106. floatFragmentTextures: floatFragmentTextures,
  9107. floatVertexTextures: floatVertexTextures,
  9108. maxSamples: maxSamples
  9109. };
  9110. }
  9111. function WebGLClipping(properties) {
  9112. const scope = this;
  9113. let globalState = null,
  9114. numGlobalPlanes = 0,
  9115. localClippingEnabled = false,
  9116. renderingShadows = false;
  9117. const plane = new Plane(),
  9118. viewNormalMatrix = new Matrix3(),
  9119. uniform = {
  9120. value: null,
  9121. needsUpdate: false
  9122. };
  9123. this.uniform = uniform;
  9124. this.numPlanes = 0;
  9125. this.numIntersection = 0;
  9126. this.init = function (planes, enableLocalClipping, camera) {
  9127. const enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  9128. // run another frame in order to reset the state:
  9129. numGlobalPlanes !== 0 || localClippingEnabled;
  9130. localClippingEnabled = enableLocalClipping;
  9131. globalState = projectPlanes(planes, camera, 0);
  9132. numGlobalPlanes = planes.length;
  9133. return enabled;
  9134. };
  9135. this.beginShadows = function () {
  9136. renderingShadows = true;
  9137. projectPlanes(null);
  9138. };
  9139. this.endShadows = function () {
  9140. renderingShadows = false;
  9141. resetGlobalState();
  9142. };
  9143. this.setState = function (material, camera, useCache) {
  9144. const planes = material.clippingPlanes,
  9145. clipIntersection = material.clipIntersection,
  9146. clipShadows = material.clipShadows;
  9147. const materialProperties = properties.get(material);
  9148. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  9149. // there's no local clipping
  9150. if (renderingShadows) {
  9151. // there's no global clipping
  9152. projectPlanes(null);
  9153. } else {
  9154. resetGlobalState();
  9155. }
  9156. } else {
  9157. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9158. lGlobal = nGlobal * 4;
  9159. let dstArray = materialProperties.clippingState || null;
  9160. uniform.value = dstArray; // ensure unique state
  9161. dstArray = projectPlanes(planes, camera, lGlobal, useCache);
  9162. for (let i = 0; i !== lGlobal; ++i) {
  9163. dstArray[i] = globalState[i];
  9164. }
  9165. materialProperties.clippingState = dstArray;
  9166. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9167. this.numPlanes += nGlobal;
  9168. }
  9169. };
  9170. function resetGlobalState() {
  9171. if (uniform.value !== globalState) {
  9172. uniform.value = globalState;
  9173. uniform.needsUpdate = numGlobalPlanes > 0;
  9174. }
  9175. scope.numPlanes = numGlobalPlanes;
  9176. scope.numIntersection = 0;
  9177. }
  9178. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  9179. const nPlanes = planes !== null ? planes.length : 0;
  9180. let dstArray = null;
  9181. if (nPlanes !== 0) {
  9182. dstArray = uniform.value;
  9183. if (skipTransform !== true || dstArray === null) {
  9184. const flatSize = dstOffset + nPlanes * 4,
  9185. viewMatrix = camera.matrixWorldInverse;
  9186. viewNormalMatrix.getNormalMatrix(viewMatrix);
  9187. if (dstArray === null || dstArray.length < flatSize) {
  9188. dstArray = new Float32Array(flatSize);
  9189. }
  9190. for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  9191. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  9192. plane.normal.toArray(dstArray, i4);
  9193. dstArray[i4 + 3] = plane.constant;
  9194. }
  9195. }
  9196. uniform.value = dstArray;
  9197. uniform.needsUpdate = true;
  9198. }
  9199. scope.numPlanes = nPlanes;
  9200. scope.numIntersection = 0;
  9201. return dstArray;
  9202. }
  9203. }
  9204. function WebGLCubeMaps(renderer) {
  9205. let cubemaps = new WeakMap();
  9206. function mapTextureMapping(texture, mapping) {
  9207. if (mapping === EquirectangularReflectionMapping) {
  9208. texture.mapping = CubeReflectionMapping;
  9209. } else if (mapping === EquirectangularRefractionMapping) {
  9210. texture.mapping = CubeRefractionMapping;
  9211. }
  9212. return texture;
  9213. }
  9214. function get(texture) {
  9215. if (texture && texture.isTexture) {
  9216. const mapping = texture.mapping;
  9217. if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
  9218. if (cubemaps.has(texture)) {
  9219. const cubemap = cubemaps.get(texture).texture;
  9220. return mapTextureMapping(cubemap, texture.mapping);
  9221. } else {
  9222. const image = texture.image;
  9223. if (image && image.height > 0) {
  9224. const currentRenderTarget = renderer.getRenderTarget();
  9225. const renderTarget = new WebGLCubeRenderTarget(image.height / 2);
  9226. renderTarget.fromEquirectangularTexture(renderer, texture);
  9227. cubemaps.set(texture, renderTarget);
  9228. renderer.setRenderTarget(currentRenderTarget);
  9229. texture.addEventListener('dispose', onTextureDispose);
  9230. return mapTextureMapping(renderTarget.texture, texture.mapping);
  9231. } else {
  9232. // image not yet ready. try the conversion next frame
  9233. return null;
  9234. }
  9235. }
  9236. }
  9237. }
  9238. return texture;
  9239. }
  9240. function onTextureDispose(event) {
  9241. const texture = event.target;
  9242. texture.removeEventListener('dispose', onTextureDispose);
  9243. const cubemap = cubemaps.get(texture);
  9244. if (cubemap !== undefined) {
  9245. cubemaps.delete(texture);
  9246. cubemap.dispose();
  9247. }
  9248. }
  9249. function dispose() {
  9250. cubemaps = new WeakMap();
  9251. }
  9252. return {
  9253. get: get,
  9254. dispose: dispose
  9255. };
  9256. }
  9257. function WebGLExtensions(gl) {
  9258. const extensions = {};
  9259. function getExtension(name) {
  9260. if (extensions[name] !== undefined) {
  9261. return extensions[name];
  9262. }
  9263. let extension;
  9264. switch (name) {
  9265. case 'WEBGL_depth_texture':
  9266. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  9267. break;
  9268. case 'EXT_texture_filter_anisotropic':
  9269. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  9270. break;
  9271. case 'WEBGL_compressed_texture_s3tc':
  9272. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  9273. break;
  9274. case 'WEBGL_compressed_texture_pvrtc':
  9275. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  9276. break;
  9277. default:
  9278. extension = gl.getExtension(name);
  9279. }
  9280. extensions[name] = extension;
  9281. return extension;
  9282. }
  9283. return {
  9284. has: function (name) {
  9285. return getExtension(name) !== null;
  9286. },
  9287. init: function (capabilities) {
  9288. if (capabilities.isWebGL2) {
  9289. getExtension('EXT_color_buffer_float');
  9290. } else {
  9291. getExtension('WEBGL_depth_texture');
  9292. getExtension('OES_texture_float');
  9293. getExtension('OES_texture_half_float');
  9294. getExtension('OES_texture_half_float_linear');
  9295. getExtension('OES_standard_derivatives');
  9296. getExtension('OES_element_index_uint');
  9297. getExtension('OES_vertex_array_object');
  9298. getExtension('ANGLE_instanced_arrays');
  9299. }
  9300. getExtension('OES_texture_float_linear');
  9301. getExtension('EXT_color_buffer_half_float');
  9302. },
  9303. get: function (name) {
  9304. const extension = getExtension(name);
  9305. if (extension === null) {
  9306. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  9307. }
  9308. return extension;
  9309. }
  9310. };
  9311. }
  9312. function WebGLGeometries(gl, attributes, info, bindingStates) {
  9313. const geometries = {};
  9314. const wireframeAttributes = new WeakMap();
  9315. function onGeometryDispose(event) {
  9316. const geometry = event.target;
  9317. if (geometry.index !== null) {
  9318. attributes.remove(geometry.index);
  9319. }
  9320. for (const name in geometry.attributes) {
  9321. attributes.remove(geometry.attributes[name]);
  9322. }
  9323. geometry.removeEventListener('dispose', onGeometryDispose);
  9324. delete geometries[geometry.id];
  9325. const attribute = wireframeAttributes.get(geometry);
  9326. if (attribute) {
  9327. attributes.remove(attribute);
  9328. wireframeAttributes.delete(geometry);
  9329. }
  9330. bindingStates.releaseStatesOfGeometry(geometry);
  9331. if (geometry.isInstancedBufferGeometry === true) {
  9332. delete geometry._maxInstanceCount;
  9333. } //
  9334. info.memory.geometries--;
  9335. }
  9336. function get(object, geometry) {
  9337. if (geometries[geometry.id] === true) return geometry;
  9338. geometry.addEventListener('dispose', onGeometryDispose);
  9339. geometries[geometry.id] = true;
  9340. info.memory.geometries++;
  9341. return geometry;
  9342. }
  9343. function update(geometry) {
  9344. const geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates.
  9345. for (const name in geometryAttributes) {
  9346. attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER);
  9347. } // morph targets
  9348. const morphAttributes = geometry.morphAttributes;
  9349. for (const name in morphAttributes) {
  9350. const array = morphAttributes[name];
  9351. for (let i = 0, l = array.length; i < l; i++) {
  9352. attributes.update(array[i], gl.ARRAY_BUFFER);
  9353. }
  9354. }
  9355. }
  9356. function updateWireframeAttribute(geometry) {
  9357. const indices = [];
  9358. const geometryIndex = geometry.index;
  9359. const geometryPosition = geometry.attributes.position;
  9360. let version = 0;
  9361. if (geometryIndex !== null) {
  9362. const array = geometryIndex.array;
  9363. version = geometryIndex.version;
  9364. for (let i = 0, l = array.length; i < l; i += 3) {
  9365. const a = array[i + 0];
  9366. const b = array[i + 1];
  9367. const c = array[i + 2];
  9368. indices.push(a, b, b, c, c, a);
  9369. }
  9370. } else {
  9371. const array = geometryPosition.array;
  9372. version = geometryPosition.version;
  9373. for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  9374. const a = i + 0;
  9375. const b = i + 1;
  9376. const c = i + 2;
  9377. indices.push(a, b, b, c, c, a);
  9378. }
  9379. }
  9380. const attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  9381. attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
  9382. //
  9383. const previousAttribute = wireframeAttributes.get(geometry);
  9384. if (previousAttribute) attributes.remove(previousAttribute); //
  9385. wireframeAttributes.set(geometry, attribute);
  9386. }
  9387. function getWireframeAttribute(geometry) {
  9388. const currentAttribute = wireframeAttributes.get(geometry);
  9389. if (currentAttribute) {
  9390. const geometryIndex = geometry.index;
  9391. if (geometryIndex !== null) {
  9392. // if the attribute is obsolete, create a new one
  9393. if (currentAttribute.version < geometryIndex.version) {
  9394. updateWireframeAttribute(geometry);
  9395. }
  9396. }
  9397. } else {
  9398. updateWireframeAttribute(geometry);
  9399. }
  9400. return wireframeAttributes.get(geometry);
  9401. }
  9402. return {
  9403. get: get,
  9404. update: update,
  9405. getWireframeAttribute: getWireframeAttribute
  9406. };
  9407. }
  9408. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  9409. const isWebGL2 = capabilities.isWebGL2;
  9410. let mode;
  9411. function setMode(value) {
  9412. mode = value;
  9413. }
  9414. let type, bytesPerElement;
  9415. function setIndex(value) {
  9416. type = value.type;
  9417. bytesPerElement = value.bytesPerElement;
  9418. }
  9419. function render(start, count) {
  9420. gl.drawElements(mode, count, type, start * bytesPerElement);
  9421. info.update(count, mode, 1);
  9422. }
  9423. function renderInstances(start, count, primcount) {
  9424. if (primcount === 0) return;
  9425. let extension, methodName;
  9426. if (isWebGL2) {
  9427. extension = gl;
  9428. methodName = 'drawElementsInstanced';
  9429. } else {
  9430. extension = extensions.get('ANGLE_instanced_arrays');
  9431. methodName = 'drawElementsInstancedANGLE';
  9432. if (extension === null) {
  9433. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9434. return;
  9435. }
  9436. }
  9437. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  9438. info.update(count, mode, primcount);
  9439. } //
  9440. this.setMode = setMode;
  9441. this.setIndex = setIndex;
  9442. this.render = render;
  9443. this.renderInstances = renderInstances;
  9444. }
  9445. function WebGLInfo(gl) {
  9446. const memory = {
  9447. geometries: 0,
  9448. textures: 0
  9449. };
  9450. const render = {
  9451. frame: 0,
  9452. calls: 0,
  9453. triangles: 0,
  9454. points: 0,
  9455. lines: 0
  9456. };
  9457. function update(count, mode, instanceCount) {
  9458. render.calls++;
  9459. switch (mode) {
  9460. case gl.TRIANGLES:
  9461. render.triangles += instanceCount * (count / 3);
  9462. break;
  9463. case gl.LINES:
  9464. render.lines += instanceCount * (count / 2);
  9465. break;
  9466. case gl.LINE_STRIP:
  9467. render.lines += instanceCount * (count - 1);
  9468. break;
  9469. case gl.LINE_LOOP:
  9470. render.lines += instanceCount * count;
  9471. break;
  9472. case gl.POINTS:
  9473. render.points += instanceCount * count;
  9474. break;
  9475. default:
  9476. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  9477. break;
  9478. }
  9479. }
  9480. function reset() {
  9481. render.frame++;
  9482. render.calls = 0;
  9483. render.triangles = 0;
  9484. render.points = 0;
  9485. render.lines = 0;
  9486. }
  9487. return {
  9488. memory: memory,
  9489. render: render,
  9490. programs: null,
  9491. autoReset: true,
  9492. reset: reset,
  9493. update: update
  9494. };
  9495. }
  9496. function numericalSort(a, b) {
  9497. return a[0] - b[0];
  9498. }
  9499. function absNumericalSort(a, b) {
  9500. return Math.abs(b[1]) - Math.abs(a[1]);
  9501. }
  9502. function WebGLMorphtargets(gl) {
  9503. const influencesList = {};
  9504. const morphInfluences = new Float32Array(8);
  9505. const workInfluences = [];
  9506. for (let i = 0; i < 8; i++) {
  9507. workInfluences[i] = [i, 0];
  9508. }
  9509. function update(object, geometry, material, program) {
  9510. const objectInfluences = object.morphTargetInfluences; // When object doesn't have morph target influences defined, we treat it as a 0-length array
  9511. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  9512. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  9513. let influences = influencesList[geometry.id];
  9514. if (influences === undefined) {
  9515. // initialise list
  9516. influences = [];
  9517. for (let i = 0; i < length; i++) {
  9518. influences[i] = [i, 0];
  9519. }
  9520. influencesList[geometry.id] = influences;
  9521. } // Collect influences
  9522. for (let i = 0; i < length; i++) {
  9523. const influence = influences[i];
  9524. influence[0] = i;
  9525. influence[1] = objectInfluences[i];
  9526. }
  9527. influences.sort(absNumericalSort);
  9528. for (let i = 0; i < 8; i++) {
  9529. if (i < length && influences[i][1]) {
  9530. workInfluences[i][0] = influences[i][0];
  9531. workInfluences[i][1] = influences[i][1];
  9532. } else {
  9533. workInfluences[i][0] = Number.MAX_SAFE_INTEGER;
  9534. workInfluences[i][1] = 0;
  9535. }
  9536. }
  9537. workInfluences.sort(numericalSort);
  9538. const morphTargets = material.morphTargets && geometry.morphAttributes.position;
  9539. const morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  9540. let morphInfluencesSum = 0;
  9541. for (let i = 0; i < 8; i++) {
  9542. const influence = workInfluences[i];
  9543. const index = influence[0];
  9544. const value = influence[1];
  9545. if (index !== Number.MAX_SAFE_INTEGER && value) {
  9546. if (morphTargets && geometry.getAttribute('morphTarget' + i) !== morphTargets[index]) {
  9547. geometry.setAttribute('morphTarget' + i, morphTargets[index]);
  9548. }
  9549. if (morphNormals && geometry.getAttribute('morphNormal' + i) !== morphNormals[index]) {
  9550. geometry.setAttribute('morphNormal' + i, morphNormals[index]);
  9551. }
  9552. morphInfluences[i] = value;
  9553. morphInfluencesSum += value;
  9554. } else {
  9555. if (morphTargets && geometry.hasAttribute('morphTarget' + i) === true) {
  9556. geometry.deleteAttribute('morphTarget' + i);
  9557. }
  9558. if (morphNormals && geometry.hasAttribute('morphNormal' + i) === true) {
  9559. geometry.deleteAttribute('morphNormal' + i);
  9560. }
  9561. morphInfluences[i] = 0;
  9562. }
  9563. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  9564. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  9565. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  9566. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  9567. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  9568. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  9569. }
  9570. return {
  9571. update: update
  9572. };
  9573. }
  9574. function WebGLObjects(gl, geometries, attributes, info) {
  9575. let updateMap = new WeakMap();
  9576. function update(object) {
  9577. const frame = info.render.frame;
  9578. const geometry = object.geometry;
  9579. const buffergeometry = geometries.get(object, geometry); // Update once per frame
  9580. if (updateMap.get(buffergeometry) !== frame) {
  9581. geometries.update(buffergeometry);
  9582. updateMap.set(buffergeometry, frame);
  9583. }
  9584. if (object.isInstancedMesh) {
  9585. if (object.hasEventListener('dispose', onInstancedMeshDispose) === false) {
  9586. object.addEventListener('dispose', onInstancedMeshDispose);
  9587. }
  9588. attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER);
  9589. if (object.instanceColor !== null) {
  9590. attributes.update(object.instanceColor, gl.ARRAY_BUFFER);
  9591. }
  9592. }
  9593. return buffergeometry;
  9594. }
  9595. function dispose() {
  9596. updateMap = new WeakMap();
  9597. }
  9598. function onInstancedMeshDispose(event) {
  9599. const instancedMesh = event.target;
  9600. instancedMesh.removeEventListener('dispose', onInstancedMeshDispose);
  9601. attributes.remove(instancedMesh.instanceMatrix);
  9602. if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor);
  9603. }
  9604. return {
  9605. update: update,
  9606. dispose: dispose
  9607. };
  9608. }
  9609. class DataTexture2DArray extends Texture {
  9610. constructor(data = null, width = 1, height = 1, depth = 1) {
  9611. super(null);
  9612. this.image = {
  9613. data,
  9614. width,
  9615. height,
  9616. depth
  9617. };
  9618. this.magFilter = NearestFilter;
  9619. this.minFilter = NearestFilter;
  9620. this.wrapR = ClampToEdgeWrapping;
  9621. this.generateMipmaps = false;
  9622. this.flipY = false;
  9623. this.unpackAlignment = 1;
  9624. this.needsUpdate = true;
  9625. }
  9626. }
  9627. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  9628. class DataTexture3D extends Texture {
  9629. constructor(data = null, width = 1, height = 1, depth = 1) {
  9630. // We're going to add .setXXX() methods for setting properties later.
  9631. // Users can still set in DataTexture3D directly.
  9632. //
  9633. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  9634. // texture.anisotropy = 16;
  9635. //
  9636. // See #14839
  9637. super(null);
  9638. this.image = {
  9639. data,
  9640. width,
  9641. height,
  9642. depth
  9643. };
  9644. this.magFilter = NearestFilter;
  9645. this.minFilter = NearestFilter;
  9646. this.wrapR = ClampToEdgeWrapping;
  9647. this.generateMipmaps = false;
  9648. this.flipY = false;
  9649. this.unpackAlignment = 1;
  9650. this.needsUpdate = true;
  9651. }
  9652. }
  9653. DataTexture3D.prototype.isDataTexture3D = true;
  9654. /**
  9655. * Uniforms of a program.
  9656. * Those form a tree structure with a special top-level container for the root,
  9657. * which you get by calling 'new WebGLUniforms( gl, program )'.
  9658. *
  9659. *
  9660. * Properties of inner nodes including the top-level container:
  9661. *
  9662. * .seq - array of nested uniforms
  9663. * .map - nested uniforms by name
  9664. *
  9665. *
  9666. * Methods of all nodes except the top-level container:
  9667. *
  9668. * .setValue( gl, value, [textures] )
  9669. *
  9670. * uploads a uniform value(s)
  9671. * the 'textures' parameter is needed for sampler uniforms
  9672. *
  9673. *
  9674. * Static methods of the top-level container (textures factorizations):
  9675. *
  9676. * .upload( gl, seq, values, textures )
  9677. *
  9678. * sets uniforms in 'seq' to 'values[id].value'
  9679. *
  9680. * .seqWithValue( seq, values ) : filteredSeq
  9681. *
  9682. * filters 'seq' entries with corresponding entry in values
  9683. *
  9684. *
  9685. * Methods of the top-level container (textures factorizations):
  9686. *
  9687. * .setValue( gl, name, value, textures )
  9688. *
  9689. * sets uniform with name 'name' to 'value'
  9690. *
  9691. * .setOptional( gl, obj, prop )
  9692. *
  9693. * like .set for an optional property of the object
  9694. *
  9695. */
  9696. const emptyTexture = new Texture();
  9697. const emptyTexture2dArray = new DataTexture2DArray();
  9698. const emptyTexture3d = new DataTexture3D();
  9699. const emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  9700. // Array Caches (provide typed arrays for temporary by size)
  9701. const arrayCacheF32 = [];
  9702. const arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  9703. const mat4array = new Float32Array(16);
  9704. const mat3array = new Float32Array(9);
  9705. const mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  9706. function flatten(array, nBlocks, blockSize) {
  9707. const firstElem = array[0];
  9708. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  9709. // see http://jacksondunstan.com/articles/983
  9710. const n = nBlocks * blockSize;
  9711. let r = arrayCacheF32[n];
  9712. if (r === undefined) {
  9713. r = new Float32Array(n);
  9714. arrayCacheF32[n] = r;
  9715. }
  9716. if (nBlocks !== 0) {
  9717. firstElem.toArray(r, 0);
  9718. for (let i = 1, offset = 0; i !== nBlocks; ++i) {
  9719. offset += blockSize;
  9720. array[i].toArray(r, offset);
  9721. }
  9722. }
  9723. return r;
  9724. }
  9725. function arraysEqual(a, b) {
  9726. if (a.length !== b.length) return false;
  9727. for (let i = 0, l = a.length; i < l; i++) {
  9728. if (a[i] !== b[i]) return false;
  9729. }
  9730. return true;
  9731. }
  9732. function copyArray(a, b) {
  9733. for (let i = 0, l = b.length; i < l; i++) {
  9734. a[i] = b[i];
  9735. }
  9736. } // Texture unit allocation
  9737. function allocTexUnits(textures, n) {
  9738. let r = arrayCacheI32[n];
  9739. if (r === undefined) {
  9740. r = new Int32Array(n);
  9741. arrayCacheI32[n] = r;
  9742. }
  9743. for (let i = 0; i !== n; ++i) {
  9744. r[i] = textures.allocateTextureUnit();
  9745. }
  9746. return r;
  9747. } // --- Setters ---
  9748. // Note: Defining these methods externally, because they come in a bunch
  9749. // and this way their names minify.
  9750. // Single scalar
  9751. function setValueV1f(gl, v) {
  9752. const cache = this.cache;
  9753. if (cache[0] === v) return;
  9754. gl.uniform1f(this.addr, v);
  9755. cache[0] = v;
  9756. } // Single float vector (from flat array or THREE.VectorN)
  9757. function setValueV2f(gl, v) {
  9758. const cache = this.cache;
  9759. if (v.x !== undefined) {
  9760. if (cache[0] !== v.x || cache[1] !== v.y) {
  9761. gl.uniform2f(this.addr, v.x, v.y);
  9762. cache[0] = v.x;
  9763. cache[1] = v.y;
  9764. }
  9765. } else {
  9766. if (arraysEqual(cache, v)) return;
  9767. gl.uniform2fv(this.addr, v);
  9768. copyArray(cache, v);
  9769. }
  9770. }
  9771. function setValueV3f(gl, v) {
  9772. const cache = this.cache;
  9773. if (v.x !== undefined) {
  9774. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  9775. gl.uniform3f(this.addr, v.x, v.y, v.z);
  9776. cache[0] = v.x;
  9777. cache[1] = v.y;
  9778. cache[2] = v.z;
  9779. }
  9780. } else if (v.r !== undefined) {
  9781. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  9782. gl.uniform3f(this.addr, v.r, v.g, v.b);
  9783. cache[0] = v.r;
  9784. cache[1] = v.g;
  9785. cache[2] = v.b;
  9786. }
  9787. } else {
  9788. if (arraysEqual(cache, v)) return;
  9789. gl.uniform3fv(this.addr, v);
  9790. copyArray(cache, v);
  9791. }
  9792. }
  9793. function setValueV4f(gl, v) {
  9794. const cache = this.cache;
  9795. if (v.x !== undefined) {
  9796. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  9797. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  9798. cache[0] = v.x;
  9799. cache[1] = v.y;
  9800. cache[2] = v.z;
  9801. cache[3] = v.w;
  9802. }
  9803. } else {
  9804. if (arraysEqual(cache, v)) return;
  9805. gl.uniform4fv(this.addr, v);
  9806. copyArray(cache, v);
  9807. }
  9808. } // Single matrix (from flat array or THREE.MatrixN)
  9809. function setValueM2(gl, v) {
  9810. const cache = this.cache;
  9811. const elements = v.elements;
  9812. if (elements === undefined) {
  9813. if (arraysEqual(cache, v)) return;
  9814. gl.uniformMatrix2fv(this.addr, false, v);
  9815. copyArray(cache, v);
  9816. } else {
  9817. if (arraysEqual(cache, elements)) return;
  9818. mat2array.set(elements);
  9819. gl.uniformMatrix2fv(this.addr, false, mat2array);
  9820. copyArray(cache, elements);
  9821. }
  9822. }
  9823. function setValueM3(gl, v) {
  9824. const cache = this.cache;
  9825. const elements = v.elements;
  9826. if (elements === undefined) {
  9827. if (arraysEqual(cache, v)) return;
  9828. gl.uniformMatrix3fv(this.addr, false, v);
  9829. copyArray(cache, v);
  9830. } else {
  9831. if (arraysEqual(cache, elements)) return;
  9832. mat3array.set(elements);
  9833. gl.uniformMatrix3fv(this.addr, false, mat3array);
  9834. copyArray(cache, elements);
  9835. }
  9836. }
  9837. function setValueM4(gl, v) {
  9838. const cache = this.cache;
  9839. const elements = v.elements;
  9840. if (elements === undefined) {
  9841. if (arraysEqual(cache, v)) return;
  9842. gl.uniformMatrix4fv(this.addr, false, v);
  9843. copyArray(cache, v);
  9844. } else {
  9845. if (arraysEqual(cache, elements)) return;
  9846. mat4array.set(elements);
  9847. gl.uniformMatrix4fv(this.addr, false, mat4array);
  9848. copyArray(cache, elements);
  9849. }
  9850. } // Single integer / boolean
  9851. function setValueV1i(gl, v) {
  9852. const cache = this.cache;
  9853. if (cache[0] === v) return;
  9854. gl.uniform1i(this.addr, v);
  9855. cache[0] = v;
  9856. } // Single integer / boolean vector (from flat array)
  9857. function setValueV2i(gl, v) {
  9858. const cache = this.cache;
  9859. if (arraysEqual(cache, v)) return;
  9860. gl.uniform2iv(this.addr, v);
  9861. copyArray(cache, v);
  9862. }
  9863. function setValueV3i(gl, v) {
  9864. const cache = this.cache;
  9865. if (arraysEqual(cache, v)) return;
  9866. gl.uniform3iv(this.addr, v);
  9867. copyArray(cache, v);
  9868. }
  9869. function setValueV4i(gl, v) {
  9870. const cache = this.cache;
  9871. if (arraysEqual(cache, v)) return;
  9872. gl.uniform4iv(this.addr, v);
  9873. copyArray(cache, v);
  9874. } // Single unsigned integer
  9875. function setValueV1ui(gl, v) {
  9876. const cache = this.cache;
  9877. if (cache[0] === v) return;
  9878. gl.uniform1ui(this.addr, v);
  9879. cache[0] = v;
  9880. } // Single unsigned integer vector (from flat array)
  9881. function setValueV2ui(gl, v) {
  9882. const cache = this.cache;
  9883. if (arraysEqual(cache, v)) return;
  9884. gl.uniform2uiv(this.addr, v);
  9885. copyArray(cache, v);
  9886. }
  9887. function setValueV3ui(gl, v) {
  9888. const cache = this.cache;
  9889. if (arraysEqual(cache, v)) return;
  9890. gl.uniform3uiv(this.addr, v);
  9891. copyArray(cache, v);
  9892. }
  9893. function setValueV4ui(gl, v) {
  9894. const cache = this.cache;
  9895. if (arraysEqual(cache, v)) return;
  9896. gl.uniform4uiv(this.addr, v);
  9897. copyArray(cache, v);
  9898. } // Single texture (2D / Cube)
  9899. function setValueT1(gl, v, textures) {
  9900. const cache = this.cache;
  9901. const unit = textures.allocateTextureUnit();
  9902. if (cache[0] !== unit) {
  9903. gl.uniform1i(this.addr, unit);
  9904. cache[0] = unit;
  9905. }
  9906. textures.safeSetTexture2D(v || emptyTexture, unit);
  9907. }
  9908. function setValueT3D1(gl, v, textures) {
  9909. const cache = this.cache;
  9910. const unit = textures.allocateTextureUnit();
  9911. if (cache[0] !== unit) {
  9912. gl.uniform1i(this.addr, unit);
  9913. cache[0] = unit;
  9914. }
  9915. textures.setTexture3D(v || emptyTexture3d, unit);
  9916. }
  9917. function setValueT6(gl, v, textures) {
  9918. const cache = this.cache;
  9919. const unit = textures.allocateTextureUnit();
  9920. if (cache[0] !== unit) {
  9921. gl.uniform1i(this.addr, unit);
  9922. cache[0] = unit;
  9923. }
  9924. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  9925. }
  9926. function setValueT2DArray1(gl, v, textures) {
  9927. const cache = this.cache;
  9928. const unit = textures.allocateTextureUnit();
  9929. if (cache[0] !== unit) {
  9930. gl.uniform1i(this.addr, unit);
  9931. cache[0] = unit;
  9932. }
  9933. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  9934. } // Helper to pick the right setter for the singular case
  9935. function getSingularSetter(type) {
  9936. switch (type) {
  9937. case 0x1406:
  9938. return setValueV1f;
  9939. // FLOAT
  9940. case 0x8b50:
  9941. return setValueV2f;
  9942. // _VEC2
  9943. case 0x8b51:
  9944. return setValueV3f;
  9945. // _VEC3
  9946. case 0x8b52:
  9947. return setValueV4f;
  9948. // _VEC4
  9949. case 0x8b5a:
  9950. return setValueM2;
  9951. // _MAT2
  9952. case 0x8b5b:
  9953. return setValueM3;
  9954. // _MAT3
  9955. case 0x8b5c:
  9956. return setValueM4;
  9957. // _MAT4
  9958. case 0x1404:
  9959. case 0x8b56:
  9960. return setValueV1i;
  9961. // INT, BOOL
  9962. case 0x8b53:
  9963. case 0x8b57:
  9964. return setValueV2i;
  9965. // _VEC2
  9966. case 0x8b54:
  9967. case 0x8b58:
  9968. return setValueV3i;
  9969. // _VEC3
  9970. case 0x8b55:
  9971. case 0x8b59:
  9972. return setValueV4i;
  9973. // _VEC4
  9974. case 0x1405:
  9975. return setValueV1ui;
  9976. // UINT
  9977. case 0x8dc6:
  9978. return setValueV2ui;
  9979. // _VEC2
  9980. case 0x8dc7:
  9981. return setValueV3ui;
  9982. // _VEC3
  9983. case 0x8dc8:
  9984. return setValueV4ui;
  9985. // _VEC4
  9986. case 0x8b5e: // SAMPLER_2D
  9987. case 0x8d66: // SAMPLER_EXTERNAL_OES
  9988. case 0x8dca: // INT_SAMPLER_2D
  9989. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  9990. case 0x8b62:
  9991. // SAMPLER_2D_SHADOW
  9992. return setValueT1;
  9993. case 0x8b5f: // SAMPLER_3D
  9994. case 0x8dcb: // INT_SAMPLER_3D
  9995. case 0x8dd3:
  9996. // UNSIGNED_INT_SAMPLER_3D
  9997. return setValueT3D1;
  9998. case 0x8b60: // SAMPLER_CUBE
  9999. case 0x8dcc: // INT_SAMPLER_CUBE
  10000. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10001. case 0x8dc5:
  10002. // SAMPLER_CUBE_SHADOW
  10003. return setValueT6;
  10004. case 0x8dc1: // SAMPLER_2D_ARRAY
  10005. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10006. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10007. case 0x8dc4:
  10008. // SAMPLER_2D_ARRAY_SHADOW
  10009. return setValueT2DArray1;
  10010. }
  10011. } // Array of scalars
  10012. function setValueV1fArray(gl, v) {
  10013. gl.uniform1fv(this.addr, v);
  10014. } // Array of vectors (from flat array or array of THREE.VectorN)
  10015. function setValueV2fArray(gl, v) {
  10016. const data = flatten(v, this.size, 2);
  10017. gl.uniform2fv(this.addr, data);
  10018. }
  10019. function setValueV3fArray(gl, v) {
  10020. const data = flatten(v, this.size, 3);
  10021. gl.uniform3fv(this.addr, data);
  10022. }
  10023. function setValueV4fArray(gl, v) {
  10024. const data = flatten(v, this.size, 4);
  10025. gl.uniform4fv(this.addr, data);
  10026. } // Array of matrices (from flat array or array of THREE.MatrixN)
  10027. function setValueM2Array(gl, v) {
  10028. const data = flatten(v, this.size, 4);
  10029. gl.uniformMatrix2fv(this.addr, false, data);
  10030. }
  10031. function setValueM3Array(gl, v) {
  10032. const data = flatten(v, this.size, 9);
  10033. gl.uniformMatrix3fv(this.addr, false, data);
  10034. }
  10035. function setValueM4Array(gl, v) {
  10036. const data = flatten(v, this.size, 16);
  10037. gl.uniformMatrix4fv(this.addr, false, data);
  10038. } // Array of integer / boolean
  10039. function setValueV1iArray(gl, v) {
  10040. gl.uniform1iv(this.addr, v);
  10041. } // Array of integer / boolean vectors (from flat array)
  10042. function setValueV2iArray(gl, v) {
  10043. gl.uniform2iv(this.addr, v);
  10044. }
  10045. function setValueV3iArray(gl, v) {
  10046. gl.uniform3iv(this.addr, v);
  10047. }
  10048. function setValueV4iArray(gl, v) {
  10049. gl.uniform4iv(this.addr, v);
  10050. } // Array of unsigned integer
  10051. function setValueV1uiArray(gl, v) {
  10052. gl.uniform1uiv(this.addr, v);
  10053. } // Array of unsigned integer vectors (from flat array)
  10054. function setValueV2uiArray(gl, v) {
  10055. gl.uniform2uiv(this.addr, v);
  10056. }
  10057. function setValueV3uiArray(gl, v) {
  10058. gl.uniform3uiv(this.addr, v);
  10059. }
  10060. function setValueV4uiArray(gl, v) {
  10061. gl.uniform4uiv(this.addr, v);
  10062. } // Array of textures (2D / Cube)
  10063. function setValueT1Array(gl, v, textures) {
  10064. const n = v.length;
  10065. const units = allocTexUnits(textures, n);
  10066. gl.uniform1iv(this.addr, units);
  10067. for (let i = 0; i !== n; ++i) {
  10068. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  10069. }
  10070. }
  10071. function setValueT6Array(gl, v, textures) {
  10072. const n = v.length;
  10073. const units = allocTexUnits(textures, n);
  10074. gl.uniform1iv(this.addr, units);
  10075. for (let i = 0; i !== n; ++i) {
  10076. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  10077. }
  10078. } // Helper to pick the right setter for a pure (bottom-level) array
  10079. function getPureArraySetter(type) {
  10080. switch (type) {
  10081. case 0x1406:
  10082. return setValueV1fArray;
  10083. // FLOAT
  10084. case 0x8b50:
  10085. return setValueV2fArray;
  10086. // _VEC2
  10087. case 0x8b51:
  10088. return setValueV3fArray;
  10089. // _VEC3
  10090. case 0x8b52:
  10091. return setValueV4fArray;
  10092. // _VEC4
  10093. case 0x8b5a:
  10094. return setValueM2Array;
  10095. // _MAT2
  10096. case 0x8b5b:
  10097. return setValueM3Array;
  10098. // _MAT3
  10099. case 0x8b5c:
  10100. return setValueM4Array;
  10101. // _MAT4
  10102. case 0x1404:
  10103. case 0x8b56:
  10104. return setValueV1iArray;
  10105. // INT, BOOL
  10106. case 0x8b53:
  10107. case 0x8b57:
  10108. return setValueV2iArray;
  10109. // _VEC2
  10110. case 0x8b54:
  10111. case 0x8b58:
  10112. return setValueV3iArray;
  10113. // _VEC3
  10114. case 0x8b55:
  10115. case 0x8b59:
  10116. return setValueV4iArray;
  10117. // _VEC4
  10118. case 0x1405:
  10119. return setValueV1uiArray;
  10120. // UINT
  10121. case 0x8dc6:
  10122. return setValueV2uiArray;
  10123. // _VEC2
  10124. case 0x8dc7:
  10125. return setValueV3uiArray;
  10126. // _VEC3
  10127. case 0x8dc8:
  10128. return setValueV4uiArray;
  10129. // _VEC4
  10130. case 0x8b5e: // SAMPLER_2D
  10131. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10132. case 0x8dca: // INT_SAMPLER_2D
  10133. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10134. case 0x8b62:
  10135. // SAMPLER_2D_SHADOW
  10136. return setValueT1Array;
  10137. case 0x8b60: // SAMPLER_CUBE
  10138. case 0x8dcc: // INT_SAMPLER_CUBE
  10139. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10140. case 0x8dc5:
  10141. // SAMPLER_CUBE_SHADOW
  10142. return setValueT6Array;
  10143. }
  10144. } // --- Uniform Classes ---
  10145. function SingleUniform(id, activeInfo, addr) {
  10146. this.id = id;
  10147. this.addr = addr;
  10148. this.cache = [];
  10149. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  10150. }
  10151. function PureArrayUniform(id, activeInfo, addr) {
  10152. this.id = id;
  10153. this.addr = addr;
  10154. this.cache = [];
  10155. this.size = activeInfo.size;
  10156. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  10157. }
  10158. PureArrayUniform.prototype.updateCache = function (data) {
  10159. const cache = this.cache;
  10160. if (data instanceof Float32Array && cache.length !== data.length) {
  10161. this.cache = new Float32Array(data.length);
  10162. }
  10163. copyArray(cache, data);
  10164. };
  10165. function StructuredUniform(id) {
  10166. this.id = id;
  10167. this.seq = [];
  10168. this.map = {};
  10169. }
  10170. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  10171. const seq = this.seq;
  10172. for (let i = 0, n = seq.length; i !== n; ++i) {
  10173. const u = seq[i];
  10174. u.setValue(gl, value[u.id], textures);
  10175. }
  10176. }; // --- Top-level ---
  10177. // Parser - builds up the property tree from the path strings
  10178. const RePathPart = /(\w+)(\])?(\[|\.)?/g; // extracts
  10179. // - the identifier (member name or array index)
  10180. // - followed by an optional right bracket (found when array index)
  10181. // - followed by an optional left bracket or dot (type of subscript)
  10182. //
  10183. // Note: These portions can be read in a non-overlapping fashion and
  10184. // allow straightforward parsing of the hierarchy that WebGL encodes
  10185. // in the uniform names.
  10186. function addUniform(container, uniformObject) {
  10187. container.seq.push(uniformObject);
  10188. container.map[uniformObject.id] = uniformObject;
  10189. }
  10190. function parseUniform(activeInfo, addr, container) {
  10191. const path = activeInfo.name,
  10192. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  10193. RePathPart.lastIndex = 0;
  10194. while (true) {
  10195. const match = RePathPart.exec(path),
  10196. matchEnd = RePathPart.lastIndex;
  10197. let id = match[1];
  10198. const idIsIndex = match[2] === ']',
  10199. subscript = match[3];
  10200. if (idIsIndex) id = id | 0; // convert to integer
  10201. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  10202. // bare name or "pure" bottom-level array "[0]" suffix
  10203. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  10204. break;
  10205. } else {
  10206. // step into inner node / create it in case it doesn't exist
  10207. const map = container.map;
  10208. let next = map[id];
  10209. if (next === undefined) {
  10210. next = new StructuredUniform(id);
  10211. addUniform(container, next);
  10212. }
  10213. container = next;
  10214. }
  10215. }
  10216. } // Root Container
  10217. function WebGLUniforms(gl, program) {
  10218. this.seq = [];
  10219. this.map = {};
  10220. const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  10221. for (let i = 0; i < n; ++i) {
  10222. const info = gl.getActiveUniform(program, i),
  10223. addr = gl.getUniformLocation(program, info.name);
  10224. parseUniform(info, addr, this);
  10225. }
  10226. }
  10227. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  10228. const u = this.map[name];
  10229. if (u !== undefined) u.setValue(gl, value, textures);
  10230. };
  10231. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  10232. const v = object[name];
  10233. if (v !== undefined) this.setValue(gl, name, v);
  10234. }; // Static interface
  10235. WebGLUniforms.upload = function (gl, seq, values, textures) {
  10236. for (let i = 0, n = seq.length; i !== n; ++i) {
  10237. const u = seq[i],
  10238. v = values[u.id];
  10239. if (v.needsUpdate !== false) {
  10240. // note: always updating when .needsUpdate is undefined
  10241. u.setValue(gl, v.value, textures);
  10242. }
  10243. }
  10244. };
  10245. WebGLUniforms.seqWithValue = function (seq, values) {
  10246. const r = [];
  10247. for (let i = 0, n = seq.length; i !== n; ++i) {
  10248. const u = seq[i];
  10249. if (u.id in values) r.push(u);
  10250. }
  10251. return r;
  10252. };
  10253. function WebGLShader(gl, type, string) {
  10254. const shader = gl.createShader(type);
  10255. gl.shaderSource(shader, string);
  10256. gl.compileShader(shader);
  10257. return shader;
  10258. }
  10259. let programIdCount = 0;
  10260. function addLineNumbers(string) {
  10261. const lines = string.split('\n');
  10262. for (let i = 0; i < lines.length; i++) {
  10263. lines[i] = i + 1 + ': ' + lines[i];
  10264. }
  10265. return lines.join('\n');
  10266. }
  10267. function getEncodingComponents(encoding) {
  10268. switch (encoding) {
  10269. case LinearEncoding:
  10270. return ['Linear', '( value )'];
  10271. case sRGBEncoding:
  10272. return ['sRGB', '( value )'];
  10273. case RGBEEncoding:
  10274. return ['RGBE', '( value )'];
  10275. case RGBM7Encoding:
  10276. return ['RGBM', '( value, 7.0 )'];
  10277. case RGBM16Encoding:
  10278. return ['RGBM', '( value, 16.0 )'];
  10279. case RGBDEncoding:
  10280. return ['RGBD', '( value, 256.0 )'];
  10281. case GammaEncoding:
  10282. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  10283. case LogLuvEncoding:
  10284. return ['LogLuv', '( value )'];
  10285. default:
  10286. console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
  10287. return ['Linear', '( value )'];
  10288. }
  10289. }
  10290. function getShaderErrors(gl, shader, type) {
  10291. const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  10292. const log = gl.getShaderInfoLog(shader).trim();
  10293. if (status && log === '') return ''; // --enable-privileged-webgl-extension
  10294. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10295. const source = gl.getShaderSource(shader);
  10296. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers(source);
  10297. }
  10298. function getTexelDecodingFunction(functionName, encoding) {
  10299. const components = getEncodingComponents(encoding);
  10300. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  10301. }
  10302. function getTexelEncodingFunction(functionName, encoding) {
  10303. const components = getEncodingComponents(encoding);
  10304. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  10305. }
  10306. function getToneMappingFunction(functionName, toneMapping) {
  10307. let toneMappingName;
  10308. switch (toneMapping) {
  10309. case LinearToneMapping:
  10310. toneMappingName = 'Linear';
  10311. break;
  10312. case ReinhardToneMapping:
  10313. toneMappingName = 'Reinhard';
  10314. break;
  10315. case CineonToneMapping:
  10316. toneMappingName = 'OptimizedCineon';
  10317. break;
  10318. case ACESFilmicToneMapping:
  10319. toneMappingName = 'ACESFilmic';
  10320. break;
  10321. case CustomToneMapping:
  10322. toneMappingName = 'Custom';
  10323. break;
  10324. default:
  10325. console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
  10326. toneMappingName = 'Linear';
  10327. }
  10328. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  10329. }
  10330. function generateExtensions(parameters) {
  10331. 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.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''];
  10332. return chunks.filter(filterEmptyLine).join('\n');
  10333. }
  10334. function generateDefines(defines) {
  10335. const chunks = [];
  10336. for (const name in defines) {
  10337. const value = defines[name];
  10338. if (value === false) continue;
  10339. chunks.push('#define ' + name + ' ' + value);
  10340. }
  10341. return chunks.join('\n');
  10342. }
  10343. function fetchAttributeLocations(gl, program) {
  10344. const attributes = {};
  10345. const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  10346. for (let i = 0; i < n; i++) {
  10347. const info = gl.getActiveAttrib(program, i);
  10348. const name = info.name; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  10349. attributes[name] = gl.getAttribLocation(program, name);
  10350. }
  10351. return attributes;
  10352. }
  10353. function filterEmptyLine(string) {
  10354. return string !== '';
  10355. }
  10356. function replaceLightNums(string, parameters) {
  10357. 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);
  10358. }
  10359. function replaceClippingPlaneNums(string, parameters) {
  10360. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  10361. } // Resolve Includes
  10362. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  10363. function resolveIncludes(string) {
  10364. return string.replace(includePattern, includeReplacer);
  10365. }
  10366. function includeReplacer(match, include) {
  10367. const string = ShaderChunk[include];
  10368. if (string === undefined) {
  10369. throw new Error('Can not resolve #include <' + include + '>');
  10370. }
  10371. return resolveIncludes(string);
  10372. } // Unroll Loops
  10373. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  10374. 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;
  10375. function unrollLoops(string) {
  10376. return string.replace(unrollLoopPattern, loopReplacer).replace(deprecatedUnrollLoopPattern, deprecatedLoopReplacer);
  10377. }
  10378. function deprecatedLoopReplacer(match, start, end, snippet) {
  10379. console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');
  10380. return loopReplacer(match, start, end, snippet);
  10381. }
  10382. function loopReplacer(match, start, end, snippet) {
  10383. let string = '';
  10384. for (let i = parseInt(start); i < parseInt(end); i++) {
  10385. string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  10386. }
  10387. return string;
  10388. } //
  10389. function generatePrecision(parameters) {
  10390. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  10391. if (parameters.precision === 'highp') {
  10392. precisionstring += '\n#define HIGH_PRECISION';
  10393. } else if (parameters.precision === 'mediump') {
  10394. precisionstring += '\n#define MEDIUM_PRECISION';
  10395. } else if (parameters.precision === 'lowp') {
  10396. precisionstring += '\n#define LOW_PRECISION';
  10397. }
  10398. return precisionstring;
  10399. }
  10400. function generateShadowMapTypeDefine(parameters) {
  10401. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  10402. if (parameters.shadowMapType === PCFShadowMap) {
  10403. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  10404. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  10405. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  10406. } else if (parameters.shadowMapType === VSMShadowMap) {
  10407. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  10408. }
  10409. return shadowMapTypeDefine;
  10410. }
  10411. function generateEnvMapTypeDefine(parameters) {
  10412. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10413. if (parameters.envMap) {
  10414. switch (parameters.envMapMode) {
  10415. case CubeReflectionMapping:
  10416. case CubeRefractionMapping:
  10417. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10418. break;
  10419. case CubeUVReflectionMapping:
  10420. case CubeUVRefractionMapping:
  10421. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  10422. break;
  10423. }
  10424. }
  10425. return envMapTypeDefine;
  10426. }
  10427. function generateEnvMapModeDefine(parameters) {
  10428. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  10429. if (parameters.envMap) {
  10430. switch (parameters.envMapMode) {
  10431. case CubeRefractionMapping:
  10432. case CubeUVRefractionMapping:
  10433. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  10434. break;
  10435. }
  10436. }
  10437. return envMapModeDefine;
  10438. }
  10439. function generateEnvMapBlendingDefine(parameters) {
  10440. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  10441. if (parameters.envMap) {
  10442. switch (parameters.combine) {
  10443. case MultiplyOperation:
  10444. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10445. break;
  10446. case MixOperation:
  10447. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  10448. break;
  10449. case AddOperation:
  10450. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  10451. break;
  10452. }
  10453. }
  10454. return envMapBlendingDefine;
  10455. }
  10456. function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
  10457. const gl = renderer.getContext();
  10458. const defines = parameters.defines;
  10459. let vertexShader = parameters.vertexShader;
  10460. let fragmentShader = parameters.fragmentShader;
  10461. const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  10462. const envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  10463. const envMapModeDefine = generateEnvMapModeDefine(parameters);
  10464. const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  10465. const gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  10466. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  10467. const customDefines = generateDefines(defines);
  10468. const program = gl.createProgram();
  10469. let prefixVertex, prefixFragment;
  10470. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  10471. if (parameters.isRawShaderMaterial) {
  10472. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  10473. if (prefixVertex.length > 0) {
  10474. prefixVertex += '\n';
  10475. }
  10476. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  10477. if (prefixFragment.length > 0) {
  10478. prefixFragment += '\n';
  10479. }
  10480. } else {
  10481. 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.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', 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.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', '#ifdef USE_MORPHTARGETS', ' 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');
  10482. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + (parameters.alphaTest % 1 ? '' : '.0') : '', // add '.0' if integer
  10483. '#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.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', 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
  10484. parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', ShaderChunk['encodings_pars_fragment'], // this code is required here because it is used by the various encoding/decoding function defined below
  10485. 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.lightMap ? getTexelDecodingFunction('lightMapTexelToLinear', parameters.lightMapEncoding) : '', getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  10486. }
  10487. vertexShader = resolveIncludes(vertexShader);
  10488. vertexShader = replaceLightNums(vertexShader, parameters);
  10489. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  10490. fragmentShader = resolveIncludes(fragmentShader);
  10491. fragmentShader = replaceLightNums(fragmentShader, parameters);
  10492. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  10493. vertexShader = unrollLoops(vertexShader);
  10494. fragmentShader = unrollLoops(fragmentShader);
  10495. if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
  10496. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  10497. versionString = '#version 300 es\n';
  10498. prefixVertex = ['#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  10499. prefixFragment = ['#define varying in', parameters.glslVersion === GLSL3 ? '' : '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;
  10500. }
  10501. const vertexGlsl = versionString + prefixVertex + vertexShader;
  10502. const fragmentGlsl = versionString + prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  10503. // console.log( '*FRAGMENT*', fragmentGlsl );
  10504. const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl);
  10505. const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl);
  10506. gl.attachShader(program, glVertexShader);
  10507. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  10508. if (parameters.index0AttributeName !== undefined) {
  10509. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  10510. } else if (parameters.morphTargets === true) {
  10511. // programs with morphTargets displace position out of attribute 0
  10512. gl.bindAttribLocation(program, 0, 'position');
  10513. }
  10514. gl.linkProgram(program); // check for link errors
  10515. if (renderer.debug.checkShaderErrors) {
  10516. const programLog = gl.getProgramInfoLog(program).trim();
  10517. const vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  10518. const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  10519. let runnable = true;
  10520. let haveDiagnostics = true;
  10521. if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {
  10522. runnable = false;
  10523. const vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  10524. const fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  10525. console.error('THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors);
  10526. } else if (programLog !== '') {
  10527. console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()', programLog);
  10528. } else if (vertexLog === '' || fragmentLog === '') {
  10529. haveDiagnostics = false;
  10530. }
  10531. if (haveDiagnostics) {
  10532. this.diagnostics = {
  10533. runnable: runnable,
  10534. programLog: programLog,
  10535. vertexShader: {
  10536. log: vertexLog,
  10537. prefix: prefixVertex
  10538. },
  10539. fragmentShader: {
  10540. log: fragmentLog,
  10541. prefix: prefixFragment
  10542. }
  10543. };
  10544. }
  10545. } // Clean up
  10546. // Crashes in iOS9 and iOS10. #18402
  10547. // gl.detachShader( program, glVertexShader );
  10548. // gl.detachShader( program, glFragmentShader );
  10549. gl.deleteShader(glVertexShader);
  10550. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  10551. let cachedUniforms;
  10552. this.getUniforms = function () {
  10553. if (cachedUniforms === undefined) {
  10554. cachedUniforms = new WebGLUniforms(gl, program);
  10555. }
  10556. return cachedUniforms;
  10557. }; // set up caching for attribute locations
  10558. let cachedAttributes;
  10559. this.getAttributes = function () {
  10560. if (cachedAttributes === undefined) {
  10561. cachedAttributes = fetchAttributeLocations(gl, program);
  10562. }
  10563. return cachedAttributes;
  10564. }; // free resource
  10565. this.destroy = function () {
  10566. bindingStates.releaseStatesOfProgram(this);
  10567. gl.deleteProgram(program);
  10568. this.program = undefined;
  10569. }; //
  10570. this.name = parameters.shaderName;
  10571. this.id = programIdCount++;
  10572. this.cacheKey = cacheKey;
  10573. this.usedTimes = 1;
  10574. this.program = program;
  10575. this.vertexShader = glVertexShader;
  10576. this.fragmentShader = glFragmentShader;
  10577. return this;
  10578. }
  10579. function WebGLPrograms(renderer, cubemaps, extensions, capabilities, bindingStates, clipping) {
  10580. const programs = [];
  10581. const isWebGL2 = capabilities.isWebGL2;
  10582. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  10583. const floatVertexTextures = capabilities.floatVertexTextures;
  10584. const maxVertexUniforms = capabilities.maxVertexUniforms;
  10585. const vertexTextures = capabilities.vertexTextures;
  10586. let precision = capabilities.precision;
  10587. const shaderIDs = {
  10588. MeshDepthMaterial: 'depth',
  10589. MeshDistanceMaterial: 'distanceRGBA',
  10590. MeshNormalMaterial: 'normal',
  10591. MeshBasicMaterial: 'basic',
  10592. MeshLambertMaterial: 'lambert',
  10593. MeshPhongMaterial: 'phong',
  10594. MeshToonMaterial: 'toon',
  10595. MeshStandardMaterial: 'physical',
  10596. MeshPhysicalMaterial: 'physical',
  10597. MeshMatcapMaterial: 'matcap',
  10598. LineBasicMaterial: 'basic',
  10599. LineDashedMaterial: 'dashed',
  10600. PointsMaterial: 'points',
  10601. ShadowMaterial: 'shadow',
  10602. SpriteMaterial: 'sprite'
  10603. };
  10604. const parameterNames = ['precision', 'isWebGL2', 'supportsVertexTextures', 'outputEncoding', 'instancing', 'instancingColor', 'map', 'mapEncoding', 'matcap', 'matcapEncoding', 'envMap', 'envMapMode', 'envMapEncoding', 'envMapCubeUV', 'lightMap', 'lightMapEncoding', 'aoMap', 'emissiveMap', 'emissiveMapEncoding', 'bumpMap', 'normalMap', 'objectSpaceNormalMap', 'tangentSpaceNormalMap', 'clearcoatMap', 'clearcoatRoughnessMap', 'clearcoatNormalMap', 'displacementMap', 'specularMap', 'roughnessMap', 'metalnessMap', 'gradientMap', 'alphaMap', 'combine', 'vertexColors', 'vertexAlphas', 'vertexTangents', 'vertexUvs', 'uvsVertexOnly', 'fog', 'useFog', 'fogExp2', 'flatShading', 'sizeAttenuation', 'logarithmicDepthBuffer', 'skinning', 'maxBones', 'useVertexTexture', 'morphTargets', 'morphNormals', 'premultipliedAlpha', 'numDirLights', 'numPointLights', 'numSpotLights', 'numHemiLights', 'numRectAreaLights', 'numDirLightShadows', 'numPointLightShadows', 'numSpotLightShadows', 'shadowMapEnabled', 'shadowMapType', 'toneMapping', 'physicallyCorrectLights', 'alphaTest', 'doubleSided', 'flipSided', 'numClippingPlanes', 'numClipIntersection', 'depthPacking', 'dithering', 'sheen', 'transmissionMap'];
  10605. function getMaxBones(object) {
  10606. const skeleton = object.skeleton;
  10607. const bones = skeleton.bones;
  10608. if (floatVertexTextures) {
  10609. return 1024;
  10610. } else {
  10611. // default for when object is not specified
  10612. // ( for example when prebuilding shader to be used with multiple objects )
  10613. //
  10614. // - leave some extra space for other uniforms
  10615. // - limit here is ANGLE's 254 max uniform vectors
  10616. // (up to 54 should be safe)
  10617. const nVertexUniforms = maxVertexUniforms;
  10618. const nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  10619. const maxBones = Math.min(nVertexMatrices, bones.length);
  10620. if (maxBones < bones.length) {
  10621. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  10622. return 0;
  10623. }
  10624. return maxBones;
  10625. }
  10626. }
  10627. function getTextureEncodingFromMap(map) {
  10628. let encoding;
  10629. if (map && map.isTexture) {
  10630. encoding = map.encoding;
  10631. } else if (map && map.isWebGLRenderTarget) {
  10632. console.warn('THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.');
  10633. encoding = map.texture.encoding;
  10634. } else {
  10635. encoding = LinearEncoding;
  10636. }
  10637. return encoding;
  10638. }
  10639. function getParameters(material, lights, shadows, scene, object) {
  10640. const fog = scene.fog;
  10641. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  10642. const envMap = cubemaps.get(material.envMap || environment);
  10643. const shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  10644. // (not to blow over maxLights budget)
  10645. const maxBones = object.isSkinnedMesh ? getMaxBones(object) : 0;
  10646. if (material.precision !== null) {
  10647. precision = capabilities.getMaxPrecision(material.precision);
  10648. if (precision !== material.precision) {
  10649. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  10650. }
  10651. }
  10652. let vertexShader, fragmentShader;
  10653. if (shaderID) {
  10654. const shader = ShaderLib[shaderID];
  10655. vertexShader = shader.vertexShader;
  10656. fragmentShader = shader.fragmentShader;
  10657. } else {
  10658. vertexShader = material.vertexShader;
  10659. fragmentShader = material.fragmentShader;
  10660. }
  10661. const currentRenderTarget = renderer.getRenderTarget();
  10662. const parameters = {
  10663. isWebGL2: isWebGL2,
  10664. shaderID: shaderID,
  10665. shaderName: material.type,
  10666. vertexShader: vertexShader,
  10667. fragmentShader: fragmentShader,
  10668. defines: material.defines,
  10669. isRawShaderMaterial: material.isRawShaderMaterial === true,
  10670. glslVersion: material.glslVersion,
  10671. precision: precision,
  10672. instancing: object.isInstancedMesh === true,
  10673. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  10674. supportsVertexTextures: vertexTextures,
  10675. outputEncoding: currentRenderTarget !== null ? getTextureEncodingFromMap(currentRenderTarget.texture) : renderer.outputEncoding,
  10676. map: !!material.map,
  10677. mapEncoding: getTextureEncodingFromMap(material.map),
  10678. matcap: !!material.matcap,
  10679. matcapEncoding: getTextureEncodingFromMap(material.matcap),
  10680. envMap: !!envMap,
  10681. envMapMode: envMap && envMap.mapping,
  10682. envMapEncoding: getTextureEncodingFromMap(envMap),
  10683. envMapCubeUV: !!envMap && (envMap.mapping === CubeUVReflectionMapping || envMap.mapping === CubeUVRefractionMapping),
  10684. lightMap: !!material.lightMap,
  10685. lightMapEncoding: getTextureEncodingFromMap(material.lightMap),
  10686. aoMap: !!material.aoMap,
  10687. emissiveMap: !!material.emissiveMap,
  10688. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap),
  10689. bumpMap: !!material.bumpMap,
  10690. normalMap: !!material.normalMap,
  10691. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  10692. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  10693. clearcoatMap: !!material.clearcoatMap,
  10694. clearcoatRoughnessMap: !!material.clearcoatRoughnessMap,
  10695. clearcoatNormalMap: !!material.clearcoatNormalMap,
  10696. displacementMap: !!material.displacementMap,
  10697. roughnessMap: !!material.roughnessMap,
  10698. metalnessMap: !!material.metalnessMap,
  10699. specularMap: !!material.specularMap,
  10700. alphaMap: !!material.alphaMap,
  10701. gradientMap: !!material.gradientMap,
  10702. sheen: !!material.sheen,
  10703. transmissionMap: !!material.transmissionMap,
  10704. combine: material.combine,
  10705. vertexTangents: material.normalMap && material.vertexTangents,
  10706. vertexColors: material.vertexColors,
  10707. vertexAlphas: material.vertexColors === true && object.geometry && object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4,
  10708. 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,
  10709. uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap || !!material.transmissionMap) && !!material.displacementMap,
  10710. fog: !!fog,
  10711. useFog: material.fog,
  10712. fogExp2: fog && fog.isFogExp2,
  10713. flatShading: !!material.flatShading,
  10714. sizeAttenuation: material.sizeAttenuation,
  10715. logarithmicDepthBuffer: logarithmicDepthBuffer,
  10716. skinning: material.skinning && maxBones > 0,
  10717. maxBones: maxBones,
  10718. useVertexTexture: floatVertexTextures,
  10719. morphTargets: material.morphTargets,
  10720. morphNormals: material.morphNormals,
  10721. numDirLights: lights.directional.length,
  10722. numPointLights: lights.point.length,
  10723. numSpotLights: lights.spot.length,
  10724. numRectAreaLights: lights.rectArea.length,
  10725. numHemiLights: lights.hemi.length,
  10726. numDirLightShadows: lights.directionalShadowMap.length,
  10727. numPointLightShadows: lights.pointShadowMap.length,
  10728. numSpotLightShadows: lights.spotShadowMap.length,
  10729. numClippingPlanes: clipping.numPlanes,
  10730. numClipIntersection: clipping.numIntersection,
  10731. dithering: material.dithering,
  10732. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  10733. shadowMapType: renderer.shadowMap.type,
  10734. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  10735. physicallyCorrectLights: renderer.physicallyCorrectLights,
  10736. premultipliedAlpha: material.premultipliedAlpha,
  10737. alphaTest: material.alphaTest,
  10738. doubleSided: material.side === DoubleSide,
  10739. flipSided: material.side === BackSide,
  10740. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false,
  10741. index0AttributeName: material.index0AttributeName,
  10742. extensionDerivatives: material.extensions && material.extensions.derivatives,
  10743. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  10744. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  10745. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  10746. rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
  10747. rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
  10748. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
  10749. customProgramCacheKey: material.customProgramCacheKey()
  10750. };
  10751. return parameters;
  10752. }
  10753. function getProgramCacheKey(parameters) {
  10754. const array = [];
  10755. if (parameters.shaderID) {
  10756. array.push(parameters.shaderID);
  10757. } else {
  10758. array.push(parameters.fragmentShader);
  10759. array.push(parameters.vertexShader);
  10760. }
  10761. if (parameters.defines !== undefined) {
  10762. for (const name in parameters.defines) {
  10763. array.push(name);
  10764. array.push(parameters.defines[name]);
  10765. }
  10766. }
  10767. if (parameters.isRawShaderMaterial === false) {
  10768. for (let i = 0; i < parameterNames.length; i++) {
  10769. array.push(parameters[parameterNames[i]]);
  10770. }
  10771. array.push(renderer.outputEncoding);
  10772. array.push(renderer.gammaFactor);
  10773. }
  10774. array.push(parameters.customProgramCacheKey);
  10775. return array.join();
  10776. }
  10777. function getUniforms(material) {
  10778. const shaderID = shaderIDs[material.type];
  10779. let uniforms;
  10780. if (shaderID) {
  10781. const shader = ShaderLib[shaderID];
  10782. uniforms = UniformsUtils.clone(shader.uniforms);
  10783. } else {
  10784. uniforms = material.uniforms;
  10785. }
  10786. return uniforms;
  10787. }
  10788. function acquireProgram(parameters, cacheKey) {
  10789. let program; // Check if code has been already compiled
  10790. for (let p = 0, pl = programs.length; p < pl; p++) {
  10791. const preexistingProgram = programs[p];
  10792. if (preexistingProgram.cacheKey === cacheKey) {
  10793. program = preexistingProgram;
  10794. ++program.usedTimes;
  10795. break;
  10796. }
  10797. }
  10798. if (program === undefined) {
  10799. program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
  10800. programs.push(program);
  10801. }
  10802. return program;
  10803. }
  10804. function releaseProgram(program) {
  10805. if (--program.usedTimes === 0) {
  10806. // Remove from unordered set
  10807. const i = programs.indexOf(program);
  10808. programs[i] = programs[programs.length - 1];
  10809. programs.pop(); // Free WebGL resources
  10810. program.destroy();
  10811. }
  10812. }
  10813. return {
  10814. getParameters: getParameters,
  10815. getProgramCacheKey: getProgramCacheKey,
  10816. getUniforms: getUniforms,
  10817. acquireProgram: acquireProgram,
  10818. releaseProgram: releaseProgram,
  10819. // Exposed for resource monitoring & error feedback via renderer.info:
  10820. programs: programs
  10821. };
  10822. }
  10823. function WebGLProperties() {
  10824. let properties = new WeakMap();
  10825. function get(object) {
  10826. let map = properties.get(object);
  10827. if (map === undefined) {
  10828. map = {};
  10829. properties.set(object, map);
  10830. }
  10831. return map;
  10832. }
  10833. function remove(object) {
  10834. properties.delete(object);
  10835. }
  10836. function update(object, key, value) {
  10837. properties.get(object)[key] = value;
  10838. }
  10839. function dispose() {
  10840. properties = new WeakMap();
  10841. }
  10842. return {
  10843. get: get,
  10844. remove: remove,
  10845. update: update,
  10846. dispose: dispose
  10847. };
  10848. }
  10849. function painterSortStable(a, b) {
  10850. if (a.groupOrder !== b.groupOrder) {
  10851. return a.groupOrder - b.groupOrder;
  10852. } else if (a.renderOrder !== b.renderOrder) {
  10853. return a.renderOrder - b.renderOrder;
  10854. } else if (a.program !== b.program) {
  10855. return a.program.id - b.program.id;
  10856. } else if (a.material.id !== b.material.id) {
  10857. return a.material.id - b.material.id;
  10858. } else if (a.z !== b.z) {
  10859. return a.z - b.z;
  10860. } else {
  10861. return a.id - b.id;
  10862. }
  10863. }
  10864. function reversePainterSortStable(a, b) {
  10865. if (a.groupOrder !== b.groupOrder) {
  10866. return a.groupOrder - b.groupOrder;
  10867. } else if (a.renderOrder !== b.renderOrder) {
  10868. return a.renderOrder - b.renderOrder;
  10869. } else if (a.z !== b.z) {
  10870. return b.z - a.z;
  10871. } else {
  10872. return a.id - b.id;
  10873. }
  10874. }
  10875. function WebGLRenderList(properties) {
  10876. const renderItems = [];
  10877. let renderItemsIndex = 0;
  10878. const opaque = [];
  10879. const transparent = [];
  10880. const defaultProgram = {
  10881. id: -1
  10882. };
  10883. function init() {
  10884. renderItemsIndex = 0;
  10885. opaque.length = 0;
  10886. transparent.length = 0;
  10887. }
  10888. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  10889. let renderItem = renderItems[renderItemsIndex];
  10890. const materialProperties = properties.get(material);
  10891. if (renderItem === undefined) {
  10892. renderItem = {
  10893. id: object.id,
  10894. object: object,
  10895. geometry: geometry,
  10896. material: material,
  10897. program: materialProperties.program || defaultProgram,
  10898. groupOrder: groupOrder,
  10899. renderOrder: object.renderOrder,
  10900. z: z,
  10901. group: group
  10902. };
  10903. renderItems[renderItemsIndex] = renderItem;
  10904. } else {
  10905. renderItem.id = object.id;
  10906. renderItem.object = object;
  10907. renderItem.geometry = geometry;
  10908. renderItem.material = material;
  10909. renderItem.program = materialProperties.program || defaultProgram;
  10910. renderItem.groupOrder = groupOrder;
  10911. renderItem.renderOrder = object.renderOrder;
  10912. renderItem.z = z;
  10913. renderItem.group = group;
  10914. }
  10915. renderItemsIndex++;
  10916. return renderItem;
  10917. }
  10918. function push(object, geometry, material, groupOrder, z, group) {
  10919. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  10920. (material.transparent === true ? transparent : opaque).push(renderItem);
  10921. }
  10922. function unshift(object, geometry, material, groupOrder, z, group) {
  10923. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  10924. (material.transparent === true ? transparent : opaque).unshift(renderItem);
  10925. }
  10926. function sort(customOpaqueSort, customTransparentSort) {
  10927. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  10928. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  10929. }
  10930. function finish() {
  10931. // Clear references from inactive renderItems in the list
  10932. for (let i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  10933. const renderItem = renderItems[i];
  10934. if (renderItem.id === null) break;
  10935. renderItem.id = null;
  10936. renderItem.object = null;
  10937. renderItem.geometry = null;
  10938. renderItem.material = null;
  10939. renderItem.program = null;
  10940. renderItem.group = null;
  10941. }
  10942. }
  10943. return {
  10944. opaque: opaque,
  10945. transparent: transparent,
  10946. init: init,
  10947. push: push,
  10948. unshift: unshift,
  10949. finish: finish,
  10950. sort: sort
  10951. };
  10952. }
  10953. function WebGLRenderLists(properties) {
  10954. let lists = new WeakMap();
  10955. function get(scene, renderCallDepth) {
  10956. let list;
  10957. if (lists.has(scene) === false) {
  10958. list = new WebGLRenderList(properties);
  10959. lists.set(scene, [list]);
  10960. } else {
  10961. if (renderCallDepth >= lists.get(scene).length) {
  10962. list = new WebGLRenderList(properties);
  10963. lists.get(scene).push(list);
  10964. } else {
  10965. list = lists.get(scene)[renderCallDepth];
  10966. }
  10967. }
  10968. return list;
  10969. }
  10970. function dispose() {
  10971. lists = new WeakMap();
  10972. }
  10973. return {
  10974. get: get,
  10975. dispose: dispose
  10976. };
  10977. }
  10978. function UniformsCache() {
  10979. const lights = {};
  10980. return {
  10981. get: function (light) {
  10982. if (lights[light.id] !== undefined) {
  10983. return lights[light.id];
  10984. }
  10985. let uniforms;
  10986. switch (light.type) {
  10987. case 'DirectionalLight':
  10988. uniforms = {
  10989. direction: new Vector3(),
  10990. color: new Color()
  10991. };
  10992. break;
  10993. case 'SpotLight':
  10994. uniforms = {
  10995. position: new Vector3(),
  10996. direction: new Vector3(),
  10997. color: new Color(),
  10998. distance: 0,
  10999. coneCos: 0,
  11000. penumbraCos: 0,
  11001. decay: 0
  11002. };
  11003. break;
  11004. case 'PointLight':
  11005. uniforms = {
  11006. position: new Vector3(),
  11007. color: new Color(),
  11008. distance: 0,
  11009. decay: 0
  11010. };
  11011. break;
  11012. case 'HemisphereLight':
  11013. uniforms = {
  11014. direction: new Vector3(),
  11015. skyColor: new Color(),
  11016. groundColor: new Color()
  11017. };
  11018. break;
  11019. case 'RectAreaLight':
  11020. uniforms = {
  11021. color: new Color(),
  11022. position: new Vector3(),
  11023. halfWidth: new Vector3(),
  11024. halfHeight: new Vector3()
  11025. };
  11026. break;
  11027. }
  11028. lights[light.id] = uniforms;
  11029. return uniforms;
  11030. }
  11031. };
  11032. }
  11033. function ShadowUniformsCache() {
  11034. const lights = {};
  11035. return {
  11036. get: function (light) {
  11037. if (lights[light.id] !== undefined) {
  11038. return lights[light.id];
  11039. }
  11040. let uniforms;
  11041. switch (light.type) {
  11042. case 'DirectionalLight':
  11043. uniforms = {
  11044. shadowBias: 0,
  11045. shadowNormalBias: 0,
  11046. shadowRadius: 1,
  11047. shadowMapSize: new Vector2()
  11048. };
  11049. break;
  11050. case 'SpotLight':
  11051. uniforms = {
  11052. shadowBias: 0,
  11053. shadowNormalBias: 0,
  11054. shadowRadius: 1,
  11055. shadowMapSize: new Vector2()
  11056. };
  11057. break;
  11058. case 'PointLight':
  11059. uniforms = {
  11060. shadowBias: 0,
  11061. shadowNormalBias: 0,
  11062. shadowRadius: 1,
  11063. shadowMapSize: new Vector2(),
  11064. shadowCameraNear: 1,
  11065. shadowCameraFar: 1000
  11066. };
  11067. break;
  11068. // TODO (abelnation): set RectAreaLight shadow uniforms
  11069. }
  11070. lights[light.id] = uniforms;
  11071. return uniforms;
  11072. }
  11073. };
  11074. }
  11075. let nextVersion = 0;
  11076. function shadowCastingLightsFirst(lightA, lightB) {
  11077. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  11078. }
  11079. function WebGLLights(extensions, capabilities) {
  11080. const cache = new UniformsCache();
  11081. const shadowCache = ShadowUniformsCache();
  11082. const state = {
  11083. version: 0,
  11084. hash: {
  11085. directionalLength: -1,
  11086. pointLength: -1,
  11087. spotLength: -1,
  11088. rectAreaLength: -1,
  11089. hemiLength: -1,
  11090. numDirectionalShadows: -1,
  11091. numPointShadows: -1,
  11092. numSpotShadows: -1
  11093. },
  11094. ambient: [0, 0, 0],
  11095. probe: [],
  11096. directional: [],
  11097. directionalShadow: [],
  11098. directionalShadowMap: [],
  11099. directionalShadowMatrix: [],
  11100. spot: [],
  11101. spotShadow: [],
  11102. spotShadowMap: [],
  11103. spotShadowMatrix: [],
  11104. rectArea: [],
  11105. rectAreaLTC1: null,
  11106. rectAreaLTC2: null,
  11107. point: [],
  11108. pointShadow: [],
  11109. pointShadowMap: [],
  11110. pointShadowMatrix: [],
  11111. hemi: []
  11112. };
  11113. for (let i = 0; i < 9; i++) state.probe.push(new Vector3());
  11114. const vector3 = new Vector3();
  11115. const matrix4 = new Matrix4();
  11116. const matrix42 = new Matrix4();
  11117. function setup(lights) {
  11118. let r = 0,
  11119. g = 0,
  11120. b = 0;
  11121. for (let i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  11122. let directionalLength = 0;
  11123. let pointLength = 0;
  11124. let spotLength = 0;
  11125. let rectAreaLength = 0;
  11126. let hemiLength = 0;
  11127. let numDirectionalShadows = 0;
  11128. let numPointShadows = 0;
  11129. let numSpotShadows = 0;
  11130. lights.sort(shadowCastingLightsFirst);
  11131. for (let i = 0, l = lights.length; i < l; i++) {
  11132. const light = lights[i];
  11133. const color = light.color;
  11134. const intensity = light.intensity;
  11135. const distance = light.distance;
  11136. const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  11137. if (light.isAmbientLight) {
  11138. r += color.r * intensity;
  11139. g += color.g * intensity;
  11140. b += color.b * intensity;
  11141. } else if (light.isLightProbe) {
  11142. for (let j = 0; j < 9; j++) {
  11143. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  11144. }
  11145. } else if (light.isDirectionalLight) {
  11146. const uniforms = cache.get(light);
  11147. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  11148. if (light.castShadow) {
  11149. const shadow = light.shadow;
  11150. const shadowUniforms = shadowCache.get(light);
  11151. shadowUniforms.shadowBias = shadow.bias;
  11152. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11153. shadowUniforms.shadowRadius = shadow.radius;
  11154. shadowUniforms.shadowMapSize = shadow.mapSize;
  11155. state.directionalShadow[directionalLength] = shadowUniforms;
  11156. state.directionalShadowMap[directionalLength] = shadowMap;
  11157. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  11158. numDirectionalShadows++;
  11159. }
  11160. state.directional[directionalLength] = uniforms;
  11161. directionalLength++;
  11162. } else if (light.isSpotLight) {
  11163. const uniforms = cache.get(light);
  11164. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11165. uniforms.color.copy(color).multiplyScalar(intensity);
  11166. uniforms.distance = distance;
  11167. uniforms.coneCos = Math.cos(light.angle);
  11168. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  11169. uniforms.decay = light.decay;
  11170. if (light.castShadow) {
  11171. const shadow = light.shadow;
  11172. const shadowUniforms = shadowCache.get(light);
  11173. shadowUniforms.shadowBias = shadow.bias;
  11174. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11175. shadowUniforms.shadowRadius = shadow.radius;
  11176. shadowUniforms.shadowMapSize = shadow.mapSize;
  11177. state.spotShadow[spotLength] = shadowUniforms;
  11178. state.spotShadowMap[spotLength] = shadowMap;
  11179. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  11180. numSpotShadows++;
  11181. }
  11182. state.spot[spotLength] = uniforms;
  11183. spotLength++;
  11184. } else if (light.isRectAreaLight) {
  11185. const uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  11186. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  11187. // (b) intensity is the brightness of the light
  11188. uniforms.color.copy(color).multiplyScalar(intensity);
  11189. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  11190. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  11191. state.rectArea[rectAreaLength] = uniforms;
  11192. rectAreaLength++;
  11193. } else if (light.isPointLight) {
  11194. const uniforms = cache.get(light);
  11195. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  11196. uniforms.distance = light.distance;
  11197. uniforms.decay = light.decay;
  11198. if (light.castShadow) {
  11199. const shadow = light.shadow;
  11200. const shadowUniforms = shadowCache.get(light);
  11201. shadowUniforms.shadowBias = shadow.bias;
  11202. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11203. shadowUniforms.shadowRadius = shadow.radius;
  11204. shadowUniforms.shadowMapSize = shadow.mapSize;
  11205. shadowUniforms.shadowCameraNear = shadow.camera.near;
  11206. shadowUniforms.shadowCameraFar = shadow.camera.far;
  11207. state.pointShadow[pointLength] = shadowUniforms;
  11208. state.pointShadowMap[pointLength] = shadowMap;
  11209. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  11210. numPointShadows++;
  11211. }
  11212. state.point[pointLength] = uniforms;
  11213. pointLength++;
  11214. } else if (light.isHemisphereLight) {
  11215. const uniforms = cache.get(light);
  11216. uniforms.skyColor.copy(light.color).multiplyScalar(intensity);
  11217. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity);
  11218. state.hemi[hemiLength] = uniforms;
  11219. hemiLength++;
  11220. }
  11221. }
  11222. if (rectAreaLength > 0) {
  11223. if (capabilities.isWebGL2) {
  11224. // WebGL 2
  11225. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11226. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11227. } else {
  11228. // WebGL 1
  11229. if (extensions.has('OES_texture_float_linear') === true) {
  11230. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11231. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11232. } else if (extensions.has('OES_texture_half_float_linear') === true) {
  11233. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  11234. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  11235. } else {
  11236. console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
  11237. }
  11238. }
  11239. }
  11240. state.ambient[0] = r;
  11241. state.ambient[1] = g;
  11242. state.ambient[2] = b;
  11243. const hash = state.hash;
  11244. 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) {
  11245. state.directional.length = directionalLength;
  11246. state.spot.length = spotLength;
  11247. state.rectArea.length = rectAreaLength;
  11248. state.point.length = pointLength;
  11249. state.hemi.length = hemiLength;
  11250. state.directionalShadow.length = numDirectionalShadows;
  11251. state.directionalShadowMap.length = numDirectionalShadows;
  11252. state.pointShadow.length = numPointShadows;
  11253. state.pointShadowMap.length = numPointShadows;
  11254. state.spotShadow.length = numSpotShadows;
  11255. state.spotShadowMap.length = numSpotShadows;
  11256. state.directionalShadowMatrix.length = numDirectionalShadows;
  11257. state.pointShadowMatrix.length = numPointShadows;
  11258. state.spotShadowMatrix.length = numSpotShadows;
  11259. hash.directionalLength = directionalLength;
  11260. hash.pointLength = pointLength;
  11261. hash.spotLength = spotLength;
  11262. hash.rectAreaLength = rectAreaLength;
  11263. hash.hemiLength = hemiLength;
  11264. hash.numDirectionalShadows = numDirectionalShadows;
  11265. hash.numPointShadows = numPointShadows;
  11266. hash.numSpotShadows = numSpotShadows;
  11267. state.version = nextVersion++;
  11268. }
  11269. }
  11270. function setupView(lights, camera) {
  11271. let directionalLength = 0;
  11272. let pointLength = 0;
  11273. let spotLength = 0;
  11274. let rectAreaLength = 0;
  11275. let hemiLength = 0;
  11276. const viewMatrix = camera.matrixWorldInverse;
  11277. for (let i = 0, l = lights.length; i < l; i++) {
  11278. const light = lights[i];
  11279. if (light.isDirectionalLight) {
  11280. const uniforms = state.directional[directionalLength];
  11281. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11282. vector3.setFromMatrixPosition(light.target.matrixWorld);
  11283. uniforms.direction.sub(vector3);
  11284. uniforms.direction.transformDirection(viewMatrix);
  11285. directionalLength++;
  11286. } else if (light.isSpotLight) {
  11287. const uniforms = state.spot[spotLength];
  11288. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11289. uniforms.position.applyMatrix4(viewMatrix);
  11290. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11291. vector3.setFromMatrixPosition(light.target.matrixWorld);
  11292. uniforms.direction.sub(vector3);
  11293. uniforms.direction.transformDirection(viewMatrix);
  11294. spotLength++;
  11295. } else if (light.isRectAreaLight) {
  11296. const uniforms = state.rectArea[rectAreaLength];
  11297. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11298. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  11299. matrix42.identity();
  11300. matrix4.copy(light.matrixWorld);
  11301. matrix4.premultiply(viewMatrix);
  11302. matrix42.extractRotation(matrix4);
  11303. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  11304. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  11305. uniforms.halfWidth.applyMatrix4(matrix42);
  11306. uniforms.halfHeight.applyMatrix4(matrix42);
  11307. rectAreaLength++;
  11308. } else if (light.isPointLight) {
  11309. const uniforms = state.point[pointLength];
  11310. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11311. uniforms.position.applyMatrix4(viewMatrix);
  11312. pointLength++;
  11313. } else if (light.isHemisphereLight) {
  11314. const uniforms = state.hemi[hemiLength];
  11315. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11316. uniforms.direction.transformDirection(viewMatrix);
  11317. uniforms.direction.normalize();
  11318. hemiLength++;
  11319. }
  11320. }
  11321. }
  11322. return {
  11323. setup: setup,
  11324. setupView: setupView,
  11325. state: state
  11326. };
  11327. }
  11328. function WebGLRenderState(extensions, capabilities) {
  11329. const lights = new WebGLLights(extensions, capabilities);
  11330. const lightsArray = [];
  11331. const shadowsArray = [];
  11332. function init() {
  11333. lightsArray.length = 0;
  11334. shadowsArray.length = 0;
  11335. }
  11336. function pushLight(light) {
  11337. lightsArray.push(light);
  11338. }
  11339. function pushShadow(shadowLight) {
  11340. shadowsArray.push(shadowLight);
  11341. }
  11342. function setupLights() {
  11343. lights.setup(lightsArray);
  11344. }
  11345. function setupLightsView(camera) {
  11346. lights.setupView(lightsArray, camera);
  11347. }
  11348. const state = {
  11349. lightsArray: lightsArray,
  11350. shadowsArray: shadowsArray,
  11351. lights: lights
  11352. };
  11353. return {
  11354. init: init,
  11355. state: state,
  11356. setupLights: setupLights,
  11357. setupLightsView: setupLightsView,
  11358. pushLight: pushLight,
  11359. pushShadow: pushShadow
  11360. };
  11361. }
  11362. function WebGLRenderStates(extensions, capabilities) {
  11363. let renderStates = new WeakMap();
  11364. function get(scene, renderCallDepth = 0) {
  11365. let renderState;
  11366. if (renderStates.has(scene) === false) {
  11367. renderState = new WebGLRenderState(extensions, capabilities);
  11368. renderStates.set(scene, [renderState]);
  11369. } else {
  11370. if (renderCallDepth >= renderStates.get(scene).length) {
  11371. renderState = new WebGLRenderState(extensions, capabilities);
  11372. renderStates.get(scene).push(renderState);
  11373. } else {
  11374. renderState = renderStates.get(scene)[renderCallDepth];
  11375. }
  11376. }
  11377. return renderState;
  11378. }
  11379. function dispose() {
  11380. renderStates = new WeakMap();
  11381. }
  11382. return {
  11383. get: get,
  11384. dispose: dispose
  11385. };
  11386. }
  11387. /**
  11388. * parameters = {
  11389. *
  11390. * opacity: <float>,
  11391. *
  11392. * map: new THREE.Texture( <Image> ),
  11393. *
  11394. * alphaMap: new THREE.Texture( <Image> ),
  11395. *
  11396. * displacementMap: new THREE.Texture( <Image> ),
  11397. * displacementScale: <float>,
  11398. * displacementBias: <float>,
  11399. *
  11400. * wireframe: <boolean>,
  11401. * wireframeLinewidth: <float>
  11402. * }
  11403. */
  11404. class MeshDepthMaterial extends Material {
  11405. constructor(parameters) {
  11406. super();
  11407. this.type = 'MeshDepthMaterial';
  11408. this.depthPacking = BasicDepthPacking;
  11409. this.skinning = false;
  11410. this.morphTargets = false;
  11411. this.map = null;
  11412. this.alphaMap = null;
  11413. this.displacementMap = null;
  11414. this.displacementScale = 1;
  11415. this.displacementBias = 0;
  11416. this.wireframe = false;
  11417. this.wireframeLinewidth = 1;
  11418. this.fog = false;
  11419. this.setValues(parameters);
  11420. }
  11421. copy(source) {
  11422. super.copy(source);
  11423. this.depthPacking = source.depthPacking;
  11424. this.skinning = source.skinning;
  11425. this.morphTargets = source.morphTargets;
  11426. this.map = source.map;
  11427. this.alphaMap = source.alphaMap;
  11428. this.displacementMap = source.displacementMap;
  11429. this.displacementScale = source.displacementScale;
  11430. this.displacementBias = source.displacementBias;
  11431. this.wireframe = source.wireframe;
  11432. this.wireframeLinewidth = source.wireframeLinewidth;
  11433. return this;
  11434. }
  11435. }
  11436. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  11437. /**
  11438. * parameters = {
  11439. *
  11440. * referencePosition: <float>,
  11441. * nearDistance: <float>,
  11442. * farDistance: <float>,
  11443. *
  11444. * skinning: <bool>,
  11445. * morphTargets: <bool>,
  11446. *
  11447. * map: new THREE.Texture( <Image> ),
  11448. *
  11449. * alphaMap: new THREE.Texture( <Image> ),
  11450. *
  11451. * displacementMap: new THREE.Texture( <Image> ),
  11452. * displacementScale: <float>,
  11453. * displacementBias: <float>
  11454. *
  11455. * }
  11456. */
  11457. class MeshDistanceMaterial extends Material {
  11458. constructor(parameters) {
  11459. super();
  11460. this.type = 'MeshDistanceMaterial';
  11461. this.referencePosition = new Vector3();
  11462. this.nearDistance = 1;
  11463. this.farDistance = 1000;
  11464. this.skinning = false;
  11465. this.morphTargets = false;
  11466. this.map = null;
  11467. this.alphaMap = null;
  11468. this.displacementMap = null;
  11469. this.displacementScale = 1;
  11470. this.displacementBias = 0;
  11471. this.fog = false;
  11472. this.setValues(parameters);
  11473. }
  11474. copy(source) {
  11475. super.copy(source);
  11476. this.referencePosition.copy(source.referencePosition);
  11477. this.nearDistance = source.nearDistance;
  11478. this.farDistance = source.farDistance;
  11479. this.skinning = source.skinning;
  11480. this.morphTargets = source.morphTargets;
  11481. this.map = source.map;
  11482. this.alphaMap = source.alphaMap;
  11483. this.displacementMap = source.displacementMap;
  11484. this.displacementScale = source.displacementScale;
  11485. this.displacementBias = source.displacementBias;
  11486. return this;
  11487. }
  11488. }
  11489. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  11490. var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n\tfor ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 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, i ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean * HALF_SAMPLE_RATE;\n\tsquared_mean = squared_mean * HALF_SAMPLE_RATE;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  11491. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  11492. function WebGLShadowMap(_renderer, _objects, _capabilities) {
  11493. let _frustum = new Frustum();
  11494. const _shadowMapSize = new Vector2(),
  11495. _viewportSize = new Vector2(),
  11496. _viewport = new Vector4(),
  11497. _depthMaterials = [],
  11498. _distanceMaterials = [],
  11499. _materialCache = {},
  11500. _maxTextureSize = _capabilities.maxTextureSize;
  11501. const shadowSide = {
  11502. 0: BackSide,
  11503. 1: FrontSide,
  11504. 2: DoubleSide
  11505. };
  11506. const shadowMaterialVertical = new ShaderMaterial({
  11507. defines: {
  11508. SAMPLE_RATE: 2.0 / 8.0,
  11509. HALF_SAMPLE_RATE: 1.0 / 8.0
  11510. },
  11511. uniforms: {
  11512. shadow_pass: {
  11513. value: null
  11514. },
  11515. resolution: {
  11516. value: new Vector2()
  11517. },
  11518. radius: {
  11519. value: 4.0
  11520. }
  11521. },
  11522. vertexShader: vsm_vert,
  11523. fragmentShader: vsm_frag
  11524. });
  11525. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  11526. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  11527. const fullScreenTri = new BufferGeometry();
  11528. fullScreenTri.setAttribute('position', new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  11529. const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  11530. const scope = this;
  11531. this.enabled = false;
  11532. this.autoUpdate = true;
  11533. this.needsUpdate = false;
  11534. this.type = PCFShadowMap;
  11535. this.render = function (lights, scene, camera) {
  11536. if (scope.enabled === false) return;
  11537. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  11538. if (lights.length === 0) return;
  11539. const currentRenderTarget = _renderer.getRenderTarget();
  11540. const activeCubeFace = _renderer.getActiveCubeFace();
  11541. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  11542. const _state = _renderer.state; // Set GL state for depth map.
  11543. _state.setBlending(NoBlending);
  11544. _state.buffers.color.setClear(1, 1, 1, 1);
  11545. _state.buffers.depth.setTest(true);
  11546. _state.setScissorTest(false); // render depth map
  11547. for (let i = 0, il = lights.length; i < il; i++) {
  11548. const light = lights[i];
  11549. const shadow = light.shadow;
  11550. if (shadow === undefined) {
  11551. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  11552. continue;
  11553. }
  11554. if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
  11555. _shadowMapSize.copy(shadow.mapSize);
  11556. const shadowFrameExtents = shadow.getFrameExtents();
  11557. _shadowMapSize.multiply(shadowFrameExtents);
  11558. _viewportSize.copy(shadow.mapSize);
  11559. if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) {
  11560. if (_shadowMapSize.x > _maxTextureSize) {
  11561. _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x);
  11562. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  11563. shadow.mapSize.x = _viewportSize.x;
  11564. }
  11565. if (_shadowMapSize.y > _maxTextureSize) {
  11566. _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y);
  11567. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  11568. shadow.mapSize.y = _viewportSize.y;
  11569. }
  11570. }
  11571. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  11572. const pars = {
  11573. minFilter: LinearFilter,
  11574. magFilter: LinearFilter,
  11575. format: RGBAFormat
  11576. };
  11577. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  11578. shadow.map.texture.name = light.name + '.shadowMap';
  11579. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  11580. shadow.camera.updateProjectionMatrix();
  11581. }
  11582. if (shadow.map === null) {
  11583. const pars = {
  11584. minFilter: NearestFilter,
  11585. magFilter: NearestFilter,
  11586. format: RGBAFormat
  11587. };
  11588. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  11589. shadow.map.texture.name = light.name + '.shadowMap';
  11590. shadow.camera.updateProjectionMatrix();
  11591. }
  11592. _renderer.setRenderTarget(shadow.map);
  11593. _renderer.clear();
  11594. const viewportCount = shadow.getViewportCount();
  11595. for (let vp = 0; vp < viewportCount; vp++) {
  11596. const viewport = shadow.getViewport(vp);
  11597. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  11598. _state.viewport(_viewport);
  11599. shadow.updateMatrices(light, vp);
  11600. _frustum = shadow.getFrustum();
  11601. renderObject(scene, camera, shadow.camera, light, this.type);
  11602. } // do blur pass for VSM
  11603. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  11604. VSMPass(shadow, camera);
  11605. }
  11606. shadow.needsUpdate = false;
  11607. }
  11608. scope.needsUpdate = false;
  11609. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  11610. };
  11611. function VSMPass(shadow, camera) {
  11612. const geometry = _objects.update(fullScreenMesh); // vertical pass
  11613. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  11614. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  11615. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  11616. _renderer.setRenderTarget(shadow.mapPass);
  11617. _renderer.clear();
  11618. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizontal pass
  11619. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  11620. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  11621. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  11622. _renderer.setRenderTarget(shadow.map);
  11623. _renderer.clear();
  11624. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null);
  11625. }
  11626. function getDepthMaterialVariant(useMorphing, useSkinning, useInstancing) {
  11627. const index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  11628. let material = _depthMaterials[index];
  11629. if (material === undefined) {
  11630. material = new MeshDepthMaterial({
  11631. depthPacking: RGBADepthPacking,
  11632. morphTargets: useMorphing,
  11633. skinning: useSkinning
  11634. });
  11635. _depthMaterials[index] = material;
  11636. }
  11637. return material;
  11638. }
  11639. function getDistanceMaterialVariant(useMorphing, useSkinning, useInstancing) {
  11640. const index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  11641. let material = _distanceMaterials[index];
  11642. if (material === undefined) {
  11643. material = new MeshDistanceMaterial({
  11644. morphTargets: useMorphing,
  11645. skinning: useSkinning
  11646. });
  11647. _distanceMaterials[index] = material;
  11648. }
  11649. return material;
  11650. }
  11651. function getDepthMaterial(object, geometry, material, light, shadowCameraNear, shadowCameraFar, type) {
  11652. let result = null;
  11653. let getMaterialVariant = getDepthMaterialVariant;
  11654. let customMaterial = object.customDepthMaterial;
  11655. if (light.isPointLight === true) {
  11656. getMaterialVariant = getDistanceMaterialVariant;
  11657. customMaterial = object.customDistanceMaterial;
  11658. }
  11659. if (customMaterial === undefined) {
  11660. let useMorphing = false;
  11661. if (material.morphTargets === true) {
  11662. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  11663. }
  11664. let useSkinning = false;
  11665. if (object.isSkinnedMesh === true) {
  11666. if (material.skinning === true) {
  11667. useSkinning = true;
  11668. } else {
  11669. console.warn('THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object);
  11670. }
  11671. }
  11672. const useInstancing = object.isInstancedMesh === true;
  11673. result = getMaterialVariant(useMorphing, useSkinning, useInstancing);
  11674. } else {
  11675. result = customMaterial;
  11676. }
  11677. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0) {
  11678. // in this case we need a unique material instance reflecting the
  11679. // appropriate state
  11680. const keyA = result.uuid,
  11681. keyB = material.uuid;
  11682. let materialsForVariant = _materialCache[keyA];
  11683. if (materialsForVariant === undefined) {
  11684. materialsForVariant = {};
  11685. _materialCache[keyA] = materialsForVariant;
  11686. }
  11687. let cachedMaterial = materialsForVariant[keyB];
  11688. if (cachedMaterial === undefined) {
  11689. cachedMaterial = result.clone();
  11690. materialsForVariant[keyB] = cachedMaterial;
  11691. }
  11692. result = cachedMaterial;
  11693. }
  11694. result.visible = material.visible;
  11695. result.wireframe = material.wireframe;
  11696. if (type === VSMShadowMap) {
  11697. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  11698. } else {
  11699. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  11700. }
  11701. result.clipShadows = material.clipShadows;
  11702. result.clippingPlanes = material.clippingPlanes;
  11703. result.clipIntersection = material.clipIntersection;
  11704. result.wireframeLinewidth = material.wireframeLinewidth;
  11705. result.linewidth = material.linewidth;
  11706. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  11707. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  11708. result.nearDistance = shadowCameraNear;
  11709. result.farDistance = shadowCameraFar;
  11710. }
  11711. return result;
  11712. }
  11713. function renderObject(object, camera, shadowCamera, light, type) {
  11714. if (object.visible === false) return;
  11715. const visible = object.layers.test(camera.layers);
  11716. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  11717. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  11718. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  11719. const geometry = _objects.update(object);
  11720. const material = object.material;
  11721. if (Array.isArray(material)) {
  11722. const groups = geometry.groups;
  11723. for (let k = 0, kl = groups.length; k < kl; k++) {
  11724. const group = groups[k];
  11725. const groupMaterial = material[group.materialIndex];
  11726. if (groupMaterial && groupMaterial.visible) {
  11727. const depthMaterial = getDepthMaterial(object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  11728. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  11729. }
  11730. }
  11731. } else if (material.visible) {
  11732. const depthMaterial = getDepthMaterial(object, geometry, material, light, shadowCamera.near, shadowCamera.far, type);
  11733. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  11734. }
  11735. }
  11736. }
  11737. const children = object.children;
  11738. for (let i = 0, l = children.length; i < l; i++) {
  11739. renderObject(children[i], camera, shadowCamera, light, type);
  11740. }
  11741. }
  11742. }
  11743. function WebGLState(gl, extensions, capabilities) {
  11744. const isWebGL2 = capabilities.isWebGL2;
  11745. function ColorBuffer() {
  11746. let locked = false;
  11747. const color = new Vector4();
  11748. let currentColorMask = null;
  11749. const currentColorClear = new Vector4(0, 0, 0, 0);
  11750. return {
  11751. setMask: function (colorMask) {
  11752. if (currentColorMask !== colorMask && !locked) {
  11753. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  11754. currentColorMask = colorMask;
  11755. }
  11756. },
  11757. setLocked: function (lock) {
  11758. locked = lock;
  11759. },
  11760. setClear: function (r, g, b, a, premultipliedAlpha) {
  11761. if (premultipliedAlpha === true) {
  11762. r *= a;
  11763. g *= a;
  11764. b *= a;
  11765. }
  11766. color.set(r, g, b, a);
  11767. if (currentColorClear.equals(color) === false) {
  11768. gl.clearColor(r, g, b, a);
  11769. currentColorClear.copy(color);
  11770. }
  11771. },
  11772. reset: function () {
  11773. locked = false;
  11774. currentColorMask = null;
  11775. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  11776. }
  11777. };
  11778. }
  11779. function DepthBuffer() {
  11780. let locked = false;
  11781. let currentDepthMask = null;
  11782. let currentDepthFunc = null;
  11783. let currentDepthClear = null;
  11784. return {
  11785. setTest: function (depthTest) {
  11786. if (depthTest) {
  11787. enable(gl.DEPTH_TEST);
  11788. } else {
  11789. disable(gl.DEPTH_TEST);
  11790. }
  11791. },
  11792. setMask: function (depthMask) {
  11793. if (currentDepthMask !== depthMask && !locked) {
  11794. gl.depthMask(depthMask);
  11795. currentDepthMask = depthMask;
  11796. }
  11797. },
  11798. setFunc: function (depthFunc) {
  11799. if (currentDepthFunc !== depthFunc) {
  11800. if (depthFunc) {
  11801. switch (depthFunc) {
  11802. case NeverDepth:
  11803. gl.depthFunc(gl.NEVER);
  11804. break;
  11805. case AlwaysDepth:
  11806. gl.depthFunc(gl.ALWAYS);
  11807. break;
  11808. case LessDepth:
  11809. gl.depthFunc(gl.LESS);
  11810. break;
  11811. case LessEqualDepth:
  11812. gl.depthFunc(gl.LEQUAL);
  11813. break;
  11814. case EqualDepth:
  11815. gl.depthFunc(gl.EQUAL);
  11816. break;
  11817. case GreaterEqualDepth:
  11818. gl.depthFunc(gl.GEQUAL);
  11819. break;
  11820. case GreaterDepth:
  11821. gl.depthFunc(gl.GREATER);
  11822. break;
  11823. case NotEqualDepth:
  11824. gl.depthFunc(gl.NOTEQUAL);
  11825. break;
  11826. default:
  11827. gl.depthFunc(gl.LEQUAL);
  11828. }
  11829. } else {
  11830. gl.depthFunc(gl.LEQUAL);
  11831. }
  11832. currentDepthFunc = depthFunc;
  11833. }
  11834. },
  11835. setLocked: function (lock) {
  11836. locked = lock;
  11837. },
  11838. setClear: function (depth) {
  11839. if (currentDepthClear !== depth) {
  11840. gl.clearDepth(depth);
  11841. currentDepthClear = depth;
  11842. }
  11843. },
  11844. reset: function () {
  11845. locked = false;
  11846. currentDepthMask = null;
  11847. currentDepthFunc = null;
  11848. currentDepthClear = null;
  11849. }
  11850. };
  11851. }
  11852. function StencilBuffer() {
  11853. let locked = false;
  11854. let currentStencilMask = null;
  11855. let currentStencilFunc = null;
  11856. let currentStencilRef = null;
  11857. let currentStencilFuncMask = null;
  11858. let currentStencilFail = null;
  11859. let currentStencilZFail = null;
  11860. let currentStencilZPass = null;
  11861. let currentStencilClear = null;
  11862. return {
  11863. setTest: function (stencilTest) {
  11864. if (!locked) {
  11865. if (stencilTest) {
  11866. enable(gl.STENCIL_TEST);
  11867. } else {
  11868. disable(gl.STENCIL_TEST);
  11869. }
  11870. }
  11871. },
  11872. setMask: function (stencilMask) {
  11873. if (currentStencilMask !== stencilMask && !locked) {
  11874. gl.stencilMask(stencilMask);
  11875. currentStencilMask = stencilMask;
  11876. }
  11877. },
  11878. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  11879. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  11880. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  11881. currentStencilFunc = stencilFunc;
  11882. currentStencilRef = stencilRef;
  11883. currentStencilFuncMask = stencilMask;
  11884. }
  11885. },
  11886. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  11887. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  11888. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  11889. currentStencilFail = stencilFail;
  11890. currentStencilZFail = stencilZFail;
  11891. currentStencilZPass = stencilZPass;
  11892. }
  11893. },
  11894. setLocked: function (lock) {
  11895. locked = lock;
  11896. },
  11897. setClear: function (stencil) {
  11898. if (currentStencilClear !== stencil) {
  11899. gl.clearStencil(stencil);
  11900. currentStencilClear = stencil;
  11901. }
  11902. },
  11903. reset: function () {
  11904. locked = false;
  11905. currentStencilMask = null;
  11906. currentStencilFunc = null;
  11907. currentStencilRef = null;
  11908. currentStencilFuncMask = null;
  11909. currentStencilFail = null;
  11910. currentStencilZFail = null;
  11911. currentStencilZPass = null;
  11912. currentStencilClear = null;
  11913. }
  11914. };
  11915. } //
  11916. const colorBuffer = new ColorBuffer();
  11917. const depthBuffer = new DepthBuffer();
  11918. const stencilBuffer = new StencilBuffer();
  11919. let enabledCapabilities = {};
  11920. let xrFramebuffer = null;
  11921. let currentBoundFramebuffers = {};
  11922. let currentProgram = null;
  11923. let currentBlendingEnabled = false;
  11924. let currentBlending = null;
  11925. let currentBlendEquation = null;
  11926. let currentBlendSrc = null;
  11927. let currentBlendDst = null;
  11928. let currentBlendEquationAlpha = null;
  11929. let currentBlendSrcAlpha = null;
  11930. let currentBlendDstAlpha = null;
  11931. let currentPremultipledAlpha = false;
  11932. let currentFlipSided = null;
  11933. let currentCullFace = null;
  11934. let currentLineWidth = null;
  11935. let currentPolygonOffsetFactor = null;
  11936. let currentPolygonOffsetUnits = null;
  11937. const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11938. let lineWidthAvailable = false;
  11939. let version = 0;
  11940. const glVersion = gl.getParameter(gl.VERSION);
  11941. if (glVersion.indexOf('WebGL') !== -1) {
  11942. version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]);
  11943. lineWidthAvailable = version >= 1.0;
  11944. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  11945. version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);
  11946. lineWidthAvailable = version >= 2.0;
  11947. }
  11948. let currentTextureSlot = null;
  11949. let currentBoundTextures = {};
  11950. const currentScissor = new Vector4(0, 0, gl.canvas.width, gl.canvas.height);
  11951. const currentViewport = new Vector4(0, 0, gl.canvas.width, gl.canvas.height);
  11952. function createTexture(type, target, count) {
  11953. const data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  11954. const texture = gl.createTexture();
  11955. gl.bindTexture(type, texture);
  11956. gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11957. gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11958. for (let i = 0; i < count; i++) {
  11959. gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
  11960. }
  11961. return texture;
  11962. }
  11963. const emptyTextures = {};
  11964. emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1);
  11965. emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); // init
  11966. colorBuffer.setClear(0, 0, 0, 1);
  11967. depthBuffer.setClear(1);
  11968. stencilBuffer.setClear(0);
  11969. enable(gl.DEPTH_TEST);
  11970. depthBuffer.setFunc(LessEqualDepth);
  11971. setFlipSided(false);
  11972. setCullFace(CullFaceBack);
  11973. enable(gl.CULL_FACE);
  11974. setBlending(NoBlending); //
  11975. function enable(id) {
  11976. if (enabledCapabilities[id] !== true) {
  11977. gl.enable(id);
  11978. enabledCapabilities[id] = true;
  11979. }
  11980. }
  11981. function disable(id) {
  11982. if (enabledCapabilities[id] !== false) {
  11983. gl.disable(id);
  11984. enabledCapabilities[id] = false;
  11985. }
  11986. }
  11987. function bindXRFramebuffer(framebuffer) {
  11988. if (framebuffer !== xrFramebuffer) {
  11989. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  11990. xrFramebuffer = framebuffer;
  11991. }
  11992. }
  11993. function bindFramebuffer(target, framebuffer) {
  11994. if (framebuffer === null && xrFramebuffer !== null) framebuffer = xrFramebuffer; // use active XR framebuffer if available
  11995. if (currentBoundFramebuffers[target] !== framebuffer) {
  11996. gl.bindFramebuffer(target, framebuffer);
  11997. currentBoundFramebuffers[target] = framebuffer;
  11998. if (isWebGL2) {
  11999. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  12000. if (target === gl.DRAW_FRAMEBUFFER) {
  12001. currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer;
  12002. }
  12003. if (target === gl.FRAMEBUFFER) {
  12004. currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer;
  12005. }
  12006. }
  12007. }
  12008. }
  12009. function useProgram(program) {
  12010. if (currentProgram !== program) {
  12011. gl.useProgram(program);
  12012. currentProgram = program;
  12013. return true;
  12014. }
  12015. return false;
  12016. }
  12017. const equationToGL = {
  12018. [AddEquation]: gl.FUNC_ADD,
  12019. [SubtractEquation]: gl.FUNC_SUBTRACT,
  12020. [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT
  12021. };
  12022. if (isWebGL2) {
  12023. equationToGL[MinEquation] = gl.MIN;
  12024. equationToGL[MaxEquation] = gl.MAX;
  12025. } else {
  12026. const extension = extensions.get('EXT_blend_minmax');
  12027. if (extension !== null) {
  12028. equationToGL[MinEquation] = extension.MIN_EXT;
  12029. equationToGL[MaxEquation] = extension.MAX_EXT;
  12030. }
  12031. }
  12032. const factorToGL = {
  12033. [ZeroFactor]: gl.ZERO,
  12034. [OneFactor]: gl.ONE,
  12035. [SrcColorFactor]: gl.SRC_COLOR,
  12036. [SrcAlphaFactor]: gl.SRC_ALPHA,
  12037. [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE,
  12038. [DstColorFactor]: gl.DST_COLOR,
  12039. [DstAlphaFactor]: gl.DST_ALPHA,
  12040. [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR,
  12041. [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA,
  12042. [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR,
  12043. [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA
  12044. };
  12045. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  12046. if (blending === NoBlending) {
  12047. if (currentBlendingEnabled === true) {
  12048. disable(gl.BLEND);
  12049. currentBlendingEnabled = false;
  12050. }
  12051. return;
  12052. }
  12053. if (currentBlendingEnabled === false) {
  12054. enable(gl.BLEND);
  12055. currentBlendingEnabled = true;
  12056. }
  12057. if (blending !== CustomBlending) {
  12058. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  12059. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  12060. gl.blendEquation(gl.FUNC_ADD);
  12061. currentBlendEquation = AddEquation;
  12062. currentBlendEquationAlpha = AddEquation;
  12063. }
  12064. if (premultipliedAlpha) {
  12065. switch (blending) {
  12066. case NormalBlending:
  12067. gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  12068. break;
  12069. case AdditiveBlending:
  12070. gl.blendFunc(gl.ONE, gl.ONE);
  12071. break;
  12072. case SubtractiveBlending:
  12073. gl.blendFuncSeparate(gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA);
  12074. break;
  12075. case MultiplyBlending:
  12076. gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA);
  12077. break;
  12078. default:
  12079. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12080. break;
  12081. }
  12082. } else {
  12083. switch (blending) {
  12084. case NormalBlending:
  12085. gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  12086. break;
  12087. case AdditiveBlending:
  12088. gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  12089. break;
  12090. case SubtractiveBlending:
  12091. gl.blendFunc(gl.ZERO, gl.ONE_MINUS_SRC_COLOR);
  12092. break;
  12093. case MultiplyBlending:
  12094. gl.blendFunc(gl.ZERO, gl.SRC_COLOR);
  12095. break;
  12096. default:
  12097. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12098. break;
  12099. }
  12100. }
  12101. currentBlendSrc = null;
  12102. currentBlendDst = null;
  12103. currentBlendSrcAlpha = null;
  12104. currentBlendDstAlpha = null;
  12105. currentBlending = blending;
  12106. currentPremultipledAlpha = premultipliedAlpha;
  12107. }
  12108. return;
  12109. } // custom blending
  12110. blendEquationAlpha = blendEquationAlpha || blendEquation;
  12111. blendSrcAlpha = blendSrcAlpha || blendSrc;
  12112. blendDstAlpha = blendDstAlpha || blendDst;
  12113. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  12114. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  12115. currentBlendEquation = blendEquation;
  12116. currentBlendEquationAlpha = blendEquationAlpha;
  12117. }
  12118. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  12119. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  12120. currentBlendSrc = blendSrc;
  12121. currentBlendDst = blendDst;
  12122. currentBlendSrcAlpha = blendSrcAlpha;
  12123. currentBlendDstAlpha = blendDstAlpha;
  12124. }
  12125. currentBlending = blending;
  12126. currentPremultipledAlpha = null;
  12127. }
  12128. function setMaterial(material, frontFaceCW) {
  12129. material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE);
  12130. let flipSided = material.side === BackSide;
  12131. if (frontFaceCW) flipSided = !flipSided;
  12132. setFlipSided(flipSided);
  12133. 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);
  12134. depthBuffer.setFunc(material.depthFunc);
  12135. depthBuffer.setTest(material.depthTest);
  12136. depthBuffer.setMask(material.depthWrite);
  12137. colorBuffer.setMask(material.colorWrite);
  12138. const stencilWrite = material.stencilWrite;
  12139. stencilBuffer.setTest(stencilWrite);
  12140. if (stencilWrite) {
  12141. stencilBuffer.setMask(material.stencilWriteMask);
  12142. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  12143. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  12144. }
  12145. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  12146. material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  12147. } //
  12148. function setFlipSided(flipSided) {
  12149. if (currentFlipSided !== flipSided) {
  12150. if (flipSided) {
  12151. gl.frontFace(gl.CW);
  12152. } else {
  12153. gl.frontFace(gl.CCW);
  12154. }
  12155. currentFlipSided = flipSided;
  12156. }
  12157. }
  12158. function setCullFace(cullFace) {
  12159. if (cullFace !== CullFaceNone) {
  12160. enable(gl.CULL_FACE);
  12161. if (cullFace !== currentCullFace) {
  12162. if (cullFace === CullFaceBack) {
  12163. gl.cullFace(gl.BACK);
  12164. } else if (cullFace === CullFaceFront) {
  12165. gl.cullFace(gl.FRONT);
  12166. } else {
  12167. gl.cullFace(gl.FRONT_AND_BACK);
  12168. }
  12169. }
  12170. } else {
  12171. disable(gl.CULL_FACE);
  12172. }
  12173. currentCullFace = cullFace;
  12174. }
  12175. function setLineWidth(width) {
  12176. if (width !== currentLineWidth) {
  12177. if (lineWidthAvailable) gl.lineWidth(width);
  12178. currentLineWidth = width;
  12179. }
  12180. }
  12181. function setPolygonOffset(polygonOffset, factor, units) {
  12182. if (polygonOffset) {
  12183. enable(gl.POLYGON_OFFSET_FILL);
  12184. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  12185. gl.polygonOffset(factor, units);
  12186. currentPolygonOffsetFactor = factor;
  12187. currentPolygonOffsetUnits = units;
  12188. }
  12189. } else {
  12190. disable(gl.POLYGON_OFFSET_FILL);
  12191. }
  12192. }
  12193. function setScissorTest(scissorTest) {
  12194. if (scissorTest) {
  12195. enable(gl.SCISSOR_TEST);
  12196. } else {
  12197. disable(gl.SCISSOR_TEST);
  12198. }
  12199. } // texture
  12200. function activeTexture(webglSlot) {
  12201. if (webglSlot === undefined) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  12202. if (currentTextureSlot !== webglSlot) {
  12203. gl.activeTexture(webglSlot);
  12204. currentTextureSlot = webglSlot;
  12205. }
  12206. }
  12207. function bindTexture(webglType, webglTexture) {
  12208. if (currentTextureSlot === null) {
  12209. activeTexture();
  12210. }
  12211. let boundTexture = currentBoundTextures[currentTextureSlot];
  12212. if (boundTexture === undefined) {
  12213. boundTexture = {
  12214. type: undefined,
  12215. texture: undefined
  12216. };
  12217. currentBoundTextures[currentTextureSlot] = boundTexture;
  12218. }
  12219. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  12220. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  12221. boundTexture.type = webglType;
  12222. boundTexture.texture = webglTexture;
  12223. }
  12224. }
  12225. function unbindTexture() {
  12226. const boundTexture = currentBoundTextures[currentTextureSlot];
  12227. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  12228. gl.bindTexture(boundTexture.type, null);
  12229. boundTexture.type = undefined;
  12230. boundTexture.texture = undefined;
  12231. }
  12232. }
  12233. function compressedTexImage2D() {
  12234. try {
  12235. gl.compressedTexImage2D.apply(gl, arguments);
  12236. } catch (error) {
  12237. console.error('THREE.WebGLState:', error);
  12238. }
  12239. }
  12240. function texImage2D() {
  12241. try {
  12242. gl.texImage2D.apply(gl, arguments);
  12243. } catch (error) {
  12244. console.error('THREE.WebGLState:', error);
  12245. }
  12246. }
  12247. function texImage3D() {
  12248. try {
  12249. gl.texImage3D.apply(gl, arguments);
  12250. } catch (error) {
  12251. console.error('THREE.WebGLState:', error);
  12252. }
  12253. } //
  12254. function scissor(scissor) {
  12255. if (currentScissor.equals(scissor) === false) {
  12256. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  12257. currentScissor.copy(scissor);
  12258. }
  12259. }
  12260. function viewport(viewport) {
  12261. if (currentViewport.equals(viewport) === false) {
  12262. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  12263. currentViewport.copy(viewport);
  12264. }
  12265. } //
  12266. function reset() {
  12267. // reset state
  12268. gl.disable(gl.BLEND);
  12269. gl.disable(gl.CULL_FACE);
  12270. gl.disable(gl.DEPTH_TEST);
  12271. gl.disable(gl.POLYGON_OFFSET_FILL);
  12272. gl.disable(gl.SCISSOR_TEST);
  12273. gl.disable(gl.STENCIL_TEST);
  12274. gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  12275. gl.blendEquation(gl.FUNC_ADD);
  12276. gl.blendFunc(gl.ONE, gl.ZERO);
  12277. gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO);
  12278. gl.colorMask(true, true, true, true);
  12279. gl.clearColor(0, 0, 0, 0);
  12280. gl.depthMask(true);
  12281. gl.depthFunc(gl.LESS);
  12282. gl.clearDepth(1);
  12283. gl.stencilMask(0xffffffff);
  12284. gl.stencilFunc(gl.ALWAYS, 0, 0xffffffff);
  12285. gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
  12286. gl.clearStencil(0);
  12287. gl.cullFace(gl.BACK);
  12288. gl.frontFace(gl.CCW);
  12289. gl.polygonOffset(0, 0);
  12290. gl.activeTexture(gl.TEXTURE0);
  12291. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12292. if (isWebGL2 === true) {
  12293. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
  12294. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  12295. }
  12296. gl.useProgram(null);
  12297. gl.lineWidth(1);
  12298. gl.scissor(0, 0, gl.canvas.width, gl.canvas.height);
  12299. gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); // reset internals
  12300. enabledCapabilities = {};
  12301. currentTextureSlot = null;
  12302. currentBoundTextures = {};
  12303. xrFramebuffer = null;
  12304. currentBoundFramebuffers = {};
  12305. currentProgram = null;
  12306. currentBlendingEnabled = false;
  12307. currentBlending = null;
  12308. currentBlendEquation = null;
  12309. currentBlendSrc = null;
  12310. currentBlendDst = null;
  12311. currentBlendEquationAlpha = null;
  12312. currentBlendSrcAlpha = null;
  12313. currentBlendDstAlpha = null;
  12314. currentPremultipledAlpha = false;
  12315. currentFlipSided = null;
  12316. currentCullFace = null;
  12317. currentLineWidth = null;
  12318. currentPolygonOffsetFactor = null;
  12319. currentPolygonOffsetUnits = null;
  12320. currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height);
  12321. currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height);
  12322. colorBuffer.reset();
  12323. depthBuffer.reset();
  12324. stencilBuffer.reset();
  12325. }
  12326. return {
  12327. buffers: {
  12328. color: colorBuffer,
  12329. depth: depthBuffer,
  12330. stencil: stencilBuffer
  12331. },
  12332. enable: enable,
  12333. disable: disable,
  12334. bindFramebuffer: bindFramebuffer,
  12335. bindXRFramebuffer: bindXRFramebuffer,
  12336. useProgram: useProgram,
  12337. setBlending: setBlending,
  12338. setMaterial: setMaterial,
  12339. setFlipSided: setFlipSided,
  12340. setCullFace: setCullFace,
  12341. setLineWidth: setLineWidth,
  12342. setPolygonOffset: setPolygonOffset,
  12343. setScissorTest: setScissorTest,
  12344. activeTexture: activeTexture,
  12345. bindTexture: bindTexture,
  12346. unbindTexture: unbindTexture,
  12347. compressedTexImage2D: compressedTexImage2D,
  12348. texImage2D: texImage2D,
  12349. texImage3D: texImage3D,
  12350. scissor: scissor,
  12351. viewport: viewport,
  12352. reset: reset
  12353. };
  12354. }
  12355. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  12356. const isWebGL2 = capabilities.isWebGL2;
  12357. const maxTextures = capabilities.maxTextures;
  12358. const maxCubemapSize = capabilities.maxCubemapSize;
  12359. const maxTextureSize = capabilities.maxTextureSize;
  12360. const maxSamples = capabilities.maxSamples;
  12361. const _videoTextures = new WeakMap();
  12362. let _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  12363. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  12364. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  12365. let useOffscreenCanvas = false;
  12366. try {
  12367. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext('2d') !== null;
  12368. } catch (err) {// Ignore any errors
  12369. }
  12370. function createCanvas(width, height) {
  12371. // Use OffscreenCanvas when available. Specially needed in web workers
  12372. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  12373. }
  12374. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  12375. let scale = 1; // handle case if texture exceeds max size
  12376. if (image.width > maxSize || image.height > maxSize) {
  12377. scale = maxSize / Math.max(image.width, image.height);
  12378. } // only perform resize if necessary
  12379. if (scale < 1 || needsPowerOfTwo === true) {
  12380. // only perform resize for certain image types
  12381. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  12382. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  12383. const width = floor(scale * image.width);
  12384. const height = floor(scale * image.height);
  12385. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  12386. const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  12387. canvas.width = width;
  12388. canvas.height = height;
  12389. const context = canvas.getContext('2d');
  12390. context.drawImage(image, 0, 0, width, height);
  12391. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  12392. return canvas;
  12393. } else {
  12394. if ('data' in image) {
  12395. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  12396. }
  12397. return image;
  12398. }
  12399. }
  12400. return image;
  12401. }
  12402. function isPowerOfTwo$1(image) {
  12403. return isPowerOfTwo(image.width) && isPowerOfTwo(image.height);
  12404. }
  12405. function textureNeedsPowerOfTwo(texture) {
  12406. if (isWebGL2) return false;
  12407. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  12408. }
  12409. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  12410. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  12411. }
  12412. function generateMipmap(target, texture, width, height) {
  12413. _gl.generateMipmap(target);
  12414. const textureProperties = properties.get(texture);
  12415. textureProperties.__maxMipLevel = Math.log2(Math.max(width, height));
  12416. }
  12417. function getInternalFormat(internalFormatName, glFormat, glType) {
  12418. if (isWebGL2 === false) return glFormat;
  12419. if (internalFormatName !== null) {
  12420. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  12421. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  12422. }
  12423. let internalFormat = glFormat;
  12424. if (glFormat === _gl.RED) {
  12425. if (glType === _gl.FLOAT) internalFormat = _gl.R32F;
  12426. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.R16F;
  12427. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8;
  12428. }
  12429. if (glFormat === _gl.RGB) {
  12430. if (glType === _gl.FLOAT) internalFormat = _gl.RGB32F;
  12431. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGB16F;
  12432. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGB8;
  12433. }
  12434. if (glFormat === _gl.RGBA) {
  12435. if (glType === _gl.FLOAT) internalFormat = _gl.RGBA32F;
  12436. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGBA16F;
  12437. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGBA8;
  12438. }
  12439. if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) {
  12440. extensions.get('EXT_color_buffer_float');
  12441. }
  12442. return internalFormat;
  12443. } // Fallback filters for non-power-of-2 textures
  12444. function filterFallback(f) {
  12445. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  12446. return _gl.NEAREST;
  12447. }
  12448. return _gl.LINEAR;
  12449. } //
  12450. function onTextureDispose(event) {
  12451. const texture = event.target;
  12452. texture.removeEventListener('dispose', onTextureDispose);
  12453. deallocateTexture(texture);
  12454. if (texture.isVideoTexture) {
  12455. _videoTextures.delete(texture);
  12456. }
  12457. info.memory.textures--;
  12458. }
  12459. function onRenderTargetDispose(event) {
  12460. const renderTarget = event.target;
  12461. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  12462. deallocateRenderTarget(renderTarget);
  12463. info.memory.textures--;
  12464. } //
  12465. function deallocateTexture(texture) {
  12466. const textureProperties = properties.get(texture);
  12467. if (textureProperties.__webglInit === undefined) return;
  12468. _gl.deleteTexture(textureProperties.__webglTexture);
  12469. properties.remove(texture);
  12470. }
  12471. function deallocateRenderTarget(renderTarget) {
  12472. const texture = renderTarget.texture;
  12473. const renderTargetProperties = properties.get(renderTarget);
  12474. const textureProperties = properties.get(texture);
  12475. if (!renderTarget) return;
  12476. if (textureProperties.__webglTexture !== undefined) {
  12477. _gl.deleteTexture(textureProperties.__webglTexture);
  12478. }
  12479. if (renderTarget.depthTexture) {
  12480. renderTarget.depthTexture.dispose();
  12481. }
  12482. if (renderTarget.isWebGLCubeRenderTarget) {
  12483. for (let i = 0; i < 6; i++) {
  12484. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  12485. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  12486. }
  12487. } else {
  12488. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  12489. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  12490. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  12491. if (renderTargetProperties.__webglColorRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);
  12492. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  12493. }
  12494. properties.remove(texture);
  12495. properties.remove(renderTarget);
  12496. } //
  12497. let textureUnits = 0;
  12498. function resetTextureUnits() {
  12499. textureUnits = 0;
  12500. }
  12501. function allocateTextureUnit() {
  12502. const textureUnit = textureUnits;
  12503. if (textureUnit >= maxTextures) {
  12504. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  12505. }
  12506. textureUnits += 1;
  12507. return textureUnit;
  12508. } //
  12509. function setTexture2D(texture, slot) {
  12510. const textureProperties = properties.get(texture);
  12511. if (texture.isVideoTexture) updateVideoTexture(texture);
  12512. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  12513. const image = texture.image;
  12514. if (image === undefined) {
  12515. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  12516. } else if (image.complete === false) {
  12517. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  12518. } else {
  12519. uploadTexture(textureProperties, texture, slot);
  12520. return;
  12521. }
  12522. }
  12523. state.activeTexture(_gl.TEXTURE0 + slot);
  12524. state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture);
  12525. }
  12526. function setTexture2DArray(texture, slot) {
  12527. const textureProperties = properties.get(texture);
  12528. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  12529. uploadTexture(textureProperties, texture, slot);
  12530. return;
  12531. }
  12532. state.activeTexture(_gl.TEXTURE0 + slot);
  12533. state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture);
  12534. }
  12535. function setTexture3D(texture, slot) {
  12536. const textureProperties = properties.get(texture);
  12537. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  12538. uploadTexture(textureProperties, texture, slot);
  12539. return;
  12540. }
  12541. state.activeTexture(_gl.TEXTURE0 + slot);
  12542. state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture);
  12543. }
  12544. function setTextureCube(texture, slot) {
  12545. const textureProperties = properties.get(texture);
  12546. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  12547. uploadCubeTexture(textureProperties, texture, slot);
  12548. return;
  12549. }
  12550. state.activeTexture(_gl.TEXTURE0 + slot);
  12551. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  12552. }
  12553. const wrappingToGL = {
  12554. [RepeatWrapping]: _gl.REPEAT,
  12555. [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE,
  12556. [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT
  12557. };
  12558. const filterToGL = {
  12559. [NearestFilter]: _gl.NEAREST,
  12560. [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST,
  12561. [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR,
  12562. [LinearFilter]: _gl.LINEAR,
  12563. [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST,
  12564. [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR
  12565. };
  12566. function setTextureParameters(textureType, texture, supportsMips) {
  12567. if (supportsMips) {
  12568. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]);
  12569. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]);
  12570. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  12571. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]);
  12572. }
  12573. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]);
  12574. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]);
  12575. } else {
  12576. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE);
  12577. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE);
  12578. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  12579. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE);
  12580. }
  12581. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  12582. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  12583. }
  12584. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterFallback(texture.magFilter));
  12585. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterFallback(texture.minFilter));
  12586. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  12587. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  12588. }
  12589. }
  12590. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  12591. const extension = extensions.get('EXT_texture_filter_anisotropic');
  12592. if (texture.type === FloatType && extensions.has('OES_texture_float_linear') === false) return; // verify extension for WebGL 1 and WebGL 2
  12593. if (isWebGL2 === false && texture.type === HalfFloatType && extensions.has('OES_texture_half_float_linear') === false) return; // verify extension for WebGL 1 only
  12594. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  12595. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  12596. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  12597. }
  12598. }
  12599. }
  12600. function initTexture(textureProperties, texture) {
  12601. if (textureProperties.__webglInit === undefined) {
  12602. textureProperties.__webglInit = true;
  12603. texture.addEventListener('dispose', onTextureDispose);
  12604. textureProperties.__webglTexture = _gl.createTexture();
  12605. info.memory.textures++;
  12606. }
  12607. }
  12608. function uploadTexture(textureProperties, texture, slot) {
  12609. let textureType = _gl.TEXTURE_2D;
  12610. if (texture.isDataTexture2DArray) textureType = _gl.TEXTURE_2D_ARRAY;
  12611. if (texture.isDataTexture3D) textureType = _gl.TEXTURE_3D;
  12612. initTexture(textureProperties, texture);
  12613. state.activeTexture(_gl.TEXTURE0 + slot);
  12614. state.bindTexture(textureType, textureProperties.__webglTexture);
  12615. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  12616. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  12617. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  12618. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  12619. const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo$1(texture.image) === false;
  12620. const image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  12621. const supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  12622. glFormat = utils.convert(texture.format);
  12623. let glType = utils.convert(texture.type),
  12624. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12625. setTextureParameters(textureType, texture, supportsMips);
  12626. let mipmap;
  12627. const mipmaps = texture.mipmaps;
  12628. if (texture.isDepthTexture) {
  12629. // populate depth texture with dummy data
  12630. glInternalFormat = _gl.DEPTH_COMPONENT;
  12631. if (isWebGL2) {
  12632. if (texture.type === FloatType) {
  12633. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  12634. } else if (texture.type === UnsignedIntType) {
  12635. glInternalFormat = _gl.DEPTH_COMPONENT24;
  12636. } else if (texture.type === UnsignedInt248Type) {
  12637. glInternalFormat = _gl.DEPTH24_STENCIL8;
  12638. } else {
  12639. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  12640. }
  12641. } else {
  12642. if (texture.type === FloatType) {
  12643. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  12644. }
  12645. } // validation checks for WebGL 1
  12646. if (texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  12647. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  12648. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  12649. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12650. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  12651. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  12652. texture.type = UnsignedShortType;
  12653. glType = utils.convert(texture.type);
  12654. }
  12655. }
  12656. if (texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  12657. // Depth stencil textures need the DEPTH_STENCIL internal format
  12658. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12659. glInternalFormat = _gl.DEPTH_STENCIL; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  12660. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  12661. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12662. if (texture.type !== UnsignedInt248Type) {
  12663. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  12664. texture.type = UnsignedInt248Type;
  12665. glType = utils.convert(texture.type);
  12666. }
  12667. } //
  12668. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  12669. } else if (texture.isDataTexture) {
  12670. // use manually created mipmaps if available
  12671. // if there are no manual mipmaps
  12672. // set 0 level mipmap and then use GL to generate other mipmap levels
  12673. if (mipmaps.length > 0 && supportsMips) {
  12674. for (let i = 0, il = mipmaps.length; i < il; i++) {
  12675. mipmap = mipmaps[i];
  12676. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  12677. }
  12678. texture.generateMipmaps = false;
  12679. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12680. } else {
  12681. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  12682. textureProperties.__maxMipLevel = 0;
  12683. }
  12684. } else if (texture.isCompressedTexture) {
  12685. for (let i = 0, il = mipmaps.length; i < il; i++) {
  12686. mipmap = mipmaps[i];
  12687. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  12688. if (glFormat !== null) {
  12689. state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  12690. } else {
  12691. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  12692. }
  12693. } else {
  12694. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  12695. }
  12696. }
  12697. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12698. } else if (texture.isDataTexture2DArray) {
  12699. state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  12700. textureProperties.__maxMipLevel = 0;
  12701. } else if (texture.isDataTexture3D) {
  12702. state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  12703. textureProperties.__maxMipLevel = 0;
  12704. } else {
  12705. // regular Texture (image, video, canvas)
  12706. // use manually created mipmaps if available
  12707. // if there are no manual mipmaps
  12708. // set 0 level mipmap and then use GL to generate other mipmap levels
  12709. if (mipmaps.length > 0 && supportsMips) {
  12710. for (let i = 0, il = mipmaps.length; i < il; i++) {
  12711. mipmap = mipmaps[i];
  12712. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap);
  12713. }
  12714. texture.generateMipmaps = false;
  12715. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12716. } else {
  12717. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image);
  12718. textureProperties.__maxMipLevel = 0;
  12719. }
  12720. }
  12721. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  12722. generateMipmap(textureType, texture, image.width, image.height);
  12723. }
  12724. textureProperties.__version = texture.version;
  12725. if (texture.onUpdate) texture.onUpdate(texture);
  12726. }
  12727. function uploadCubeTexture(textureProperties, texture, slot) {
  12728. if (texture.image.length !== 6) return;
  12729. initTexture(textureProperties, texture);
  12730. state.activeTexture(_gl.TEXTURE0 + slot);
  12731. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  12732. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  12733. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  12734. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  12735. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  12736. const isCompressed = texture && (texture.isCompressedTexture || texture.image[0].isCompressedTexture);
  12737. const isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  12738. const cubeImage = [];
  12739. for (let i = 0; i < 6; i++) {
  12740. if (!isCompressed && !isDataTexture) {
  12741. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  12742. } else {
  12743. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  12744. }
  12745. }
  12746. const image = cubeImage[0],
  12747. supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  12748. glFormat = utils.convert(texture.format),
  12749. glType = utils.convert(texture.type),
  12750. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12751. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  12752. let mipmaps;
  12753. if (isCompressed) {
  12754. for (let i = 0; i < 6; i++) {
  12755. mipmaps = cubeImage[i].mipmaps;
  12756. for (let j = 0; j < mipmaps.length; j++) {
  12757. const mipmap = mipmaps[j];
  12758. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  12759. if (glFormat !== null) {
  12760. state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  12761. } else {
  12762. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  12763. }
  12764. } else {
  12765. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  12766. }
  12767. }
  12768. }
  12769. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12770. } else {
  12771. mipmaps = texture.mipmaps;
  12772. for (let i = 0; i < 6; i++) {
  12773. if (isDataTexture) {
  12774. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  12775. for (let j = 0; j < mipmaps.length; j++) {
  12776. const mipmap = mipmaps[j];
  12777. const mipmapImage = mipmap.image[i].image;
  12778. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  12779. }
  12780. } else {
  12781. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  12782. for (let j = 0; j < mipmaps.length; j++) {
  12783. const mipmap = mipmaps[j];
  12784. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  12785. }
  12786. }
  12787. }
  12788. textureProperties.__maxMipLevel = mipmaps.length;
  12789. }
  12790. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  12791. // We assume images for cube map have the same size.
  12792. generateMipmap(_gl.TEXTURE_CUBE_MAP, texture, image.width, image.height);
  12793. }
  12794. textureProperties.__version = texture.version;
  12795. if (texture.onUpdate) texture.onUpdate(texture);
  12796. } // Render targets
  12797. // Setup storage for target texture and bind it to correct framebuffer
  12798. function setupFrameBufferTexture(framebuffer, renderTarget, attachment, textureTarget) {
  12799. const texture = renderTarget.texture;
  12800. const glFormat = utils.convert(texture.format);
  12801. const glType = utils.convert(texture.type);
  12802. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12803. if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) {
  12804. state.texImage3D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null);
  12805. } else {
  12806. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  12807. }
  12808. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  12809. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0);
  12810. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  12811. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  12812. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  12813. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer);
  12814. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  12815. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  12816. if (isMultisample) {
  12817. const depthTexture = renderTarget.depthTexture;
  12818. if (depthTexture && depthTexture.isDepthTexture) {
  12819. if (depthTexture.type === FloatType) {
  12820. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  12821. } else if (depthTexture.type === UnsignedIntType) {
  12822. glInternalFormat = _gl.DEPTH_COMPONENT24;
  12823. }
  12824. }
  12825. const samples = getRenderTargetSamples(renderTarget);
  12826. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  12827. } else {
  12828. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  12829. }
  12830. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  12831. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  12832. if (isMultisample) {
  12833. const samples = getRenderTargetSamples(renderTarget);
  12834. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  12835. } else {
  12836. _gl.renderbufferStorage(_gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height);
  12837. }
  12838. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  12839. } else {
  12840. const texture = renderTarget.texture;
  12841. const glFormat = utils.convert(texture.format);
  12842. const glType = utils.convert(texture.type);
  12843. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12844. if (isMultisample) {
  12845. const samples = getRenderTargetSamples(renderTarget);
  12846. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  12847. } else {
  12848. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  12849. }
  12850. }
  12851. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  12852. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  12853. function setupDepthTexture(framebuffer, renderTarget) {
  12854. const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  12855. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  12856. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  12857. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  12858. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  12859. } // upload an empty depth texture with framebuffer size
  12860. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  12861. renderTarget.depthTexture.image.width = renderTarget.width;
  12862. renderTarget.depthTexture.image.height = renderTarget.height;
  12863. renderTarget.depthTexture.needsUpdate = true;
  12864. }
  12865. setTexture2D(renderTarget.depthTexture, 0);
  12866. const webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  12867. if (renderTarget.depthTexture.format === DepthFormat) {
  12868. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  12869. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  12870. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  12871. } else {
  12872. throw new Error('Unknown depthTexture format');
  12873. }
  12874. } // Setup GL resources for a non-texture depth buffer
  12875. function setupDepthRenderbuffer(renderTarget) {
  12876. const renderTargetProperties = properties.get(renderTarget);
  12877. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  12878. if (renderTarget.depthTexture) {
  12879. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  12880. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  12881. } else {
  12882. if (isCube) {
  12883. renderTargetProperties.__webglDepthbuffer = [];
  12884. for (let i = 0; i < 6; i++) {
  12885. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]);
  12886. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  12887. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  12888. }
  12889. } else {
  12890. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  12891. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  12892. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  12893. }
  12894. }
  12895. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  12896. } // Set up GL resources for the render target
  12897. function setupRenderTarget(renderTarget) {
  12898. const texture = renderTarget.texture;
  12899. const renderTargetProperties = properties.get(renderTarget);
  12900. const textureProperties = properties.get(texture);
  12901. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  12902. textureProperties.__webglTexture = _gl.createTexture();
  12903. textureProperties.__version = texture.version;
  12904. info.memory.textures++;
  12905. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  12906. const isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
  12907. const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray;
  12908. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2; // Handles WebGL2 RGBFormat fallback - #18858
  12909. if (isWebGL2 && texture.format === RGBFormat && (texture.type === FloatType || texture.type === HalfFloatType)) {
  12910. texture.format = RGBAFormat;
  12911. console.warn('THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.');
  12912. } // Setup framebuffer
  12913. if (isCube) {
  12914. renderTargetProperties.__webglFramebuffer = [];
  12915. for (let i = 0; i < 6; i++) {
  12916. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  12917. }
  12918. } else {
  12919. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  12920. if (isMultisample) {
  12921. if (isWebGL2) {
  12922. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  12923. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  12924. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  12925. const glFormat = utils.convert(texture.format);
  12926. const glType = utils.convert(texture.type);
  12927. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12928. const samples = getRenderTargetSamples(renderTarget);
  12929. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  12930. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  12931. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  12932. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  12933. if (renderTarget.depthBuffer) {
  12934. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  12935. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  12936. }
  12937. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  12938. } else {
  12939. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  12940. }
  12941. }
  12942. } // Setup color buffer
  12943. if (isCube) {
  12944. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  12945. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  12946. for (let i = 0; i < 6; i++) {
  12947. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i);
  12948. }
  12949. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  12950. generateMipmap(_gl.TEXTURE_CUBE_MAP, texture, renderTarget.width, renderTarget.height);
  12951. }
  12952. state.bindTexture(_gl.TEXTURE_CUBE_MAP, null);
  12953. } else {
  12954. let glTextureType = _gl.TEXTURE_2D;
  12955. if (isRenderTarget3D) {
  12956. // Render targets containing layers, i.e: Texture 3D and 2d arrays
  12957. if (isWebGL2) {
  12958. const isTexture3D = texture.isDataTexture3D;
  12959. glTextureType = isTexture3D ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  12960. } else {
  12961. console.warn('THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.');
  12962. }
  12963. }
  12964. state.bindTexture(glTextureType, textureProperties.__webglTexture);
  12965. setTextureParameters(glTextureType, texture, supportsMips);
  12966. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, glTextureType);
  12967. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  12968. generateMipmap(_gl.TEXTURE_2D, texture, renderTarget.width, renderTarget.height);
  12969. }
  12970. state.bindTexture(_gl.TEXTURE_2D, null);
  12971. } // Setup depth and stencil buffers
  12972. if (renderTarget.depthBuffer) {
  12973. setupDepthRenderbuffer(renderTarget);
  12974. }
  12975. }
  12976. function updateRenderTargetMipmap(renderTarget) {
  12977. const texture = renderTarget.texture;
  12978. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2;
  12979. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  12980. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  12981. const webglTexture = properties.get(texture).__webglTexture;
  12982. state.bindTexture(target, webglTexture);
  12983. generateMipmap(target, texture, renderTarget.width, renderTarget.height);
  12984. state.bindTexture(target, null);
  12985. }
  12986. }
  12987. function updateMultisampleRenderTarget(renderTarget) {
  12988. if (renderTarget.isWebGLMultisampleRenderTarget) {
  12989. if (isWebGL2) {
  12990. const width = renderTarget.width;
  12991. const height = renderTarget.height;
  12992. let mask = _gl.COLOR_BUFFER_BIT;
  12993. if (renderTarget.depthBuffer) mask |= _gl.DEPTH_BUFFER_BIT;
  12994. if (renderTarget.stencilBuffer) mask |= _gl.STENCIL_BUFFER_BIT;
  12995. const renderTargetProperties = properties.get(renderTarget);
  12996. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  12997. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  12998. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST);
  12999. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null);
  13000. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  13001. } else {
  13002. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  13003. }
  13004. }
  13005. }
  13006. function getRenderTargetSamples(renderTarget) {
  13007. return isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(maxSamples, renderTarget.samples) : 0;
  13008. }
  13009. function updateVideoTexture(texture) {
  13010. const frame = info.render.frame; // Check the last frame we updated the VideoTexture
  13011. if (_videoTextures.get(texture) !== frame) {
  13012. _videoTextures.set(texture, frame);
  13013. texture.update();
  13014. }
  13015. } // backwards compatibility
  13016. let warnedTexture2D = false;
  13017. let warnedTextureCube = false;
  13018. function safeSetTexture2D(texture, slot) {
  13019. if (texture && texture.isWebGLRenderTarget) {
  13020. if (warnedTexture2D === false) {
  13021. console.warn('THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.');
  13022. warnedTexture2D = true;
  13023. }
  13024. texture = texture.texture;
  13025. }
  13026. setTexture2D(texture, slot);
  13027. }
  13028. function safeSetTextureCube(texture, slot) {
  13029. if (texture && texture.isWebGLCubeRenderTarget) {
  13030. if (warnedTextureCube === false) {
  13031. console.warn('THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.');
  13032. warnedTextureCube = true;
  13033. }
  13034. texture = texture.texture;
  13035. }
  13036. setTextureCube(texture, slot);
  13037. } //
  13038. this.allocateTextureUnit = allocateTextureUnit;
  13039. this.resetTextureUnits = resetTextureUnits;
  13040. this.setTexture2D = setTexture2D;
  13041. this.setTexture2DArray = setTexture2DArray;
  13042. this.setTexture3D = setTexture3D;
  13043. this.setTextureCube = setTextureCube;
  13044. this.setupRenderTarget = setupRenderTarget;
  13045. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  13046. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  13047. this.safeSetTexture2D = safeSetTexture2D;
  13048. this.safeSetTextureCube = safeSetTextureCube;
  13049. }
  13050. function WebGLUtils(gl, extensions, capabilities) {
  13051. const isWebGL2 = capabilities.isWebGL2;
  13052. function convert(p) {
  13053. let extension;
  13054. if (p === UnsignedByteType) return gl.UNSIGNED_BYTE;
  13055. if (p === UnsignedShort4444Type) return gl.UNSIGNED_SHORT_4_4_4_4;
  13056. if (p === UnsignedShort5551Type) return gl.UNSIGNED_SHORT_5_5_5_1;
  13057. if (p === UnsignedShort565Type) return gl.UNSIGNED_SHORT_5_6_5;
  13058. if (p === ByteType) return gl.BYTE;
  13059. if (p === ShortType) return gl.SHORT;
  13060. if (p === UnsignedShortType) return gl.UNSIGNED_SHORT;
  13061. if (p === IntType) return gl.INT;
  13062. if (p === UnsignedIntType) return gl.UNSIGNED_INT;
  13063. if (p === FloatType) return gl.FLOAT;
  13064. if (p === HalfFloatType) {
  13065. if (isWebGL2) return gl.HALF_FLOAT;
  13066. extension = extensions.get('OES_texture_half_float');
  13067. if (extension !== null) {
  13068. return extension.HALF_FLOAT_OES;
  13069. } else {
  13070. return null;
  13071. }
  13072. }
  13073. if (p === AlphaFormat) return gl.ALPHA;
  13074. if (p === RGBFormat) return gl.RGB;
  13075. if (p === RGBAFormat) return gl.RGBA;
  13076. if (p === LuminanceFormat) return gl.LUMINANCE;
  13077. if (p === LuminanceAlphaFormat) return gl.LUMINANCE_ALPHA;
  13078. if (p === DepthFormat) return gl.DEPTH_COMPONENT;
  13079. if (p === DepthStencilFormat) return gl.DEPTH_STENCIL;
  13080. if (p === RedFormat) return gl.RED; // WebGL2 formats.
  13081. if (p === RedIntegerFormat) return gl.RED_INTEGER;
  13082. if (p === RGFormat) return gl.RG;
  13083. if (p === RGIntegerFormat) return gl.RG_INTEGER;
  13084. if (p === RGBIntegerFormat) return gl.RGB_INTEGER;
  13085. if (p === RGBAIntegerFormat) return gl.RGBA_INTEGER;
  13086. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  13087. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  13088. if (extension !== null) {
  13089. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13090. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13091. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13092. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13093. } else {
  13094. return null;
  13095. }
  13096. }
  13097. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  13098. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  13099. if (extension !== null) {
  13100. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13101. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13102. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13103. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13104. } else {
  13105. return null;
  13106. }
  13107. }
  13108. if (p === RGB_ETC1_Format) {
  13109. extension = extensions.get('WEBGL_compressed_texture_etc1');
  13110. if (extension !== null) {
  13111. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13112. } else {
  13113. return null;
  13114. }
  13115. }
  13116. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  13117. extension = extensions.get('WEBGL_compressed_texture_etc');
  13118. if (extension !== null) {
  13119. if (p === RGB_ETC2_Format) return extension.COMPRESSED_RGB8_ETC2;
  13120. if (p === RGBA_ETC2_EAC_Format) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  13121. }
  13122. }
  13123. 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) {
  13124. extension = extensions.get('WEBGL_compressed_texture_astc');
  13125. if (extension !== null) {
  13126. // TODO Complete?
  13127. return p;
  13128. } else {
  13129. return null;
  13130. }
  13131. }
  13132. if (p === RGBA_BPTC_Format) {
  13133. extension = extensions.get('EXT_texture_compression_bptc');
  13134. if (extension !== null) {
  13135. // TODO Complete?
  13136. return p;
  13137. } else {
  13138. return null;
  13139. }
  13140. }
  13141. if (p === UnsignedInt248Type) {
  13142. if (isWebGL2) return gl.UNSIGNED_INT_24_8;
  13143. extension = extensions.get('WEBGL_depth_texture');
  13144. if (extension !== null) {
  13145. return extension.UNSIGNED_INT_24_8_WEBGL;
  13146. } else {
  13147. return null;
  13148. }
  13149. }
  13150. }
  13151. return {
  13152. convert: convert
  13153. };
  13154. }
  13155. class ArrayCamera extends PerspectiveCamera {
  13156. constructor(array = []) {
  13157. super();
  13158. this.cameras = array;
  13159. }
  13160. }
  13161. ArrayCamera.prototype.isArrayCamera = true;
  13162. class Group extends Object3D {
  13163. constructor() {
  13164. super();
  13165. this.type = 'Group';
  13166. }
  13167. }
  13168. Group.prototype.isGroup = true;
  13169. const _moveEvent = {
  13170. type: 'move'
  13171. };
  13172. class WebXRController {
  13173. constructor() {
  13174. this._targetRay = null;
  13175. this._grip = null;
  13176. this._hand = null;
  13177. }
  13178. getHandSpace() {
  13179. if (this._hand === null) {
  13180. this._hand = new Group();
  13181. this._hand.matrixAutoUpdate = false;
  13182. this._hand.visible = false;
  13183. this._hand.joints = {};
  13184. this._hand.inputState = {
  13185. pinching: false
  13186. };
  13187. }
  13188. return this._hand;
  13189. }
  13190. getTargetRaySpace() {
  13191. if (this._targetRay === null) {
  13192. this._targetRay = new Group();
  13193. this._targetRay.matrixAutoUpdate = false;
  13194. this._targetRay.visible = false;
  13195. this._targetRay.hasLinearVelocity = false;
  13196. this._targetRay.linearVelocity = new Vector3();
  13197. this._targetRay.hasAngularVelocity = false;
  13198. this._targetRay.angularVelocity = new Vector3();
  13199. }
  13200. return this._targetRay;
  13201. }
  13202. getGripSpace() {
  13203. if (this._grip === null) {
  13204. this._grip = new Group();
  13205. this._grip.matrixAutoUpdate = false;
  13206. this._grip.visible = false;
  13207. this._grip.hasLinearVelocity = false;
  13208. this._grip.linearVelocity = new Vector3();
  13209. this._grip.hasAngularVelocity = false;
  13210. this._grip.angularVelocity = new Vector3();
  13211. }
  13212. return this._grip;
  13213. }
  13214. dispatchEvent(event) {
  13215. if (this._targetRay !== null) {
  13216. this._targetRay.dispatchEvent(event);
  13217. }
  13218. if (this._grip !== null) {
  13219. this._grip.dispatchEvent(event);
  13220. }
  13221. if (this._hand !== null) {
  13222. this._hand.dispatchEvent(event);
  13223. }
  13224. return this;
  13225. }
  13226. disconnect(inputSource) {
  13227. this.dispatchEvent({
  13228. type: 'disconnected',
  13229. data: inputSource
  13230. });
  13231. if (this._targetRay !== null) {
  13232. this._targetRay.visible = false;
  13233. }
  13234. if (this._grip !== null) {
  13235. this._grip.visible = false;
  13236. }
  13237. if (this._hand !== null) {
  13238. this._hand.visible = false;
  13239. }
  13240. return this;
  13241. }
  13242. update(inputSource, frame, referenceSpace) {
  13243. let inputPose = null;
  13244. let gripPose = null;
  13245. let handPose = null;
  13246. const targetRay = this._targetRay;
  13247. const grip = this._grip;
  13248. const hand = this._hand;
  13249. if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
  13250. if (targetRay !== null) {
  13251. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  13252. if (inputPose !== null) {
  13253. targetRay.matrix.fromArray(inputPose.transform.matrix);
  13254. targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
  13255. if (inputPose.linearVelocity) {
  13256. targetRay.hasLinearVelocity = true;
  13257. targetRay.linearVelocity.copy(inputPose.linearVelocity);
  13258. } else {
  13259. targetRay.hasLinearVelocity = false;
  13260. }
  13261. if (inputPose.angularVelocity) {
  13262. targetRay.hasAngularVelocity = true;
  13263. targetRay.angularVelocity.copy(inputPose.angularVelocity);
  13264. } else {
  13265. targetRay.hasAngularVelocity = false;
  13266. }
  13267. this.dispatchEvent(_moveEvent);
  13268. }
  13269. }
  13270. if (hand && inputSource.hand) {
  13271. handPose = true;
  13272. for (const inputjoint of inputSource.hand.values()) {
  13273. // Update the joints groups with the XRJoint poses
  13274. const jointPose = frame.getJointPose(inputjoint, referenceSpace);
  13275. if (hand.joints[inputjoint.jointName] === undefined) {
  13276. // The transform of this joint will be updated with the joint pose on each frame
  13277. const joint = new Group();
  13278. joint.matrixAutoUpdate = false;
  13279. joint.visible = false;
  13280. hand.joints[inputjoint.jointName] = joint; // ??
  13281. hand.add(joint);
  13282. }
  13283. const joint = hand.joints[inputjoint.jointName];
  13284. if (jointPose !== null) {
  13285. joint.matrix.fromArray(jointPose.transform.matrix);
  13286. joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
  13287. joint.jointRadius = jointPose.radius;
  13288. }
  13289. joint.visible = jointPose !== null;
  13290. } // Custom events
  13291. // Check pinchz
  13292. const indexTip = hand.joints['index-finger-tip'];
  13293. const thumbTip = hand.joints['thumb-tip'];
  13294. const distance = indexTip.position.distanceTo(thumbTip.position);
  13295. const distanceToPinch = 0.02;
  13296. const threshold = 0.005;
  13297. if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
  13298. hand.inputState.pinching = false;
  13299. this.dispatchEvent({
  13300. type: 'pinchend',
  13301. handedness: inputSource.handedness,
  13302. target: this
  13303. });
  13304. } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
  13305. hand.inputState.pinching = true;
  13306. this.dispatchEvent({
  13307. type: 'pinchstart',
  13308. handedness: inputSource.handedness,
  13309. target: this
  13310. });
  13311. }
  13312. } else {
  13313. if (grip !== null && inputSource.gripSpace) {
  13314. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  13315. if (gripPose !== null) {
  13316. grip.matrix.fromArray(gripPose.transform.matrix);
  13317. grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
  13318. if (gripPose.linearVelocity) {
  13319. grip.hasLinearVelocity = true;
  13320. grip.linearVelocity.copy(gripPose.linearVelocity);
  13321. } else {
  13322. grip.hasLinearVelocity = false;
  13323. }
  13324. if (gripPose.angularVelocity) {
  13325. grip.hasAngularVelocity = true;
  13326. grip.angularVelocity.copy(gripPose.angularVelocity);
  13327. } else {
  13328. grip.hasAngularVelocity = false;
  13329. }
  13330. }
  13331. }
  13332. }
  13333. }
  13334. if (targetRay !== null) {
  13335. targetRay.visible = inputPose !== null;
  13336. }
  13337. if (grip !== null) {
  13338. grip.visible = gripPose !== null;
  13339. }
  13340. if (hand !== null) {
  13341. hand.visible = handPose !== null;
  13342. }
  13343. return this;
  13344. }
  13345. }
  13346. class WebXRManager extends EventDispatcher {
  13347. constructor(renderer, gl) {
  13348. super();
  13349. const scope = this;
  13350. const state = renderer.state;
  13351. let session = null;
  13352. let framebufferScaleFactor = 1.0;
  13353. let referenceSpace = null;
  13354. let referenceSpaceType = 'local-floor';
  13355. let pose = null;
  13356. const controllers = [];
  13357. const inputSourcesMap = new Map(); //
  13358. const cameraL = new PerspectiveCamera();
  13359. cameraL.layers.enable(1);
  13360. cameraL.viewport = new Vector4();
  13361. const cameraR = new PerspectiveCamera();
  13362. cameraR.layers.enable(2);
  13363. cameraR.viewport = new Vector4();
  13364. const cameras = [cameraL, cameraR];
  13365. const cameraVR = new ArrayCamera();
  13366. cameraVR.layers.enable(1);
  13367. cameraVR.layers.enable(2);
  13368. let _currentDepthNear = null;
  13369. let _currentDepthFar = null; //
  13370. this.enabled = false;
  13371. this.isPresenting = false;
  13372. this.getController = function (index) {
  13373. let controller = controllers[index];
  13374. if (controller === undefined) {
  13375. controller = new WebXRController();
  13376. controllers[index] = controller;
  13377. }
  13378. return controller.getTargetRaySpace();
  13379. };
  13380. this.getControllerGrip = function (index) {
  13381. let controller = controllers[index];
  13382. if (controller === undefined) {
  13383. controller = new WebXRController();
  13384. controllers[index] = controller;
  13385. }
  13386. return controller.getGripSpace();
  13387. };
  13388. this.getHand = function (index) {
  13389. let controller = controllers[index];
  13390. if (controller === undefined) {
  13391. controller = new WebXRController();
  13392. controllers[index] = controller;
  13393. }
  13394. return controller.getHandSpace();
  13395. }; //
  13396. function onSessionEvent(event) {
  13397. const controller = inputSourcesMap.get(event.inputSource);
  13398. if (controller) {
  13399. controller.dispatchEvent({
  13400. type: event.type,
  13401. data: event.inputSource
  13402. });
  13403. }
  13404. }
  13405. function onSessionEnd() {
  13406. inputSourcesMap.forEach(function (controller, inputSource) {
  13407. controller.disconnect(inputSource);
  13408. });
  13409. inputSourcesMap.clear();
  13410. _currentDepthNear = null;
  13411. _currentDepthFar = null; // restore framebuffer/rendering state
  13412. state.bindXRFramebuffer(null);
  13413. renderer.setRenderTarget(renderer.getRenderTarget()); //
  13414. animation.stop();
  13415. scope.isPresenting = false;
  13416. scope.dispatchEvent({
  13417. type: 'sessionend'
  13418. });
  13419. }
  13420. this.setFramebufferScaleFactor = function (value) {
  13421. framebufferScaleFactor = value;
  13422. if (scope.isPresenting === true) {
  13423. console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
  13424. }
  13425. };
  13426. this.setReferenceSpaceType = function (value) {
  13427. referenceSpaceType = value;
  13428. if (scope.isPresenting === true) {
  13429. console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
  13430. }
  13431. };
  13432. this.getReferenceSpace = function () {
  13433. return referenceSpace;
  13434. };
  13435. this.getSession = function () {
  13436. return session;
  13437. };
  13438. this.setSession = async function (value) {
  13439. session = value;
  13440. if (session !== null) {
  13441. session.addEventListener('select', onSessionEvent);
  13442. session.addEventListener('selectstart', onSessionEvent);
  13443. session.addEventListener('selectend', onSessionEvent);
  13444. session.addEventListener('squeeze', onSessionEvent);
  13445. session.addEventListener('squeezestart', onSessionEvent);
  13446. session.addEventListener('squeezeend', onSessionEvent);
  13447. session.addEventListener('end', onSessionEnd);
  13448. session.addEventListener('inputsourceschange', onInputSourcesChange);
  13449. const attributes = gl.getContextAttributes();
  13450. if (attributes.xrCompatible !== true) {
  13451. await gl.makeXRCompatible();
  13452. }
  13453. const layerInit = {
  13454. antialias: attributes.antialias,
  13455. alpha: attributes.alpha,
  13456. depth: attributes.depth,
  13457. stencil: attributes.stencil,
  13458. framebufferScaleFactor: framebufferScaleFactor
  13459. }; // eslint-disable-next-line no-undef
  13460. const baseLayer = new XRWebGLLayer(session, gl, layerInit);
  13461. session.updateRenderState({
  13462. baseLayer: baseLayer
  13463. });
  13464. referenceSpace = await session.requestReferenceSpace(referenceSpaceType);
  13465. animation.setContext(session);
  13466. animation.start();
  13467. scope.isPresenting = true;
  13468. scope.dispatchEvent({
  13469. type: 'sessionstart'
  13470. });
  13471. }
  13472. };
  13473. function onInputSourcesChange(event) {
  13474. const inputSources = session.inputSources; // Assign inputSources to available controllers
  13475. for (let i = 0; i < controllers.length; i++) {
  13476. inputSourcesMap.set(inputSources[i], controllers[i]);
  13477. } // Notify disconnected
  13478. for (let i = 0; i < event.removed.length; i++) {
  13479. const inputSource = event.removed[i];
  13480. const controller = inputSourcesMap.get(inputSource);
  13481. if (controller) {
  13482. controller.dispatchEvent({
  13483. type: 'disconnected',
  13484. data: inputSource
  13485. });
  13486. inputSourcesMap.delete(inputSource);
  13487. }
  13488. } // Notify connected
  13489. for (let i = 0; i < event.added.length; i++) {
  13490. const inputSource = event.added[i];
  13491. const controller = inputSourcesMap.get(inputSource);
  13492. if (controller) {
  13493. controller.dispatchEvent({
  13494. type: 'connected',
  13495. data: inputSource
  13496. });
  13497. }
  13498. }
  13499. } //
  13500. const cameraLPos = new Vector3();
  13501. const cameraRPos = new Vector3();
  13502. /**
  13503. * Assumes 2 cameras that are parallel and share an X-axis, and that
  13504. * the cameras' projection and world matrices have already been set.
  13505. * And that near and far planes are identical for both cameras.
  13506. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  13507. */
  13508. function setProjectionFromUnion(camera, cameraL, cameraR) {
  13509. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  13510. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  13511. const ipd = cameraLPos.distanceTo(cameraRPos);
  13512. const projL = cameraL.projectionMatrix.elements;
  13513. const projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  13514. // most likely identical top and bottom frustum extents.
  13515. // Use the left camera for these values.
  13516. const near = projL[14] / (projL[10] - 1);
  13517. const far = projL[14] / (projL[10] + 1);
  13518. const topFov = (projL[9] + 1) / projL[5];
  13519. const bottomFov = (projL[9] - 1) / projL[5];
  13520. const leftFov = (projL[8] - 1) / projL[0];
  13521. const rightFov = (projR[8] + 1) / projR[0];
  13522. const left = near * leftFov;
  13523. const right = near * rightFov; // Calculate the new camera's position offset from the
  13524. // left camera. xOffset should be roughly half `ipd`.
  13525. const zOffset = ipd / (-leftFov + rightFov);
  13526. const xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  13527. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  13528. camera.translateX(xOffset);
  13529. camera.translateZ(zOffset);
  13530. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  13531. camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); // Find the union of the frustum values of the cameras and scale
  13532. // the values so that the near plane's position does not change in world space,
  13533. // although must now be relative to the new union camera.
  13534. const near2 = near + zOffset;
  13535. const far2 = far + zOffset;
  13536. const left2 = left - xOffset;
  13537. const right2 = right + (ipd - xOffset);
  13538. const top2 = topFov * far / far2 * near2;
  13539. const bottom2 = bottomFov * far / far2 * near2;
  13540. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  13541. }
  13542. function updateCamera(camera, parent) {
  13543. if (parent === null) {
  13544. camera.matrixWorld.copy(camera.matrix);
  13545. } else {
  13546. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  13547. }
  13548. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  13549. }
  13550. this.getCamera = function (camera) {
  13551. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  13552. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  13553. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  13554. // Note that the new renderState won't apply until the next frame. See #18320
  13555. session.updateRenderState({
  13556. depthNear: cameraVR.near,
  13557. depthFar: cameraVR.far
  13558. });
  13559. _currentDepthNear = cameraVR.near;
  13560. _currentDepthFar = cameraVR.far;
  13561. }
  13562. const parent = camera.parent;
  13563. const cameras = cameraVR.cameras;
  13564. updateCamera(cameraVR, parent);
  13565. for (let i = 0; i < cameras.length; i++) {
  13566. updateCamera(cameras[i], parent);
  13567. } // update camera and its children
  13568. camera.matrixWorld.copy(cameraVR.matrixWorld);
  13569. camera.matrix.copy(cameraVR.matrix);
  13570. camera.matrix.decompose(camera.position, camera.quaternion, camera.scale);
  13571. const children = camera.children;
  13572. for (let i = 0, l = children.length; i < l; i++) {
  13573. children[i].updateMatrixWorld(true);
  13574. } // update projection matrix for proper view frustum culling
  13575. if (cameras.length === 2) {
  13576. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  13577. } else {
  13578. // assume single camera setup (AR)
  13579. cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
  13580. }
  13581. return cameraVR;
  13582. }; // Animation Loop
  13583. let onAnimationFrameCallback = null;
  13584. function onAnimationFrame(time, frame) {
  13585. pose = frame.getViewerPose(referenceSpace);
  13586. if (pose !== null) {
  13587. const views = pose.views;
  13588. const baseLayer = session.renderState.baseLayer;
  13589. state.bindXRFramebuffer(baseLayer.framebuffer);
  13590. let cameraVRNeedsUpdate = false; // check if it's necessary to rebuild cameraVR's camera list
  13591. if (views.length !== cameraVR.cameras.length) {
  13592. cameraVR.cameras.length = 0;
  13593. cameraVRNeedsUpdate = true;
  13594. }
  13595. for (let i = 0; i < views.length; i++) {
  13596. const view = views[i];
  13597. const viewport = baseLayer.getViewport(view);
  13598. const camera = cameras[i];
  13599. camera.matrix.fromArray(view.transform.matrix);
  13600. camera.projectionMatrix.fromArray(view.projectionMatrix);
  13601. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  13602. if (i === 0) {
  13603. cameraVR.matrix.copy(camera.matrix);
  13604. }
  13605. if (cameraVRNeedsUpdate === true) {
  13606. cameraVR.cameras.push(camera);
  13607. }
  13608. }
  13609. } //
  13610. const inputSources = session.inputSources;
  13611. for (let i = 0; i < controllers.length; i++) {
  13612. const controller = controllers[i];
  13613. const inputSource = inputSources[i];
  13614. controller.update(inputSource, frame, referenceSpace);
  13615. }
  13616. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  13617. }
  13618. const animation = new WebGLAnimation();
  13619. animation.setAnimationLoop(onAnimationFrame);
  13620. this.setAnimationLoop = function (callback) {
  13621. onAnimationFrameCallback = callback;
  13622. };
  13623. this.dispose = function () {};
  13624. }
  13625. }
  13626. function WebGLMaterials(properties) {
  13627. function refreshFogUniforms(uniforms, fog) {
  13628. uniforms.fogColor.value.copy(fog.color);
  13629. if (fog.isFog) {
  13630. uniforms.fogNear.value = fog.near;
  13631. uniforms.fogFar.value = fog.far;
  13632. } else if (fog.isFogExp2) {
  13633. uniforms.fogDensity.value = fog.density;
  13634. }
  13635. }
  13636. function refreshMaterialUniforms(uniforms, material, pixelRatio, height) {
  13637. if (material.isMeshBasicMaterial) {
  13638. refreshUniformsCommon(uniforms, material);
  13639. } else if (material.isMeshLambertMaterial) {
  13640. refreshUniformsCommon(uniforms, material);
  13641. refreshUniformsLambert(uniforms, material);
  13642. } else if (material.isMeshToonMaterial) {
  13643. refreshUniformsCommon(uniforms, material);
  13644. refreshUniformsToon(uniforms, material);
  13645. } else if (material.isMeshPhongMaterial) {
  13646. refreshUniformsCommon(uniforms, material);
  13647. refreshUniformsPhong(uniforms, material);
  13648. } else if (material.isMeshStandardMaterial) {
  13649. refreshUniformsCommon(uniforms, material);
  13650. if (material.isMeshPhysicalMaterial) {
  13651. refreshUniformsPhysical(uniforms, material);
  13652. } else {
  13653. refreshUniformsStandard(uniforms, material);
  13654. }
  13655. } else if (material.isMeshMatcapMaterial) {
  13656. refreshUniformsCommon(uniforms, material);
  13657. refreshUniformsMatcap(uniforms, material);
  13658. } else if (material.isMeshDepthMaterial) {
  13659. refreshUniformsCommon(uniforms, material);
  13660. refreshUniformsDepth(uniforms, material);
  13661. } else if (material.isMeshDistanceMaterial) {
  13662. refreshUniformsCommon(uniforms, material);
  13663. refreshUniformsDistance(uniforms, material);
  13664. } else if (material.isMeshNormalMaterial) {
  13665. refreshUniformsCommon(uniforms, material);
  13666. refreshUniformsNormal(uniforms, material);
  13667. } else if (material.isLineBasicMaterial) {
  13668. refreshUniformsLine(uniforms, material);
  13669. if (material.isLineDashedMaterial) {
  13670. refreshUniformsDash(uniforms, material);
  13671. }
  13672. } else if (material.isPointsMaterial) {
  13673. refreshUniformsPoints(uniforms, material, pixelRatio, height);
  13674. } else if (material.isSpriteMaterial) {
  13675. refreshUniformsSprites(uniforms, material);
  13676. } else if (material.isShadowMaterial) {
  13677. uniforms.color.value.copy(material.color);
  13678. uniforms.opacity.value = material.opacity;
  13679. } else if (material.isShaderMaterial) {
  13680. material.uniformsNeedUpdate = false; // #15581
  13681. }
  13682. }
  13683. function refreshUniformsCommon(uniforms, material) {
  13684. uniforms.opacity.value = material.opacity;
  13685. if (material.color) {
  13686. uniforms.diffuse.value.copy(material.color);
  13687. }
  13688. if (material.emissive) {
  13689. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  13690. }
  13691. if (material.map) {
  13692. uniforms.map.value = material.map;
  13693. }
  13694. if (material.alphaMap) {
  13695. uniforms.alphaMap.value = material.alphaMap;
  13696. }
  13697. if (material.specularMap) {
  13698. uniforms.specularMap.value = material.specularMap;
  13699. }
  13700. const envMap = properties.get(material).envMap;
  13701. if (envMap) {
  13702. uniforms.envMap.value = envMap;
  13703. uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap._needsFlipEnvMap ? -1 : 1;
  13704. uniforms.reflectivity.value = material.reflectivity;
  13705. uniforms.refractionRatio.value = material.refractionRatio;
  13706. const maxMipLevel = properties.get(envMap).__maxMipLevel;
  13707. if (maxMipLevel !== undefined) {
  13708. uniforms.maxMipLevel.value = maxMipLevel;
  13709. }
  13710. }
  13711. if (material.lightMap) {
  13712. uniforms.lightMap.value = material.lightMap;
  13713. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  13714. }
  13715. if (material.aoMap) {
  13716. uniforms.aoMap.value = material.aoMap;
  13717. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  13718. } // uv repeat and offset setting priorities
  13719. // 1. color map
  13720. // 2. specular map
  13721. // 3. displacementMap map
  13722. // 4. normal map
  13723. // 5. bump map
  13724. // 6. roughnessMap map
  13725. // 7. metalnessMap map
  13726. // 8. alphaMap map
  13727. // 9. emissiveMap map
  13728. // 10. clearcoat map
  13729. // 11. clearcoat normal map
  13730. // 12. clearcoat roughnessMap map
  13731. let uvScaleMap;
  13732. if (material.map) {
  13733. uvScaleMap = material.map;
  13734. } else if (material.specularMap) {
  13735. uvScaleMap = material.specularMap;
  13736. } else if (material.displacementMap) {
  13737. uvScaleMap = material.displacementMap;
  13738. } else if (material.normalMap) {
  13739. uvScaleMap = material.normalMap;
  13740. } else if (material.bumpMap) {
  13741. uvScaleMap = material.bumpMap;
  13742. } else if (material.roughnessMap) {
  13743. uvScaleMap = material.roughnessMap;
  13744. } else if (material.metalnessMap) {
  13745. uvScaleMap = material.metalnessMap;
  13746. } else if (material.alphaMap) {
  13747. uvScaleMap = material.alphaMap;
  13748. } else if (material.emissiveMap) {
  13749. uvScaleMap = material.emissiveMap;
  13750. } else if (material.clearcoatMap) {
  13751. uvScaleMap = material.clearcoatMap;
  13752. } else if (material.clearcoatNormalMap) {
  13753. uvScaleMap = material.clearcoatNormalMap;
  13754. } else if (material.clearcoatRoughnessMap) {
  13755. uvScaleMap = material.clearcoatRoughnessMap;
  13756. }
  13757. if (uvScaleMap !== undefined) {
  13758. // backwards compatibility
  13759. if (uvScaleMap.isWebGLRenderTarget) {
  13760. uvScaleMap = uvScaleMap.texture;
  13761. }
  13762. if (uvScaleMap.matrixAutoUpdate === true) {
  13763. uvScaleMap.updateMatrix();
  13764. }
  13765. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  13766. } // uv repeat and offset setting priorities for uv2
  13767. // 1. ao map
  13768. // 2. light map
  13769. let uv2ScaleMap;
  13770. if (material.aoMap) {
  13771. uv2ScaleMap = material.aoMap;
  13772. } else if (material.lightMap) {
  13773. uv2ScaleMap = material.lightMap;
  13774. }
  13775. if (uv2ScaleMap !== undefined) {
  13776. // backwards compatibility
  13777. if (uv2ScaleMap.isWebGLRenderTarget) {
  13778. uv2ScaleMap = uv2ScaleMap.texture;
  13779. }
  13780. if (uv2ScaleMap.matrixAutoUpdate === true) {
  13781. uv2ScaleMap.updateMatrix();
  13782. }
  13783. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  13784. }
  13785. }
  13786. function refreshUniformsLine(uniforms, material) {
  13787. uniforms.diffuse.value.copy(material.color);
  13788. uniforms.opacity.value = material.opacity;
  13789. }
  13790. function refreshUniformsDash(uniforms, material) {
  13791. uniforms.dashSize.value = material.dashSize;
  13792. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13793. uniforms.scale.value = material.scale;
  13794. }
  13795. function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
  13796. uniforms.diffuse.value.copy(material.color);
  13797. uniforms.opacity.value = material.opacity;
  13798. uniforms.size.value = material.size * pixelRatio;
  13799. uniforms.scale.value = height * 0.5;
  13800. if (material.map) {
  13801. uniforms.map.value = material.map;
  13802. }
  13803. if (material.alphaMap) {
  13804. uniforms.alphaMap.value = material.alphaMap;
  13805. } // uv repeat and offset setting priorities
  13806. // 1. color map
  13807. // 2. alpha map
  13808. let uvScaleMap;
  13809. if (material.map) {
  13810. uvScaleMap = material.map;
  13811. } else if (material.alphaMap) {
  13812. uvScaleMap = material.alphaMap;
  13813. }
  13814. if (uvScaleMap !== undefined) {
  13815. if (uvScaleMap.matrixAutoUpdate === true) {
  13816. uvScaleMap.updateMatrix();
  13817. }
  13818. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  13819. }
  13820. }
  13821. function refreshUniformsSprites(uniforms, material) {
  13822. uniforms.diffuse.value.copy(material.color);
  13823. uniforms.opacity.value = material.opacity;
  13824. uniforms.rotation.value = material.rotation;
  13825. if (material.map) {
  13826. uniforms.map.value = material.map;
  13827. }
  13828. if (material.alphaMap) {
  13829. uniforms.alphaMap.value = material.alphaMap;
  13830. } // uv repeat and offset setting priorities
  13831. // 1. color map
  13832. // 2. alpha map
  13833. let uvScaleMap;
  13834. if (material.map) {
  13835. uvScaleMap = material.map;
  13836. } else if (material.alphaMap) {
  13837. uvScaleMap = material.alphaMap;
  13838. }
  13839. if (uvScaleMap !== undefined) {
  13840. if (uvScaleMap.matrixAutoUpdate === true) {
  13841. uvScaleMap.updateMatrix();
  13842. }
  13843. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  13844. }
  13845. }
  13846. function refreshUniformsLambert(uniforms, material) {
  13847. if (material.emissiveMap) {
  13848. uniforms.emissiveMap.value = material.emissiveMap;
  13849. }
  13850. }
  13851. function refreshUniformsPhong(uniforms, material) {
  13852. uniforms.specular.value.copy(material.specular);
  13853. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  13854. if (material.emissiveMap) {
  13855. uniforms.emissiveMap.value = material.emissiveMap;
  13856. }
  13857. if (material.bumpMap) {
  13858. uniforms.bumpMap.value = material.bumpMap;
  13859. uniforms.bumpScale.value = material.bumpScale;
  13860. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  13861. }
  13862. if (material.normalMap) {
  13863. uniforms.normalMap.value = material.normalMap;
  13864. uniforms.normalScale.value.copy(material.normalScale);
  13865. if (material.side === BackSide) uniforms.normalScale.value.negate();
  13866. }
  13867. if (material.displacementMap) {
  13868. uniforms.displacementMap.value = material.displacementMap;
  13869. uniforms.displacementScale.value = material.displacementScale;
  13870. uniforms.displacementBias.value = material.displacementBias;
  13871. }
  13872. }
  13873. function refreshUniformsToon(uniforms, material) {
  13874. if (material.gradientMap) {
  13875. uniforms.gradientMap.value = material.gradientMap;
  13876. }
  13877. if (material.emissiveMap) {
  13878. uniforms.emissiveMap.value = material.emissiveMap;
  13879. }
  13880. if (material.bumpMap) {
  13881. uniforms.bumpMap.value = material.bumpMap;
  13882. uniforms.bumpScale.value = material.bumpScale;
  13883. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  13884. }
  13885. if (material.normalMap) {
  13886. uniforms.normalMap.value = material.normalMap;
  13887. uniforms.normalScale.value.copy(material.normalScale);
  13888. if (material.side === BackSide) uniforms.normalScale.value.negate();
  13889. }
  13890. if (material.displacementMap) {
  13891. uniforms.displacementMap.value = material.displacementMap;
  13892. uniforms.displacementScale.value = material.displacementScale;
  13893. uniforms.displacementBias.value = material.displacementBias;
  13894. }
  13895. }
  13896. function refreshUniformsStandard(uniforms, material) {
  13897. uniforms.roughness.value = material.roughness;
  13898. uniforms.metalness.value = material.metalness;
  13899. if (material.roughnessMap) {
  13900. uniforms.roughnessMap.value = material.roughnessMap;
  13901. }
  13902. if (material.metalnessMap) {
  13903. uniforms.metalnessMap.value = material.metalnessMap;
  13904. }
  13905. if (material.emissiveMap) {
  13906. uniforms.emissiveMap.value = material.emissiveMap;
  13907. }
  13908. if (material.bumpMap) {
  13909. uniforms.bumpMap.value = material.bumpMap;
  13910. uniforms.bumpScale.value = material.bumpScale;
  13911. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  13912. }
  13913. if (material.normalMap) {
  13914. uniforms.normalMap.value = material.normalMap;
  13915. uniforms.normalScale.value.copy(material.normalScale);
  13916. if (material.side === BackSide) uniforms.normalScale.value.negate();
  13917. }
  13918. if (material.displacementMap) {
  13919. uniforms.displacementMap.value = material.displacementMap;
  13920. uniforms.displacementScale.value = material.displacementScale;
  13921. uniforms.displacementBias.value = material.displacementBias;
  13922. }
  13923. const envMap = properties.get(material).envMap;
  13924. if (envMap) {
  13925. //uniforms.envMap.value = material.envMap; // part of uniforms common
  13926. uniforms.envMapIntensity.value = material.envMapIntensity;
  13927. }
  13928. }
  13929. function refreshUniformsPhysical(uniforms, material) {
  13930. refreshUniformsStandard(uniforms, material);
  13931. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  13932. uniforms.clearcoat.value = material.clearcoat;
  13933. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  13934. if (material.sheen) uniforms.sheen.value.copy(material.sheen);
  13935. if (material.clearcoatMap) {
  13936. uniforms.clearcoatMap.value = material.clearcoatMap;
  13937. }
  13938. if (material.clearcoatRoughnessMap) {
  13939. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  13940. }
  13941. if (material.clearcoatNormalMap) {
  13942. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  13943. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  13944. if (material.side === BackSide) {
  13945. uniforms.clearcoatNormalScale.value.negate();
  13946. }
  13947. }
  13948. uniforms.transmission.value = material.transmission;
  13949. if (material.transmissionMap) {
  13950. uniforms.transmissionMap.value = material.transmissionMap;
  13951. }
  13952. }
  13953. function refreshUniformsMatcap(uniforms, material) {
  13954. if (material.matcap) {
  13955. uniforms.matcap.value = material.matcap;
  13956. }
  13957. if (material.bumpMap) {
  13958. uniforms.bumpMap.value = material.bumpMap;
  13959. uniforms.bumpScale.value = material.bumpScale;
  13960. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  13961. }
  13962. if (material.normalMap) {
  13963. uniforms.normalMap.value = material.normalMap;
  13964. uniforms.normalScale.value.copy(material.normalScale);
  13965. if (material.side === BackSide) uniforms.normalScale.value.negate();
  13966. }
  13967. if (material.displacementMap) {
  13968. uniforms.displacementMap.value = material.displacementMap;
  13969. uniforms.displacementScale.value = material.displacementScale;
  13970. uniforms.displacementBias.value = material.displacementBias;
  13971. }
  13972. }
  13973. function refreshUniformsDepth(uniforms, material) {
  13974. if (material.displacementMap) {
  13975. uniforms.displacementMap.value = material.displacementMap;
  13976. uniforms.displacementScale.value = material.displacementScale;
  13977. uniforms.displacementBias.value = material.displacementBias;
  13978. }
  13979. }
  13980. function refreshUniformsDistance(uniforms, material) {
  13981. if (material.displacementMap) {
  13982. uniforms.displacementMap.value = material.displacementMap;
  13983. uniforms.displacementScale.value = material.displacementScale;
  13984. uniforms.displacementBias.value = material.displacementBias;
  13985. }
  13986. uniforms.referencePosition.value.copy(material.referencePosition);
  13987. uniforms.nearDistance.value = material.nearDistance;
  13988. uniforms.farDistance.value = material.farDistance;
  13989. }
  13990. function refreshUniformsNormal(uniforms, material) {
  13991. if (material.bumpMap) {
  13992. uniforms.bumpMap.value = material.bumpMap;
  13993. uniforms.bumpScale.value = material.bumpScale;
  13994. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  13995. }
  13996. if (material.normalMap) {
  13997. uniforms.normalMap.value = material.normalMap;
  13998. uniforms.normalScale.value.copy(material.normalScale);
  13999. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14000. }
  14001. if (material.displacementMap) {
  14002. uniforms.displacementMap.value = material.displacementMap;
  14003. uniforms.displacementScale.value = material.displacementScale;
  14004. uniforms.displacementBias.value = material.displacementBias;
  14005. }
  14006. }
  14007. return {
  14008. refreshFogUniforms: refreshFogUniforms,
  14009. refreshMaterialUniforms: refreshMaterialUniforms
  14010. };
  14011. }
  14012. function createCanvasElement() {
  14013. const canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  14014. canvas.style.display = 'block';
  14015. return canvas;
  14016. }
  14017. function WebGLRenderer(parameters) {
  14018. parameters = parameters || {};
  14019. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  14020. _context = parameters.context !== undefined ? parameters.context : null,
  14021. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14022. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14023. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  14024. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  14025. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  14026. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  14027. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  14028. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  14029. let currentRenderList = null;
  14030. let currentRenderState = null; // render() can be called from within a callback triggered by another render.
  14031. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  14032. const renderListStack = [];
  14033. const renderStateStack = []; // public properties
  14034. this.domElement = _canvas; // Debug configuration container
  14035. this.debug = {
  14036. /**
  14037. * Enables error checking and reporting when shader programs are being compiled
  14038. * @type {boolean}
  14039. */
  14040. checkShaderErrors: true
  14041. }; // clearing
  14042. this.autoClear = true;
  14043. this.autoClearColor = true;
  14044. this.autoClearDepth = true;
  14045. this.autoClearStencil = true; // scene graph
  14046. this.sortObjects = true; // user-defined clipping
  14047. this.clippingPlanes = [];
  14048. this.localClippingEnabled = false; // physically based shading
  14049. this.gammaFactor = 2.0; // for backwards compatibility
  14050. this.outputEncoding = LinearEncoding; // physical lights
  14051. this.physicallyCorrectLights = false; // tone mapping
  14052. this.toneMapping = NoToneMapping;
  14053. this.toneMappingExposure = 1.0; // internal properties
  14054. const _this = this;
  14055. let _isContextLost = false; // internal state cache
  14056. let _currentActiveCubeFace = 0;
  14057. let _currentActiveMipmapLevel = 0;
  14058. let _currentRenderTarget = null;
  14059. let _currentMaterialId = -1;
  14060. let _currentCamera = null;
  14061. const _currentViewport = new Vector4();
  14062. const _currentScissor = new Vector4();
  14063. let _currentScissorTest = null; //
  14064. let _width = _canvas.width;
  14065. let _height = _canvas.height;
  14066. let _pixelRatio = 1;
  14067. let _opaqueSort = null;
  14068. let _transparentSort = null;
  14069. const _viewport = new Vector4(0, 0, _width, _height);
  14070. const _scissor = new Vector4(0, 0, _width, _height);
  14071. let _scissorTest = false; // frustum
  14072. const _frustum = new Frustum(); // clipping
  14073. let _clippingEnabled = false;
  14074. let _localClippingEnabled = false; // camera matrices cache
  14075. const _projScreenMatrix = new Matrix4();
  14076. const _vector3 = new Vector3();
  14077. const _emptyScene = {
  14078. background: null,
  14079. fog: null,
  14080. environment: null,
  14081. overrideMaterial: null,
  14082. isScene: true
  14083. };
  14084. function getTargetPixelRatio() {
  14085. return _currentRenderTarget === null ? _pixelRatio : 1;
  14086. } // initialize
  14087. let _gl = _context;
  14088. function getContext(contextNames, contextAttributes) {
  14089. for (let i = 0; i < contextNames.length; i++) {
  14090. const contextName = contextNames[i];
  14091. const context = _canvas.getContext(contextName, contextAttributes);
  14092. if (context !== null) return context;
  14093. }
  14094. return null;
  14095. }
  14096. try {
  14097. const contextAttributes = {
  14098. alpha: _alpha,
  14099. depth: _depth,
  14100. stencil: _stencil,
  14101. antialias: _antialias,
  14102. premultipliedAlpha: _premultipliedAlpha,
  14103. preserveDrawingBuffer: _preserveDrawingBuffer,
  14104. powerPreference: _powerPreference,
  14105. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  14106. }; // event listeners must be registered before WebGL context is created, see #12753
  14107. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  14108. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  14109. if (_gl === null) {
  14110. const contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
  14111. if (_this.isWebGL1Renderer === true) {
  14112. contextNames.shift();
  14113. }
  14114. _gl = getContext(contextNames, contextAttributes);
  14115. if (_gl === null) {
  14116. if (getContext(contextNames)) {
  14117. throw new Error('Error creating WebGL context with your selected attributes.');
  14118. } else {
  14119. throw new Error('Error creating WebGL context.');
  14120. }
  14121. }
  14122. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  14123. if (_gl.getShaderPrecisionFormat === undefined) {
  14124. _gl.getShaderPrecisionFormat = function () {
  14125. return {
  14126. 'rangeMin': 1,
  14127. 'rangeMax': 1,
  14128. 'precision': 1
  14129. };
  14130. };
  14131. }
  14132. } catch (error) {
  14133. console.error('THREE.WebGLRenderer: ' + error.message);
  14134. throw error;
  14135. }
  14136. let extensions, capabilities, state, info;
  14137. let properties, textures, cubemaps, attributes, geometries, objects;
  14138. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  14139. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  14140. let utils, bindingStates;
  14141. function initGLContext() {
  14142. extensions = new WebGLExtensions(_gl);
  14143. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  14144. extensions.init(capabilities);
  14145. utils = new WebGLUtils(_gl, extensions, capabilities);
  14146. state = new WebGLState(_gl, extensions, capabilities);
  14147. info = new WebGLInfo(_gl);
  14148. properties = new WebGLProperties();
  14149. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  14150. cubemaps = new WebGLCubeMaps(_this);
  14151. attributes = new WebGLAttributes(_gl, capabilities);
  14152. bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
  14153. geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
  14154. objects = new WebGLObjects(_gl, geometries, attributes, info);
  14155. morphtargets = new WebGLMorphtargets(_gl);
  14156. clipping = new WebGLClipping(properties);
  14157. programCache = new WebGLPrograms(_this, cubemaps, extensions, capabilities, bindingStates, clipping);
  14158. materials = new WebGLMaterials(properties);
  14159. renderLists = new WebGLRenderLists(properties);
  14160. renderStates = new WebGLRenderStates(extensions, capabilities);
  14161. background = new WebGLBackground(_this, cubemaps, state, objects, _premultipliedAlpha);
  14162. shadowMap = new WebGLShadowMap(_this, objects, capabilities);
  14163. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  14164. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  14165. info.programs = programCache.programs;
  14166. _this.capabilities = capabilities;
  14167. _this.extensions = extensions;
  14168. _this.properties = properties;
  14169. _this.renderLists = renderLists;
  14170. _this.shadowMap = shadowMap;
  14171. _this.state = state;
  14172. _this.info = info;
  14173. }
  14174. initGLContext(); // xr
  14175. const xr = new WebXRManager(_this, _gl);
  14176. this.xr = xr; // API
  14177. this.getContext = function () {
  14178. return _gl;
  14179. };
  14180. this.getContextAttributes = function () {
  14181. return _gl.getContextAttributes();
  14182. };
  14183. this.forceContextLoss = function () {
  14184. const extension = extensions.get('WEBGL_lose_context');
  14185. if (extension) extension.loseContext();
  14186. };
  14187. this.forceContextRestore = function () {
  14188. const extension = extensions.get('WEBGL_lose_context');
  14189. if (extension) extension.restoreContext();
  14190. };
  14191. this.getPixelRatio = function () {
  14192. return _pixelRatio;
  14193. };
  14194. this.setPixelRatio = function (value) {
  14195. if (value === undefined) return;
  14196. _pixelRatio = value;
  14197. this.setSize(_width, _height, false);
  14198. };
  14199. this.getSize = function (target) {
  14200. if (target === undefined) {
  14201. console.warn('WebGLRenderer: .getsize() now requires a Vector2 as an argument');
  14202. target = new Vector2();
  14203. }
  14204. return target.set(_width, _height);
  14205. };
  14206. this.setSize = function (width, height, updateStyle) {
  14207. if (xr.isPresenting) {
  14208. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  14209. return;
  14210. }
  14211. _width = width;
  14212. _height = height;
  14213. _canvas.width = Math.floor(width * _pixelRatio);
  14214. _canvas.height = Math.floor(height * _pixelRatio);
  14215. if (updateStyle !== false) {
  14216. _canvas.style.width = width + 'px';
  14217. _canvas.style.height = height + 'px';
  14218. }
  14219. this.setViewport(0, 0, width, height);
  14220. };
  14221. this.getDrawingBufferSize = function (target) {
  14222. if (target === undefined) {
  14223. console.warn('WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument');
  14224. target = new Vector2();
  14225. }
  14226. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  14227. };
  14228. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  14229. _width = width;
  14230. _height = height;
  14231. _pixelRatio = pixelRatio;
  14232. _canvas.width = Math.floor(width * pixelRatio);
  14233. _canvas.height = Math.floor(height * pixelRatio);
  14234. this.setViewport(0, 0, width, height);
  14235. };
  14236. this.getCurrentViewport = function (target) {
  14237. if (target === undefined) {
  14238. console.warn('WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument');
  14239. target = new Vector4();
  14240. }
  14241. return target.copy(_currentViewport);
  14242. };
  14243. this.getViewport = function (target) {
  14244. return target.copy(_viewport);
  14245. };
  14246. this.setViewport = function (x, y, width, height) {
  14247. if (x.isVector4) {
  14248. _viewport.set(x.x, x.y, x.z, x.w);
  14249. } else {
  14250. _viewport.set(x, y, width, height);
  14251. }
  14252. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  14253. };
  14254. this.getScissor = function (target) {
  14255. return target.copy(_scissor);
  14256. };
  14257. this.setScissor = function (x, y, width, height) {
  14258. if (x.isVector4) {
  14259. _scissor.set(x.x, x.y, x.z, x.w);
  14260. } else {
  14261. _scissor.set(x, y, width, height);
  14262. }
  14263. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  14264. };
  14265. this.getScissorTest = function () {
  14266. return _scissorTest;
  14267. };
  14268. this.setScissorTest = function (boolean) {
  14269. state.setScissorTest(_scissorTest = boolean);
  14270. };
  14271. this.setOpaqueSort = function (method) {
  14272. _opaqueSort = method;
  14273. };
  14274. this.setTransparentSort = function (method) {
  14275. _transparentSort = method;
  14276. }; // Clearing
  14277. this.getClearColor = function (target) {
  14278. if (target === undefined) {
  14279. console.warn('WebGLRenderer: .getClearColor() now requires a Color as an argument');
  14280. target = new Color();
  14281. }
  14282. return target.copy(background.getClearColor());
  14283. };
  14284. this.setClearColor = function () {
  14285. background.setClearColor.apply(background, arguments);
  14286. };
  14287. this.getClearAlpha = function () {
  14288. return background.getClearAlpha();
  14289. };
  14290. this.setClearAlpha = function () {
  14291. background.setClearAlpha.apply(background, arguments);
  14292. };
  14293. this.clear = function (color, depth, stencil) {
  14294. let bits = 0;
  14295. if (color === undefined || color) bits |= _gl.COLOR_BUFFER_BIT;
  14296. if (depth === undefined || depth) bits |= _gl.DEPTH_BUFFER_BIT;
  14297. if (stencil === undefined || stencil) bits |= _gl.STENCIL_BUFFER_BIT;
  14298. _gl.clear(bits);
  14299. };
  14300. this.clearColor = function () {
  14301. this.clear(true, false, false);
  14302. };
  14303. this.clearDepth = function () {
  14304. this.clear(false, true, false);
  14305. };
  14306. this.clearStencil = function () {
  14307. this.clear(false, false, true);
  14308. }; //
  14309. this.dispose = function () {
  14310. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  14311. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  14312. renderLists.dispose();
  14313. renderStates.dispose();
  14314. properties.dispose();
  14315. cubemaps.dispose();
  14316. objects.dispose();
  14317. bindingStates.dispose();
  14318. xr.dispose();
  14319. xr.removeEventListener('sessionstart', onXRSessionStart);
  14320. xr.removeEventListener('sessionend', onXRSessionEnd);
  14321. animation.stop();
  14322. }; // Events
  14323. function onContextLost(event) {
  14324. event.preventDefault();
  14325. console.log('THREE.WebGLRenderer: Context Lost.');
  14326. _isContextLost = true;
  14327. }
  14328. function onContextRestore()
  14329. /* event */
  14330. {
  14331. console.log('THREE.WebGLRenderer: Context Restored.');
  14332. _isContextLost = false;
  14333. const infoAutoReset = info.autoReset;
  14334. const shadowMapEnabled = shadowMap.enabled;
  14335. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  14336. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  14337. const shadowMapType = shadowMap.type;
  14338. initGLContext();
  14339. info.autoReset = infoAutoReset;
  14340. shadowMap.enabled = shadowMapEnabled;
  14341. shadowMap.autoUpdate = shadowMapAutoUpdate;
  14342. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  14343. shadowMap.type = shadowMapType;
  14344. }
  14345. function onMaterialDispose(event) {
  14346. const material = event.target;
  14347. material.removeEventListener('dispose', onMaterialDispose);
  14348. deallocateMaterial(material);
  14349. } // Buffer deallocation
  14350. function deallocateMaterial(material) {
  14351. releaseMaterialProgramReferences(material);
  14352. properties.remove(material);
  14353. }
  14354. function releaseMaterialProgramReferences(material) {
  14355. const programs = properties.get(material).programs;
  14356. if (programs !== undefined) {
  14357. programs.forEach(function (program) {
  14358. programCache.releaseProgram(program);
  14359. });
  14360. }
  14361. } // Buffer rendering
  14362. function renderObjectImmediate(object, program) {
  14363. object.render(function (object) {
  14364. _this.renderBufferImmediate(object, program);
  14365. });
  14366. }
  14367. this.renderBufferImmediate = function (object, program) {
  14368. bindingStates.initAttributes();
  14369. const buffers = properties.get(object);
  14370. if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
  14371. if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
  14372. if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
  14373. if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
  14374. const programAttributes = program.getAttributes();
  14375. if (object.hasPositions) {
  14376. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.position);
  14377. _gl.bufferData(_gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW);
  14378. bindingStates.enableAttribute(programAttributes.position);
  14379. _gl.vertexAttribPointer(programAttributes.position, 3, _gl.FLOAT, false, 0, 0);
  14380. }
  14381. if (object.hasNormals) {
  14382. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.normal);
  14383. _gl.bufferData(_gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW);
  14384. bindingStates.enableAttribute(programAttributes.normal);
  14385. _gl.vertexAttribPointer(programAttributes.normal, 3, _gl.FLOAT, false, 0, 0);
  14386. }
  14387. if (object.hasUvs) {
  14388. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.uv);
  14389. _gl.bufferData(_gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW);
  14390. bindingStates.enableAttribute(programAttributes.uv);
  14391. _gl.vertexAttribPointer(programAttributes.uv, 2, _gl.FLOAT, false, 0, 0);
  14392. }
  14393. if (object.hasColors) {
  14394. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.color);
  14395. _gl.bufferData(_gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW);
  14396. bindingStates.enableAttribute(programAttributes.color);
  14397. _gl.vertexAttribPointer(programAttributes.color, 3, _gl.FLOAT, false, 0, 0);
  14398. }
  14399. bindingStates.disableUnusedAttributes();
  14400. _gl.drawArrays(_gl.TRIANGLES, 0, object.count);
  14401. object.count = 0;
  14402. };
  14403. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  14404. if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  14405. const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  14406. const program = setProgram(camera, scene, material, object);
  14407. state.setMaterial(material, frontFaceCW); //
  14408. let index = geometry.index;
  14409. const position = geometry.attributes.position; //
  14410. if (index === null) {
  14411. if (position === undefined || position.count === 0) return;
  14412. } else if (index.count === 0) {
  14413. return;
  14414. } //
  14415. let rangeFactor = 1;
  14416. if (material.wireframe === true) {
  14417. index = geometries.getWireframeAttribute(geometry);
  14418. rangeFactor = 2;
  14419. }
  14420. if (material.morphTargets || material.morphNormals) {
  14421. morphtargets.update(object, geometry, material, program);
  14422. }
  14423. bindingStates.setup(object, material, program, geometry, index);
  14424. let attribute;
  14425. let renderer = bufferRenderer;
  14426. if (index !== null) {
  14427. attribute = attributes.get(index);
  14428. renderer = indexedBufferRenderer;
  14429. renderer.setIndex(attribute);
  14430. } //
  14431. const dataCount = index !== null ? index.count : position.count;
  14432. const rangeStart = geometry.drawRange.start * rangeFactor;
  14433. const rangeCount = geometry.drawRange.count * rangeFactor;
  14434. const groupStart = group !== null ? group.start * rangeFactor : 0;
  14435. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  14436. const drawStart = Math.max(rangeStart, groupStart);
  14437. const drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  14438. const drawCount = Math.max(0, drawEnd - drawStart + 1);
  14439. if (drawCount === 0) return; //
  14440. if (object.isMesh) {
  14441. if (material.wireframe === true) {
  14442. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  14443. renderer.setMode(_gl.LINES);
  14444. } else {
  14445. renderer.setMode(_gl.TRIANGLES);
  14446. }
  14447. } else if (object.isLine) {
  14448. let lineWidth = material.linewidth;
  14449. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  14450. state.setLineWidth(lineWidth * getTargetPixelRatio());
  14451. if (object.isLineSegments) {
  14452. renderer.setMode(_gl.LINES);
  14453. } else if (object.isLineLoop) {
  14454. renderer.setMode(_gl.LINE_LOOP);
  14455. } else {
  14456. renderer.setMode(_gl.LINE_STRIP);
  14457. }
  14458. } else if (object.isPoints) {
  14459. renderer.setMode(_gl.POINTS);
  14460. } else if (object.isSprite) {
  14461. renderer.setMode(_gl.TRIANGLES);
  14462. }
  14463. if (object.isInstancedMesh) {
  14464. renderer.renderInstances(drawStart, drawCount, object.count);
  14465. } else if (geometry.isInstancedBufferGeometry) {
  14466. const instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount);
  14467. renderer.renderInstances(drawStart, drawCount, instanceCount);
  14468. } else {
  14469. renderer.render(drawStart, drawCount);
  14470. }
  14471. }; // Compile
  14472. this.compile = function (scene, camera) {
  14473. currentRenderState = renderStates.get(scene);
  14474. currentRenderState.init();
  14475. scene.traverseVisible(function (object) {
  14476. if (object.isLight && object.layers.test(camera.layers)) {
  14477. currentRenderState.pushLight(object);
  14478. if (object.castShadow) {
  14479. currentRenderState.pushShadow(object);
  14480. }
  14481. }
  14482. });
  14483. currentRenderState.setupLights();
  14484. scene.traverse(function (object) {
  14485. const material = object.material;
  14486. if (material) {
  14487. if (Array.isArray(material)) {
  14488. for (let i = 0; i < material.length; i++) {
  14489. const material2 = material[i];
  14490. getProgram(material2, scene, object);
  14491. }
  14492. } else {
  14493. getProgram(material, scene, object);
  14494. }
  14495. }
  14496. });
  14497. }; // Animation Loop
  14498. let onAnimationFrameCallback = null;
  14499. function onAnimationFrame(time) {
  14500. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  14501. }
  14502. function onXRSessionStart() {
  14503. animation.stop();
  14504. }
  14505. function onXRSessionEnd() {
  14506. animation.start();
  14507. }
  14508. const animation = new WebGLAnimation();
  14509. animation.setAnimationLoop(onAnimationFrame);
  14510. if (typeof window !== 'undefined') animation.setContext(window);
  14511. this.setAnimationLoop = function (callback) {
  14512. onAnimationFrameCallback = callback;
  14513. xr.setAnimationLoop(callback);
  14514. callback === null ? animation.stop() : animation.start();
  14515. };
  14516. xr.addEventListener('sessionstart', onXRSessionStart);
  14517. xr.addEventListener('sessionend', onXRSessionEnd); // Rendering
  14518. this.render = function (scene, camera) {
  14519. let renderTarget, forceClear;
  14520. if (arguments[2] !== undefined) {
  14521. console.warn('THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.');
  14522. renderTarget = arguments[2];
  14523. }
  14524. if (arguments[3] !== undefined) {
  14525. console.warn('THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.');
  14526. forceClear = arguments[3];
  14527. }
  14528. if (camera !== undefined && camera.isCamera !== true) {
  14529. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  14530. return;
  14531. }
  14532. if (_isContextLost === true) return; // update scene graph
  14533. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  14534. if (camera.parent === null) camera.updateMatrixWorld();
  14535. if (xr.enabled === true && xr.isPresenting === true) {
  14536. camera = xr.getCamera(camera);
  14537. } //
  14538. if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, renderTarget || _currentRenderTarget);
  14539. currentRenderState = renderStates.get(scene, renderStateStack.length);
  14540. currentRenderState.init();
  14541. renderStateStack.push(currentRenderState);
  14542. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  14543. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  14544. _localClippingEnabled = this.localClippingEnabled;
  14545. _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  14546. currentRenderList = renderLists.get(scene, renderListStack.length);
  14547. currentRenderList.init();
  14548. renderListStack.push(currentRenderList);
  14549. projectObject(scene, camera, 0, _this.sortObjects);
  14550. currentRenderList.finish();
  14551. if (_this.sortObjects === true) {
  14552. currentRenderList.sort(_opaqueSort, _transparentSort);
  14553. } //
  14554. if (_clippingEnabled === true) clipping.beginShadows();
  14555. const shadowsArray = currentRenderState.state.shadowsArray;
  14556. shadowMap.render(shadowsArray, scene, camera);
  14557. currentRenderState.setupLights();
  14558. currentRenderState.setupLightsView(camera);
  14559. if (_clippingEnabled === true) clipping.endShadows(); //
  14560. if (this.info.autoReset === true) this.info.reset();
  14561. if (renderTarget !== undefined) {
  14562. this.setRenderTarget(renderTarget);
  14563. } //
  14564. background.render(currentRenderList, scene, camera, forceClear); // render scene
  14565. const opaqueObjects = currentRenderList.opaque;
  14566. const transparentObjects = currentRenderList.transparent;
  14567. if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
  14568. if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera); //
  14569. if (_currentRenderTarget !== null) {
  14570. // Generate mipmap if we're using any kind of mipmap filtering
  14571. textures.updateRenderTargetMipmap(_currentRenderTarget); // resolve multisample renderbuffers to a single-sample texture if necessary
  14572. textures.updateMultisampleRenderTarget(_currentRenderTarget);
  14573. } //
  14574. if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); // Ensure depth buffer writing is enabled so it can be cleared on next render
  14575. state.buffers.depth.setTest(true);
  14576. state.buffers.depth.setMask(true);
  14577. state.buffers.color.setMask(true);
  14578. state.setPolygonOffset(false); // _gl.finish();
  14579. bindingStates.resetDefaultState();
  14580. _currentMaterialId = -1;
  14581. _currentCamera = null;
  14582. renderStateStack.pop();
  14583. if (renderStateStack.length > 0) {
  14584. currentRenderState = renderStateStack[renderStateStack.length - 1];
  14585. } else {
  14586. currentRenderState = null;
  14587. }
  14588. renderListStack.pop();
  14589. if (renderListStack.length > 0) {
  14590. currentRenderList = renderListStack[renderListStack.length - 1];
  14591. } else {
  14592. currentRenderList = null;
  14593. }
  14594. };
  14595. function projectObject(object, camera, groupOrder, sortObjects) {
  14596. if (object.visible === false) return;
  14597. const visible = object.layers.test(camera.layers);
  14598. if (visible) {
  14599. if (object.isGroup) {
  14600. groupOrder = object.renderOrder;
  14601. } else if (object.isLOD) {
  14602. if (object.autoUpdate === true) object.update(camera);
  14603. } else if (object.isLight) {
  14604. currentRenderState.pushLight(object);
  14605. if (object.castShadow) {
  14606. currentRenderState.pushShadow(object);
  14607. }
  14608. } else if (object.isSprite) {
  14609. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  14610. if (sortObjects) {
  14611. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  14612. }
  14613. const geometry = objects.update(object);
  14614. const material = object.material;
  14615. if (material.visible) {
  14616. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  14617. }
  14618. }
  14619. } else if (object.isImmediateRenderObject) {
  14620. if (sortObjects) {
  14621. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  14622. }
  14623. currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
  14624. } else if (object.isMesh || object.isLine || object.isPoints) {
  14625. if (object.isSkinnedMesh) {
  14626. // update skeleton only once in a frame
  14627. if (object.skeleton.frame !== info.render.frame) {
  14628. object.skeleton.update();
  14629. object.skeleton.frame = info.render.frame;
  14630. }
  14631. }
  14632. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  14633. if (sortObjects) {
  14634. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  14635. }
  14636. const geometry = objects.update(object);
  14637. const material = object.material;
  14638. if (Array.isArray(material)) {
  14639. const groups = geometry.groups;
  14640. for (let i = 0, l = groups.length; i < l; i++) {
  14641. const group = groups[i];
  14642. const groupMaterial = material[group.materialIndex];
  14643. if (groupMaterial && groupMaterial.visible) {
  14644. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  14645. }
  14646. }
  14647. } else if (material.visible) {
  14648. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  14649. }
  14650. }
  14651. }
  14652. }
  14653. const children = object.children;
  14654. for (let i = 0, l = children.length; i < l; i++) {
  14655. projectObject(children[i], camera, groupOrder, sortObjects);
  14656. }
  14657. }
  14658. function renderObjects(renderList, scene, camera) {
  14659. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  14660. for (let i = 0, l = renderList.length; i < l; i++) {
  14661. const renderItem = renderList[i];
  14662. const object = renderItem.object;
  14663. const geometry = renderItem.geometry;
  14664. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  14665. const group = renderItem.group;
  14666. if (camera.isArrayCamera) {
  14667. const cameras = camera.cameras;
  14668. for (let j = 0, jl = cameras.length; j < jl; j++) {
  14669. const camera2 = cameras[j];
  14670. if (object.layers.test(camera2.layers)) {
  14671. state.viewport(_currentViewport.copy(camera2.viewport));
  14672. currentRenderState.setupLightsView(camera2);
  14673. renderObject(object, scene, camera2, geometry, material, group);
  14674. }
  14675. }
  14676. } else {
  14677. renderObject(object, scene, camera, geometry, material, group);
  14678. }
  14679. }
  14680. }
  14681. function renderObject(object, scene, camera, geometry, material, group) {
  14682. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  14683. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  14684. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  14685. if (object.isImmediateRenderObject) {
  14686. const program = setProgram(camera, scene, material, object);
  14687. state.setMaterial(material);
  14688. bindingStates.reset();
  14689. renderObjectImmediate(object, program);
  14690. } else {
  14691. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  14692. }
  14693. object.onAfterRender(_this, scene, camera, geometry, material, group);
  14694. }
  14695. function getProgram(material, scene, object) {
  14696. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  14697. const materialProperties = properties.get(material);
  14698. const lights = currentRenderState.state.lights;
  14699. const shadowsArray = currentRenderState.state.shadowsArray;
  14700. const lightsStateVersion = lights.state.version;
  14701. const parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
  14702. const programCacheKey = programCache.getProgramCacheKey(parameters);
  14703. 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
  14704. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  14705. materialProperties.fog = scene.fog;
  14706. materialProperties.envMap = cubemaps.get(material.envMap || materialProperties.environment);
  14707. if (programs === undefined) {
  14708. // new material
  14709. material.addEventListener('dispose', onMaterialDispose);
  14710. programs = new Map();
  14711. materialProperties.programs = programs;
  14712. }
  14713. let program = programs.get(programCacheKey);
  14714. if (program !== undefined) {
  14715. // early out if program and light state is identical
  14716. if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) {
  14717. updateCommonMaterialProperties(material, parameters);
  14718. return program;
  14719. }
  14720. } else {
  14721. parameters.uniforms = programCache.getUniforms(material);
  14722. material.onBuild(parameters, _this);
  14723. material.onBeforeCompile(parameters, _this);
  14724. program = programCache.acquireProgram(parameters, programCacheKey);
  14725. programs.set(programCacheKey, program);
  14726. materialProperties.uniforms = parameters.uniforms;
  14727. }
  14728. const uniforms = materialProperties.uniforms;
  14729. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  14730. uniforms.clippingPlanes = clipping.uniform;
  14731. }
  14732. updateCommonMaterialProperties(material, parameters); // store the light setup it was created for
  14733. materialProperties.needsLights = materialNeedsLights(material);
  14734. materialProperties.lightsStateVersion = lightsStateVersion;
  14735. if (materialProperties.needsLights) {
  14736. // wire up the material to this renderer's lighting state
  14737. uniforms.ambientLightColor.value = lights.state.ambient;
  14738. uniforms.lightProbe.value = lights.state.probe;
  14739. uniforms.directionalLights.value = lights.state.directional;
  14740. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  14741. uniforms.spotLights.value = lights.state.spot;
  14742. uniforms.spotLightShadows.value = lights.state.spotShadow;
  14743. uniforms.rectAreaLights.value = lights.state.rectArea;
  14744. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  14745. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  14746. uniforms.pointLights.value = lights.state.point;
  14747. uniforms.pointLightShadows.value = lights.state.pointShadow;
  14748. uniforms.hemisphereLights.value = lights.state.hemi;
  14749. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  14750. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  14751. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  14752. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  14753. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  14754. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  14755. }
  14756. const progUniforms = program.getUniforms();
  14757. const uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  14758. materialProperties.currentProgram = program;
  14759. materialProperties.uniformsList = uniformsList;
  14760. return program;
  14761. }
  14762. function updateCommonMaterialProperties(material, parameters) {
  14763. const materialProperties = properties.get(material);
  14764. materialProperties.outputEncoding = parameters.outputEncoding;
  14765. materialProperties.instancing = parameters.instancing;
  14766. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  14767. materialProperties.numIntersection = parameters.numClipIntersection;
  14768. materialProperties.vertexAlphas = parameters.vertexAlphas;
  14769. }
  14770. function setProgram(camera, scene, material, object) {
  14771. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  14772. textures.resetTextureUnits();
  14773. const fog = scene.fog;
  14774. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  14775. const encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  14776. const envMap = cubemaps.get(material.envMap || environment);
  14777. const vertexAlphas = material.vertexColors === true && object.geometry && object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4;
  14778. const materialProperties = properties.get(material);
  14779. const lights = currentRenderState.state.lights;
  14780. if (_clippingEnabled === true) {
  14781. if (_localClippingEnabled === true || camera !== _currentCamera) {
  14782. const useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  14783. // object instead of the material, once it becomes feasible
  14784. // (#8465, #8379)
  14785. clipping.setState(material, camera, useCache);
  14786. }
  14787. } //
  14788. let needsProgramChange = false;
  14789. if (material.version === materialProperties.__version) {
  14790. if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  14791. needsProgramChange = true;
  14792. } else if (materialProperties.outputEncoding !== encoding) {
  14793. needsProgramChange = true;
  14794. } else if (object.isInstancedMesh && materialProperties.instancing === false) {
  14795. needsProgramChange = true;
  14796. } else if (!object.isInstancedMesh && materialProperties.instancing === true) {
  14797. needsProgramChange = true;
  14798. } else if (materialProperties.envMap !== envMap) {
  14799. needsProgramChange = true;
  14800. } else if (material.fog && materialProperties.fog !== fog) {
  14801. needsProgramChange = true;
  14802. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
  14803. needsProgramChange = true;
  14804. } else if (materialProperties.vertexAlphas !== vertexAlphas) {
  14805. needsProgramChange = true;
  14806. }
  14807. } else {
  14808. needsProgramChange = true;
  14809. materialProperties.__version = material.version;
  14810. } //
  14811. let program = materialProperties.currentProgram;
  14812. if (needsProgramChange === true) {
  14813. program = getProgram(material, scene, object);
  14814. }
  14815. let refreshProgram = false;
  14816. let refreshMaterial = false;
  14817. let refreshLights = false;
  14818. const p_uniforms = program.getUniforms(),
  14819. m_uniforms = materialProperties.uniforms;
  14820. if (state.useProgram(program.program)) {
  14821. refreshProgram = true;
  14822. refreshMaterial = true;
  14823. refreshLights = true;
  14824. }
  14825. if (material.id !== _currentMaterialId) {
  14826. _currentMaterialId = material.id;
  14827. refreshMaterial = true;
  14828. }
  14829. if (refreshProgram || _currentCamera !== camera) {
  14830. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  14831. if (capabilities.logarithmicDepthBuffer) {
  14832. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  14833. }
  14834. if (_currentCamera !== camera) {
  14835. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  14836. // now, in case this material supports lights - or later, when
  14837. // the next material that does gets activated:
  14838. refreshMaterial = true; // set to true on material change
  14839. refreshLights = true; // remains set until update done
  14840. } // load material specific uniforms
  14841. // (shader material also gets them for the sake of genericity)
  14842. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  14843. const uCamPos = p_uniforms.map.cameraPosition;
  14844. if (uCamPos !== undefined) {
  14845. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  14846. }
  14847. }
  14848. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  14849. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  14850. }
  14851. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || material.skinning) {
  14852. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  14853. }
  14854. } // skinning uniforms must be set even if material didn't change
  14855. // auto-setting of texture unit for bone texture must go before other textures
  14856. // otherwise textures used for skinning can take over texture units reserved for other material textures
  14857. if (material.skinning) {
  14858. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  14859. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  14860. const skeleton = object.skeleton;
  14861. if (skeleton) {
  14862. const bones = skeleton.bones;
  14863. if (capabilities.floatVertexTextures) {
  14864. if (skeleton.boneTexture === null) {
  14865. // layout (1 matrix = 4 pixels)
  14866. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  14867. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  14868. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  14869. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  14870. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  14871. let size = Math.sqrt(bones.length * 4); // 4 pixels needed for 1 matrix
  14872. size = ceilPowerOfTwo(size);
  14873. size = Math.max(size, 4);
  14874. const boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  14875. boneMatrices.set(skeleton.boneMatrices); // copy current values
  14876. const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  14877. skeleton.boneMatrices = boneMatrices;
  14878. skeleton.boneTexture = boneTexture;
  14879. skeleton.boneTextureSize = size;
  14880. }
  14881. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  14882. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  14883. } else {
  14884. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  14885. }
  14886. }
  14887. }
  14888. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  14889. materialProperties.receiveShadow = object.receiveShadow;
  14890. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  14891. }
  14892. if (refreshMaterial) {
  14893. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  14894. if (materialProperties.needsLights) {
  14895. // the current material requires lighting info
  14896. // note: all lighting uniforms are always set correctly
  14897. // they simply reference the renderer's state for their
  14898. // values
  14899. //
  14900. // use the current material's .needsUpdate flags to set
  14901. // the GL state when required
  14902. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  14903. } // refresh uniforms common to several materials
  14904. if (fog && material.fog) {
  14905. materials.refreshFogUniforms(m_uniforms, fog);
  14906. }
  14907. materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height);
  14908. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  14909. }
  14910. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  14911. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  14912. material.uniformsNeedUpdate = false;
  14913. }
  14914. if (material.isSpriteMaterial) {
  14915. p_uniforms.setValue(_gl, 'center', object.center);
  14916. } // common matrices
  14917. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  14918. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  14919. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  14920. return program;
  14921. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  14922. function markUniformsLightsNeedsUpdate(uniforms, value) {
  14923. uniforms.ambientLightColor.needsUpdate = value;
  14924. uniforms.lightProbe.needsUpdate = value;
  14925. uniforms.directionalLights.needsUpdate = value;
  14926. uniforms.directionalLightShadows.needsUpdate = value;
  14927. uniforms.pointLights.needsUpdate = value;
  14928. uniforms.pointLightShadows.needsUpdate = value;
  14929. uniforms.spotLights.needsUpdate = value;
  14930. uniforms.spotLightShadows.needsUpdate = value;
  14931. uniforms.rectAreaLights.needsUpdate = value;
  14932. uniforms.hemisphereLights.needsUpdate = value;
  14933. }
  14934. function materialNeedsLights(material) {
  14935. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  14936. }
  14937. this.getActiveCubeFace = function () {
  14938. return _currentActiveCubeFace;
  14939. };
  14940. this.getActiveMipmapLevel = function () {
  14941. return _currentActiveMipmapLevel;
  14942. };
  14943. this.getRenderTarget = function () {
  14944. return _currentRenderTarget;
  14945. };
  14946. this.setRenderTarget = function (renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) {
  14947. _currentRenderTarget = renderTarget;
  14948. _currentActiveCubeFace = activeCubeFace;
  14949. _currentActiveMipmapLevel = activeMipmapLevel;
  14950. if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
  14951. textures.setupRenderTarget(renderTarget);
  14952. }
  14953. let framebuffer = null;
  14954. let isCube = false;
  14955. let isRenderTarget3D = false;
  14956. if (renderTarget) {
  14957. const texture = renderTarget.texture;
  14958. if (texture.isDataTexture3D || texture.isDataTexture2DArray) {
  14959. isRenderTarget3D = true;
  14960. }
  14961. const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  14962. if (renderTarget.isWebGLCubeRenderTarget) {
  14963. framebuffer = __webglFramebuffer[activeCubeFace];
  14964. isCube = true;
  14965. } else if (renderTarget.isWebGLMultisampleRenderTarget) {
  14966. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  14967. } else {
  14968. framebuffer = __webglFramebuffer;
  14969. }
  14970. _currentViewport.copy(renderTarget.viewport);
  14971. _currentScissor.copy(renderTarget.scissor);
  14972. _currentScissorTest = renderTarget.scissorTest;
  14973. } else {
  14974. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  14975. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  14976. _currentScissorTest = _scissorTest;
  14977. }
  14978. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  14979. state.viewport(_currentViewport);
  14980. state.scissor(_currentScissor);
  14981. state.setScissorTest(_currentScissorTest);
  14982. if (isCube) {
  14983. const textureProperties = properties.get(renderTarget.texture);
  14984. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
  14985. } else if (isRenderTarget3D) {
  14986. const textureProperties = properties.get(renderTarget.texture);
  14987. const layer = activeCubeFace || 0;
  14988. _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer);
  14989. }
  14990. };
  14991. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  14992. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  14993. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  14994. return;
  14995. }
  14996. let framebuffer = properties.get(renderTarget).__webglFramebuffer;
  14997. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  14998. framebuffer = framebuffer[activeCubeFaceIndex];
  14999. }
  15000. if (framebuffer) {
  15001. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  15002. try {
  15003. const texture = renderTarget.texture;
  15004. const textureFormat = texture.format;
  15005. const textureType = texture.type;
  15006. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_FORMAT)) {
  15007. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  15008. return;
  15009. }
  15010. const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has('EXT_color_buffer_half_float') || capabilities.isWebGL2 && extensions.has('EXT_color_buffer_float'));
  15011. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513)
  15012. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.has('OES_texture_float') || extensions.has('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  15013. !halfFloatSupportedByExt) {
  15014. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  15015. return;
  15016. }
  15017. if (_gl.checkFramebufferStatus(_gl.FRAMEBUFFER) === _gl.FRAMEBUFFER_COMPLETE) {
  15018. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  15019. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  15020. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  15021. }
  15022. } else {
  15023. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  15024. }
  15025. } finally {
  15026. // restore framebuffer of current render target if necessary
  15027. const framebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null;
  15028. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  15029. }
  15030. }
  15031. };
  15032. this.copyFramebufferToTexture = function (position, texture, level = 0) {
  15033. const levelScale = Math.pow(2, -level);
  15034. const width = Math.floor(texture.image.width * levelScale);
  15035. const height = Math.floor(texture.image.height * levelScale);
  15036. const glFormat = utils.convert(texture.format);
  15037. textures.setTexture2D(texture, 0);
  15038. _gl.copyTexImage2D(_gl.TEXTURE_2D, level, glFormat, position.x, position.y, width, height, 0);
  15039. state.unbindTexture();
  15040. };
  15041. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level = 0) {
  15042. const width = srcTexture.image.width;
  15043. const height = srcTexture.image.height;
  15044. const glFormat = utils.convert(dstTexture.format);
  15045. const glType = utils.convert(dstTexture.type);
  15046. textures.setTexture2D(dstTexture, 0); // As another texture upload may have changed pixelStorei
  15047. // parameters, make sure they are correct for the dstTexture
  15048. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  15049. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  15050. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  15051. if (srcTexture.isDataTexture) {
  15052. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  15053. } else {
  15054. if (srcTexture.isCompressedTexture) {
  15055. _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
  15056. } else {
  15057. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image);
  15058. }
  15059. } // Generate mipmaps only when copying level 0
  15060. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(_gl.TEXTURE_2D);
  15061. state.unbindTexture();
  15062. };
  15063. this.copyTextureToTexture3D = function (sourceBox, position, srcTexture, dstTexture, level = 0) {
  15064. if (_this.isWebGL1Renderer) {
  15065. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.');
  15066. return;
  15067. }
  15068. const {
  15069. width,
  15070. height,
  15071. data
  15072. } = srcTexture.image;
  15073. const glFormat = utils.convert(dstTexture.format);
  15074. const glType = utils.convert(dstTexture.type);
  15075. let glTarget;
  15076. if (dstTexture.isDataTexture3D) {
  15077. textures.setTexture3D(dstTexture, 0);
  15078. glTarget = _gl.TEXTURE_3D;
  15079. } else if (dstTexture.isDataTexture2DArray) {
  15080. textures.setTexture2DArray(dstTexture, 0);
  15081. glTarget = _gl.TEXTURE_2D_ARRAY;
  15082. } else {
  15083. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.');
  15084. return;
  15085. }
  15086. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  15087. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  15088. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  15089. const unpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH);
  15090. const unpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT);
  15091. const unpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS);
  15092. const unpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS);
  15093. const unpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES);
  15094. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, width);
  15095. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, height);
  15096. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, sourceBox.min.x);
  15097. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, sourceBox.min.y);
  15098. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, sourceBox.min.z);
  15099. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, sourceBox.max.x - sourceBox.min.x + 1, sourceBox.max.y - sourceBox.min.y + 1, sourceBox.max.z - sourceBox.min.z + 1, glFormat, glType, data);
  15100. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, unpackRowLen);
  15101. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight);
  15102. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, unpackSkipPixels);
  15103. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, unpackSkipRows);
  15104. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, unpackSkipImages); // Generate mipmaps only when copying level 0
  15105. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(glTarget);
  15106. state.unbindTexture();
  15107. };
  15108. this.initTexture = function (texture) {
  15109. textures.setTexture2D(texture, 0);
  15110. state.unbindTexture();
  15111. };
  15112. this.resetState = function () {
  15113. _currentActiveCubeFace = 0;
  15114. _currentActiveMipmapLevel = 0;
  15115. _currentRenderTarget = null;
  15116. state.reset();
  15117. bindingStates.reset();
  15118. };
  15119. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  15120. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  15121. detail: this
  15122. })); // eslint-disable-line no-undef
  15123. }
  15124. }
  15125. class WebGL1Renderer extends WebGLRenderer {}
  15126. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  15127. class FogExp2 {
  15128. constructor(color, density = 0.00025) {
  15129. this.name = '';
  15130. this.color = new Color(color);
  15131. this.density = density;
  15132. }
  15133. clone() {
  15134. return new FogExp2(this.color, this.density);
  15135. }
  15136. toJSON()
  15137. /* meta */
  15138. {
  15139. return {
  15140. type: 'FogExp2',
  15141. color: this.color.getHex(),
  15142. density: this.density
  15143. };
  15144. }
  15145. }
  15146. FogExp2.prototype.isFogExp2 = true;
  15147. class Fog {
  15148. constructor(color, near = 1, far = 1000) {
  15149. this.name = '';
  15150. this.color = new Color(color);
  15151. this.near = near;
  15152. this.far = far;
  15153. }
  15154. clone() {
  15155. return new Fog(this.color, this.near, this.far);
  15156. }
  15157. toJSON()
  15158. /* meta */
  15159. {
  15160. return {
  15161. type: 'Fog',
  15162. color: this.color.getHex(),
  15163. near: this.near,
  15164. far: this.far
  15165. };
  15166. }
  15167. }
  15168. Fog.prototype.isFog = true;
  15169. class Scene extends Object3D {
  15170. constructor() {
  15171. super();
  15172. this.type = 'Scene';
  15173. this.background = null;
  15174. this.environment = null;
  15175. this.fog = null;
  15176. this.overrideMaterial = null;
  15177. this.autoUpdate = true; // checked by the renderer
  15178. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  15179. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  15180. detail: this
  15181. })); // eslint-disable-line no-undef
  15182. }
  15183. }
  15184. copy(source, recursive) {
  15185. super.copy(source, recursive);
  15186. if (source.background !== null) this.background = source.background.clone();
  15187. if (source.environment !== null) this.environment = source.environment.clone();
  15188. if (source.fog !== null) this.fog = source.fog.clone();
  15189. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  15190. this.autoUpdate = source.autoUpdate;
  15191. this.matrixAutoUpdate = source.matrixAutoUpdate;
  15192. return this;
  15193. }
  15194. toJSON(meta) {
  15195. const data = super.toJSON(meta);
  15196. if (this.background !== null) data.object.background = this.background.toJSON(meta);
  15197. if (this.environment !== null) data.object.environment = this.environment.toJSON(meta);
  15198. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  15199. return data;
  15200. }
  15201. }
  15202. Scene.prototype.isScene = true;
  15203. class InterleavedBuffer {
  15204. constructor(array, stride) {
  15205. this.array = array;
  15206. this.stride = stride;
  15207. this.count = array !== undefined ? array.length / stride : 0;
  15208. this.usage = StaticDrawUsage;
  15209. this.updateRange = {
  15210. offset: 0,
  15211. count: -1
  15212. };
  15213. this.version = 0;
  15214. this.uuid = generateUUID();
  15215. this.onUploadCallback = function () {};
  15216. }
  15217. set needsUpdate(value) {
  15218. if (value === true) this.version++;
  15219. }
  15220. setUsage(value) {
  15221. this.usage = value;
  15222. return this;
  15223. }
  15224. copy(source) {
  15225. this.array = new source.array.constructor(source.array);
  15226. this.count = source.count;
  15227. this.stride = source.stride;
  15228. this.usage = source.usage;
  15229. return this;
  15230. }
  15231. copyAt(index1, attribute, index2) {
  15232. index1 *= this.stride;
  15233. index2 *= attribute.stride;
  15234. for (let i = 0, l = this.stride; i < l; i++) {
  15235. this.array[index1 + i] = attribute.array[index2 + i];
  15236. }
  15237. return this;
  15238. }
  15239. set(value, offset = 0) {
  15240. this.array.set(value, offset);
  15241. return this;
  15242. }
  15243. clone(data) {
  15244. if (data.arrayBuffers === undefined) {
  15245. data.arrayBuffers = {};
  15246. }
  15247. if (this.array.buffer._uuid === undefined) {
  15248. this.array.buffer._uuid = generateUUID();
  15249. }
  15250. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  15251. data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
  15252. }
  15253. const array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
  15254. const ib = new InterleavedBuffer(array, this.stride);
  15255. ib.setUsage(this.usage);
  15256. return ib;
  15257. }
  15258. onUpload(callback) {
  15259. this.onUploadCallback = callback;
  15260. return this;
  15261. }
  15262. toJSON(data) {
  15263. if (data.arrayBuffers === undefined) {
  15264. data.arrayBuffers = {};
  15265. } // generate UUID for array buffer if necessary
  15266. if (this.array.buffer._uuid === undefined) {
  15267. this.array.buffer._uuid = generateUUID();
  15268. }
  15269. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  15270. data.arrayBuffers[this.array.buffer._uuid] = Array.prototype.slice.call(new Uint32Array(this.array.buffer));
  15271. } //
  15272. return {
  15273. uuid: this.uuid,
  15274. buffer: this.array.buffer._uuid,
  15275. type: this.array.constructor.name,
  15276. stride: this.stride
  15277. };
  15278. }
  15279. }
  15280. InterleavedBuffer.prototype.isInterleavedBuffer = true;
  15281. const _vector$6 = new /*@__PURE__*/Vector3();
  15282. class InterleavedBufferAttribute {
  15283. constructor(interleavedBuffer, itemSize, offset, normalized) {
  15284. this.name = '';
  15285. this.data = interleavedBuffer;
  15286. this.itemSize = itemSize;
  15287. this.offset = offset;
  15288. this.normalized = normalized === true;
  15289. }
  15290. get count() {
  15291. return this.data.count;
  15292. }
  15293. get array() {
  15294. return this.data.array;
  15295. }
  15296. set needsUpdate(value) {
  15297. this.data.needsUpdate = value;
  15298. }
  15299. applyMatrix4(m) {
  15300. for (let i = 0, l = this.data.count; i < l; i++) {
  15301. _vector$6.x = this.getX(i);
  15302. _vector$6.y = this.getY(i);
  15303. _vector$6.z = this.getZ(i);
  15304. _vector$6.applyMatrix4(m);
  15305. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  15306. }
  15307. return this;
  15308. }
  15309. applyNormalMatrix(m) {
  15310. for (let i = 0, l = this.count; i < l; i++) {
  15311. _vector$6.x = this.getX(i);
  15312. _vector$6.y = this.getY(i);
  15313. _vector$6.z = this.getZ(i);
  15314. _vector$6.applyNormalMatrix(m);
  15315. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  15316. }
  15317. return this;
  15318. }
  15319. transformDirection(m) {
  15320. for (let i = 0, l = this.count; i < l; i++) {
  15321. _vector$6.x = this.getX(i);
  15322. _vector$6.y = this.getY(i);
  15323. _vector$6.z = this.getZ(i);
  15324. _vector$6.transformDirection(m);
  15325. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  15326. }
  15327. return this;
  15328. }
  15329. setX(index, x) {
  15330. this.data.array[index * this.data.stride + this.offset] = x;
  15331. return this;
  15332. }
  15333. setY(index, y) {
  15334. this.data.array[index * this.data.stride + this.offset + 1] = y;
  15335. return this;
  15336. }
  15337. setZ(index, z) {
  15338. this.data.array[index * this.data.stride + this.offset + 2] = z;
  15339. return this;
  15340. }
  15341. setW(index, w) {
  15342. this.data.array[index * this.data.stride + this.offset + 3] = w;
  15343. return this;
  15344. }
  15345. getX(index) {
  15346. return this.data.array[index * this.data.stride + this.offset];
  15347. }
  15348. getY(index) {
  15349. return this.data.array[index * this.data.stride + this.offset + 1];
  15350. }
  15351. getZ(index) {
  15352. return this.data.array[index * this.data.stride + this.offset + 2];
  15353. }
  15354. getW(index) {
  15355. return this.data.array[index * this.data.stride + this.offset + 3];
  15356. }
  15357. setXY(index, x, y) {
  15358. index = index * this.data.stride + this.offset;
  15359. this.data.array[index + 0] = x;
  15360. this.data.array[index + 1] = y;
  15361. return this;
  15362. }
  15363. setXYZ(index, x, y, z) {
  15364. index = index * this.data.stride + this.offset;
  15365. this.data.array[index + 0] = x;
  15366. this.data.array[index + 1] = y;
  15367. this.data.array[index + 2] = z;
  15368. return this;
  15369. }
  15370. setXYZW(index, x, y, z, w) {
  15371. index = index * this.data.stride + this.offset;
  15372. this.data.array[index + 0] = x;
  15373. this.data.array[index + 1] = y;
  15374. this.data.array[index + 2] = z;
  15375. this.data.array[index + 3] = w;
  15376. return this;
  15377. }
  15378. clone(data) {
  15379. if (data === undefined) {
  15380. console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.');
  15381. const array = [];
  15382. for (let i = 0; i < this.count; i++) {
  15383. const index = i * this.data.stride + this.offset;
  15384. for (let j = 0; j < this.itemSize; j++) {
  15385. array.push(this.data.array[index + j]);
  15386. }
  15387. }
  15388. return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
  15389. } else {
  15390. if (data.interleavedBuffers === undefined) {
  15391. data.interleavedBuffers = {};
  15392. }
  15393. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  15394. data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
  15395. }
  15396. return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  15397. }
  15398. }
  15399. toJSON(data) {
  15400. if (data === undefined) {
  15401. console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.');
  15402. const array = [];
  15403. for (let i = 0; i < this.count; i++) {
  15404. const index = i * this.data.stride + this.offset;
  15405. for (let j = 0; j < this.itemSize; j++) {
  15406. array.push(this.data.array[index + j]);
  15407. }
  15408. } // deinterleave data and save it as an ordinary buffer attribute for now
  15409. return {
  15410. itemSize: this.itemSize,
  15411. type: this.array.constructor.name,
  15412. array: array,
  15413. normalized: this.normalized
  15414. };
  15415. } else {
  15416. // save as true interlaved attribtue
  15417. if (data.interleavedBuffers === undefined) {
  15418. data.interleavedBuffers = {};
  15419. }
  15420. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  15421. data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
  15422. }
  15423. return {
  15424. isInterleavedBufferAttribute: true,
  15425. itemSize: this.itemSize,
  15426. data: this.data.uuid,
  15427. offset: this.offset,
  15428. normalized: this.normalized
  15429. };
  15430. }
  15431. }
  15432. }
  15433. InterleavedBufferAttribute.prototype.isInterleavedBufferAttribute = true;
  15434. /**
  15435. * parameters = {
  15436. * color: <hex>,
  15437. * map: new THREE.Texture( <Image> ),
  15438. * alphaMap: new THREE.Texture( <Image> ),
  15439. * rotation: <float>,
  15440. * sizeAttenuation: <bool>
  15441. * }
  15442. */
  15443. class SpriteMaterial extends Material {
  15444. constructor(parameters) {
  15445. super();
  15446. this.type = 'SpriteMaterial';
  15447. this.color = new Color(0xffffff);
  15448. this.map = null;
  15449. this.alphaMap = null;
  15450. this.rotation = 0;
  15451. this.sizeAttenuation = true;
  15452. this.transparent = true;
  15453. this.setValues(parameters);
  15454. }
  15455. copy(source) {
  15456. super.copy(source);
  15457. this.color.copy(source.color);
  15458. this.map = source.map;
  15459. this.alphaMap = source.alphaMap;
  15460. this.rotation = source.rotation;
  15461. this.sizeAttenuation = source.sizeAttenuation;
  15462. return this;
  15463. }
  15464. }
  15465. SpriteMaterial.prototype.isSpriteMaterial = true;
  15466. let _geometry;
  15467. const _intersectPoint = /*@__PURE__*/new Vector3();
  15468. const _worldScale = /*@__PURE__*/new Vector3();
  15469. const _mvPosition = /*@__PURE__*/new Vector3();
  15470. const _alignedPosition = /*@__PURE__*/new Vector2();
  15471. const _rotatedPosition = /*@__PURE__*/new Vector2();
  15472. const _viewWorldMatrix = /*@__PURE__*/new Matrix4();
  15473. const _vA = /*@__PURE__*/new Vector3();
  15474. const _vB = /*@__PURE__*/new Vector3();
  15475. const _vC = /*@__PURE__*/new Vector3();
  15476. const _uvA = /*@__PURE__*/new Vector2();
  15477. const _uvB = /*@__PURE__*/new Vector2();
  15478. const _uvC = /*@__PURE__*/new Vector2();
  15479. class Sprite extends Object3D {
  15480. constructor(material) {
  15481. super();
  15482. this.type = 'Sprite';
  15483. if (_geometry === undefined) {
  15484. _geometry = new BufferGeometry();
  15485. 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]);
  15486. const interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  15487. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  15488. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  15489. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  15490. }
  15491. this.geometry = _geometry;
  15492. this.material = material !== undefined ? material : new SpriteMaterial();
  15493. this.center = new Vector2(0.5, 0.5);
  15494. }
  15495. raycast(raycaster, intersects) {
  15496. if (raycaster.camera === null) {
  15497. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  15498. }
  15499. _worldScale.setFromMatrixScale(this.matrixWorld);
  15500. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  15501. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  15502. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  15503. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  15504. _worldScale.multiplyScalar(-_mvPosition.z);
  15505. }
  15506. const rotation = this.material.rotation;
  15507. let sin, cos;
  15508. if (rotation !== 0) {
  15509. cos = Math.cos(rotation);
  15510. sin = Math.sin(rotation);
  15511. }
  15512. const center = this.center;
  15513. transformVertex(_vA.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15514. transformVertex(_vB.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15515. transformVertex(_vC.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15516. _uvA.set(0, 0);
  15517. _uvB.set(1, 0);
  15518. _uvC.set(1, 1); // check first triangle
  15519. let intersect = raycaster.ray.intersectTriangle(_vA, _vB, _vC, false, _intersectPoint);
  15520. if (intersect === null) {
  15521. // check second triangle
  15522. transformVertex(_vB.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15523. _uvB.set(0, 1);
  15524. intersect = raycaster.ray.intersectTriangle(_vA, _vC, _vB, false, _intersectPoint);
  15525. if (intersect === null) {
  15526. return;
  15527. }
  15528. }
  15529. const distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  15530. if (distance < raycaster.near || distance > raycaster.far) return;
  15531. intersects.push({
  15532. distance: distance,
  15533. point: _intersectPoint.clone(),
  15534. uv: Triangle.getUV(_intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2()),
  15535. face: null,
  15536. object: this
  15537. });
  15538. }
  15539. copy(source) {
  15540. super.copy(source);
  15541. if (source.center !== undefined) this.center.copy(source.center);
  15542. this.material = source.material;
  15543. return this;
  15544. }
  15545. }
  15546. Sprite.prototype.isSprite = true;
  15547. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  15548. // compute position in camera space
  15549. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  15550. if (sin !== undefined) {
  15551. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  15552. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  15553. } else {
  15554. _rotatedPosition.copy(_alignedPosition);
  15555. }
  15556. vertexPosition.copy(mvPosition);
  15557. vertexPosition.x += _rotatedPosition.x;
  15558. vertexPosition.y += _rotatedPosition.y; // transform to world space
  15559. vertexPosition.applyMatrix4(_viewWorldMatrix);
  15560. }
  15561. const _v1$2 = /*@__PURE__*/new Vector3();
  15562. const _v2$1 = /*@__PURE__*/new Vector3();
  15563. class LOD extends Object3D {
  15564. constructor() {
  15565. super();
  15566. this._currentLevel = 0;
  15567. this.type = 'LOD';
  15568. Object.defineProperties(this, {
  15569. levels: {
  15570. enumerable: true,
  15571. value: []
  15572. },
  15573. isLOD: {
  15574. value: true
  15575. }
  15576. });
  15577. this.autoUpdate = true;
  15578. }
  15579. copy(source) {
  15580. super.copy(source, false);
  15581. const levels = source.levels;
  15582. for (let i = 0, l = levels.length; i < l; i++) {
  15583. const level = levels[i];
  15584. this.addLevel(level.object.clone(), level.distance);
  15585. }
  15586. this.autoUpdate = source.autoUpdate;
  15587. return this;
  15588. }
  15589. addLevel(object, distance = 0) {
  15590. distance = Math.abs(distance);
  15591. const levels = this.levels;
  15592. let l;
  15593. for (l = 0; l < levels.length; l++) {
  15594. if (distance < levels[l].distance) {
  15595. break;
  15596. }
  15597. }
  15598. levels.splice(l, 0, {
  15599. distance: distance,
  15600. object: object
  15601. });
  15602. this.add(object);
  15603. return this;
  15604. }
  15605. getCurrentLevel() {
  15606. return this._currentLevel;
  15607. }
  15608. getObjectForDistance(distance) {
  15609. const levels = this.levels;
  15610. if (levels.length > 0) {
  15611. let i, l;
  15612. for (i = 1, l = levels.length; i < l; i++) {
  15613. if (distance < levels[i].distance) {
  15614. break;
  15615. }
  15616. }
  15617. return levels[i - 1].object;
  15618. }
  15619. return null;
  15620. }
  15621. raycast(raycaster, intersects) {
  15622. const levels = this.levels;
  15623. if (levels.length > 0) {
  15624. _v1$2.setFromMatrixPosition(this.matrixWorld);
  15625. const distance = raycaster.ray.origin.distanceTo(_v1$2);
  15626. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  15627. }
  15628. }
  15629. update(camera) {
  15630. const levels = this.levels;
  15631. if (levels.length > 1) {
  15632. _v1$2.setFromMatrixPosition(camera.matrixWorld);
  15633. _v2$1.setFromMatrixPosition(this.matrixWorld);
  15634. const distance = _v1$2.distanceTo(_v2$1) / camera.zoom;
  15635. levels[0].object.visible = true;
  15636. let i, l;
  15637. for (i = 1, l = levels.length; i < l; i++) {
  15638. if (distance >= levels[i].distance) {
  15639. levels[i - 1].object.visible = false;
  15640. levels[i].object.visible = true;
  15641. } else {
  15642. break;
  15643. }
  15644. }
  15645. this._currentLevel = i - 1;
  15646. for (; i < l; i++) {
  15647. levels[i].object.visible = false;
  15648. }
  15649. }
  15650. }
  15651. toJSON(meta) {
  15652. const data = super.toJSON(meta);
  15653. if (this.autoUpdate === false) data.object.autoUpdate = false;
  15654. data.object.levels = [];
  15655. const levels = this.levels;
  15656. for (let i = 0, l = levels.length; i < l; i++) {
  15657. const level = levels[i];
  15658. data.object.levels.push({
  15659. object: level.object.uuid,
  15660. distance: level.distance
  15661. });
  15662. }
  15663. return data;
  15664. }
  15665. }
  15666. const _basePosition = /*@__PURE__*/new Vector3();
  15667. const _skinIndex = /*@__PURE__*/new Vector4();
  15668. const _skinWeight = /*@__PURE__*/new Vector4();
  15669. const _vector$5 = /*@__PURE__*/new Vector3();
  15670. const _matrix = /*@__PURE__*/new Matrix4();
  15671. class SkinnedMesh extends Mesh {
  15672. constructor(geometry, material) {
  15673. super(geometry, material);
  15674. this.type = 'SkinnedMesh';
  15675. this.bindMode = 'attached';
  15676. this.bindMatrix = new Matrix4();
  15677. this.bindMatrixInverse = new Matrix4();
  15678. }
  15679. copy(source) {
  15680. super.copy(source);
  15681. this.bindMode = source.bindMode;
  15682. this.bindMatrix.copy(source.bindMatrix);
  15683. this.bindMatrixInverse.copy(source.bindMatrixInverse);
  15684. this.skeleton = source.skeleton;
  15685. return this;
  15686. }
  15687. bind(skeleton, bindMatrix) {
  15688. this.skeleton = skeleton;
  15689. if (bindMatrix === undefined) {
  15690. this.updateMatrixWorld(true);
  15691. this.skeleton.calculateInverses();
  15692. bindMatrix = this.matrixWorld;
  15693. }
  15694. this.bindMatrix.copy(bindMatrix);
  15695. this.bindMatrixInverse.copy(bindMatrix).invert();
  15696. }
  15697. pose() {
  15698. this.skeleton.pose();
  15699. }
  15700. normalizeSkinWeights() {
  15701. const vector = new Vector4();
  15702. const skinWeight = this.geometry.attributes.skinWeight;
  15703. for (let i = 0, l = skinWeight.count; i < l; i++) {
  15704. vector.x = skinWeight.getX(i);
  15705. vector.y = skinWeight.getY(i);
  15706. vector.z = skinWeight.getZ(i);
  15707. vector.w = skinWeight.getW(i);
  15708. const scale = 1.0 / vector.manhattanLength();
  15709. if (scale !== Infinity) {
  15710. vector.multiplyScalar(scale);
  15711. } else {
  15712. vector.set(1, 0, 0, 0); // do something reasonable
  15713. }
  15714. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  15715. }
  15716. }
  15717. updateMatrixWorld(force) {
  15718. super.updateMatrixWorld(force);
  15719. if (this.bindMode === 'attached') {
  15720. this.bindMatrixInverse.copy(this.matrixWorld).invert();
  15721. } else if (this.bindMode === 'detached') {
  15722. this.bindMatrixInverse.copy(this.bindMatrix).invert();
  15723. } else {
  15724. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  15725. }
  15726. }
  15727. boneTransform(index, target) {
  15728. const skeleton = this.skeleton;
  15729. const geometry = this.geometry;
  15730. _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
  15731. _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
  15732. _basePosition.fromBufferAttribute(geometry.attributes.position, index).applyMatrix4(this.bindMatrix);
  15733. target.set(0, 0, 0);
  15734. for (let i = 0; i < 4; i++) {
  15735. const weight = _skinWeight.getComponent(i);
  15736. if (weight !== 0) {
  15737. const boneIndex = _skinIndex.getComponent(i);
  15738. _matrix.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
  15739. target.addScaledVector(_vector$5.copy(_basePosition).applyMatrix4(_matrix), weight);
  15740. }
  15741. }
  15742. return target.applyMatrix4(this.bindMatrixInverse);
  15743. }
  15744. }
  15745. SkinnedMesh.prototype.isSkinnedMesh = true;
  15746. class Bone extends Object3D {
  15747. constructor() {
  15748. super();
  15749. this.type = 'Bone';
  15750. }
  15751. }
  15752. Bone.prototype.isBone = true;
  15753. const _offsetMatrix = /*@__PURE__*/new Matrix4();
  15754. const _identityMatrix = /*@__PURE__*/new Matrix4();
  15755. class Skeleton {
  15756. constructor(bones = [], boneInverses = []) {
  15757. this.uuid = generateUUID();
  15758. this.bones = bones.slice(0);
  15759. this.boneInverses = boneInverses;
  15760. this.boneMatrices = null;
  15761. this.boneTexture = null;
  15762. this.boneTextureSize = 0;
  15763. this.frame = -1;
  15764. this.init();
  15765. }
  15766. init() {
  15767. const bones = this.bones;
  15768. const boneInverses = this.boneInverses;
  15769. this.boneMatrices = new Float32Array(bones.length * 16); // calculate inverse bone matrices if necessary
  15770. if (boneInverses.length === 0) {
  15771. this.calculateInverses();
  15772. } else {
  15773. // handle special case
  15774. if (bones.length !== boneInverses.length) {
  15775. console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
  15776. this.boneInverses = [];
  15777. for (let i = 0, il = this.bones.length; i < il; i++) {
  15778. this.boneInverses.push(new Matrix4());
  15779. }
  15780. }
  15781. }
  15782. }
  15783. calculateInverses() {
  15784. this.boneInverses.length = 0;
  15785. for (let i = 0, il = this.bones.length; i < il; i++) {
  15786. const inverse = new Matrix4();
  15787. if (this.bones[i]) {
  15788. inverse.copy(this.bones[i].matrixWorld).invert();
  15789. }
  15790. this.boneInverses.push(inverse);
  15791. }
  15792. }
  15793. pose() {
  15794. // recover the bind-time world matrices
  15795. for (let i = 0, il = this.bones.length; i < il; i++) {
  15796. const bone = this.bones[i];
  15797. if (bone) {
  15798. bone.matrixWorld.copy(this.boneInverses[i]).invert();
  15799. }
  15800. } // compute the local matrices, positions, rotations and scales
  15801. for (let i = 0, il = this.bones.length; i < il; i++) {
  15802. const bone = this.bones[i];
  15803. if (bone) {
  15804. if (bone.parent && bone.parent.isBone) {
  15805. bone.matrix.copy(bone.parent.matrixWorld).invert();
  15806. bone.matrix.multiply(bone.matrixWorld);
  15807. } else {
  15808. bone.matrix.copy(bone.matrixWorld);
  15809. }
  15810. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  15811. }
  15812. }
  15813. }
  15814. update() {
  15815. const bones = this.bones;
  15816. const boneInverses = this.boneInverses;
  15817. const boneMatrices = this.boneMatrices;
  15818. const boneTexture = this.boneTexture; // flatten bone matrices to array
  15819. for (let i = 0, il = bones.length; i < il; i++) {
  15820. // compute the offset between the current and the original transform
  15821. const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  15822. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  15823. _offsetMatrix.toArray(boneMatrices, i * 16);
  15824. }
  15825. if (boneTexture !== null) {
  15826. boneTexture.needsUpdate = true;
  15827. }
  15828. }
  15829. clone() {
  15830. return new Skeleton(this.bones, this.boneInverses);
  15831. }
  15832. getBoneByName(name) {
  15833. for (let i = 0, il = this.bones.length; i < il; i++) {
  15834. const bone = this.bones[i];
  15835. if (bone.name === name) {
  15836. return bone;
  15837. }
  15838. }
  15839. return undefined;
  15840. }
  15841. dispose() {
  15842. if (this.boneTexture !== null) {
  15843. this.boneTexture.dispose();
  15844. this.boneTexture = null;
  15845. }
  15846. }
  15847. fromJSON(json, bones) {
  15848. this.uuid = json.uuid;
  15849. for (let i = 0, l = json.bones.length; i < l; i++) {
  15850. const uuid = json.bones[i];
  15851. let bone = bones[uuid];
  15852. if (bone === undefined) {
  15853. console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
  15854. bone = new Bone();
  15855. }
  15856. this.bones.push(bone);
  15857. this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
  15858. }
  15859. this.init();
  15860. return this;
  15861. }
  15862. toJSON() {
  15863. const data = {
  15864. metadata: {
  15865. version: 4.5,
  15866. type: 'Skeleton',
  15867. generator: 'Skeleton.toJSON'
  15868. },
  15869. bones: [],
  15870. boneInverses: []
  15871. };
  15872. data.uuid = this.uuid;
  15873. const bones = this.bones;
  15874. const boneInverses = this.boneInverses;
  15875. for (let i = 0, l = bones.length; i < l; i++) {
  15876. const bone = bones[i];
  15877. data.bones.push(bone.uuid);
  15878. const boneInverse = boneInverses[i];
  15879. data.boneInverses.push(boneInverse.toArray());
  15880. }
  15881. return data;
  15882. }
  15883. }
  15884. const _instanceLocalMatrix = /*@__PURE__*/new Matrix4();
  15885. const _instanceWorldMatrix = /*@__PURE__*/new Matrix4();
  15886. const _instanceIntersects = [];
  15887. const _mesh = /*@__PURE__*/new Mesh();
  15888. class InstancedMesh extends Mesh {
  15889. constructor(geometry, material, count) {
  15890. super(geometry, material);
  15891. this.instanceMatrix = new BufferAttribute(new Float32Array(count * 16), 16);
  15892. this.instanceColor = null;
  15893. this.count = count;
  15894. this.frustumCulled = false;
  15895. }
  15896. copy(source) {
  15897. super.copy(source);
  15898. this.instanceMatrix.copy(source.instanceMatrix);
  15899. if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone();
  15900. this.count = source.count;
  15901. return this;
  15902. }
  15903. getColorAt(index, color) {
  15904. color.fromArray(this.instanceColor.array, index * 3);
  15905. }
  15906. getMatrixAt(index, matrix) {
  15907. matrix.fromArray(this.instanceMatrix.array, index * 16);
  15908. }
  15909. raycast(raycaster, intersects) {
  15910. const matrixWorld = this.matrixWorld;
  15911. const raycastTimes = this.count;
  15912. _mesh.geometry = this.geometry;
  15913. _mesh.material = this.material;
  15914. if (_mesh.material === undefined) return;
  15915. for (let instanceId = 0; instanceId < raycastTimes; instanceId++) {
  15916. // calculate the world matrix for each instance
  15917. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  15918. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
  15919. _mesh.matrixWorld = _instanceWorldMatrix;
  15920. _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
  15921. for (let i = 0, l = _instanceIntersects.length; i < l; i++) {
  15922. const intersect = _instanceIntersects[i];
  15923. intersect.instanceId = instanceId;
  15924. intersect.object = this;
  15925. intersects.push(intersect);
  15926. }
  15927. _instanceIntersects.length = 0;
  15928. }
  15929. }
  15930. setColorAt(index, color) {
  15931. if (this.instanceColor === null) {
  15932. this.instanceColor = new BufferAttribute(new Float32Array(this.count * 3), 3);
  15933. }
  15934. color.toArray(this.instanceColor.array, index * 3);
  15935. }
  15936. setMatrixAt(index, matrix) {
  15937. matrix.toArray(this.instanceMatrix.array, index * 16);
  15938. }
  15939. updateMorphTargets() {}
  15940. dispose() {
  15941. this.dispatchEvent({
  15942. type: 'dispose'
  15943. });
  15944. }
  15945. }
  15946. InstancedMesh.prototype.isInstancedMesh = true;
  15947. /**
  15948. * parameters = {
  15949. * color: <hex>,
  15950. * opacity: <float>,
  15951. *
  15952. * linewidth: <float>,
  15953. * linecap: "round",
  15954. * linejoin: "round"
  15955. * }
  15956. */
  15957. class LineBasicMaterial extends Material {
  15958. constructor(parameters) {
  15959. super();
  15960. this.type = 'LineBasicMaterial';
  15961. this.color = new Color(0xffffff);
  15962. this.linewidth = 1;
  15963. this.linecap = 'round';
  15964. this.linejoin = 'round';
  15965. this.morphTargets = false;
  15966. this.setValues(parameters);
  15967. }
  15968. copy(source) {
  15969. super.copy(source);
  15970. this.color.copy(source.color);
  15971. this.linewidth = source.linewidth;
  15972. this.linecap = source.linecap;
  15973. this.linejoin = source.linejoin;
  15974. this.morphTargets = source.morphTargets;
  15975. return this;
  15976. }
  15977. }
  15978. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  15979. const _start$1 = /*@__PURE__*/new Vector3();
  15980. const _end$1 = /*@__PURE__*/new Vector3();
  15981. const _inverseMatrix$1 = /*@__PURE__*/new Matrix4();
  15982. const _ray$1 = /*@__PURE__*/new Ray();
  15983. const _sphere$1 = /*@__PURE__*/new Sphere();
  15984. class Line extends Object3D {
  15985. constructor(geometry = new BufferGeometry(), material = new LineBasicMaterial()) {
  15986. super();
  15987. this.type = 'Line';
  15988. this.geometry = geometry;
  15989. this.material = material;
  15990. this.updateMorphTargets();
  15991. }
  15992. copy(source) {
  15993. super.copy(source);
  15994. this.material = source.material;
  15995. this.geometry = source.geometry;
  15996. return this;
  15997. }
  15998. computeLineDistances() {
  15999. const geometry = this.geometry;
  16000. if (geometry.isBufferGeometry) {
  16001. // we assume non-indexed geometry
  16002. if (geometry.index === null) {
  16003. const positionAttribute = geometry.attributes.position;
  16004. const lineDistances = [0];
  16005. for (let i = 1, l = positionAttribute.count; i < l; i++) {
  16006. _start$1.fromBufferAttribute(positionAttribute, i - 1);
  16007. _end$1.fromBufferAttribute(positionAttribute, i);
  16008. lineDistances[i] = lineDistances[i - 1];
  16009. lineDistances[i] += _start$1.distanceTo(_end$1);
  16010. }
  16011. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16012. } else {
  16013. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16014. }
  16015. } else if (geometry.isGeometry) {
  16016. console.error('THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16017. }
  16018. return this;
  16019. }
  16020. raycast(raycaster, intersects) {
  16021. const geometry = this.geometry;
  16022. const matrixWorld = this.matrixWorld;
  16023. const threshold = raycaster.params.Line.threshold;
  16024. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  16025. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16026. _sphere$1.copy(geometry.boundingSphere);
  16027. _sphere$1.applyMatrix4(matrixWorld);
  16028. _sphere$1.radius += threshold;
  16029. if (raycaster.ray.intersectsSphere(_sphere$1) === false) return; //
  16030. _inverseMatrix$1.copy(matrixWorld).invert();
  16031. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  16032. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16033. const localThresholdSq = localThreshold * localThreshold;
  16034. const vStart = new Vector3();
  16035. const vEnd = new Vector3();
  16036. const interSegment = new Vector3();
  16037. const interRay = new Vector3();
  16038. const step = this.isLineSegments ? 2 : 1;
  16039. if (geometry.isBufferGeometry) {
  16040. const index = geometry.index;
  16041. const attributes = geometry.attributes;
  16042. const positionAttribute = attributes.position;
  16043. if (index !== null) {
  16044. const start = Math.max(0, drawRange.start);
  16045. const end = Math.min(index.count, drawRange.start + drawRange.count);
  16046. for (let i = start, l = end - 1; i < l; i += step) {
  16047. const a = index.getX(i);
  16048. const b = index.getX(i + 1);
  16049. vStart.fromBufferAttribute(positionAttribute, a);
  16050. vEnd.fromBufferAttribute(positionAttribute, b);
  16051. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16052. if (distSq > localThresholdSq) continue;
  16053. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16054. const distance = raycaster.ray.origin.distanceTo(interRay);
  16055. if (distance < raycaster.near || distance > raycaster.far) continue;
  16056. intersects.push({
  16057. distance: distance,
  16058. // What do we want? intersection point on the ray or on the segment??
  16059. // point: raycaster.ray.at( distance ),
  16060. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16061. index: i,
  16062. face: null,
  16063. faceIndex: null,
  16064. object: this
  16065. });
  16066. }
  16067. } else {
  16068. const start = Math.max(0, drawRange.start);
  16069. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  16070. for (let i = start, l = end - 1; i < l; i += step) {
  16071. vStart.fromBufferAttribute(positionAttribute, i);
  16072. vEnd.fromBufferAttribute(positionAttribute, i + 1);
  16073. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16074. if (distSq > localThresholdSq) continue;
  16075. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16076. const distance = raycaster.ray.origin.distanceTo(interRay);
  16077. if (distance < raycaster.near || distance > raycaster.far) continue;
  16078. intersects.push({
  16079. distance: distance,
  16080. // What do we want? intersection point on the ray or on the segment??
  16081. // point: raycaster.ray.at( distance ),
  16082. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16083. index: i,
  16084. face: null,
  16085. faceIndex: null,
  16086. object: this
  16087. });
  16088. }
  16089. }
  16090. } else if (geometry.isGeometry) {
  16091. console.error('THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16092. }
  16093. }
  16094. updateMorphTargets() {
  16095. const geometry = this.geometry;
  16096. if (geometry.isBufferGeometry) {
  16097. const morphAttributes = geometry.morphAttributes;
  16098. const keys = Object.keys(morphAttributes);
  16099. if (keys.length > 0) {
  16100. const morphAttribute = morphAttributes[keys[0]];
  16101. if (morphAttribute !== undefined) {
  16102. this.morphTargetInfluences = [];
  16103. this.morphTargetDictionary = {};
  16104. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  16105. const name = morphAttribute[m].name || String(m);
  16106. this.morphTargetInfluences.push(0);
  16107. this.morphTargetDictionary[name] = m;
  16108. }
  16109. }
  16110. }
  16111. } else {
  16112. const morphTargets = geometry.morphTargets;
  16113. if (morphTargets !== undefined && morphTargets.length > 0) {
  16114. console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  16115. }
  16116. }
  16117. }
  16118. }
  16119. Line.prototype.isLine = true;
  16120. const _start = /*@__PURE__*/new Vector3();
  16121. const _end = /*@__PURE__*/new Vector3();
  16122. class LineSegments extends Line {
  16123. constructor(geometry, material) {
  16124. super(geometry, material);
  16125. this.type = 'LineSegments';
  16126. }
  16127. computeLineDistances() {
  16128. const geometry = this.geometry;
  16129. if (geometry.isBufferGeometry) {
  16130. // we assume non-indexed geometry
  16131. if (geometry.index === null) {
  16132. const positionAttribute = geometry.attributes.position;
  16133. const lineDistances = [];
  16134. for (let i = 0, l = positionAttribute.count; i < l; i += 2) {
  16135. _start.fromBufferAttribute(positionAttribute, i);
  16136. _end.fromBufferAttribute(positionAttribute, i + 1);
  16137. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  16138. lineDistances[i + 1] = lineDistances[i] + _start.distanceTo(_end);
  16139. }
  16140. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16141. } else {
  16142. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16143. }
  16144. } else if (geometry.isGeometry) {
  16145. console.error('THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16146. }
  16147. return this;
  16148. }
  16149. }
  16150. LineSegments.prototype.isLineSegments = true;
  16151. class LineLoop extends Line {
  16152. constructor(geometry, material) {
  16153. super(geometry, material);
  16154. this.type = 'LineLoop';
  16155. }
  16156. }
  16157. LineLoop.prototype.isLineLoop = true;
  16158. /**
  16159. * parameters = {
  16160. * color: <hex>,
  16161. * opacity: <float>,
  16162. * map: new THREE.Texture( <Image> ),
  16163. * alphaMap: new THREE.Texture( <Image> ),
  16164. *
  16165. * size: <float>,
  16166. * sizeAttenuation: <bool>
  16167. *
  16168. * morphTargets: <bool>
  16169. * }
  16170. */
  16171. class PointsMaterial extends Material {
  16172. constructor(parameters) {
  16173. super();
  16174. this.type = 'PointsMaterial';
  16175. this.color = new Color(0xffffff);
  16176. this.map = null;
  16177. this.alphaMap = null;
  16178. this.size = 1;
  16179. this.sizeAttenuation = true;
  16180. this.morphTargets = false;
  16181. this.setValues(parameters);
  16182. }
  16183. copy(source) {
  16184. super.copy(source);
  16185. this.color.copy(source.color);
  16186. this.map = source.map;
  16187. this.alphaMap = source.alphaMap;
  16188. this.size = source.size;
  16189. this.sizeAttenuation = source.sizeAttenuation;
  16190. this.morphTargets = source.morphTargets;
  16191. return this;
  16192. }
  16193. }
  16194. PointsMaterial.prototype.isPointsMaterial = true;
  16195. const _inverseMatrix = /*@__PURE__*/new Matrix4();
  16196. const _ray = /*@__PURE__*/new Ray();
  16197. const _sphere = /*@__PURE__*/new Sphere();
  16198. const _position$2 = /*@__PURE__*/new Vector3();
  16199. class Points extends Object3D {
  16200. constructor(geometry = new BufferGeometry(), material = new PointsMaterial()) {
  16201. super();
  16202. this.type = 'Points';
  16203. this.geometry = geometry;
  16204. this.material = material;
  16205. this.updateMorphTargets();
  16206. }
  16207. copy(source) {
  16208. super.copy(source);
  16209. this.material = source.material;
  16210. this.geometry = source.geometry;
  16211. return this;
  16212. }
  16213. raycast(raycaster, intersects) {
  16214. const geometry = this.geometry;
  16215. const matrixWorld = this.matrixWorld;
  16216. const threshold = raycaster.params.Points.threshold;
  16217. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  16218. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16219. _sphere.copy(geometry.boundingSphere);
  16220. _sphere.applyMatrix4(matrixWorld);
  16221. _sphere.radius += threshold;
  16222. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  16223. _inverseMatrix.copy(matrixWorld).invert();
  16224. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix);
  16225. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16226. const localThresholdSq = localThreshold * localThreshold;
  16227. if (geometry.isBufferGeometry) {
  16228. const index = geometry.index;
  16229. const attributes = geometry.attributes;
  16230. const positionAttribute = attributes.position;
  16231. if (index !== null) {
  16232. const start = Math.max(0, drawRange.start);
  16233. const end = Math.min(index.count, drawRange.start + drawRange.count);
  16234. for (let i = start, il = end; i < il; i++) {
  16235. const a = index.getX(i);
  16236. _position$2.fromBufferAttribute(positionAttribute, a);
  16237. testPoint(_position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  16238. }
  16239. } else {
  16240. const start = Math.max(0, drawRange.start);
  16241. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  16242. for (let i = start, l = end; i < l; i++) {
  16243. _position$2.fromBufferAttribute(positionAttribute, i);
  16244. testPoint(_position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  16245. }
  16246. }
  16247. } else {
  16248. console.error('THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16249. }
  16250. }
  16251. updateMorphTargets() {
  16252. const geometry = this.geometry;
  16253. if (geometry.isBufferGeometry) {
  16254. const morphAttributes = geometry.morphAttributes;
  16255. const keys = Object.keys(morphAttributes);
  16256. if (keys.length > 0) {
  16257. const morphAttribute = morphAttributes[keys[0]];
  16258. if (morphAttribute !== undefined) {
  16259. this.morphTargetInfluences = [];
  16260. this.morphTargetDictionary = {};
  16261. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  16262. const name = morphAttribute[m].name || String(m);
  16263. this.morphTargetInfluences.push(0);
  16264. this.morphTargetDictionary[name] = m;
  16265. }
  16266. }
  16267. }
  16268. } else {
  16269. const morphTargets = geometry.morphTargets;
  16270. if (morphTargets !== undefined && morphTargets.length > 0) {
  16271. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  16272. }
  16273. }
  16274. }
  16275. }
  16276. Points.prototype.isPoints = true;
  16277. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  16278. const rayPointDistanceSq = _ray.distanceSqToPoint(point);
  16279. if (rayPointDistanceSq < localThresholdSq) {
  16280. const intersectPoint = new Vector3();
  16281. _ray.closestPointToPoint(point, intersectPoint);
  16282. intersectPoint.applyMatrix4(matrixWorld);
  16283. const distance = raycaster.ray.origin.distanceTo(intersectPoint);
  16284. if (distance < raycaster.near || distance > raycaster.far) return;
  16285. intersects.push({
  16286. distance: distance,
  16287. distanceToRay: Math.sqrt(rayPointDistanceSq),
  16288. point: intersectPoint,
  16289. index: index,
  16290. face: null,
  16291. object: object
  16292. });
  16293. }
  16294. }
  16295. class VideoTexture extends Texture {
  16296. constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  16297. super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16298. this.format = format !== undefined ? format : RGBFormat;
  16299. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  16300. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  16301. this.generateMipmaps = false;
  16302. const scope = this;
  16303. function updateVideo() {
  16304. scope.needsUpdate = true;
  16305. video.requestVideoFrameCallback(updateVideo);
  16306. }
  16307. if ('requestVideoFrameCallback' in video) {
  16308. video.requestVideoFrameCallback(updateVideo);
  16309. }
  16310. }
  16311. clone() {
  16312. return new this.constructor(this.image).copy(this);
  16313. }
  16314. update() {
  16315. const video = this.image;
  16316. const hasVideoFrameCallback = ('requestVideoFrameCallback' in video);
  16317. if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
  16318. this.needsUpdate = true;
  16319. }
  16320. }
  16321. }
  16322. VideoTexture.prototype.isVideoTexture = true;
  16323. class CompressedTexture extends Texture {
  16324. constructor(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  16325. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  16326. this.image = {
  16327. width: width,
  16328. height: height
  16329. };
  16330. this.mipmaps = mipmaps; // no flipping for cube textures
  16331. // (also flipping doesn't work for compressed textures )
  16332. this.flipY = false; // can't generate mipmaps for compressed textures
  16333. // mips must be embedded in DDS files
  16334. this.generateMipmaps = false;
  16335. }
  16336. }
  16337. CompressedTexture.prototype.isCompressedTexture = true;
  16338. class CanvasTexture extends Texture {
  16339. constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  16340. super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16341. this.needsUpdate = true;
  16342. }
  16343. }
  16344. CanvasTexture.prototype.isCanvasTexture = true;
  16345. class DepthTexture extends Texture {
  16346. constructor(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  16347. format = format !== undefined ? format : DepthFormat;
  16348. if (format !== DepthFormat && format !== DepthStencilFormat) {
  16349. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  16350. }
  16351. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  16352. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  16353. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16354. this.image = {
  16355. width: width,
  16356. height: height
  16357. };
  16358. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  16359. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  16360. this.flipY = false;
  16361. this.generateMipmaps = false;
  16362. }
  16363. }
  16364. DepthTexture.prototype.isDepthTexture = true;
  16365. class CircleGeometry extends BufferGeometry {
  16366. constructor(radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2) {
  16367. super();
  16368. this.type = 'CircleGeometry';
  16369. this.parameters = {
  16370. radius: radius,
  16371. segments: segments,
  16372. thetaStart: thetaStart,
  16373. thetaLength: thetaLength
  16374. };
  16375. segments = Math.max(3, segments); // buffers
  16376. const indices = [];
  16377. const vertices = [];
  16378. const normals = [];
  16379. const uvs = []; // helper variables
  16380. const vertex = new Vector3();
  16381. const uv = new Vector2(); // center point
  16382. vertices.push(0, 0, 0);
  16383. normals.push(0, 0, 1);
  16384. uvs.push(0.5, 0.5);
  16385. for (let s = 0, i = 3; s <= segments; s++, i += 3) {
  16386. const segment = thetaStart + s / segments * thetaLength; // vertex
  16387. vertex.x = radius * Math.cos(segment);
  16388. vertex.y = radius * Math.sin(segment);
  16389. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  16390. normals.push(0, 0, 1); // uvs
  16391. uv.x = (vertices[i] / radius + 1) / 2;
  16392. uv.y = (vertices[i + 1] / radius + 1) / 2;
  16393. uvs.push(uv.x, uv.y);
  16394. } // indices
  16395. for (let i = 1; i <= segments; i++) {
  16396. indices.push(i, i + 1, 0);
  16397. } // build geometry
  16398. this.setIndex(indices);
  16399. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  16400. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  16401. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  16402. }
  16403. }
  16404. class CylinderGeometry extends BufferGeometry {
  16405. constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  16406. super();
  16407. this.type = 'CylinderGeometry';
  16408. this.parameters = {
  16409. radiusTop: radiusTop,
  16410. radiusBottom: radiusBottom,
  16411. height: height,
  16412. radialSegments: radialSegments,
  16413. heightSegments: heightSegments,
  16414. openEnded: openEnded,
  16415. thetaStart: thetaStart,
  16416. thetaLength: thetaLength
  16417. };
  16418. const scope = this;
  16419. radialSegments = Math.floor(radialSegments);
  16420. heightSegments = Math.floor(heightSegments); // buffers
  16421. const indices = [];
  16422. const vertices = [];
  16423. const normals = [];
  16424. const uvs = []; // helper variables
  16425. let index = 0;
  16426. const indexArray = [];
  16427. const halfHeight = height / 2;
  16428. let groupStart = 0; // generate geometry
  16429. generateTorso();
  16430. if (openEnded === false) {
  16431. if (radiusTop > 0) generateCap(true);
  16432. if (radiusBottom > 0) generateCap(false);
  16433. } // build geometry
  16434. this.setIndex(indices);
  16435. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  16436. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  16437. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  16438. function generateTorso() {
  16439. const normal = new Vector3();
  16440. const vertex = new Vector3();
  16441. let groupCount = 0; // this will be used to calculate the normal
  16442. const slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  16443. for (let y = 0; y <= heightSegments; y++) {
  16444. const indexRow = [];
  16445. const v = y / heightSegments; // calculate the radius of the current row
  16446. const radius = v * (radiusBottom - radiusTop) + radiusTop;
  16447. for (let x = 0; x <= radialSegments; x++) {
  16448. const u = x / radialSegments;
  16449. const theta = u * thetaLength + thetaStart;
  16450. const sinTheta = Math.sin(theta);
  16451. const cosTheta = Math.cos(theta); // vertex
  16452. vertex.x = radius * sinTheta;
  16453. vertex.y = -v * height + halfHeight;
  16454. vertex.z = radius * cosTheta;
  16455. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  16456. normal.set(sinTheta, slope, cosTheta).normalize();
  16457. normals.push(normal.x, normal.y, normal.z); // uv
  16458. uvs.push(u, 1 - v); // save index of vertex in respective row
  16459. indexRow.push(index++);
  16460. } // now save vertices of the row in our index array
  16461. indexArray.push(indexRow);
  16462. } // generate indices
  16463. for (let x = 0; x < radialSegments; x++) {
  16464. for (let y = 0; y < heightSegments; y++) {
  16465. // we use the index array to access the correct indices
  16466. const a = indexArray[y][x];
  16467. const b = indexArray[y + 1][x];
  16468. const c = indexArray[y + 1][x + 1];
  16469. const d = indexArray[y][x + 1]; // faces
  16470. indices.push(a, b, d);
  16471. indices.push(b, c, d); // update group counter
  16472. groupCount += 6;
  16473. }
  16474. } // add a group to the geometry. this will ensure multi material support
  16475. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  16476. groupStart += groupCount;
  16477. }
  16478. function generateCap(top) {
  16479. // save the index of the first center vertex
  16480. const centerIndexStart = index;
  16481. const uv = new Vector2();
  16482. const vertex = new Vector3();
  16483. let groupCount = 0;
  16484. const radius = top === true ? radiusTop : radiusBottom;
  16485. const sign = top === true ? 1 : -1; // first we generate the center vertex data of the cap.
  16486. // because the geometry needs one set of uvs per face,
  16487. // we must generate a center vertex per face/segment
  16488. for (let x = 1; x <= radialSegments; x++) {
  16489. // vertex
  16490. vertices.push(0, halfHeight * sign, 0); // normal
  16491. normals.push(0, sign, 0); // uv
  16492. uvs.push(0.5, 0.5); // increase index
  16493. index++;
  16494. } // save the index of the last center vertex
  16495. const centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  16496. for (let x = 0; x <= radialSegments; x++) {
  16497. const u = x / radialSegments;
  16498. const theta = u * thetaLength + thetaStart;
  16499. const cosTheta = Math.cos(theta);
  16500. const sinTheta = Math.sin(theta); // vertex
  16501. vertex.x = radius * sinTheta;
  16502. vertex.y = halfHeight * sign;
  16503. vertex.z = radius * cosTheta;
  16504. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  16505. normals.push(0, sign, 0); // uv
  16506. uv.x = cosTheta * 0.5 + 0.5;
  16507. uv.y = sinTheta * 0.5 * sign + 0.5;
  16508. uvs.push(uv.x, uv.y); // increase index
  16509. index++;
  16510. } // generate indices
  16511. for (let x = 0; x < radialSegments; x++) {
  16512. const c = centerIndexStart + x;
  16513. const i = centerIndexEnd + x;
  16514. if (top === true) {
  16515. // face top
  16516. indices.push(i, i + 1, c);
  16517. } else {
  16518. // face bottom
  16519. indices.push(i + 1, i, c);
  16520. }
  16521. groupCount += 3;
  16522. } // add a group to the geometry. this will ensure multi material support
  16523. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  16524. groupStart += groupCount;
  16525. }
  16526. }
  16527. }
  16528. class ConeGeometry extends CylinderGeometry {
  16529. constructor(radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  16530. super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  16531. this.type = 'ConeGeometry';
  16532. this.parameters = {
  16533. radius: radius,
  16534. height: height,
  16535. radialSegments: radialSegments,
  16536. heightSegments: heightSegments,
  16537. openEnded: openEnded,
  16538. thetaStart: thetaStart,
  16539. thetaLength: thetaLength
  16540. };
  16541. }
  16542. }
  16543. class PolyhedronGeometry extends BufferGeometry {
  16544. constructor(vertices, indices, radius = 1, detail = 0) {
  16545. super();
  16546. this.type = 'PolyhedronGeometry';
  16547. this.parameters = {
  16548. vertices: vertices,
  16549. indices: indices,
  16550. radius: radius,
  16551. detail: detail
  16552. }; // default buffer data
  16553. const vertexBuffer = [];
  16554. const uvBuffer = []; // the subdivision creates the vertex buffer data
  16555. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  16556. applyRadius(radius); // finally, create the uv data
  16557. generateUVs(); // build non-indexed geometry
  16558. this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  16559. this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  16560. this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  16561. if (detail === 0) {
  16562. this.computeVertexNormals(); // flat normals
  16563. } else {
  16564. this.normalizeNormals(); // smooth normals
  16565. } // helper functions
  16566. function subdivide(detail) {
  16567. const a = new Vector3();
  16568. const b = new Vector3();
  16569. const c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  16570. for (let i = 0; i < indices.length; i += 3) {
  16571. // get the vertices of the face
  16572. getVertexByIndex(indices[i + 0], a);
  16573. getVertexByIndex(indices[i + 1], b);
  16574. getVertexByIndex(indices[i + 2], c); // perform subdivision
  16575. subdivideFace(a, b, c, detail);
  16576. }
  16577. }
  16578. function subdivideFace(a, b, c, detail) {
  16579. const cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision
  16580. const v = []; // construct all of the vertices for this subdivision
  16581. for (let i = 0; i <= cols; i++) {
  16582. v[i] = [];
  16583. const aj = a.clone().lerp(c, i / cols);
  16584. const bj = b.clone().lerp(c, i / cols);
  16585. const rows = cols - i;
  16586. for (let j = 0; j <= rows; j++) {
  16587. if (j === 0 && i === cols) {
  16588. v[i][j] = aj;
  16589. } else {
  16590. v[i][j] = aj.clone().lerp(bj, j / rows);
  16591. }
  16592. }
  16593. } // construct all of the faces
  16594. for (let i = 0; i < cols; i++) {
  16595. for (let j = 0; j < 2 * (cols - i) - 1; j++) {
  16596. const k = Math.floor(j / 2);
  16597. if (j % 2 === 0) {
  16598. pushVertex(v[i][k + 1]);
  16599. pushVertex(v[i + 1][k]);
  16600. pushVertex(v[i][k]);
  16601. } else {
  16602. pushVertex(v[i][k + 1]);
  16603. pushVertex(v[i + 1][k + 1]);
  16604. pushVertex(v[i + 1][k]);
  16605. }
  16606. }
  16607. }
  16608. }
  16609. function applyRadius(radius) {
  16610. const vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  16611. for (let i = 0; i < vertexBuffer.length; i += 3) {
  16612. vertex.x = vertexBuffer[i + 0];
  16613. vertex.y = vertexBuffer[i + 1];
  16614. vertex.z = vertexBuffer[i + 2];
  16615. vertex.normalize().multiplyScalar(radius);
  16616. vertexBuffer[i + 0] = vertex.x;
  16617. vertexBuffer[i + 1] = vertex.y;
  16618. vertexBuffer[i + 2] = vertex.z;
  16619. }
  16620. }
  16621. function generateUVs() {
  16622. const vertex = new Vector3();
  16623. for (let i = 0; i < vertexBuffer.length; i += 3) {
  16624. vertex.x = vertexBuffer[i + 0];
  16625. vertex.y = vertexBuffer[i + 1];
  16626. vertex.z = vertexBuffer[i + 2];
  16627. const u = azimuth(vertex) / 2 / Math.PI + 0.5;
  16628. const v = inclination(vertex) / Math.PI + 0.5;
  16629. uvBuffer.push(u, 1 - v);
  16630. }
  16631. correctUVs();
  16632. correctSeam();
  16633. }
  16634. function correctSeam() {
  16635. // handle case when face straddles the seam, see #3269
  16636. for (let i = 0; i < uvBuffer.length; i += 6) {
  16637. // uv data of a single face
  16638. const x0 = uvBuffer[i + 0];
  16639. const x1 = uvBuffer[i + 2];
  16640. const x2 = uvBuffer[i + 4];
  16641. const max = Math.max(x0, x1, x2);
  16642. const min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  16643. if (max > 0.9 && min < 0.1) {
  16644. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  16645. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  16646. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  16647. }
  16648. }
  16649. }
  16650. function pushVertex(vertex) {
  16651. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  16652. }
  16653. function getVertexByIndex(index, vertex) {
  16654. const stride = index * 3;
  16655. vertex.x = vertices[stride + 0];
  16656. vertex.y = vertices[stride + 1];
  16657. vertex.z = vertices[stride + 2];
  16658. }
  16659. function correctUVs() {
  16660. const a = new Vector3();
  16661. const b = new Vector3();
  16662. const c = new Vector3();
  16663. const centroid = new Vector3();
  16664. const uvA = new Vector2();
  16665. const uvB = new Vector2();
  16666. const uvC = new Vector2();
  16667. for (let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  16668. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  16669. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  16670. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  16671. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  16672. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  16673. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  16674. centroid.copy(a).add(b).add(c).divideScalar(3);
  16675. const azi = azimuth(centroid);
  16676. correctUV(uvA, j + 0, a, azi);
  16677. correctUV(uvB, j + 2, b, azi);
  16678. correctUV(uvC, j + 4, c, azi);
  16679. }
  16680. }
  16681. function correctUV(uv, stride, vector, azimuth) {
  16682. if (azimuth < 0 && uv.x === 1) {
  16683. uvBuffer[stride] = uv.x - 1;
  16684. }
  16685. if (vector.x === 0 && vector.z === 0) {
  16686. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  16687. }
  16688. } // Angle around the Y axis, counter-clockwise when looking from above.
  16689. function azimuth(vector) {
  16690. return Math.atan2(vector.z, -vector.x);
  16691. } // Angle above the XZ plane.
  16692. function inclination(vector) {
  16693. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  16694. }
  16695. }
  16696. }
  16697. class DodecahedronGeometry extends PolyhedronGeometry {
  16698. constructor(radius = 1, detail = 0) {
  16699. const t = (1 + Math.sqrt(5)) / 2;
  16700. const r = 1 / t;
  16701. const vertices = [// (±1, ±1, ±1)
  16702. -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/φ, ±φ)
  16703. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  16704. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  16705. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  16706. 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];
  16707. super(vertices, indices, radius, detail);
  16708. this.type = 'DodecahedronGeometry';
  16709. this.parameters = {
  16710. radius: radius,
  16711. detail: detail
  16712. };
  16713. }
  16714. }
  16715. const _v0 = new Vector3();
  16716. const _v1$1 = new Vector3();
  16717. const _normal = new Vector3();
  16718. const _triangle = new Triangle();
  16719. class EdgesGeometry extends BufferGeometry {
  16720. constructor(geometry, thresholdAngle) {
  16721. super();
  16722. this.type = 'EdgesGeometry';
  16723. this.parameters = {
  16724. thresholdAngle: thresholdAngle
  16725. };
  16726. thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1;
  16727. if (geometry.isGeometry === true) {
  16728. console.error('THREE.EdgesGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16729. return;
  16730. }
  16731. const precisionPoints = 4;
  16732. const precision = Math.pow(10, precisionPoints);
  16733. const thresholdDot = Math.cos(DEG2RAD * thresholdAngle);
  16734. const indexAttr = geometry.getIndex();
  16735. const positionAttr = geometry.getAttribute('position');
  16736. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  16737. const indexArr = [0, 0, 0];
  16738. const vertKeys = ['a', 'b', 'c'];
  16739. const hashes = new Array(3);
  16740. const edgeData = {};
  16741. const vertices = [];
  16742. for (let i = 0; i < indexCount; i += 3) {
  16743. if (indexAttr) {
  16744. indexArr[0] = indexAttr.getX(i);
  16745. indexArr[1] = indexAttr.getX(i + 1);
  16746. indexArr[2] = indexAttr.getX(i + 2);
  16747. } else {
  16748. indexArr[0] = i;
  16749. indexArr[1] = i + 1;
  16750. indexArr[2] = i + 2;
  16751. }
  16752. const {
  16753. a,
  16754. b,
  16755. c
  16756. } = _triangle;
  16757. a.fromBufferAttribute(positionAttr, indexArr[0]);
  16758. b.fromBufferAttribute(positionAttr, indexArr[1]);
  16759. c.fromBufferAttribute(positionAttr, indexArr[2]);
  16760. _triangle.getNormal(_normal); // create hashes for the edge from the vertices
  16761. hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`;
  16762. hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`;
  16763. hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`; // skip degenerate triangles
  16764. if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
  16765. continue;
  16766. } // iterate over every edge
  16767. for (let j = 0; j < 3; j++) {
  16768. // get the first and next vertex making up the edge
  16769. const jNext = (j + 1) % 3;
  16770. const vecHash0 = hashes[j];
  16771. const vecHash1 = hashes[jNext];
  16772. const v0 = _triangle[vertKeys[j]];
  16773. const v1 = _triangle[vertKeys[jNext]];
  16774. const hash = `${vecHash0}_${vecHash1}`;
  16775. const reverseHash = `${vecHash1}_${vecHash0}`;
  16776. if (reverseHash in edgeData && edgeData[reverseHash]) {
  16777. // if we found a sibling edge add it into the vertex array if
  16778. // it meets the angle threshold and delete the edge from the map.
  16779. if (_normal.dot(edgeData[reverseHash].normal) <= thresholdDot) {
  16780. vertices.push(v0.x, v0.y, v0.z);
  16781. vertices.push(v1.x, v1.y, v1.z);
  16782. }
  16783. edgeData[reverseHash] = null;
  16784. } else if (!(hash in edgeData)) {
  16785. // if we've already got an edge here then skip adding a new one
  16786. edgeData[hash] = {
  16787. index0: indexArr[j],
  16788. index1: indexArr[jNext],
  16789. normal: _normal.clone()
  16790. };
  16791. }
  16792. }
  16793. } // iterate over all remaining, unmatched edges and add them to the vertex array
  16794. for (const key in edgeData) {
  16795. if (edgeData[key]) {
  16796. const {
  16797. index0,
  16798. index1
  16799. } = edgeData[key];
  16800. _v0.fromBufferAttribute(positionAttr, index0);
  16801. _v1$1.fromBufferAttribute(positionAttr, index1);
  16802. vertices.push(_v0.x, _v0.y, _v0.z);
  16803. vertices.push(_v1$1.x, _v1$1.y, _v1$1.z);
  16804. }
  16805. }
  16806. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  16807. }
  16808. }
  16809. /**
  16810. * Port from https://github.com/mapbox/earcut (v2.2.2)
  16811. */
  16812. const Earcut = {
  16813. triangulate: function (data, holeIndices, dim) {
  16814. dim = dim || 2;
  16815. const hasHoles = holeIndices && holeIndices.length;
  16816. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  16817. let outerNode = linkedList(data, 0, outerLen, dim, true);
  16818. const triangles = [];
  16819. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  16820. let minX, minY, maxX, maxY, x, y, invSize;
  16821. 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
  16822. if (data.length > 80 * dim) {
  16823. minX = maxX = data[0];
  16824. minY = maxY = data[1];
  16825. for (let i = dim; i < outerLen; i += dim) {
  16826. x = data[i];
  16827. y = data[i + 1];
  16828. if (x < minX) minX = x;
  16829. if (y < minY) minY = y;
  16830. if (x > maxX) maxX = x;
  16831. if (y > maxY) maxY = y;
  16832. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  16833. invSize = Math.max(maxX - minX, maxY - minY);
  16834. invSize = invSize !== 0 ? 1 / invSize : 0;
  16835. }
  16836. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  16837. return triangles;
  16838. }
  16839. }; // create a circular doubly linked list from polygon points in the specified winding order
  16840. function linkedList(data, start, end, dim, clockwise) {
  16841. let i, last;
  16842. if (clockwise === signedArea(data, start, end, dim) > 0) {
  16843. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  16844. } else {
  16845. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  16846. }
  16847. if (last && equals(last, last.next)) {
  16848. removeNode(last);
  16849. last = last.next;
  16850. }
  16851. return last;
  16852. } // eliminate colinear or duplicate points
  16853. function filterPoints(start, end) {
  16854. if (!start) return start;
  16855. if (!end) end = start;
  16856. let p = start,
  16857. again;
  16858. do {
  16859. again = false;
  16860. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  16861. removeNode(p);
  16862. p = end = p.prev;
  16863. if (p === p.next) break;
  16864. again = true;
  16865. } else {
  16866. p = p.next;
  16867. }
  16868. } while (again || p !== end);
  16869. return end;
  16870. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  16871. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  16872. if (!ear) return; // interlink polygon nodes in z-order
  16873. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  16874. let stop = ear,
  16875. prev,
  16876. next; // iterate through ears, slicing them one by one
  16877. while (ear.prev !== ear.next) {
  16878. prev = ear.prev;
  16879. next = ear.next;
  16880. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  16881. // cut off the triangle
  16882. triangles.push(prev.i / dim);
  16883. triangles.push(ear.i / dim);
  16884. triangles.push(next.i / dim);
  16885. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  16886. ear = next.next;
  16887. stop = next.next;
  16888. continue;
  16889. }
  16890. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  16891. if (ear === stop) {
  16892. // try filtering points and slicing again
  16893. if (!pass) {
  16894. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  16895. } else if (pass === 1) {
  16896. ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
  16897. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  16898. } else if (pass === 2) {
  16899. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  16900. }
  16901. break;
  16902. }
  16903. }
  16904. } // check whether a polygon node forms a valid ear with adjacent nodes
  16905. function isEar(ear) {
  16906. const a = ear.prev,
  16907. b = ear,
  16908. c = ear.next;
  16909. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  16910. // now make sure we don't have other points inside the potential ear
  16911. let p = ear.next.next;
  16912. while (p !== ear.prev) {
  16913. 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;
  16914. p = p.next;
  16915. }
  16916. return true;
  16917. }
  16918. function isEarHashed(ear, minX, minY, invSize) {
  16919. const a = ear.prev,
  16920. b = ear,
  16921. c = ear.next;
  16922. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  16923. // triangle bbox; min & max are calculated like this for speed
  16924. const minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  16925. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  16926. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  16927. 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;
  16928. const minZ = zOrder(minTX, minTY, minX, minY, invSize),
  16929. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  16930. let p = ear.prevZ,
  16931. n = ear.nextZ; // look for points inside the triangle in both directions
  16932. while (p && p.z >= minZ && n && n.z <= maxZ) {
  16933. 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;
  16934. p = p.prevZ;
  16935. 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;
  16936. n = n.nextZ;
  16937. } // look for remaining points in decreasing z-order
  16938. while (p && p.z >= minZ) {
  16939. 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;
  16940. p = p.prevZ;
  16941. } // look for remaining points in increasing z-order
  16942. while (n && n.z <= maxZ) {
  16943. 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;
  16944. n = n.nextZ;
  16945. }
  16946. return true;
  16947. } // go through all polygon nodes and cure small local self-intersections
  16948. function cureLocalIntersections(start, triangles, dim) {
  16949. let p = start;
  16950. do {
  16951. const a = p.prev,
  16952. b = p.next.next;
  16953. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  16954. triangles.push(a.i / dim);
  16955. triangles.push(p.i / dim);
  16956. triangles.push(b.i / dim); // remove two nodes involved
  16957. removeNode(p);
  16958. removeNode(p.next);
  16959. p = start = b;
  16960. }
  16961. p = p.next;
  16962. } while (p !== start);
  16963. return filterPoints(p);
  16964. } // try splitting polygon into two and triangulate them independently
  16965. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  16966. // look for a valid diagonal that divides the polygon into two
  16967. let a = start;
  16968. do {
  16969. let b = a.next.next;
  16970. while (b !== a.prev) {
  16971. if (a.i !== b.i && isValidDiagonal(a, b)) {
  16972. // split the polygon in two by the diagonal
  16973. let c = splitPolygon(a, b); // filter colinear points around the cuts
  16974. a = filterPoints(a, a.next);
  16975. c = filterPoints(c, c.next); // run earcut on each half
  16976. earcutLinked(a, triangles, dim, minX, minY, invSize);
  16977. earcutLinked(c, triangles, dim, minX, minY, invSize);
  16978. return;
  16979. }
  16980. b = b.next;
  16981. }
  16982. a = a.next;
  16983. } while (a !== start);
  16984. } // link every hole into the outer loop, producing a single-ring polygon without holes
  16985. function eliminateHoles(data, holeIndices, outerNode, dim) {
  16986. const queue = [];
  16987. let i, len, start, end, list;
  16988. for (i = 0, len = holeIndices.length; i < len; i++) {
  16989. start = holeIndices[i] * dim;
  16990. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  16991. list = linkedList(data, start, end, dim, false);
  16992. if (list === list.next) list.steiner = true;
  16993. queue.push(getLeftmost(list));
  16994. }
  16995. queue.sort(compareX); // process holes from left to right
  16996. for (i = 0; i < queue.length; i++) {
  16997. eliminateHole(queue[i], outerNode);
  16998. outerNode = filterPoints(outerNode, outerNode.next);
  16999. }
  17000. return outerNode;
  17001. }
  17002. function compareX(a, b) {
  17003. return a.x - b.x;
  17004. } // find a bridge between vertices that connects hole with an outer ring and and link it
  17005. function eliminateHole(hole, outerNode) {
  17006. outerNode = findHoleBridge(hole, outerNode);
  17007. if (outerNode) {
  17008. const b = splitPolygon(outerNode, hole); // filter collinear points around the cuts
  17009. filterPoints(outerNode, outerNode.next);
  17010. filterPoints(b, b.next);
  17011. }
  17012. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  17013. function findHoleBridge(hole, outerNode) {
  17014. let p = outerNode;
  17015. const hx = hole.x;
  17016. const hy = hole.y;
  17017. let qx = -Infinity,
  17018. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  17019. // segment's endpoint with lesser x will be potential connection point
  17020. do {
  17021. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  17022. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  17023. if (x <= hx && x > qx) {
  17024. qx = x;
  17025. if (x === hx) {
  17026. if (hy === p.y) return p;
  17027. if (hy === p.next.y) return p.next;
  17028. }
  17029. m = p.x < p.next.x ? p : p.next;
  17030. }
  17031. }
  17032. p = p.next;
  17033. } while (p !== outerNode);
  17034. if (!m) return null;
  17035. if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint
  17036. // look for points inside the triangle of hole point, segment intersection and endpoint;
  17037. // if there are no points found, we have a valid connection;
  17038. // otherwise choose the point of the minimum angle with the ray as connection point
  17039. const stop = m,
  17040. mx = m.x,
  17041. my = m.y;
  17042. let tanMin = Infinity,
  17043. tan;
  17044. p = m;
  17045. do {
  17046. 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)) {
  17047. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  17048. if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
  17049. m = p;
  17050. tanMin = tan;
  17051. }
  17052. }
  17053. p = p.next;
  17054. } while (p !== stop);
  17055. return m;
  17056. } // whether sector in vertex m contains sector in vertex p in the same coordinates
  17057. function sectorContainsSector(m, p) {
  17058. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  17059. } // interlink polygon nodes in z-order
  17060. function indexCurve(start, minX, minY, invSize) {
  17061. let p = start;
  17062. do {
  17063. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  17064. p.prevZ = p.prev;
  17065. p.nextZ = p.next;
  17066. p = p.next;
  17067. } while (p !== start);
  17068. p.prevZ.nextZ = null;
  17069. p.prevZ = null;
  17070. sortLinked(p);
  17071. } // Simon Tatham's linked list merge sort algorithm
  17072. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  17073. function sortLinked(list) {
  17074. let i,
  17075. p,
  17076. q,
  17077. e,
  17078. tail,
  17079. numMerges,
  17080. pSize,
  17081. qSize,
  17082. inSize = 1;
  17083. do {
  17084. p = list;
  17085. list = null;
  17086. tail = null;
  17087. numMerges = 0;
  17088. while (p) {
  17089. numMerges++;
  17090. q = p;
  17091. pSize = 0;
  17092. for (i = 0; i < inSize; i++) {
  17093. pSize++;
  17094. q = q.nextZ;
  17095. if (!q) break;
  17096. }
  17097. qSize = inSize;
  17098. while (pSize > 0 || qSize > 0 && q) {
  17099. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  17100. e = p;
  17101. p = p.nextZ;
  17102. pSize--;
  17103. } else {
  17104. e = q;
  17105. q = q.nextZ;
  17106. qSize--;
  17107. }
  17108. if (tail) tail.nextZ = e;else list = e;
  17109. e.prevZ = tail;
  17110. tail = e;
  17111. }
  17112. p = q;
  17113. }
  17114. tail.nextZ = null;
  17115. inSize *= 2;
  17116. } while (numMerges > 1);
  17117. return list;
  17118. } // z-order of a point given coords and inverse of the longer side of data bbox
  17119. function zOrder(x, y, minX, minY, invSize) {
  17120. // coords are transformed into non-negative 15-bit integer range
  17121. x = 32767 * (x - minX) * invSize;
  17122. y = 32767 * (y - minY) * invSize;
  17123. x = (x | x << 8) & 0x00FF00FF;
  17124. x = (x | x << 4) & 0x0F0F0F0F;
  17125. x = (x | x << 2) & 0x33333333;
  17126. x = (x | x << 1) & 0x55555555;
  17127. y = (y | y << 8) & 0x00FF00FF;
  17128. y = (y | y << 4) & 0x0F0F0F0F;
  17129. y = (y | y << 2) & 0x33333333;
  17130. y = (y | y << 1) & 0x55555555;
  17131. return x | y << 1;
  17132. } // find the leftmost node of a polygon ring
  17133. function getLeftmost(start) {
  17134. let p = start,
  17135. leftmost = start;
  17136. do {
  17137. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  17138. p = p.next;
  17139. } while (p !== start);
  17140. return leftmost;
  17141. } // check if a point lies within a convex triangle
  17142. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  17143. 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;
  17144. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  17145. function isValidDiagonal(a, b) {
  17146. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && ( // dones't intersect other edges
  17147. locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && ( // locally visible
  17148. area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  17149. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  17150. } // signed area of a triangle
  17151. function area(p, q, r) {
  17152. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  17153. } // check if two points are equal
  17154. function equals(p1, p2) {
  17155. return p1.x === p2.x && p1.y === p2.y;
  17156. } // check if two segments intersect
  17157. function intersects(p1, q1, p2, q2) {
  17158. const o1 = sign(area(p1, q1, p2));
  17159. const o2 = sign(area(p1, q1, q2));
  17160. const o3 = sign(area(p2, q2, p1));
  17161. const o4 = sign(area(p2, q2, q1));
  17162. if (o1 !== o2 && o3 !== o4) return true; // general case
  17163. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  17164. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  17165. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  17166. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  17167. return false;
  17168. } // for collinear points p, q, r, check if point q lies on segment pr
  17169. function onSegment(p, q, r) {
  17170. 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);
  17171. }
  17172. function sign(num) {
  17173. return num > 0 ? 1 : num < 0 ? -1 : 0;
  17174. } // check if a polygon diagonal intersects any polygon segments
  17175. function intersectsPolygon(a, b) {
  17176. let p = a;
  17177. do {
  17178. 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;
  17179. p = p.next;
  17180. } while (p !== a);
  17181. return false;
  17182. } // check if a polygon diagonal is locally inside the polygon
  17183. function locallyInside(a, b) {
  17184. 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;
  17185. } // check if the middle point of a polygon diagonal is inside the polygon
  17186. function middleInside(a, b) {
  17187. let p = a,
  17188. inside = false;
  17189. const px = (a.x + b.x) / 2,
  17190. py = (a.y + b.y) / 2;
  17191. do {
  17192. 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;
  17193. p = p.next;
  17194. } while (p !== a);
  17195. return inside;
  17196. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  17197. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  17198. function splitPolygon(a, b) {
  17199. const a2 = new Node(a.i, a.x, a.y),
  17200. b2 = new Node(b.i, b.x, b.y),
  17201. an = a.next,
  17202. bp = b.prev;
  17203. a.next = b;
  17204. b.prev = a;
  17205. a2.next = an;
  17206. an.prev = a2;
  17207. b2.next = a2;
  17208. a2.prev = b2;
  17209. bp.next = b2;
  17210. b2.prev = bp;
  17211. return b2;
  17212. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  17213. function insertNode(i, x, y, last) {
  17214. const p = new Node(i, x, y);
  17215. if (!last) {
  17216. p.prev = p;
  17217. p.next = p;
  17218. } else {
  17219. p.next = last.next;
  17220. p.prev = last;
  17221. last.next.prev = p;
  17222. last.next = p;
  17223. }
  17224. return p;
  17225. }
  17226. function removeNode(p) {
  17227. p.next.prev = p.prev;
  17228. p.prev.next = p.next;
  17229. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  17230. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  17231. }
  17232. function Node(i, x, y) {
  17233. // vertex index in coordinates array
  17234. this.i = i; // vertex coordinates
  17235. this.x = x;
  17236. this.y = y; // previous and next vertex nodes in a polygon ring
  17237. this.prev = null;
  17238. this.next = null; // z-order curve value
  17239. this.z = null; // previous and next nodes in z-order
  17240. this.prevZ = null;
  17241. this.nextZ = null; // indicates whether this is a steiner point
  17242. this.steiner = false;
  17243. }
  17244. function signedArea(data, start, end, dim) {
  17245. let sum = 0;
  17246. for (let i = start, j = end - dim; i < end; i += dim) {
  17247. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  17248. j = i;
  17249. }
  17250. return sum;
  17251. }
  17252. class ShapeUtils {
  17253. // calculate area of the contour polygon
  17254. static area(contour) {
  17255. const n = contour.length;
  17256. let a = 0.0;
  17257. for (let p = n - 1, q = 0; q < n; p = q++) {
  17258. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  17259. }
  17260. return a * 0.5;
  17261. }
  17262. static isClockWise(pts) {
  17263. return ShapeUtils.area(pts) < 0;
  17264. }
  17265. static triangulateShape(contour, holes) {
  17266. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  17267. const holeIndices = []; // array of hole indices
  17268. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  17269. removeDupEndPts(contour);
  17270. addContour(vertices, contour); //
  17271. let holeIndex = contour.length;
  17272. holes.forEach(removeDupEndPts);
  17273. for (let i = 0; i < holes.length; i++) {
  17274. holeIndices.push(holeIndex);
  17275. holeIndex += holes[i].length;
  17276. addContour(vertices, holes[i]);
  17277. } //
  17278. const triangles = Earcut.triangulate(vertices, holeIndices); //
  17279. for (let i = 0; i < triangles.length; i += 3) {
  17280. faces.push(triangles.slice(i, i + 3));
  17281. }
  17282. return faces;
  17283. }
  17284. }
  17285. function removeDupEndPts(points) {
  17286. const l = points.length;
  17287. if (l > 2 && points[l - 1].equals(points[0])) {
  17288. points.pop();
  17289. }
  17290. }
  17291. function addContour(vertices, contour) {
  17292. for (let i = 0; i < contour.length; i++) {
  17293. vertices.push(contour[i].x);
  17294. vertices.push(contour[i].y);
  17295. }
  17296. }
  17297. /**
  17298. * Creates extruded geometry from a path shape.
  17299. *
  17300. * parameters = {
  17301. *
  17302. * curveSegments: <int>, // number of points on the curves
  17303. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  17304. * depth: <float>, // Depth to extrude the shape
  17305. *
  17306. * bevelEnabled: <bool>, // turn on bevel
  17307. * bevelThickness: <float>, // how deep into the original shape bevel goes
  17308. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  17309. * bevelOffset: <float>, // how far from shape outline does bevel start
  17310. * bevelSegments: <int>, // number of bevel layers
  17311. *
  17312. * extrudePath: <THREE.Curve> // curve to extrude shape along
  17313. *
  17314. * UVGenerator: <Object> // object that provides UV generator functions
  17315. *
  17316. * }
  17317. */
  17318. class ExtrudeGeometry extends BufferGeometry {
  17319. constructor(shapes, options) {
  17320. super();
  17321. this.type = 'ExtrudeGeometry';
  17322. this.parameters = {
  17323. shapes: shapes,
  17324. options: options
  17325. };
  17326. shapes = Array.isArray(shapes) ? shapes : [shapes];
  17327. const scope = this;
  17328. const verticesArray = [];
  17329. const uvArray = [];
  17330. for (let i = 0, l = shapes.length; i < l; i++) {
  17331. const shape = shapes[i];
  17332. addShape(shape);
  17333. } // build geometry
  17334. this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  17335. this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  17336. this.computeVertexNormals(); // functions
  17337. function addShape(shape) {
  17338. const placeholder = []; // options
  17339. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  17340. const steps = options.steps !== undefined ? options.steps : 1;
  17341. let depth = options.depth !== undefined ? options.depth : 100;
  17342. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  17343. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  17344. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  17345. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  17346. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  17347. const extrudePath = options.extrudePath;
  17348. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  17349. if (options.amount !== undefined) {
  17350. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  17351. depth = options.amount;
  17352. } //
  17353. let extrudePts,
  17354. extrudeByPath = false;
  17355. let splineTube, binormal, normal, position2;
  17356. if (extrudePath) {
  17357. extrudePts = extrudePath.getSpacedPoints(steps);
  17358. extrudeByPath = true;
  17359. bevelEnabled = false; // bevels not supported for path extrusion
  17360. // SETUP TNB variables
  17361. // TODO1 - have a .isClosed in spline?
  17362. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  17363. binormal = new Vector3();
  17364. normal = new Vector3();
  17365. position2 = new Vector3();
  17366. } // Safeguards if bevels are not enabled
  17367. if (!bevelEnabled) {
  17368. bevelSegments = 0;
  17369. bevelThickness = 0;
  17370. bevelSize = 0;
  17371. bevelOffset = 0;
  17372. } // Variables initialization
  17373. const shapePoints = shape.extractPoints(curveSegments);
  17374. let vertices = shapePoints.shape;
  17375. const holes = shapePoints.holes;
  17376. const reverse = !ShapeUtils.isClockWise(vertices);
  17377. if (reverse) {
  17378. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  17379. for (let h = 0, hl = holes.length; h < hl; h++) {
  17380. const ahole = holes[h];
  17381. if (ShapeUtils.isClockWise(ahole)) {
  17382. holes[h] = ahole.reverse();
  17383. }
  17384. }
  17385. }
  17386. const faces = ShapeUtils.triangulateShape(vertices, holes);
  17387. /* Vertices */
  17388. const contour = vertices; // vertices has all points but contour has only points of circumference
  17389. for (let h = 0, hl = holes.length; h < hl; h++) {
  17390. const ahole = holes[h];
  17391. vertices = vertices.concat(ahole);
  17392. }
  17393. function scalePt2(pt, vec, size) {
  17394. if (!vec) console.error('THREE.ExtrudeGeometry: vec does not exist');
  17395. return vec.clone().multiplyScalar(size).add(pt);
  17396. }
  17397. const vlen = vertices.length,
  17398. flen = faces.length; // Find directions for point movement
  17399. function getBevelVec(inPt, inPrev, inNext) {
  17400. // computes for inPt the corresponding point inPt' on a new contour
  17401. // shifted by 1 unit (length of normalized vector) to the left
  17402. // if we walk along contour clockwise, this new contour is outside the old one
  17403. //
  17404. // inPt' is the intersection of the two lines parallel to the two
  17405. // adjacent edges of inPt at a distance of 1 unit on the left side.
  17406. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  17407. // good reading for geometry algorithms (here: line-line intersection)
  17408. // http://geomalgorithms.com/a05-_intersect-1.html
  17409. const v_prev_x = inPt.x - inPrev.x,
  17410. v_prev_y = inPt.y - inPrev.y;
  17411. const v_next_x = inNext.x - inPt.x,
  17412. v_next_y = inNext.y - inPt.y;
  17413. const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  17414. const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  17415. if (Math.abs(collinear0) > Number.EPSILON) {
  17416. // not collinear
  17417. // length of vectors for normalizing
  17418. const v_prev_len = Math.sqrt(v_prev_lensq);
  17419. 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
  17420. const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  17421. const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  17422. const ptNextShift_x = inNext.x - v_next_y / v_next_len;
  17423. const ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  17424. 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
  17425. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  17426. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  17427. // but prevent crazy spikes
  17428. const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  17429. if (v_trans_lensq <= 2) {
  17430. return new Vector2(v_trans_x, v_trans_y);
  17431. } else {
  17432. shrink_by = Math.sqrt(v_trans_lensq / 2);
  17433. }
  17434. } else {
  17435. // handle special case of collinear edges
  17436. let direction_eq = false; // assumes: opposite
  17437. if (v_prev_x > Number.EPSILON) {
  17438. if (v_next_x > Number.EPSILON) {
  17439. direction_eq = true;
  17440. }
  17441. } else {
  17442. if (v_prev_x < -Number.EPSILON) {
  17443. if (v_next_x < -Number.EPSILON) {
  17444. direction_eq = true;
  17445. }
  17446. } else {
  17447. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  17448. direction_eq = true;
  17449. }
  17450. }
  17451. }
  17452. if (direction_eq) {
  17453. // console.log("Warning: lines are a straight sequence");
  17454. v_trans_x = -v_prev_y;
  17455. v_trans_y = v_prev_x;
  17456. shrink_by = Math.sqrt(v_prev_lensq);
  17457. } else {
  17458. // console.log("Warning: lines are a straight spike");
  17459. v_trans_x = v_prev_x;
  17460. v_trans_y = v_prev_y;
  17461. shrink_by = Math.sqrt(v_prev_lensq / 2);
  17462. }
  17463. }
  17464. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  17465. }
  17466. const contourMovements = [];
  17467. for (let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  17468. if (j === il) j = 0;
  17469. if (k === il) k = 0; // (j)---(i)---(k)
  17470. // console.log('i,j,k', i, j , k)
  17471. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  17472. }
  17473. const holesMovements = [];
  17474. let oneHoleMovements,
  17475. verticesMovements = contourMovements.concat();
  17476. for (let h = 0, hl = holes.length; h < hl; h++) {
  17477. const ahole = holes[h];
  17478. oneHoleMovements = [];
  17479. for (let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  17480. if (j === il) j = 0;
  17481. if (k === il) k = 0; // (j)---(i)---(k)
  17482. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  17483. }
  17484. holesMovements.push(oneHoleMovements);
  17485. verticesMovements = verticesMovements.concat(oneHoleMovements);
  17486. } // Loop bevelSegments, 1 for the front, 1 for the back
  17487. for (let b = 0; b < bevelSegments; b++) {
  17488. //for ( b = bevelSegments; b > 0; b -- ) {
  17489. const t = b / bevelSegments;
  17490. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  17491. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  17492. for (let i = 0, il = contour.length; i < il; i++) {
  17493. const vert = scalePt2(contour[i], contourMovements[i], bs);
  17494. v(vert.x, vert.y, -z);
  17495. } // expand holes
  17496. for (let h = 0, hl = holes.length; h < hl; h++) {
  17497. const ahole = holes[h];
  17498. oneHoleMovements = holesMovements[h];
  17499. for (let i = 0, il = ahole.length; i < il; i++) {
  17500. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  17501. v(vert.x, vert.y, -z);
  17502. }
  17503. }
  17504. }
  17505. const bs = bevelSize + bevelOffset; // Back facing vertices
  17506. for (let i = 0; i < vlen; i++) {
  17507. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  17508. if (!extrudeByPath) {
  17509. v(vert.x, vert.y, 0);
  17510. } else {
  17511. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  17512. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  17513. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  17514. position2.copy(extrudePts[0]).add(normal).add(binormal);
  17515. v(position2.x, position2.y, position2.z);
  17516. }
  17517. } // Add stepped vertices...
  17518. // Including front facing vertices
  17519. for (let s = 1; s <= steps; s++) {
  17520. for (let i = 0; i < vlen; i++) {
  17521. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  17522. if (!extrudeByPath) {
  17523. v(vert.x, vert.y, depth / steps * s);
  17524. } else {
  17525. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  17526. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  17527. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  17528. position2.copy(extrudePts[s]).add(normal).add(binormal);
  17529. v(position2.x, position2.y, position2.z);
  17530. }
  17531. }
  17532. } // Add bevel segments planes
  17533. //for ( b = 1; b <= bevelSegments; b ++ ) {
  17534. for (let b = bevelSegments - 1; b >= 0; b--) {
  17535. const t = b / bevelSegments;
  17536. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  17537. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  17538. for (let i = 0, il = contour.length; i < il; i++) {
  17539. const vert = scalePt2(contour[i], contourMovements[i], bs);
  17540. v(vert.x, vert.y, depth + z);
  17541. } // expand holes
  17542. for (let h = 0, hl = holes.length; h < hl; h++) {
  17543. const ahole = holes[h];
  17544. oneHoleMovements = holesMovements[h];
  17545. for (let i = 0, il = ahole.length; i < il; i++) {
  17546. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  17547. if (!extrudeByPath) {
  17548. v(vert.x, vert.y, depth + z);
  17549. } else {
  17550. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  17551. }
  17552. }
  17553. }
  17554. }
  17555. /* Faces */
  17556. // Top and bottom faces
  17557. buildLidFaces(); // Sides faces
  17558. buildSideFaces(); ///// Internal functions
  17559. function buildLidFaces() {
  17560. const start = verticesArray.length / 3;
  17561. if (bevelEnabled) {
  17562. let layer = 0; // steps + 1
  17563. let offset = vlen * layer; // Bottom faces
  17564. for (let i = 0; i < flen; i++) {
  17565. const face = faces[i];
  17566. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  17567. }
  17568. layer = steps + bevelSegments * 2;
  17569. offset = vlen * layer; // Top faces
  17570. for (let i = 0; i < flen; i++) {
  17571. const face = faces[i];
  17572. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  17573. }
  17574. } else {
  17575. // Bottom faces
  17576. for (let i = 0; i < flen; i++) {
  17577. const face = faces[i];
  17578. f3(face[2], face[1], face[0]);
  17579. } // Top faces
  17580. for (let i = 0; i < flen; i++) {
  17581. const face = faces[i];
  17582. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  17583. }
  17584. }
  17585. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  17586. } // Create faces for the z-sides of the shape
  17587. function buildSideFaces() {
  17588. const start = verticesArray.length / 3;
  17589. let layeroffset = 0;
  17590. sidewalls(contour, layeroffset);
  17591. layeroffset += contour.length;
  17592. for (let h = 0, hl = holes.length; h < hl; h++) {
  17593. const ahole = holes[h];
  17594. sidewalls(ahole, layeroffset); //, true
  17595. layeroffset += ahole.length;
  17596. }
  17597. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  17598. }
  17599. function sidewalls(contour, layeroffset) {
  17600. let i = contour.length;
  17601. while (--i >= 0) {
  17602. const j = i;
  17603. let k = i - 1;
  17604. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  17605. for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) {
  17606. const slen1 = vlen * s;
  17607. const slen2 = vlen * (s + 1);
  17608. const a = layeroffset + j + slen1,
  17609. b = layeroffset + k + slen1,
  17610. c = layeroffset + k + slen2,
  17611. d = layeroffset + j + slen2;
  17612. f4(a, b, c, d);
  17613. }
  17614. }
  17615. }
  17616. function v(x, y, z) {
  17617. placeholder.push(x);
  17618. placeholder.push(y);
  17619. placeholder.push(z);
  17620. }
  17621. function f3(a, b, c) {
  17622. addVertex(a);
  17623. addVertex(b);
  17624. addVertex(c);
  17625. const nextIndex = verticesArray.length / 3;
  17626. const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  17627. addUV(uvs[0]);
  17628. addUV(uvs[1]);
  17629. addUV(uvs[2]);
  17630. }
  17631. function f4(a, b, c, d) {
  17632. addVertex(a);
  17633. addVertex(b);
  17634. addVertex(d);
  17635. addVertex(b);
  17636. addVertex(c);
  17637. addVertex(d);
  17638. const nextIndex = verticesArray.length / 3;
  17639. const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  17640. addUV(uvs[0]);
  17641. addUV(uvs[1]);
  17642. addUV(uvs[3]);
  17643. addUV(uvs[1]);
  17644. addUV(uvs[2]);
  17645. addUV(uvs[3]);
  17646. }
  17647. function addVertex(index) {
  17648. verticesArray.push(placeholder[index * 3 + 0]);
  17649. verticesArray.push(placeholder[index * 3 + 1]);
  17650. verticesArray.push(placeholder[index * 3 + 2]);
  17651. }
  17652. function addUV(vector2) {
  17653. uvArray.push(vector2.x);
  17654. uvArray.push(vector2.y);
  17655. }
  17656. }
  17657. }
  17658. toJSON() {
  17659. const data = BufferGeometry.prototype.toJSON.call(this);
  17660. const shapes = this.parameters.shapes;
  17661. const options = this.parameters.options;
  17662. return toJSON$1(shapes, options, data);
  17663. }
  17664. }
  17665. const WorldUVGenerator = {
  17666. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  17667. const a_x = vertices[indexA * 3];
  17668. const a_y = vertices[indexA * 3 + 1];
  17669. const b_x = vertices[indexB * 3];
  17670. const b_y = vertices[indexB * 3 + 1];
  17671. const c_x = vertices[indexC * 3];
  17672. const c_y = vertices[indexC * 3 + 1];
  17673. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  17674. },
  17675. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  17676. const a_x = vertices[indexA * 3];
  17677. const a_y = vertices[indexA * 3 + 1];
  17678. const a_z = vertices[indexA * 3 + 2];
  17679. const b_x = vertices[indexB * 3];
  17680. const b_y = vertices[indexB * 3 + 1];
  17681. const b_z = vertices[indexB * 3 + 2];
  17682. const c_x = vertices[indexC * 3];
  17683. const c_y = vertices[indexC * 3 + 1];
  17684. const c_z = vertices[indexC * 3 + 2];
  17685. const d_x = vertices[indexD * 3];
  17686. const d_y = vertices[indexD * 3 + 1];
  17687. const d_z = vertices[indexD * 3 + 2];
  17688. if (Math.abs(a_y - b_y) < 0.01) {
  17689. 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)];
  17690. } else {
  17691. 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)];
  17692. }
  17693. }
  17694. };
  17695. function toJSON$1(shapes, options, data) {
  17696. data.shapes = [];
  17697. if (Array.isArray(shapes)) {
  17698. for (let i = 0, l = shapes.length; i < l; i++) {
  17699. const shape = shapes[i];
  17700. data.shapes.push(shape.uuid);
  17701. }
  17702. } else {
  17703. data.shapes.push(shapes.uuid);
  17704. }
  17705. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  17706. return data;
  17707. }
  17708. class IcosahedronGeometry extends PolyhedronGeometry {
  17709. constructor(radius = 1, detail = 0) {
  17710. const t = (1 + Math.sqrt(5)) / 2;
  17711. 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];
  17712. 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];
  17713. super(vertices, indices, radius, detail);
  17714. this.type = 'IcosahedronGeometry';
  17715. this.parameters = {
  17716. radius: radius,
  17717. detail: detail
  17718. };
  17719. }
  17720. }
  17721. class LatheGeometry extends BufferGeometry {
  17722. constructor(points, segments = 12, phiStart = 0, phiLength = Math.PI * 2) {
  17723. super();
  17724. this.type = 'LatheGeometry';
  17725. this.parameters = {
  17726. points: points,
  17727. segments: segments,
  17728. phiStart: phiStart,
  17729. phiLength: phiLength
  17730. };
  17731. segments = Math.floor(segments); // clamp phiLength so it's in range of [ 0, 2PI ]
  17732. phiLength = clamp(phiLength, 0, Math.PI * 2); // buffers
  17733. const indices = [];
  17734. const vertices = [];
  17735. const uvs = []; // helper variables
  17736. const inverseSegments = 1.0 / segments;
  17737. const vertex = new Vector3();
  17738. const uv = new Vector2(); // generate vertices and uvs
  17739. for (let i = 0; i <= segments; i++) {
  17740. const phi = phiStart + i * inverseSegments * phiLength;
  17741. const sin = Math.sin(phi);
  17742. const cos = Math.cos(phi);
  17743. for (let j = 0; j <= points.length - 1; j++) {
  17744. // vertex
  17745. vertex.x = points[j].x * sin;
  17746. vertex.y = points[j].y;
  17747. vertex.z = points[j].x * cos;
  17748. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  17749. uv.x = i / segments;
  17750. uv.y = j / (points.length - 1);
  17751. uvs.push(uv.x, uv.y);
  17752. }
  17753. } // indices
  17754. for (let i = 0; i < segments; i++) {
  17755. for (let j = 0; j < points.length - 1; j++) {
  17756. const base = j + i * points.length;
  17757. const a = base;
  17758. const b = base + points.length;
  17759. const c = base + points.length + 1;
  17760. const d = base + 1; // faces
  17761. indices.push(a, b, d);
  17762. indices.push(b, c, d);
  17763. }
  17764. } // build geometry
  17765. this.setIndex(indices);
  17766. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17767. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
  17768. this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
  17769. // because the corresponding vertices are identical (but still have different UVs).
  17770. if (phiLength === Math.PI * 2) {
  17771. const normals = this.attributes.normal.array;
  17772. const n1 = new Vector3();
  17773. const n2 = new Vector3();
  17774. const n = new Vector3(); // this is the buffer offset for the last line of vertices
  17775. const base = segments * points.length * 3;
  17776. for (let i = 0, j = 0; i < points.length; i++, j += 3) {
  17777. // select the normal of the vertex in the first line
  17778. n1.x = normals[j + 0];
  17779. n1.y = normals[j + 1];
  17780. n1.z = normals[j + 2]; // select the normal of the vertex in the last line
  17781. n2.x = normals[base + j + 0];
  17782. n2.y = normals[base + j + 1];
  17783. n2.z = normals[base + j + 2]; // average normals
  17784. n.addVectors(n1, n2).normalize(); // assign the new values to both normals
  17785. normals[j + 0] = normals[base + j + 0] = n.x;
  17786. normals[j + 1] = normals[base + j + 1] = n.y;
  17787. normals[j + 2] = normals[base + j + 2] = n.z;
  17788. }
  17789. }
  17790. }
  17791. }
  17792. class OctahedronGeometry extends PolyhedronGeometry {
  17793. constructor(radius = 1, detail = 0) {
  17794. const vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  17795. 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];
  17796. super(vertices, indices, radius, detail);
  17797. this.type = 'OctahedronGeometry';
  17798. this.parameters = {
  17799. radius: radius,
  17800. detail: detail
  17801. };
  17802. }
  17803. }
  17804. /**
  17805. * Parametric Surfaces Geometry
  17806. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  17807. */
  17808. class ParametricGeometry extends BufferGeometry {
  17809. constructor(func, slices, stacks) {
  17810. super();
  17811. this.type = 'ParametricGeometry';
  17812. this.parameters = {
  17813. func: func,
  17814. slices: slices,
  17815. stacks: stacks
  17816. }; // buffers
  17817. const indices = [];
  17818. const vertices = [];
  17819. const normals = [];
  17820. const uvs = [];
  17821. const EPS = 0.00001;
  17822. const normal = new Vector3();
  17823. const p0 = new Vector3(),
  17824. p1 = new Vector3();
  17825. const pu = new Vector3(),
  17826. pv = new Vector3();
  17827. if (func.length < 3) {
  17828. console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');
  17829. } // generate vertices, normals and uvs
  17830. const sliceCount = slices + 1;
  17831. for (let i = 0; i <= stacks; i++) {
  17832. const v = i / stacks;
  17833. for (let j = 0; j <= slices; j++) {
  17834. const u = j / slices; // vertex
  17835. func(u, v, p0);
  17836. vertices.push(p0.x, p0.y, p0.z); // normal
  17837. // approximate tangent vectors via finite differences
  17838. if (u - EPS >= 0) {
  17839. func(u - EPS, v, p1);
  17840. pu.subVectors(p0, p1);
  17841. } else {
  17842. func(u + EPS, v, p1);
  17843. pu.subVectors(p1, p0);
  17844. }
  17845. if (v - EPS >= 0) {
  17846. func(u, v - EPS, p1);
  17847. pv.subVectors(p0, p1);
  17848. } else {
  17849. func(u, v + EPS, p1);
  17850. pv.subVectors(p1, p0);
  17851. } // cross product of tangent vectors returns surface normal
  17852. normal.crossVectors(pu, pv).normalize();
  17853. normals.push(normal.x, normal.y, normal.z); // uv
  17854. uvs.push(u, v);
  17855. }
  17856. } // generate indices
  17857. for (let i = 0; i < stacks; i++) {
  17858. for (let j = 0; j < slices; j++) {
  17859. const a = i * sliceCount + j;
  17860. const b = i * sliceCount + j + 1;
  17861. const c = (i + 1) * sliceCount + j + 1;
  17862. const d = (i + 1) * sliceCount + j; // faces one and two
  17863. indices.push(a, b, d);
  17864. indices.push(b, c, d);
  17865. }
  17866. } // build geometry
  17867. this.setIndex(indices);
  17868. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17869. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17870. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17871. }
  17872. }
  17873. class RingGeometry extends BufferGeometry {
  17874. constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) {
  17875. super();
  17876. this.type = 'RingGeometry';
  17877. this.parameters = {
  17878. innerRadius: innerRadius,
  17879. outerRadius: outerRadius,
  17880. thetaSegments: thetaSegments,
  17881. phiSegments: phiSegments,
  17882. thetaStart: thetaStart,
  17883. thetaLength: thetaLength
  17884. };
  17885. thetaSegments = Math.max(3, thetaSegments);
  17886. phiSegments = Math.max(1, phiSegments); // buffers
  17887. const indices = [];
  17888. const vertices = [];
  17889. const normals = [];
  17890. const uvs = []; // some helper variables
  17891. let radius = innerRadius;
  17892. const radiusStep = (outerRadius - innerRadius) / phiSegments;
  17893. const vertex = new Vector3();
  17894. const uv = new Vector2(); // generate vertices, normals and uvs
  17895. for (let j = 0; j <= phiSegments; j++) {
  17896. for (let i = 0; i <= thetaSegments; i++) {
  17897. // values are generate from the inside of the ring to the outside
  17898. const segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  17899. vertex.x = radius * Math.cos(segment);
  17900. vertex.y = radius * Math.sin(segment);
  17901. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17902. normals.push(0, 0, 1); // uv
  17903. uv.x = (vertex.x / outerRadius + 1) / 2;
  17904. uv.y = (vertex.y / outerRadius + 1) / 2;
  17905. uvs.push(uv.x, uv.y);
  17906. } // increase the radius for next row of vertices
  17907. radius += radiusStep;
  17908. } // indices
  17909. for (let j = 0; j < phiSegments; j++) {
  17910. const thetaSegmentLevel = j * (thetaSegments + 1);
  17911. for (let i = 0; i < thetaSegments; i++) {
  17912. const segment = i + thetaSegmentLevel;
  17913. const a = segment;
  17914. const b = segment + thetaSegments + 1;
  17915. const c = segment + thetaSegments + 2;
  17916. const d = segment + 1; // faces
  17917. indices.push(a, b, d);
  17918. indices.push(b, c, d);
  17919. }
  17920. } // build geometry
  17921. this.setIndex(indices);
  17922. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17923. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17924. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17925. }
  17926. }
  17927. class ShapeGeometry extends BufferGeometry {
  17928. constructor(shapes, curveSegments = 12) {
  17929. super();
  17930. this.type = 'ShapeGeometry';
  17931. this.parameters = {
  17932. shapes: shapes,
  17933. curveSegments: curveSegments
  17934. }; // buffers
  17935. const indices = [];
  17936. const vertices = [];
  17937. const normals = [];
  17938. const uvs = []; // helper variables
  17939. let groupStart = 0;
  17940. let groupCount = 0; // allow single and array values for "shapes" parameter
  17941. if (Array.isArray(shapes) === false) {
  17942. addShape(shapes);
  17943. } else {
  17944. for (let i = 0; i < shapes.length; i++) {
  17945. addShape(shapes[i]);
  17946. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  17947. groupStart += groupCount;
  17948. groupCount = 0;
  17949. }
  17950. } // build geometry
  17951. this.setIndex(indices);
  17952. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17953. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17954. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  17955. function addShape(shape) {
  17956. const indexOffset = vertices.length / 3;
  17957. const points = shape.extractPoints(curveSegments);
  17958. let shapeVertices = points.shape;
  17959. const shapeHoles = points.holes; // check direction of vertices
  17960. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  17961. shapeVertices = shapeVertices.reverse();
  17962. }
  17963. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  17964. const shapeHole = shapeHoles[i];
  17965. if (ShapeUtils.isClockWise(shapeHole) === true) {
  17966. shapeHoles[i] = shapeHole.reverse();
  17967. }
  17968. }
  17969. const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  17970. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  17971. const shapeHole = shapeHoles[i];
  17972. shapeVertices = shapeVertices.concat(shapeHole);
  17973. } // vertices, normals, uvs
  17974. for (let i = 0, l = shapeVertices.length; i < l; i++) {
  17975. const vertex = shapeVertices[i];
  17976. vertices.push(vertex.x, vertex.y, 0);
  17977. normals.push(0, 0, 1);
  17978. uvs.push(vertex.x, vertex.y); // world uvs
  17979. } // incides
  17980. for (let i = 0, l = faces.length; i < l; i++) {
  17981. const face = faces[i];
  17982. const a = face[0] + indexOffset;
  17983. const b = face[1] + indexOffset;
  17984. const c = face[2] + indexOffset;
  17985. indices.push(a, b, c);
  17986. groupCount += 3;
  17987. }
  17988. }
  17989. }
  17990. toJSON() {
  17991. const data = BufferGeometry.prototype.toJSON.call(this);
  17992. const shapes = this.parameters.shapes;
  17993. return toJSON(shapes, data);
  17994. }
  17995. }
  17996. function toJSON(shapes, data) {
  17997. data.shapes = [];
  17998. if (Array.isArray(shapes)) {
  17999. for (let i = 0, l = shapes.length; i < l; i++) {
  18000. const shape = shapes[i];
  18001. data.shapes.push(shape.uuid);
  18002. }
  18003. } else {
  18004. data.shapes.push(shapes.uuid);
  18005. }
  18006. return data;
  18007. }
  18008. class SphereGeometry extends BufferGeometry {
  18009. constructor(radius = 1, widthSegments = 8, heightSegments = 6, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) {
  18010. super();
  18011. this.type = 'SphereGeometry';
  18012. this.parameters = {
  18013. radius: radius,
  18014. widthSegments: widthSegments,
  18015. heightSegments: heightSegments,
  18016. phiStart: phiStart,
  18017. phiLength: phiLength,
  18018. thetaStart: thetaStart,
  18019. thetaLength: thetaLength
  18020. };
  18021. widthSegments = Math.max(3, Math.floor(widthSegments));
  18022. heightSegments = Math.max(2, Math.floor(heightSegments));
  18023. const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  18024. let index = 0;
  18025. const grid = [];
  18026. const vertex = new Vector3();
  18027. const normal = new Vector3(); // buffers
  18028. const indices = [];
  18029. const vertices = [];
  18030. const normals = [];
  18031. const uvs = []; // generate vertices, normals and uvs
  18032. for (let iy = 0; iy <= heightSegments; iy++) {
  18033. const verticesRow = [];
  18034. const v = iy / heightSegments; // special case for the poles
  18035. let uOffset = 0;
  18036. if (iy == 0 && thetaStart == 0) {
  18037. uOffset = 0.5 / widthSegments;
  18038. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  18039. uOffset = -0.5 / widthSegments;
  18040. }
  18041. for (let ix = 0; ix <= widthSegments; ix++) {
  18042. const u = ix / widthSegments; // vertex
  18043. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  18044. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  18045. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  18046. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18047. normal.copy(vertex).normalize();
  18048. normals.push(normal.x, normal.y, normal.z); // uv
  18049. uvs.push(u + uOffset, 1 - v);
  18050. verticesRow.push(index++);
  18051. }
  18052. grid.push(verticesRow);
  18053. } // indices
  18054. for (let iy = 0; iy < heightSegments; iy++) {
  18055. for (let ix = 0; ix < widthSegments; ix++) {
  18056. const a = grid[iy][ix + 1];
  18057. const b = grid[iy][ix];
  18058. const c = grid[iy + 1][ix];
  18059. const d = grid[iy + 1][ix + 1];
  18060. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  18061. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  18062. }
  18063. } // build geometry
  18064. this.setIndex(indices);
  18065. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18066. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18067. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18068. }
  18069. }
  18070. class TetrahedronGeometry extends PolyhedronGeometry {
  18071. constructor(radius = 1, detail = 0) {
  18072. const vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  18073. const indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  18074. super(vertices, indices, radius, detail);
  18075. this.type = 'TetrahedronGeometry';
  18076. this.parameters = {
  18077. radius: radius,
  18078. detail: detail
  18079. };
  18080. }
  18081. }
  18082. /**
  18083. * Text = 3D Text
  18084. *
  18085. * parameters = {
  18086. * font: <THREE.Font>, // font
  18087. *
  18088. * size: <float>, // size of the text
  18089. * height: <float>, // thickness to extrude text
  18090. * curveSegments: <int>, // number of points on the curves
  18091. *
  18092. * bevelEnabled: <bool>, // turn on bevel
  18093. * bevelThickness: <float>, // how deep into text bevel goes
  18094. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  18095. * bevelOffset: <float> // how far from text outline does bevel start
  18096. * }
  18097. */
  18098. class TextGeometry extends ExtrudeGeometry {
  18099. constructor(text, parameters = {}) {
  18100. const font = parameters.font;
  18101. if (!(font && font.isFont)) {
  18102. console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');
  18103. return new BufferGeometry();
  18104. }
  18105. const shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry API
  18106. parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults
  18107. if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;
  18108. if (parameters.bevelSize === undefined) parameters.bevelSize = 8;
  18109. if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;
  18110. super(shapes, parameters);
  18111. this.type = 'TextGeometry';
  18112. }
  18113. }
  18114. class TorusGeometry extends BufferGeometry {
  18115. constructor(radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) {
  18116. super();
  18117. this.type = 'TorusGeometry';
  18118. this.parameters = {
  18119. radius: radius,
  18120. tube: tube,
  18121. radialSegments: radialSegments,
  18122. tubularSegments: tubularSegments,
  18123. arc: arc
  18124. };
  18125. radialSegments = Math.floor(radialSegments);
  18126. tubularSegments = Math.floor(tubularSegments); // buffers
  18127. const indices = [];
  18128. const vertices = [];
  18129. const normals = [];
  18130. const uvs = []; // helper variables
  18131. const center = new Vector3();
  18132. const vertex = new Vector3();
  18133. const normal = new Vector3(); // generate vertices, normals and uvs
  18134. for (let j = 0; j <= radialSegments; j++) {
  18135. for (let i = 0; i <= tubularSegments; i++) {
  18136. const u = i / tubularSegments * arc;
  18137. const v = j / radialSegments * Math.PI * 2; // vertex
  18138. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  18139. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  18140. vertex.z = tube * Math.sin(v);
  18141. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18142. center.x = radius * Math.cos(u);
  18143. center.y = radius * Math.sin(u);
  18144. normal.subVectors(vertex, center).normalize();
  18145. normals.push(normal.x, normal.y, normal.z); // uv
  18146. uvs.push(i / tubularSegments);
  18147. uvs.push(j / radialSegments);
  18148. }
  18149. } // generate indices
  18150. for (let j = 1; j <= radialSegments; j++) {
  18151. for (let i = 1; i <= tubularSegments; i++) {
  18152. // indices
  18153. const a = (tubularSegments + 1) * j + i - 1;
  18154. const b = (tubularSegments + 1) * (j - 1) + i - 1;
  18155. const c = (tubularSegments + 1) * (j - 1) + i;
  18156. const d = (tubularSegments + 1) * j + i; // faces
  18157. indices.push(a, b, d);
  18158. indices.push(b, c, d);
  18159. }
  18160. } // build geometry
  18161. this.setIndex(indices);
  18162. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18163. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18164. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18165. }
  18166. }
  18167. class TorusKnotGeometry extends BufferGeometry {
  18168. constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) {
  18169. super();
  18170. this.type = 'TorusKnotGeometry';
  18171. this.parameters = {
  18172. radius: radius,
  18173. tube: tube,
  18174. tubularSegments: tubularSegments,
  18175. radialSegments: radialSegments,
  18176. p: p,
  18177. q: q
  18178. };
  18179. tubularSegments = Math.floor(tubularSegments);
  18180. radialSegments = Math.floor(radialSegments); // buffers
  18181. const indices = [];
  18182. const vertices = [];
  18183. const normals = [];
  18184. const uvs = []; // helper variables
  18185. const vertex = new Vector3();
  18186. const normal = new Vector3();
  18187. const P1 = new Vector3();
  18188. const P2 = new Vector3();
  18189. const B = new Vector3();
  18190. const T = new Vector3();
  18191. const N = new Vector3(); // generate vertices, normals and uvs
  18192. for (let i = 0; i <= tubularSegments; ++i) {
  18193. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  18194. 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.
  18195. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  18196. calculatePositionOnCurve(u, p, q, radius, P1);
  18197. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  18198. T.subVectors(P2, P1);
  18199. N.addVectors(P2, P1);
  18200. B.crossVectors(T, N);
  18201. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  18202. B.normalize();
  18203. N.normalize();
  18204. for (let j = 0; j <= radialSegments; ++j) {
  18205. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  18206. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  18207. const v = j / radialSegments * Math.PI * 2;
  18208. const cx = -tube * Math.cos(v);
  18209. const cy = tube * Math.sin(v); // now calculate the final vertex position.
  18210. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  18211. vertex.x = P1.x + (cx * N.x + cy * B.x);
  18212. vertex.y = P1.y + (cx * N.y + cy * B.y);
  18213. vertex.z = P1.z + (cx * N.z + cy * B.z);
  18214. 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)
  18215. normal.subVectors(vertex, P1).normalize();
  18216. normals.push(normal.x, normal.y, normal.z); // uv
  18217. uvs.push(i / tubularSegments);
  18218. uvs.push(j / radialSegments);
  18219. }
  18220. } // generate indices
  18221. for (let j = 1; j <= tubularSegments; j++) {
  18222. for (let i = 1; i <= radialSegments; i++) {
  18223. // indices
  18224. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  18225. const b = (radialSegments + 1) * j + (i - 1);
  18226. const c = (radialSegments + 1) * j + i;
  18227. const d = (radialSegments + 1) * (j - 1) + i; // faces
  18228. indices.push(a, b, d);
  18229. indices.push(b, c, d);
  18230. }
  18231. } // build geometry
  18232. this.setIndex(indices);
  18233. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18234. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18235. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  18236. function calculatePositionOnCurve(u, p, q, radius, position) {
  18237. const cu = Math.cos(u);
  18238. const su = Math.sin(u);
  18239. const quOverP = q / p * u;
  18240. const cs = Math.cos(quOverP);
  18241. position.x = radius * (2 + cs) * 0.5 * cu;
  18242. position.y = radius * (2 + cs) * su * 0.5;
  18243. position.z = radius * Math.sin(quOverP) * 0.5;
  18244. }
  18245. }
  18246. }
  18247. class TubeGeometry extends BufferGeometry {
  18248. constructor(path, tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) {
  18249. super();
  18250. this.type = 'TubeGeometry';
  18251. this.parameters = {
  18252. path: path,
  18253. tubularSegments: tubularSegments,
  18254. radius: radius,
  18255. radialSegments: radialSegments,
  18256. closed: closed
  18257. };
  18258. const frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  18259. this.tangents = frames.tangents;
  18260. this.normals = frames.normals;
  18261. this.binormals = frames.binormals; // helper variables
  18262. const vertex = new Vector3();
  18263. const normal = new Vector3();
  18264. const uv = new Vector2();
  18265. let P = new Vector3(); // buffer
  18266. const vertices = [];
  18267. const normals = [];
  18268. const uvs = [];
  18269. const indices = []; // create buffer data
  18270. generateBufferData(); // build geometry
  18271. this.setIndex(indices);
  18272. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18273. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18274. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  18275. function generateBufferData() {
  18276. for (let i = 0; i < tubularSegments; i++) {
  18277. generateSegment(i);
  18278. } // if the geometry is not closed, generate the last row of vertices and normals
  18279. // at the regular position on the given path
  18280. //
  18281. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  18282. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  18283. // this makes it easy compute correct values for closed geometries
  18284. generateUVs(); // finally create faces
  18285. generateIndices();
  18286. }
  18287. function generateSegment(i) {
  18288. // we use getPointAt to sample evenly distributed points from the given path
  18289. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  18290. const N = frames.normals[i];
  18291. const B = frames.binormals[i]; // generate normals and vertices for the current segment
  18292. for (let j = 0; j <= radialSegments; j++) {
  18293. const v = j / radialSegments * Math.PI * 2;
  18294. const sin = Math.sin(v);
  18295. const cos = -Math.cos(v); // normal
  18296. normal.x = cos * N.x + sin * B.x;
  18297. normal.y = cos * N.y + sin * B.y;
  18298. normal.z = cos * N.z + sin * B.z;
  18299. normal.normalize();
  18300. normals.push(normal.x, normal.y, normal.z); // vertex
  18301. vertex.x = P.x + radius * normal.x;
  18302. vertex.y = P.y + radius * normal.y;
  18303. vertex.z = P.z + radius * normal.z;
  18304. vertices.push(vertex.x, vertex.y, vertex.z);
  18305. }
  18306. }
  18307. function generateIndices() {
  18308. for (let j = 1; j <= tubularSegments; j++) {
  18309. for (let i = 1; i <= radialSegments; i++) {
  18310. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  18311. const b = (radialSegments + 1) * j + (i - 1);
  18312. const c = (radialSegments + 1) * j + i;
  18313. const d = (radialSegments + 1) * (j - 1) + i; // faces
  18314. indices.push(a, b, d);
  18315. indices.push(b, c, d);
  18316. }
  18317. }
  18318. }
  18319. function generateUVs() {
  18320. for (let i = 0; i <= tubularSegments; i++) {
  18321. for (let j = 0; j <= radialSegments; j++) {
  18322. uv.x = i / tubularSegments;
  18323. uv.y = j / radialSegments;
  18324. uvs.push(uv.x, uv.y);
  18325. }
  18326. }
  18327. }
  18328. }
  18329. toJSON() {
  18330. const data = BufferGeometry.prototype.toJSON.call(this);
  18331. data.path = this.parameters.path.toJSON();
  18332. return data;
  18333. }
  18334. }
  18335. class WireframeGeometry extends BufferGeometry {
  18336. constructor(geometry) {
  18337. super();
  18338. this.type = 'WireframeGeometry';
  18339. if (geometry.isGeometry === true) {
  18340. console.error('THREE.WireframeGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  18341. return;
  18342. } // buffer
  18343. const vertices = []; // helper variables
  18344. const edge = [0, 0],
  18345. edges = {};
  18346. const vertex = new Vector3();
  18347. if (geometry.index !== null) {
  18348. // indexed BufferGeometry
  18349. const position = geometry.attributes.position;
  18350. const indices = geometry.index;
  18351. let groups = geometry.groups;
  18352. if (groups.length === 0) {
  18353. groups = [{
  18354. start: 0,
  18355. count: indices.count,
  18356. materialIndex: 0
  18357. }];
  18358. } // create a data structure that contains all eges without duplicates
  18359. for (let o = 0, ol = groups.length; o < ol; ++o) {
  18360. const group = groups[o];
  18361. const start = group.start;
  18362. const count = group.count;
  18363. for (let i = start, l = start + count; i < l; i += 3) {
  18364. for (let j = 0; j < 3; j++) {
  18365. const edge1 = indices.getX(i + j);
  18366. const edge2 = indices.getX(i + (j + 1) % 3);
  18367. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  18368. edge[1] = Math.max(edge1, edge2);
  18369. const key = edge[0] + ',' + edge[1];
  18370. if (edges[key] === undefined) {
  18371. edges[key] = {
  18372. index1: edge[0],
  18373. index2: edge[1]
  18374. };
  18375. }
  18376. }
  18377. }
  18378. } // generate vertices
  18379. for (const key in edges) {
  18380. const e = edges[key];
  18381. vertex.fromBufferAttribute(position, e.index1);
  18382. vertices.push(vertex.x, vertex.y, vertex.z);
  18383. vertex.fromBufferAttribute(position, e.index2);
  18384. vertices.push(vertex.x, vertex.y, vertex.z);
  18385. }
  18386. } else {
  18387. // non-indexed BufferGeometry
  18388. const position = geometry.attributes.position;
  18389. for (let i = 0, l = position.count / 3; i < l; i++) {
  18390. for (let j = 0; j < 3; j++) {
  18391. // three edges per triangle, an edge is represented as (index1, index2)
  18392. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  18393. const index1 = 3 * i + j;
  18394. vertex.fromBufferAttribute(position, index1);
  18395. vertices.push(vertex.x, vertex.y, vertex.z);
  18396. const index2 = 3 * i + (j + 1) % 3;
  18397. vertex.fromBufferAttribute(position, index2);
  18398. vertices.push(vertex.x, vertex.y, vertex.z);
  18399. }
  18400. }
  18401. } // build geometry
  18402. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18403. }
  18404. }
  18405. var Geometries = /*#__PURE__*/Object.freeze({
  18406. __proto__: null,
  18407. BoxGeometry: BoxGeometry,
  18408. BoxBufferGeometry: BoxGeometry,
  18409. CircleGeometry: CircleGeometry,
  18410. CircleBufferGeometry: CircleGeometry,
  18411. ConeGeometry: ConeGeometry,
  18412. ConeBufferGeometry: ConeGeometry,
  18413. CylinderGeometry: CylinderGeometry,
  18414. CylinderBufferGeometry: CylinderGeometry,
  18415. DodecahedronGeometry: DodecahedronGeometry,
  18416. DodecahedronBufferGeometry: DodecahedronGeometry,
  18417. EdgesGeometry: EdgesGeometry,
  18418. ExtrudeGeometry: ExtrudeGeometry,
  18419. ExtrudeBufferGeometry: ExtrudeGeometry,
  18420. IcosahedronGeometry: IcosahedronGeometry,
  18421. IcosahedronBufferGeometry: IcosahedronGeometry,
  18422. LatheGeometry: LatheGeometry,
  18423. LatheBufferGeometry: LatheGeometry,
  18424. OctahedronGeometry: OctahedronGeometry,
  18425. OctahedronBufferGeometry: OctahedronGeometry,
  18426. ParametricGeometry: ParametricGeometry,
  18427. ParametricBufferGeometry: ParametricGeometry,
  18428. PlaneGeometry: PlaneGeometry,
  18429. PlaneBufferGeometry: PlaneGeometry,
  18430. PolyhedronGeometry: PolyhedronGeometry,
  18431. PolyhedronBufferGeometry: PolyhedronGeometry,
  18432. RingGeometry: RingGeometry,
  18433. RingBufferGeometry: RingGeometry,
  18434. ShapeGeometry: ShapeGeometry,
  18435. ShapeBufferGeometry: ShapeGeometry,
  18436. SphereGeometry: SphereGeometry,
  18437. SphereBufferGeometry: SphereGeometry,
  18438. TetrahedronGeometry: TetrahedronGeometry,
  18439. TetrahedronBufferGeometry: TetrahedronGeometry,
  18440. TextGeometry: TextGeometry,
  18441. TextBufferGeometry: TextGeometry,
  18442. TorusGeometry: TorusGeometry,
  18443. TorusBufferGeometry: TorusGeometry,
  18444. TorusKnotGeometry: TorusKnotGeometry,
  18445. TorusKnotBufferGeometry: TorusKnotGeometry,
  18446. TubeGeometry: TubeGeometry,
  18447. TubeBufferGeometry: TubeGeometry,
  18448. WireframeGeometry: WireframeGeometry
  18449. });
  18450. /**
  18451. * parameters = {
  18452. * color: <THREE.Color>
  18453. * }
  18454. */
  18455. class ShadowMaterial extends Material {
  18456. constructor(parameters) {
  18457. super();
  18458. this.type = 'ShadowMaterial';
  18459. this.color = new Color(0x000000);
  18460. this.transparent = true;
  18461. this.setValues(parameters);
  18462. }
  18463. copy(source) {
  18464. super.copy(source);
  18465. this.color.copy(source.color);
  18466. return this;
  18467. }
  18468. }
  18469. ShadowMaterial.prototype.isShadowMaterial = true;
  18470. class RawShaderMaterial extends ShaderMaterial {
  18471. constructor(parameters) {
  18472. super(parameters);
  18473. this.type = 'RawShaderMaterial';
  18474. }
  18475. }
  18476. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  18477. /**
  18478. * parameters = {
  18479. * color: <hex>,
  18480. * roughness: <float>,
  18481. * metalness: <float>,
  18482. * opacity: <float>,
  18483. *
  18484. * map: new THREE.Texture( <Image> ),
  18485. *
  18486. * lightMap: new THREE.Texture( <Image> ),
  18487. * lightMapIntensity: <float>
  18488. *
  18489. * aoMap: new THREE.Texture( <Image> ),
  18490. * aoMapIntensity: <float>
  18491. *
  18492. * emissive: <hex>,
  18493. * emissiveIntensity: <float>
  18494. * emissiveMap: new THREE.Texture( <Image> ),
  18495. *
  18496. * bumpMap: new THREE.Texture( <Image> ),
  18497. * bumpScale: <float>,
  18498. *
  18499. * normalMap: new THREE.Texture( <Image> ),
  18500. * normalMapType: THREE.TangentSpaceNormalMap,
  18501. * normalScale: <Vector2>,
  18502. *
  18503. * displacementMap: new THREE.Texture( <Image> ),
  18504. * displacementScale: <float>,
  18505. * displacementBias: <float>,
  18506. *
  18507. * roughnessMap: new THREE.Texture( <Image> ),
  18508. *
  18509. * metalnessMap: new THREE.Texture( <Image> ),
  18510. *
  18511. * alphaMap: new THREE.Texture( <Image> ),
  18512. *
  18513. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  18514. * envMapIntensity: <float>
  18515. *
  18516. * refractionRatio: <float>,
  18517. *
  18518. * wireframe: <boolean>,
  18519. * wireframeLinewidth: <float>,
  18520. *
  18521. * skinning: <bool>,
  18522. * morphTargets: <bool>,
  18523. * morphNormals: <bool>,
  18524. *
  18525. * flatShading: <bool>
  18526. * }
  18527. */
  18528. class MeshStandardMaterial extends Material {
  18529. constructor(parameters) {
  18530. super();
  18531. this.defines = {
  18532. 'STANDARD': ''
  18533. };
  18534. this.type = 'MeshStandardMaterial';
  18535. this.color = new Color(0xffffff); // diffuse
  18536. this.roughness = 1.0;
  18537. this.metalness = 0.0;
  18538. this.map = null;
  18539. this.lightMap = null;
  18540. this.lightMapIntensity = 1.0;
  18541. this.aoMap = null;
  18542. this.aoMapIntensity = 1.0;
  18543. this.emissive = new Color(0x000000);
  18544. this.emissiveIntensity = 1.0;
  18545. this.emissiveMap = null;
  18546. this.bumpMap = null;
  18547. this.bumpScale = 1;
  18548. this.normalMap = null;
  18549. this.normalMapType = TangentSpaceNormalMap;
  18550. this.normalScale = new Vector2(1, 1);
  18551. this.displacementMap = null;
  18552. this.displacementScale = 1;
  18553. this.displacementBias = 0;
  18554. this.roughnessMap = null;
  18555. this.metalnessMap = null;
  18556. this.alphaMap = null;
  18557. this.envMap = null;
  18558. this.envMapIntensity = 1.0;
  18559. this.refractionRatio = 0.98;
  18560. this.wireframe = false;
  18561. this.wireframeLinewidth = 1;
  18562. this.wireframeLinecap = 'round';
  18563. this.wireframeLinejoin = 'round';
  18564. this.skinning = false;
  18565. this.morphTargets = false;
  18566. this.morphNormals = false;
  18567. this.flatShading = false;
  18568. this.vertexTangents = false;
  18569. this.setValues(parameters);
  18570. }
  18571. copy(source) {
  18572. super.copy(source);
  18573. this.defines = {
  18574. 'STANDARD': ''
  18575. };
  18576. this.color.copy(source.color);
  18577. this.roughness = source.roughness;
  18578. this.metalness = source.metalness;
  18579. this.map = source.map;
  18580. this.lightMap = source.lightMap;
  18581. this.lightMapIntensity = source.lightMapIntensity;
  18582. this.aoMap = source.aoMap;
  18583. this.aoMapIntensity = source.aoMapIntensity;
  18584. this.emissive.copy(source.emissive);
  18585. this.emissiveMap = source.emissiveMap;
  18586. this.emissiveIntensity = source.emissiveIntensity;
  18587. this.bumpMap = source.bumpMap;
  18588. this.bumpScale = source.bumpScale;
  18589. this.normalMap = source.normalMap;
  18590. this.normalMapType = source.normalMapType;
  18591. this.normalScale.copy(source.normalScale);
  18592. this.displacementMap = source.displacementMap;
  18593. this.displacementScale = source.displacementScale;
  18594. this.displacementBias = source.displacementBias;
  18595. this.roughnessMap = source.roughnessMap;
  18596. this.metalnessMap = source.metalnessMap;
  18597. this.alphaMap = source.alphaMap;
  18598. this.envMap = source.envMap;
  18599. this.envMapIntensity = source.envMapIntensity;
  18600. this.refractionRatio = source.refractionRatio;
  18601. this.wireframe = source.wireframe;
  18602. this.wireframeLinewidth = source.wireframeLinewidth;
  18603. this.wireframeLinecap = source.wireframeLinecap;
  18604. this.wireframeLinejoin = source.wireframeLinejoin;
  18605. this.skinning = source.skinning;
  18606. this.morphTargets = source.morphTargets;
  18607. this.morphNormals = source.morphNormals;
  18608. this.flatShading = source.flatShading;
  18609. this.vertexTangents = source.vertexTangents;
  18610. return this;
  18611. }
  18612. }
  18613. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  18614. /**
  18615. * parameters = {
  18616. * clearcoat: <float>,
  18617. * clearcoatMap: new THREE.Texture( <Image> ),
  18618. * clearcoatRoughness: <float>,
  18619. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  18620. * clearcoatNormalScale: <Vector2>,
  18621. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  18622. *
  18623. * reflectivity: <float>,
  18624. * ior: <float>,
  18625. *
  18626. * sheen: <Color>,
  18627. *
  18628. * transmission: <float>,
  18629. * transmissionMap: new THREE.Texture( <Image> )
  18630. * }
  18631. */
  18632. class MeshPhysicalMaterial extends MeshStandardMaterial {
  18633. constructor(parameters) {
  18634. super();
  18635. this.defines = {
  18636. 'STANDARD': '',
  18637. 'PHYSICAL': ''
  18638. };
  18639. this.type = 'MeshPhysicalMaterial';
  18640. this.clearcoat = 0.0;
  18641. this.clearcoatMap = null;
  18642. this.clearcoatRoughness = 0.0;
  18643. this.clearcoatRoughnessMap = null;
  18644. this.clearcoatNormalScale = new Vector2(1, 1);
  18645. this.clearcoatNormalMap = null;
  18646. this.reflectivity = 0.5; // maps to F0 = 0.04
  18647. Object.defineProperty(this, 'ior', {
  18648. get: function () {
  18649. return (1 + 0.4 * this.reflectivity) / (1 - 0.4 * this.reflectivity);
  18650. },
  18651. set: function (ior) {
  18652. this.reflectivity = clamp(2.5 * (ior - 1) / (ior + 1), 0, 1);
  18653. }
  18654. });
  18655. this.sheen = null; // null will disable sheen bsdf
  18656. this.transmission = 0.0;
  18657. this.transmissionMap = null;
  18658. this.setValues(parameters);
  18659. }
  18660. copy(source) {
  18661. super.copy(source);
  18662. this.defines = {
  18663. 'STANDARD': '',
  18664. 'PHYSICAL': ''
  18665. };
  18666. this.clearcoat = source.clearcoat;
  18667. this.clearcoatMap = source.clearcoatMap;
  18668. this.clearcoatRoughness = source.clearcoatRoughness;
  18669. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  18670. this.clearcoatNormalMap = source.clearcoatNormalMap;
  18671. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  18672. this.reflectivity = source.reflectivity;
  18673. if (source.sheen) {
  18674. this.sheen = (this.sheen || new Color()).copy(source.sheen);
  18675. } else {
  18676. this.sheen = null;
  18677. }
  18678. this.transmission = source.transmission;
  18679. this.transmissionMap = source.transmissionMap;
  18680. return this;
  18681. }
  18682. }
  18683. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  18684. /**
  18685. * parameters = {
  18686. * color: <hex>,
  18687. * specular: <hex>,
  18688. * shininess: <float>,
  18689. * opacity: <float>,
  18690. *
  18691. * map: new THREE.Texture( <Image> ),
  18692. *
  18693. * lightMap: new THREE.Texture( <Image> ),
  18694. * lightMapIntensity: <float>
  18695. *
  18696. * aoMap: new THREE.Texture( <Image> ),
  18697. * aoMapIntensity: <float>
  18698. *
  18699. * emissive: <hex>,
  18700. * emissiveIntensity: <float>
  18701. * emissiveMap: new THREE.Texture( <Image> ),
  18702. *
  18703. * bumpMap: new THREE.Texture( <Image> ),
  18704. * bumpScale: <float>,
  18705. *
  18706. * normalMap: new THREE.Texture( <Image> ),
  18707. * normalMapType: THREE.TangentSpaceNormalMap,
  18708. * normalScale: <Vector2>,
  18709. *
  18710. * displacementMap: new THREE.Texture( <Image> ),
  18711. * displacementScale: <float>,
  18712. * displacementBias: <float>,
  18713. *
  18714. * specularMap: new THREE.Texture( <Image> ),
  18715. *
  18716. * alphaMap: new THREE.Texture( <Image> ),
  18717. *
  18718. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  18719. * combine: THREE.MultiplyOperation,
  18720. * reflectivity: <float>,
  18721. * refractionRatio: <float>,
  18722. *
  18723. * wireframe: <boolean>,
  18724. * wireframeLinewidth: <float>,
  18725. *
  18726. * skinning: <bool>,
  18727. * morphTargets: <bool>,
  18728. * morphNormals: <bool>,
  18729. *
  18730. * flatShading: <bool>
  18731. * }
  18732. */
  18733. class MeshPhongMaterial extends Material {
  18734. constructor(parameters) {
  18735. super();
  18736. this.type = 'MeshPhongMaterial';
  18737. this.color = new Color(0xffffff); // diffuse
  18738. this.specular = new Color(0x111111);
  18739. this.shininess = 30;
  18740. this.map = null;
  18741. this.lightMap = null;
  18742. this.lightMapIntensity = 1.0;
  18743. this.aoMap = null;
  18744. this.aoMapIntensity = 1.0;
  18745. this.emissive = new Color(0x000000);
  18746. this.emissiveIntensity = 1.0;
  18747. this.emissiveMap = null;
  18748. this.bumpMap = null;
  18749. this.bumpScale = 1;
  18750. this.normalMap = null;
  18751. this.normalMapType = TangentSpaceNormalMap;
  18752. this.normalScale = new Vector2(1, 1);
  18753. this.displacementMap = null;
  18754. this.displacementScale = 1;
  18755. this.displacementBias = 0;
  18756. this.specularMap = null;
  18757. this.alphaMap = null;
  18758. this.envMap = null;
  18759. this.combine = MultiplyOperation;
  18760. this.reflectivity = 1;
  18761. this.refractionRatio = 0.98;
  18762. this.wireframe = false;
  18763. this.wireframeLinewidth = 1;
  18764. this.wireframeLinecap = 'round';
  18765. this.wireframeLinejoin = 'round';
  18766. this.skinning = false;
  18767. this.morphTargets = false;
  18768. this.morphNormals = false;
  18769. this.flatShading = false;
  18770. this.setValues(parameters);
  18771. }
  18772. copy(source) {
  18773. super.copy(source);
  18774. this.color.copy(source.color);
  18775. this.specular.copy(source.specular);
  18776. this.shininess = source.shininess;
  18777. this.map = source.map;
  18778. this.lightMap = source.lightMap;
  18779. this.lightMapIntensity = source.lightMapIntensity;
  18780. this.aoMap = source.aoMap;
  18781. this.aoMapIntensity = source.aoMapIntensity;
  18782. this.emissive.copy(source.emissive);
  18783. this.emissiveMap = source.emissiveMap;
  18784. this.emissiveIntensity = source.emissiveIntensity;
  18785. this.bumpMap = source.bumpMap;
  18786. this.bumpScale = source.bumpScale;
  18787. this.normalMap = source.normalMap;
  18788. this.normalMapType = source.normalMapType;
  18789. this.normalScale.copy(source.normalScale);
  18790. this.displacementMap = source.displacementMap;
  18791. this.displacementScale = source.displacementScale;
  18792. this.displacementBias = source.displacementBias;
  18793. this.specularMap = source.specularMap;
  18794. this.alphaMap = source.alphaMap;
  18795. this.envMap = source.envMap;
  18796. this.combine = source.combine;
  18797. this.reflectivity = source.reflectivity;
  18798. this.refractionRatio = source.refractionRatio;
  18799. this.wireframe = source.wireframe;
  18800. this.wireframeLinewidth = source.wireframeLinewidth;
  18801. this.wireframeLinecap = source.wireframeLinecap;
  18802. this.wireframeLinejoin = source.wireframeLinejoin;
  18803. this.skinning = source.skinning;
  18804. this.morphTargets = source.morphTargets;
  18805. this.morphNormals = source.morphNormals;
  18806. this.flatShading = source.flatShading;
  18807. return this;
  18808. }
  18809. }
  18810. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  18811. /**
  18812. * parameters = {
  18813. * color: <hex>,
  18814. *
  18815. * map: new THREE.Texture( <Image> ),
  18816. * gradientMap: new THREE.Texture( <Image> ),
  18817. *
  18818. * lightMap: new THREE.Texture( <Image> ),
  18819. * lightMapIntensity: <float>
  18820. *
  18821. * aoMap: new THREE.Texture( <Image> ),
  18822. * aoMapIntensity: <float>
  18823. *
  18824. * emissive: <hex>,
  18825. * emissiveIntensity: <float>
  18826. * emissiveMap: new THREE.Texture( <Image> ),
  18827. *
  18828. * bumpMap: new THREE.Texture( <Image> ),
  18829. * bumpScale: <float>,
  18830. *
  18831. * normalMap: new THREE.Texture( <Image> ),
  18832. * normalMapType: THREE.TangentSpaceNormalMap,
  18833. * normalScale: <Vector2>,
  18834. *
  18835. * displacementMap: new THREE.Texture( <Image> ),
  18836. * displacementScale: <float>,
  18837. * displacementBias: <float>,
  18838. *
  18839. * alphaMap: new THREE.Texture( <Image> ),
  18840. *
  18841. * wireframe: <boolean>,
  18842. * wireframeLinewidth: <float>,
  18843. *
  18844. * skinning: <bool>,
  18845. * morphTargets: <bool>,
  18846. * morphNormals: <bool>
  18847. * }
  18848. */
  18849. class MeshToonMaterial extends Material {
  18850. constructor(parameters) {
  18851. super();
  18852. this.defines = {
  18853. 'TOON': ''
  18854. };
  18855. this.type = 'MeshToonMaterial';
  18856. this.color = new Color(0xffffff);
  18857. this.map = null;
  18858. this.gradientMap = null;
  18859. this.lightMap = null;
  18860. this.lightMapIntensity = 1.0;
  18861. this.aoMap = null;
  18862. this.aoMapIntensity = 1.0;
  18863. this.emissive = new Color(0x000000);
  18864. this.emissiveIntensity = 1.0;
  18865. this.emissiveMap = null;
  18866. this.bumpMap = null;
  18867. this.bumpScale = 1;
  18868. this.normalMap = null;
  18869. this.normalMapType = TangentSpaceNormalMap;
  18870. this.normalScale = new Vector2(1, 1);
  18871. this.displacementMap = null;
  18872. this.displacementScale = 1;
  18873. this.displacementBias = 0;
  18874. this.alphaMap = null;
  18875. this.wireframe = false;
  18876. this.wireframeLinewidth = 1;
  18877. this.wireframeLinecap = 'round';
  18878. this.wireframeLinejoin = 'round';
  18879. this.skinning = false;
  18880. this.morphTargets = false;
  18881. this.morphNormals = false;
  18882. this.setValues(parameters);
  18883. }
  18884. copy(source) {
  18885. super.copy(source);
  18886. this.color.copy(source.color);
  18887. this.map = source.map;
  18888. this.gradientMap = source.gradientMap;
  18889. this.lightMap = source.lightMap;
  18890. this.lightMapIntensity = source.lightMapIntensity;
  18891. this.aoMap = source.aoMap;
  18892. this.aoMapIntensity = source.aoMapIntensity;
  18893. this.emissive.copy(source.emissive);
  18894. this.emissiveMap = source.emissiveMap;
  18895. this.emissiveIntensity = source.emissiveIntensity;
  18896. this.bumpMap = source.bumpMap;
  18897. this.bumpScale = source.bumpScale;
  18898. this.normalMap = source.normalMap;
  18899. this.normalMapType = source.normalMapType;
  18900. this.normalScale.copy(source.normalScale);
  18901. this.displacementMap = source.displacementMap;
  18902. this.displacementScale = source.displacementScale;
  18903. this.displacementBias = source.displacementBias;
  18904. this.alphaMap = source.alphaMap;
  18905. this.wireframe = source.wireframe;
  18906. this.wireframeLinewidth = source.wireframeLinewidth;
  18907. this.wireframeLinecap = source.wireframeLinecap;
  18908. this.wireframeLinejoin = source.wireframeLinejoin;
  18909. this.skinning = source.skinning;
  18910. this.morphTargets = source.morphTargets;
  18911. this.morphNormals = source.morphNormals;
  18912. return this;
  18913. }
  18914. }
  18915. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  18916. /**
  18917. * parameters = {
  18918. * opacity: <float>,
  18919. *
  18920. * bumpMap: new THREE.Texture( <Image> ),
  18921. * bumpScale: <float>,
  18922. *
  18923. * normalMap: new THREE.Texture( <Image> ),
  18924. * normalMapType: THREE.TangentSpaceNormalMap,
  18925. * normalScale: <Vector2>,
  18926. *
  18927. * displacementMap: new THREE.Texture( <Image> ),
  18928. * displacementScale: <float>,
  18929. * displacementBias: <float>,
  18930. *
  18931. * wireframe: <boolean>,
  18932. * wireframeLinewidth: <float>
  18933. *
  18934. * skinning: <bool>,
  18935. * morphTargets: <bool>,
  18936. * morphNormals: <bool>,
  18937. *
  18938. * flatShading: <bool>
  18939. * }
  18940. */
  18941. class MeshNormalMaterial extends Material {
  18942. constructor(parameters) {
  18943. super();
  18944. this.type = 'MeshNormalMaterial';
  18945. this.bumpMap = null;
  18946. this.bumpScale = 1;
  18947. this.normalMap = null;
  18948. this.normalMapType = TangentSpaceNormalMap;
  18949. this.normalScale = new Vector2(1, 1);
  18950. this.displacementMap = null;
  18951. this.displacementScale = 1;
  18952. this.displacementBias = 0;
  18953. this.wireframe = false;
  18954. this.wireframeLinewidth = 1;
  18955. this.fog = false;
  18956. this.skinning = false;
  18957. this.morphTargets = false;
  18958. this.morphNormals = false;
  18959. this.flatShading = false;
  18960. this.setValues(parameters);
  18961. }
  18962. copy(source) {
  18963. super.copy(source);
  18964. this.bumpMap = source.bumpMap;
  18965. this.bumpScale = source.bumpScale;
  18966. this.normalMap = source.normalMap;
  18967. this.normalMapType = source.normalMapType;
  18968. this.normalScale.copy(source.normalScale);
  18969. this.displacementMap = source.displacementMap;
  18970. this.displacementScale = source.displacementScale;
  18971. this.displacementBias = source.displacementBias;
  18972. this.wireframe = source.wireframe;
  18973. this.wireframeLinewidth = source.wireframeLinewidth;
  18974. this.skinning = source.skinning;
  18975. this.morphTargets = source.morphTargets;
  18976. this.morphNormals = source.morphNormals;
  18977. this.flatShading = source.flatShading;
  18978. return this;
  18979. }
  18980. }
  18981. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  18982. /**
  18983. * parameters = {
  18984. * color: <hex>,
  18985. * opacity: <float>,
  18986. *
  18987. * map: new THREE.Texture( <Image> ),
  18988. *
  18989. * lightMap: new THREE.Texture( <Image> ),
  18990. * lightMapIntensity: <float>
  18991. *
  18992. * aoMap: new THREE.Texture( <Image> ),
  18993. * aoMapIntensity: <float>
  18994. *
  18995. * emissive: <hex>,
  18996. * emissiveIntensity: <float>
  18997. * emissiveMap: new THREE.Texture( <Image> ),
  18998. *
  18999. * specularMap: new THREE.Texture( <Image> ),
  19000. *
  19001. * alphaMap: new THREE.Texture( <Image> ),
  19002. *
  19003. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  19004. * combine: THREE.Multiply,
  19005. * reflectivity: <float>,
  19006. * refractionRatio: <float>,
  19007. *
  19008. * wireframe: <boolean>,
  19009. * wireframeLinewidth: <float>,
  19010. *
  19011. * skinning: <bool>,
  19012. * morphTargets: <bool>,
  19013. * morphNormals: <bool>
  19014. * }
  19015. */
  19016. class MeshLambertMaterial extends Material {
  19017. constructor(parameters) {
  19018. super();
  19019. this.type = 'MeshLambertMaterial';
  19020. this.color = new Color(0xffffff); // diffuse
  19021. this.map = null;
  19022. this.lightMap = null;
  19023. this.lightMapIntensity = 1.0;
  19024. this.aoMap = null;
  19025. this.aoMapIntensity = 1.0;
  19026. this.emissive = new Color(0x000000);
  19027. this.emissiveIntensity = 1.0;
  19028. this.emissiveMap = null;
  19029. this.specularMap = null;
  19030. this.alphaMap = null;
  19031. this.envMap = null;
  19032. this.combine = MultiplyOperation;
  19033. this.reflectivity = 1;
  19034. this.refractionRatio = 0.98;
  19035. this.wireframe = false;
  19036. this.wireframeLinewidth = 1;
  19037. this.wireframeLinecap = 'round';
  19038. this.wireframeLinejoin = 'round';
  19039. this.skinning = false;
  19040. this.morphTargets = false;
  19041. this.morphNormals = false;
  19042. this.setValues(parameters);
  19043. }
  19044. copy(source) {
  19045. super.copy(source);
  19046. this.color.copy(source.color);
  19047. this.map = source.map;
  19048. this.lightMap = source.lightMap;
  19049. this.lightMapIntensity = source.lightMapIntensity;
  19050. this.aoMap = source.aoMap;
  19051. this.aoMapIntensity = source.aoMapIntensity;
  19052. this.emissive.copy(source.emissive);
  19053. this.emissiveMap = source.emissiveMap;
  19054. this.emissiveIntensity = source.emissiveIntensity;
  19055. this.specularMap = source.specularMap;
  19056. this.alphaMap = source.alphaMap;
  19057. this.envMap = source.envMap;
  19058. this.combine = source.combine;
  19059. this.reflectivity = source.reflectivity;
  19060. this.refractionRatio = source.refractionRatio;
  19061. this.wireframe = source.wireframe;
  19062. this.wireframeLinewidth = source.wireframeLinewidth;
  19063. this.wireframeLinecap = source.wireframeLinecap;
  19064. this.wireframeLinejoin = source.wireframeLinejoin;
  19065. this.skinning = source.skinning;
  19066. this.morphTargets = source.morphTargets;
  19067. this.morphNormals = source.morphNormals;
  19068. return this;
  19069. }
  19070. }
  19071. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  19072. /**
  19073. * parameters = {
  19074. * color: <hex>,
  19075. * opacity: <float>,
  19076. *
  19077. * matcap: new THREE.Texture( <Image> ),
  19078. *
  19079. * map: new THREE.Texture( <Image> ),
  19080. *
  19081. * bumpMap: new THREE.Texture( <Image> ),
  19082. * bumpScale: <float>,
  19083. *
  19084. * normalMap: new THREE.Texture( <Image> ),
  19085. * normalMapType: THREE.TangentSpaceNormalMap,
  19086. * normalScale: <Vector2>,
  19087. *
  19088. * displacementMap: new THREE.Texture( <Image> ),
  19089. * displacementScale: <float>,
  19090. * displacementBias: <float>,
  19091. *
  19092. * alphaMap: new THREE.Texture( <Image> ),
  19093. *
  19094. * skinning: <bool>,
  19095. * morphTargets: <bool>,
  19096. * morphNormals: <bool>
  19097. *
  19098. * flatShading: <bool>
  19099. * }
  19100. */
  19101. class MeshMatcapMaterial extends Material {
  19102. constructor(parameters) {
  19103. super();
  19104. this.defines = {
  19105. 'MATCAP': ''
  19106. };
  19107. this.type = 'MeshMatcapMaterial';
  19108. this.color = new Color(0xffffff); // diffuse
  19109. this.matcap = null;
  19110. this.map = null;
  19111. this.bumpMap = null;
  19112. this.bumpScale = 1;
  19113. this.normalMap = null;
  19114. this.normalMapType = TangentSpaceNormalMap;
  19115. this.normalScale = new Vector2(1, 1);
  19116. this.displacementMap = null;
  19117. this.displacementScale = 1;
  19118. this.displacementBias = 0;
  19119. this.alphaMap = null;
  19120. this.skinning = false;
  19121. this.morphTargets = false;
  19122. this.morphNormals = false;
  19123. this.flatShading = false;
  19124. this.setValues(parameters);
  19125. }
  19126. copy(source) {
  19127. super.copy(source);
  19128. this.defines = {
  19129. 'MATCAP': ''
  19130. };
  19131. this.color.copy(source.color);
  19132. this.matcap = source.matcap;
  19133. this.map = source.map;
  19134. this.bumpMap = source.bumpMap;
  19135. this.bumpScale = source.bumpScale;
  19136. this.normalMap = source.normalMap;
  19137. this.normalMapType = source.normalMapType;
  19138. this.normalScale.copy(source.normalScale);
  19139. this.displacementMap = source.displacementMap;
  19140. this.displacementScale = source.displacementScale;
  19141. this.displacementBias = source.displacementBias;
  19142. this.alphaMap = source.alphaMap;
  19143. this.skinning = source.skinning;
  19144. this.morphTargets = source.morphTargets;
  19145. this.morphNormals = source.morphNormals;
  19146. this.flatShading = source.flatShading;
  19147. return this;
  19148. }
  19149. }
  19150. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  19151. /**
  19152. * parameters = {
  19153. * color: <hex>,
  19154. * opacity: <float>,
  19155. *
  19156. * linewidth: <float>,
  19157. *
  19158. * scale: <float>,
  19159. * dashSize: <float>,
  19160. * gapSize: <float>
  19161. * }
  19162. */
  19163. class LineDashedMaterial extends LineBasicMaterial {
  19164. constructor(parameters) {
  19165. super();
  19166. this.type = 'LineDashedMaterial';
  19167. this.scale = 1;
  19168. this.dashSize = 3;
  19169. this.gapSize = 1;
  19170. this.setValues(parameters);
  19171. }
  19172. copy(source) {
  19173. super.copy(source);
  19174. this.scale = source.scale;
  19175. this.dashSize = source.dashSize;
  19176. this.gapSize = source.gapSize;
  19177. return this;
  19178. }
  19179. }
  19180. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  19181. var Materials = /*#__PURE__*/Object.freeze({
  19182. __proto__: null,
  19183. ShadowMaterial: ShadowMaterial,
  19184. SpriteMaterial: SpriteMaterial,
  19185. RawShaderMaterial: RawShaderMaterial,
  19186. ShaderMaterial: ShaderMaterial,
  19187. PointsMaterial: PointsMaterial,
  19188. MeshPhysicalMaterial: MeshPhysicalMaterial,
  19189. MeshStandardMaterial: MeshStandardMaterial,
  19190. MeshPhongMaterial: MeshPhongMaterial,
  19191. MeshToonMaterial: MeshToonMaterial,
  19192. MeshNormalMaterial: MeshNormalMaterial,
  19193. MeshLambertMaterial: MeshLambertMaterial,
  19194. MeshDepthMaterial: MeshDepthMaterial,
  19195. MeshDistanceMaterial: MeshDistanceMaterial,
  19196. MeshBasicMaterial: MeshBasicMaterial,
  19197. MeshMatcapMaterial: MeshMatcapMaterial,
  19198. LineDashedMaterial: LineDashedMaterial,
  19199. LineBasicMaterial: LineBasicMaterial,
  19200. Material: Material
  19201. });
  19202. const AnimationUtils = {
  19203. // same as Array.prototype.slice, but also works on typed arrays
  19204. arraySlice: function (array, from, to) {
  19205. if (AnimationUtils.isTypedArray(array)) {
  19206. // in ios9 array.subarray(from, undefined) will return empty array
  19207. // but array.subarray(from) or array.subarray(from, len) is correct
  19208. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  19209. }
  19210. return array.slice(from, to);
  19211. },
  19212. // converts an array to a specific type
  19213. convertArray: function (array, type, forceClone) {
  19214. if (!array || // let 'undefined' and 'null' pass
  19215. !forceClone && array.constructor === type) return array;
  19216. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  19217. return new type(array); // create typed array
  19218. }
  19219. return Array.prototype.slice.call(array); // create Array
  19220. },
  19221. isTypedArray: function (object) {
  19222. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  19223. },
  19224. // returns an array by which times and values can be sorted
  19225. getKeyframeOrder: function (times) {
  19226. function compareTime(i, j) {
  19227. return times[i] - times[j];
  19228. }
  19229. const n = times.length;
  19230. const result = new Array(n);
  19231. for (let i = 0; i !== n; ++i) result[i] = i;
  19232. result.sort(compareTime);
  19233. return result;
  19234. },
  19235. // uses the array previously returned by 'getKeyframeOrder' to sort data
  19236. sortedArray: function (values, stride, order) {
  19237. const nValues = values.length;
  19238. const result = new values.constructor(nValues);
  19239. for (let i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  19240. const srcOffset = order[i] * stride;
  19241. for (let j = 0; j !== stride; ++j) {
  19242. result[dstOffset++] = values[srcOffset + j];
  19243. }
  19244. }
  19245. return result;
  19246. },
  19247. // function for parsing AOS keyframe formats
  19248. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  19249. let i = 1,
  19250. key = jsonKeys[0];
  19251. while (key !== undefined && key[valuePropertyName] === undefined) {
  19252. key = jsonKeys[i++];
  19253. }
  19254. if (key === undefined) return; // no data
  19255. let value = key[valuePropertyName];
  19256. if (value === undefined) return; // no data
  19257. if (Array.isArray(value)) {
  19258. do {
  19259. value = key[valuePropertyName];
  19260. if (value !== undefined) {
  19261. times.push(key.time);
  19262. values.push.apply(values, value); // push all elements
  19263. }
  19264. key = jsonKeys[i++];
  19265. } while (key !== undefined);
  19266. } else if (value.toArray !== undefined) {
  19267. // ...assume THREE.Math-ish
  19268. do {
  19269. value = key[valuePropertyName];
  19270. if (value !== undefined) {
  19271. times.push(key.time);
  19272. value.toArray(values, values.length);
  19273. }
  19274. key = jsonKeys[i++];
  19275. } while (key !== undefined);
  19276. } else {
  19277. // otherwise push as-is
  19278. do {
  19279. value = key[valuePropertyName];
  19280. if (value !== undefined) {
  19281. times.push(key.time);
  19282. values.push(value);
  19283. }
  19284. key = jsonKeys[i++];
  19285. } while (key !== undefined);
  19286. }
  19287. },
  19288. subclip: function (sourceClip, name, startFrame, endFrame, fps = 30) {
  19289. const clip = sourceClip.clone();
  19290. clip.name = name;
  19291. const tracks = [];
  19292. for (let i = 0; i < clip.tracks.length; ++i) {
  19293. const track = clip.tracks[i];
  19294. const valueSize = track.getValueSize();
  19295. const times = [];
  19296. const values = [];
  19297. for (let j = 0; j < track.times.length; ++j) {
  19298. const frame = track.times[j] * fps;
  19299. if (frame < startFrame || frame >= endFrame) continue;
  19300. times.push(track.times[j]);
  19301. for (let k = 0; k < valueSize; ++k) {
  19302. values.push(track.values[j * valueSize + k]);
  19303. }
  19304. }
  19305. if (times.length === 0) continue;
  19306. track.times = AnimationUtils.convertArray(times, track.times.constructor);
  19307. track.values = AnimationUtils.convertArray(values, track.values.constructor);
  19308. tracks.push(track);
  19309. }
  19310. clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
  19311. let minStartTime = Infinity;
  19312. for (let i = 0; i < clip.tracks.length; ++i) {
  19313. if (minStartTime > clip.tracks[i].times[0]) {
  19314. minStartTime = clip.tracks[i].times[0];
  19315. }
  19316. } // shift all tracks such that clip begins at t=0
  19317. for (let i = 0; i < clip.tracks.length; ++i) {
  19318. clip.tracks[i].shift(-1 * minStartTime);
  19319. }
  19320. clip.resetDuration();
  19321. return clip;
  19322. },
  19323. makeClipAdditive: function (targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) {
  19324. if (fps <= 0) fps = 30;
  19325. const numTracks = referenceClip.tracks.length;
  19326. const referenceTime = referenceFrame / fps; // Make each track's values relative to the values at the reference frame
  19327. for (let i = 0; i < numTracks; ++i) {
  19328. const referenceTrack = referenceClip.tracks[i];
  19329. const referenceTrackType = referenceTrack.ValueTypeName; // Skip this track if it's non-numeric
  19330. if (referenceTrackType === 'bool' || referenceTrackType === 'string') continue; // Find the track in the target clip whose name and type matches the reference track
  19331. const targetTrack = targetClip.tracks.find(function (track) {
  19332. return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
  19333. });
  19334. if (targetTrack === undefined) continue;
  19335. let referenceOffset = 0;
  19336. const referenceValueSize = referenceTrack.getValueSize();
  19337. if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  19338. referenceOffset = referenceValueSize / 3;
  19339. }
  19340. let targetOffset = 0;
  19341. const targetValueSize = targetTrack.getValueSize();
  19342. if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  19343. targetOffset = targetValueSize / 3;
  19344. }
  19345. const lastIndex = referenceTrack.times.length - 1;
  19346. let referenceValue; // Find the value to subtract out of the track
  19347. if (referenceTime <= referenceTrack.times[0]) {
  19348. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  19349. const startIndex = referenceOffset;
  19350. const endIndex = referenceValueSize - referenceOffset;
  19351. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  19352. } else if (referenceTime >= referenceTrack.times[lastIndex]) {
  19353. // Reference frame is after the last keyframe, so just use the last keyframe
  19354. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  19355. const endIndex = startIndex + referenceValueSize - referenceOffset;
  19356. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  19357. } else {
  19358. // Interpolate to the reference value
  19359. const interpolant = referenceTrack.createInterpolant();
  19360. const startIndex = referenceOffset;
  19361. const endIndex = referenceValueSize - referenceOffset;
  19362. interpolant.evaluate(referenceTime);
  19363. referenceValue = AnimationUtils.arraySlice(interpolant.resultBuffer, startIndex, endIndex);
  19364. } // Conjugate the quaternion
  19365. if (referenceTrackType === 'quaternion') {
  19366. const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
  19367. referenceQuat.toArray(referenceValue);
  19368. } // Subtract the reference value from all of the track values
  19369. const numTimes = targetTrack.times.length;
  19370. for (let j = 0; j < numTimes; ++j) {
  19371. const valueStart = j * targetValueSize + targetOffset;
  19372. if (referenceTrackType === 'quaternion') {
  19373. // Multiply the conjugate for quaternion track types
  19374. Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
  19375. } else {
  19376. const valueEnd = targetValueSize - targetOffset * 2; // Subtract each value for all other numeric track types
  19377. for (let k = 0; k < valueEnd; ++k) {
  19378. targetTrack.values[valueStart + k] -= referenceValue[k];
  19379. }
  19380. }
  19381. }
  19382. }
  19383. targetClip.blendMode = AdditiveAnimationBlendMode;
  19384. return targetClip;
  19385. }
  19386. };
  19387. /**
  19388. * Abstract base class of interpolants over parametric samples.
  19389. *
  19390. * The parameter domain is one dimensional, typically the time or a path
  19391. * along a curve defined by the data.
  19392. *
  19393. * The sample values can have any dimensionality and derived classes may
  19394. * apply special interpretations to the data.
  19395. *
  19396. * This class provides the interval seek in a Template Method, deferring
  19397. * the actual interpolation to derived classes.
  19398. *
  19399. * Time complexity is O(1) for linear access crossing at most two points
  19400. * and O(log N) for random access, where N is the number of positions.
  19401. *
  19402. * References:
  19403. *
  19404. * http://www.oodesign.com/template-method-pattern.html
  19405. *
  19406. */
  19407. class Interpolant {
  19408. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  19409. this.parameterPositions = parameterPositions;
  19410. this._cachedIndex = 0;
  19411. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  19412. this.sampleValues = sampleValues;
  19413. this.valueSize = sampleSize;
  19414. this.settings = null;
  19415. this.DefaultSettings_ = {};
  19416. }
  19417. evaluate(t) {
  19418. const pp = this.parameterPositions;
  19419. let i1 = this._cachedIndex,
  19420. t1 = pp[i1],
  19421. t0 = pp[i1 - 1];
  19422. validate_interval: {
  19423. seek: {
  19424. let right;
  19425. linear_scan: {
  19426. //- See http://jsperf.com/comparison-to-undefined/3
  19427. //- slower code:
  19428. //-
  19429. //- if ( t >= t1 || t1 === undefined ) {
  19430. forward_scan: if (!(t < t1)) {
  19431. for (let giveUpAt = i1 + 2;;) {
  19432. if (t1 === undefined) {
  19433. if (t < t0) break forward_scan; // after end
  19434. i1 = pp.length;
  19435. this._cachedIndex = i1;
  19436. return this.afterEnd_(i1 - 1, t, t0);
  19437. }
  19438. if (i1 === giveUpAt) break; // this loop
  19439. t0 = t1;
  19440. t1 = pp[++i1];
  19441. if (t < t1) {
  19442. // we have arrived at the sought interval
  19443. break seek;
  19444. }
  19445. } // prepare binary search on the right side of the index
  19446. right = pp.length;
  19447. break linear_scan;
  19448. } //- slower code:
  19449. //- if ( t < t0 || t0 === undefined ) {
  19450. if (!(t >= t0)) {
  19451. // looping?
  19452. const t1global = pp[1];
  19453. if (t < t1global) {
  19454. i1 = 2; // + 1, using the scan for the details
  19455. t0 = t1global;
  19456. } // linear reverse scan
  19457. for (let giveUpAt = i1 - 2;;) {
  19458. if (t0 === undefined) {
  19459. // before start
  19460. this._cachedIndex = 0;
  19461. return this.beforeStart_(0, t, t1);
  19462. }
  19463. if (i1 === giveUpAt) break; // this loop
  19464. t1 = t0;
  19465. t0 = pp[--i1 - 1];
  19466. if (t >= t0) {
  19467. // we have arrived at the sought interval
  19468. break seek;
  19469. }
  19470. } // prepare binary search on the left side of the index
  19471. right = i1;
  19472. i1 = 0;
  19473. break linear_scan;
  19474. } // the interval is valid
  19475. break validate_interval;
  19476. } // linear scan
  19477. // binary search
  19478. while (i1 < right) {
  19479. const mid = i1 + right >>> 1;
  19480. if (t < pp[mid]) {
  19481. right = mid;
  19482. } else {
  19483. i1 = mid + 1;
  19484. }
  19485. }
  19486. t1 = pp[i1];
  19487. t0 = pp[i1 - 1]; // check boundary cases, again
  19488. if (t0 === undefined) {
  19489. this._cachedIndex = 0;
  19490. return this.beforeStart_(0, t, t1);
  19491. }
  19492. if (t1 === undefined) {
  19493. i1 = pp.length;
  19494. this._cachedIndex = i1;
  19495. return this.afterEnd_(i1 - 1, t0, t);
  19496. }
  19497. } // seek
  19498. this._cachedIndex = i1;
  19499. this.intervalChanged_(i1, t0, t1);
  19500. } // validate_interval
  19501. return this.interpolate_(i1, t0, t, t1);
  19502. }
  19503. getSettings_() {
  19504. return this.settings || this.DefaultSettings_;
  19505. }
  19506. copySampleValue_(index) {
  19507. // copies a sample value to the result buffer
  19508. const result = this.resultBuffer,
  19509. values = this.sampleValues,
  19510. stride = this.valueSize,
  19511. offset = index * stride;
  19512. for (let i = 0; i !== stride; ++i) {
  19513. result[i] = values[offset + i];
  19514. }
  19515. return result;
  19516. } // Template methods for derived classes:
  19517. interpolate_()
  19518. /* i1, t0, t, t1 */
  19519. {
  19520. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  19521. }
  19522. intervalChanged_()
  19523. /* i1, t0, t1 */
  19524. {// empty
  19525. }
  19526. } // ALIAS DEFINITIONS
  19527. Interpolant.prototype.beforeStart_ = Interpolant.prototype.copySampleValue_;
  19528. Interpolant.prototype.afterEnd_ = Interpolant.prototype.copySampleValue_;
  19529. /**
  19530. * Fast and simple cubic spline interpolant.
  19531. *
  19532. * It was derived from a Hermitian construction setting the first derivative
  19533. * at each sample position to the linear slope between neighboring positions
  19534. * over their parameter interval.
  19535. */
  19536. class CubicInterpolant extends Interpolant {
  19537. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  19538. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  19539. this._weightPrev = -0;
  19540. this._offsetPrev = -0;
  19541. this._weightNext = -0;
  19542. this._offsetNext = -0;
  19543. this.DefaultSettings_ = {
  19544. endingStart: ZeroCurvatureEnding,
  19545. endingEnd: ZeroCurvatureEnding
  19546. };
  19547. }
  19548. intervalChanged_(i1, t0, t1) {
  19549. const pp = this.parameterPositions;
  19550. let iPrev = i1 - 2,
  19551. iNext = i1 + 1,
  19552. tPrev = pp[iPrev],
  19553. tNext = pp[iNext];
  19554. if (tPrev === undefined) {
  19555. switch (this.getSettings_().endingStart) {
  19556. case ZeroSlopeEnding:
  19557. // f'(t0) = 0
  19558. iPrev = i1;
  19559. tPrev = 2 * t0 - t1;
  19560. break;
  19561. case WrapAroundEnding:
  19562. // use the other end of the curve
  19563. iPrev = pp.length - 2;
  19564. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  19565. break;
  19566. default:
  19567. // ZeroCurvatureEnding
  19568. // f''(t0) = 0 a.k.a. Natural Spline
  19569. iPrev = i1;
  19570. tPrev = t1;
  19571. }
  19572. }
  19573. if (tNext === undefined) {
  19574. switch (this.getSettings_().endingEnd) {
  19575. case ZeroSlopeEnding:
  19576. // f'(tN) = 0
  19577. iNext = i1;
  19578. tNext = 2 * t1 - t0;
  19579. break;
  19580. case WrapAroundEnding:
  19581. // use the other end of the curve
  19582. iNext = 1;
  19583. tNext = t1 + pp[1] - pp[0];
  19584. break;
  19585. default:
  19586. // ZeroCurvatureEnding
  19587. // f''(tN) = 0, a.k.a. Natural Spline
  19588. iNext = i1 - 1;
  19589. tNext = t0;
  19590. }
  19591. }
  19592. const halfDt = (t1 - t0) * 0.5,
  19593. stride = this.valueSize;
  19594. this._weightPrev = halfDt / (t0 - tPrev);
  19595. this._weightNext = halfDt / (tNext - t1);
  19596. this._offsetPrev = iPrev * stride;
  19597. this._offsetNext = iNext * stride;
  19598. }
  19599. interpolate_(i1, t0, t, t1) {
  19600. const result = this.resultBuffer,
  19601. values = this.sampleValues,
  19602. stride = this.valueSize,
  19603. o1 = i1 * stride,
  19604. o0 = o1 - stride,
  19605. oP = this._offsetPrev,
  19606. oN = this._offsetNext,
  19607. wP = this._weightPrev,
  19608. wN = this._weightNext,
  19609. p = (t - t0) / (t1 - t0),
  19610. pp = p * p,
  19611. ppp = pp * p; // evaluate polynomials
  19612. const sP = -wP * ppp + 2 * wP * pp - wP * p;
  19613. const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  19614. const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  19615. const sN = wN * ppp - wN * pp; // combine data linearly
  19616. for (let i = 0; i !== stride; ++i) {
  19617. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  19618. }
  19619. return result;
  19620. }
  19621. }
  19622. class LinearInterpolant extends Interpolant {
  19623. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  19624. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  19625. }
  19626. interpolate_(i1, t0, t, t1) {
  19627. const result = this.resultBuffer,
  19628. values = this.sampleValues,
  19629. stride = this.valueSize,
  19630. offset1 = i1 * stride,
  19631. offset0 = offset1 - stride,
  19632. weight1 = (t - t0) / (t1 - t0),
  19633. weight0 = 1 - weight1;
  19634. for (let i = 0; i !== stride; ++i) {
  19635. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  19636. }
  19637. return result;
  19638. }
  19639. }
  19640. /**
  19641. *
  19642. * Interpolant that evaluates to the sample value at the position preceeding
  19643. * the parameter.
  19644. */
  19645. class DiscreteInterpolant extends Interpolant {
  19646. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  19647. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  19648. }
  19649. interpolate_(i1
  19650. /*, t0, t, t1 */
  19651. ) {
  19652. return this.copySampleValue_(i1 - 1);
  19653. }
  19654. }
  19655. class KeyframeTrack {
  19656. constructor(name, times, values, interpolation) {
  19657. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  19658. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  19659. this.name = name;
  19660. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  19661. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  19662. this.setInterpolation(interpolation || this.DefaultInterpolation);
  19663. } // Serialization (in static context, because of constructor invocation
  19664. // and automatic invocation of .toJSON):
  19665. static toJSON(track) {
  19666. const trackType = track.constructor;
  19667. let json; // derived classes can define a static toJSON method
  19668. if (trackType.toJSON !== this.toJSON) {
  19669. json = trackType.toJSON(track);
  19670. } else {
  19671. // by default, we assume the data can be serialized as-is
  19672. json = {
  19673. 'name': track.name,
  19674. 'times': AnimationUtils.convertArray(track.times, Array),
  19675. 'values': AnimationUtils.convertArray(track.values, Array)
  19676. };
  19677. const interpolation = track.getInterpolation();
  19678. if (interpolation !== track.DefaultInterpolation) {
  19679. json.interpolation = interpolation;
  19680. }
  19681. }
  19682. json.type = track.ValueTypeName; // mandatory
  19683. return json;
  19684. }
  19685. InterpolantFactoryMethodDiscrete(result) {
  19686. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  19687. }
  19688. InterpolantFactoryMethodLinear(result) {
  19689. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  19690. }
  19691. InterpolantFactoryMethodSmooth(result) {
  19692. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  19693. }
  19694. setInterpolation(interpolation) {
  19695. let factoryMethod;
  19696. switch (interpolation) {
  19697. case InterpolateDiscrete:
  19698. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  19699. break;
  19700. case InterpolateLinear:
  19701. factoryMethod = this.InterpolantFactoryMethodLinear;
  19702. break;
  19703. case InterpolateSmooth:
  19704. factoryMethod = this.InterpolantFactoryMethodSmooth;
  19705. break;
  19706. }
  19707. if (factoryMethod === undefined) {
  19708. const message = 'unsupported interpolation for ' + this.ValueTypeName + ' keyframe track named ' + this.name;
  19709. if (this.createInterpolant === undefined) {
  19710. // fall back to default, unless the default itself is messed up
  19711. if (interpolation !== this.DefaultInterpolation) {
  19712. this.setInterpolation(this.DefaultInterpolation);
  19713. } else {
  19714. throw new Error(message); // fatal, in this case
  19715. }
  19716. }
  19717. console.warn('THREE.KeyframeTrack:', message);
  19718. return this;
  19719. }
  19720. this.createInterpolant = factoryMethod;
  19721. return this;
  19722. }
  19723. getInterpolation() {
  19724. switch (this.createInterpolant) {
  19725. case this.InterpolantFactoryMethodDiscrete:
  19726. return InterpolateDiscrete;
  19727. case this.InterpolantFactoryMethodLinear:
  19728. return InterpolateLinear;
  19729. case this.InterpolantFactoryMethodSmooth:
  19730. return InterpolateSmooth;
  19731. }
  19732. }
  19733. getValueSize() {
  19734. return this.values.length / this.times.length;
  19735. } // move all keyframes either forwards or backwards in time
  19736. shift(timeOffset) {
  19737. if (timeOffset !== 0.0) {
  19738. const times = this.times;
  19739. for (let i = 0, n = times.length; i !== n; ++i) {
  19740. times[i] += timeOffset;
  19741. }
  19742. }
  19743. return this;
  19744. } // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  19745. scale(timeScale) {
  19746. if (timeScale !== 1.0) {
  19747. const times = this.times;
  19748. for (let i = 0, n = times.length; i !== n; ++i) {
  19749. times[i] *= timeScale;
  19750. }
  19751. }
  19752. return this;
  19753. } // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  19754. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  19755. trim(startTime, endTime) {
  19756. const times = this.times,
  19757. nKeys = times.length;
  19758. let from = 0,
  19759. to = nKeys - 1;
  19760. while (from !== nKeys && times[from] < startTime) {
  19761. ++from;
  19762. }
  19763. while (to !== -1 && times[to] > endTime) {
  19764. --to;
  19765. }
  19766. ++to; // inclusive -> exclusive bound
  19767. if (from !== 0 || to !== nKeys) {
  19768. // empty tracks are forbidden, so keep at least one keyframe
  19769. if (from >= to) {
  19770. to = Math.max(to, 1);
  19771. from = to - 1;
  19772. }
  19773. const stride = this.getValueSize();
  19774. this.times = AnimationUtils.arraySlice(times, from, to);
  19775. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  19776. }
  19777. return this;
  19778. } // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  19779. validate() {
  19780. let valid = true;
  19781. const valueSize = this.getValueSize();
  19782. if (valueSize - Math.floor(valueSize) !== 0) {
  19783. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  19784. valid = false;
  19785. }
  19786. const times = this.times,
  19787. values = this.values,
  19788. nKeys = times.length;
  19789. if (nKeys === 0) {
  19790. console.error('THREE.KeyframeTrack: Track is empty.', this);
  19791. valid = false;
  19792. }
  19793. let prevTime = null;
  19794. for (let i = 0; i !== nKeys; i++) {
  19795. const currTime = times[i];
  19796. if (typeof currTime === 'number' && isNaN(currTime)) {
  19797. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  19798. valid = false;
  19799. break;
  19800. }
  19801. if (prevTime !== null && prevTime > currTime) {
  19802. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  19803. valid = false;
  19804. break;
  19805. }
  19806. prevTime = currTime;
  19807. }
  19808. if (values !== undefined) {
  19809. if (AnimationUtils.isTypedArray(values)) {
  19810. for (let i = 0, n = values.length; i !== n; ++i) {
  19811. const value = values[i];
  19812. if (isNaN(value)) {
  19813. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  19814. valid = false;
  19815. break;
  19816. }
  19817. }
  19818. }
  19819. }
  19820. return valid;
  19821. } // removes equivalent sequential keys as common in morph target sequences
  19822. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  19823. optimize() {
  19824. // times or values may be shared with other tracks, so overwriting is unsafe
  19825. const times = AnimationUtils.arraySlice(this.times),
  19826. values = AnimationUtils.arraySlice(this.values),
  19827. stride = this.getValueSize(),
  19828. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  19829. lastIndex = times.length - 1;
  19830. let writeIndex = 1;
  19831. for (let i = 1; i < lastIndex; ++i) {
  19832. let keep = false;
  19833. const time = times[i];
  19834. const timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  19835. if (time !== timeNext && (i !== 1 || time !== times[0])) {
  19836. if (!smoothInterpolation) {
  19837. // remove unnecessary keyframes same as their neighbors
  19838. const offset = i * stride,
  19839. offsetP = offset - stride,
  19840. offsetN = offset + stride;
  19841. for (let j = 0; j !== stride; ++j) {
  19842. const value = values[offset + j];
  19843. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  19844. keep = true;
  19845. break;
  19846. }
  19847. }
  19848. } else {
  19849. keep = true;
  19850. }
  19851. } // in-place compaction
  19852. if (keep) {
  19853. if (i !== writeIndex) {
  19854. times[writeIndex] = times[i];
  19855. const readOffset = i * stride,
  19856. writeOffset = writeIndex * stride;
  19857. for (let j = 0; j !== stride; ++j) {
  19858. values[writeOffset + j] = values[readOffset + j];
  19859. }
  19860. }
  19861. ++writeIndex;
  19862. }
  19863. } // flush last keyframe (compaction looks ahead)
  19864. if (lastIndex > 0) {
  19865. times[writeIndex] = times[lastIndex];
  19866. for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  19867. values[writeOffset + j] = values[readOffset + j];
  19868. }
  19869. ++writeIndex;
  19870. }
  19871. if (writeIndex !== times.length) {
  19872. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  19873. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  19874. } else {
  19875. this.times = times;
  19876. this.values = values;
  19877. }
  19878. return this;
  19879. }
  19880. clone() {
  19881. const times = AnimationUtils.arraySlice(this.times, 0);
  19882. const values = AnimationUtils.arraySlice(this.values, 0);
  19883. const TypedKeyframeTrack = this.constructor;
  19884. const track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  19885. track.createInterpolant = this.createInterpolant;
  19886. return track;
  19887. }
  19888. }
  19889. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  19890. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  19891. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  19892. /**
  19893. * A Track of Boolean keyframe values.
  19894. */
  19895. class BooleanKeyframeTrack extends KeyframeTrack {}
  19896. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  19897. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  19898. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  19899. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  19900. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; // Note: Actually this track could have a optimized / compressed
  19901. /**
  19902. * A Track of keyframe values that represent color.
  19903. */
  19904. class ColorKeyframeTrack extends KeyframeTrack {}
  19905. ColorKeyframeTrack.prototype.ValueTypeName = 'color'; // ValueBufferType is inherited
  19906. /**
  19907. * A Track of numeric keyframe values.
  19908. */
  19909. class NumberKeyframeTrack extends KeyframeTrack {}
  19910. NumberKeyframeTrack.prototype.ValueTypeName = 'number'; // ValueBufferType is inherited
  19911. /**
  19912. * Spherical linear unit quaternion interpolant.
  19913. */
  19914. class QuaternionLinearInterpolant extends Interpolant {
  19915. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  19916. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  19917. }
  19918. interpolate_(i1, t0, t, t1) {
  19919. const result = this.resultBuffer,
  19920. values = this.sampleValues,
  19921. stride = this.valueSize,
  19922. alpha = (t - t0) / (t1 - t0);
  19923. let offset = i1 * stride;
  19924. for (let end = offset + stride; offset !== end; offset += 4) {
  19925. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  19926. }
  19927. return result;
  19928. }
  19929. }
  19930. /**
  19931. * A Track of quaternion keyframe values.
  19932. */
  19933. class QuaternionKeyframeTrack extends KeyframeTrack {
  19934. InterpolantFactoryMethodLinear(result) {
  19935. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  19936. }
  19937. }
  19938. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion'; // ValueBufferType is inherited
  19939. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  19940. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  19941. /**
  19942. * A Track that interpolates Strings
  19943. */
  19944. class StringKeyframeTrack extends KeyframeTrack {}
  19945. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  19946. StringKeyframeTrack.prototype.ValueBufferType = Array;
  19947. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  19948. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  19949. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  19950. /**
  19951. * A Track of vectored keyframe values.
  19952. */
  19953. class VectorKeyframeTrack extends KeyframeTrack {}
  19954. VectorKeyframeTrack.prototype.ValueTypeName = 'vector'; // ValueBufferType is inherited
  19955. class AnimationClip {
  19956. constructor(name, duration = -1, tracks, blendMode = NormalAnimationBlendMode) {
  19957. this.name = name;
  19958. this.tracks = tracks;
  19959. this.duration = duration;
  19960. this.blendMode = blendMode;
  19961. this.uuid = generateUUID(); // this means it should figure out its duration by scanning the tracks
  19962. if (this.duration < 0) {
  19963. this.resetDuration();
  19964. }
  19965. }
  19966. static parse(json) {
  19967. const tracks = [],
  19968. jsonTracks = json.tracks,
  19969. frameTime = 1.0 / (json.fps || 1.0);
  19970. for (let i = 0, n = jsonTracks.length; i !== n; ++i) {
  19971. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  19972. }
  19973. const clip = new this(json.name, json.duration, tracks, json.blendMode);
  19974. clip.uuid = json.uuid;
  19975. return clip;
  19976. }
  19977. static toJSON(clip) {
  19978. const tracks = [],
  19979. clipTracks = clip.tracks;
  19980. const json = {
  19981. 'name': clip.name,
  19982. 'duration': clip.duration,
  19983. 'tracks': tracks,
  19984. 'uuid': clip.uuid,
  19985. 'blendMode': clip.blendMode
  19986. };
  19987. for (let i = 0, n = clipTracks.length; i !== n; ++i) {
  19988. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  19989. }
  19990. return json;
  19991. }
  19992. static CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) {
  19993. const numMorphTargets = morphTargetSequence.length;
  19994. const tracks = [];
  19995. for (let i = 0; i < numMorphTargets; i++) {
  19996. let times = [];
  19997. let values = [];
  19998. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  19999. values.push(0, 1, 0);
  20000. const order = AnimationUtils.getKeyframeOrder(times);
  20001. times = AnimationUtils.sortedArray(times, 1, order);
  20002. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  20003. // last frame as well for perfect loop.
  20004. if (!noLoop && times[0] === 0) {
  20005. times.push(numMorphTargets);
  20006. values.push(values[0]);
  20007. }
  20008. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  20009. }
  20010. return new this(name, -1, tracks);
  20011. }
  20012. static findByName(objectOrClipArray, name) {
  20013. let clipArray = objectOrClipArray;
  20014. if (!Array.isArray(objectOrClipArray)) {
  20015. const o = objectOrClipArray;
  20016. clipArray = o.geometry && o.geometry.animations || o.animations;
  20017. }
  20018. for (let i = 0; i < clipArray.length; i++) {
  20019. if (clipArray[i].name === name) {
  20020. return clipArray[i];
  20021. }
  20022. }
  20023. return null;
  20024. }
  20025. static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {
  20026. const animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  20027. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  20028. const pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  20029. // patterns like Walk_001, Walk_002, Run_001, Run_002
  20030. for (let i = 0, il = morphTargets.length; i < il; i++) {
  20031. const morphTarget = morphTargets[i];
  20032. const parts = morphTarget.name.match(pattern);
  20033. if (parts && parts.length > 1) {
  20034. const name = parts[1];
  20035. let animationMorphTargets = animationToMorphTargets[name];
  20036. if (!animationMorphTargets) {
  20037. animationToMorphTargets[name] = animationMorphTargets = [];
  20038. }
  20039. animationMorphTargets.push(morphTarget);
  20040. }
  20041. }
  20042. const clips = [];
  20043. for (const name in animationToMorphTargets) {
  20044. clips.push(this.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  20045. }
  20046. return clips;
  20047. } // parse the animation.hierarchy format
  20048. static parseAnimation(animation, bones) {
  20049. if (!animation) {
  20050. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  20051. return null;
  20052. }
  20053. const addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  20054. // only return track if there are actually keys.
  20055. if (animationKeys.length !== 0) {
  20056. const times = [];
  20057. const values = [];
  20058. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  20059. if (times.length !== 0) {
  20060. destTracks.push(new trackType(trackName, times, values));
  20061. }
  20062. }
  20063. };
  20064. const tracks = [];
  20065. const clipName = animation.name || 'default';
  20066. const fps = animation.fps || 30;
  20067. const blendMode = animation.blendMode; // automatic length determination in AnimationClip.
  20068. let duration = animation.length || -1;
  20069. const hierarchyTracks = animation.hierarchy || [];
  20070. for (let h = 0; h < hierarchyTracks.length; h++) {
  20071. const animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  20072. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  20073. if (animationKeys[0].morphTargets) {
  20074. // figure out all morph targets used in this track
  20075. const morphTargetNames = {};
  20076. let k;
  20077. for (k = 0; k < animationKeys.length; k++) {
  20078. if (animationKeys[k].morphTargets) {
  20079. for (let m = 0; m < animationKeys[k].morphTargets.length; m++) {
  20080. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  20081. }
  20082. }
  20083. } // create a track for each morph target with all zero
  20084. // morphTargetInfluences except for the keys in which
  20085. // the morphTarget is named.
  20086. for (const morphTargetName in morphTargetNames) {
  20087. const times = [];
  20088. const values = [];
  20089. for (let m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  20090. const animationKey = animationKeys[k];
  20091. times.push(animationKey.time);
  20092. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  20093. }
  20094. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  20095. }
  20096. duration = morphTargetNames.length * (fps || 1.0);
  20097. } else {
  20098. // ...assume skeletal animation
  20099. const boneName = '.bones[' + bones[h].name + ']';
  20100. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  20101. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  20102. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  20103. }
  20104. }
  20105. if (tracks.length === 0) {
  20106. return null;
  20107. }
  20108. const clip = new this(clipName, duration, tracks, blendMode);
  20109. return clip;
  20110. }
  20111. resetDuration() {
  20112. const tracks = this.tracks;
  20113. let duration = 0;
  20114. for (let i = 0, n = tracks.length; i !== n; ++i) {
  20115. const track = this.tracks[i];
  20116. duration = Math.max(duration, track.times[track.times.length - 1]);
  20117. }
  20118. this.duration = duration;
  20119. return this;
  20120. }
  20121. trim() {
  20122. for (let i = 0; i < this.tracks.length; i++) {
  20123. this.tracks[i].trim(0, this.duration);
  20124. }
  20125. return this;
  20126. }
  20127. validate() {
  20128. let valid = true;
  20129. for (let i = 0; i < this.tracks.length; i++) {
  20130. valid = valid && this.tracks[i].validate();
  20131. }
  20132. return valid;
  20133. }
  20134. optimize() {
  20135. for (let i = 0; i < this.tracks.length; i++) {
  20136. this.tracks[i].optimize();
  20137. }
  20138. return this;
  20139. }
  20140. clone() {
  20141. const tracks = [];
  20142. for (let i = 0; i < this.tracks.length; i++) {
  20143. tracks.push(this.tracks[i].clone());
  20144. }
  20145. return new this.constructor(this.name, this.duration, tracks, this.blendMode);
  20146. }
  20147. toJSON() {
  20148. return this.constructor.toJSON(this);
  20149. }
  20150. }
  20151. function getTrackTypeForValueTypeName(typeName) {
  20152. switch (typeName.toLowerCase()) {
  20153. case 'scalar':
  20154. case 'double':
  20155. case 'float':
  20156. case 'number':
  20157. case 'integer':
  20158. return NumberKeyframeTrack;
  20159. case 'vector':
  20160. case 'vector2':
  20161. case 'vector3':
  20162. case 'vector4':
  20163. return VectorKeyframeTrack;
  20164. case 'color':
  20165. return ColorKeyframeTrack;
  20166. case 'quaternion':
  20167. return QuaternionKeyframeTrack;
  20168. case 'bool':
  20169. case 'boolean':
  20170. return BooleanKeyframeTrack;
  20171. case 'string':
  20172. return StringKeyframeTrack;
  20173. }
  20174. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  20175. }
  20176. function parseKeyframeTrack(json) {
  20177. if (json.type === undefined) {
  20178. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  20179. }
  20180. const trackType = getTrackTypeForValueTypeName(json.type);
  20181. if (json.times === undefined) {
  20182. const times = [],
  20183. values = [];
  20184. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  20185. json.times = times;
  20186. json.values = values;
  20187. } // derived classes can define a static parse method
  20188. if (trackType.parse !== undefined) {
  20189. return trackType.parse(json);
  20190. } else {
  20191. // by default, we assume a constructor compatible with the base
  20192. return new trackType(json.name, json.times, json.values, json.interpolation);
  20193. }
  20194. }
  20195. const Cache = {
  20196. enabled: false,
  20197. files: {},
  20198. add: function (key, file) {
  20199. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  20200. this.files[key] = file;
  20201. },
  20202. get: function (key) {
  20203. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  20204. return this.files[key];
  20205. },
  20206. remove: function (key) {
  20207. delete this.files[key];
  20208. },
  20209. clear: function () {
  20210. this.files = {};
  20211. }
  20212. };
  20213. class LoadingManager {
  20214. constructor(onLoad, onProgress, onError) {
  20215. const scope = this;
  20216. let isLoading = false;
  20217. let itemsLoaded = 0;
  20218. let itemsTotal = 0;
  20219. let urlModifier = undefined;
  20220. const handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  20221. // in the constructor
  20222. this.onStart = undefined;
  20223. this.onLoad = onLoad;
  20224. this.onProgress = onProgress;
  20225. this.onError = onError;
  20226. this.itemStart = function (url) {
  20227. itemsTotal++;
  20228. if (isLoading === false) {
  20229. if (scope.onStart !== undefined) {
  20230. scope.onStart(url, itemsLoaded, itemsTotal);
  20231. }
  20232. }
  20233. isLoading = true;
  20234. };
  20235. this.itemEnd = function (url) {
  20236. itemsLoaded++;
  20237. if (scope.onProgress !== undefined) {
  20238. scope.onProgress(url, itemsLoaded, itemsTotal);
  20239. }
  20240. if (itemsLoaded === itemsTotal) {
  20241. isLoading = false;
  20242. if (scope.onLoad !== undefined) {
  20243. scope.onLoad();
  20244. }
  20245. }
  20246. };
  20247. this.itemError = function (url) {
  20248. if (scope.onError !== undefined) {
  20249. scope.onError(url);
  20250. }
  20251. };
  20252. this.resolveURL = function (url) {
  20253. if (urlModifier) {
  20254. return urlModifier(url);
  20255. }
  20256. return url;
  20257. };
  20258. this.setURLModifier = function (transform) {
  20259. urlModifier = transform;
  20260. return this;
  20261. };
  20262. this.addHandler = function (regex, loader) {
  20263. handlers.push(regex, loader);
  20264. return this;
  20265. };
  20266. this.removeHandler = function (regex) {
  20267. const index = handlers.indexOf(regex);
  20268. if (index !== -1) {
  20269. handlers.splice(index, 2);
  20270. }
  20271. return this;
  20272. };
  20273. this.getHandler = function (file) {
  20274. for (let i = 0, l = handlers.length; i < l; i += 2) {
  20275. const regex = handlers[i];
  20276. const loader = handlers[i + 1];
  20277. if (regex.global) regex.lastIndex = 0; // see #17920
  20278. if (regex.test(file)) {
  20279. return loader;
  20280. }
  20281. }
  20282. return null;
  20283. };
  20284. }
  20285. }
  20286. const DefaultLoadingManager = new LoadingManager();
  20287. class Loader {
  20288. constructor(manager) {
  20289. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  20290. this.crossOrigin = 'anonymous';
  20291. this.withCredentials = false;
  20292. this.path = '';
  20293. this.resourcePath = '';
  20294. this.requestHeader = {};
  20295. }
  20296. load()
  20297. /* url, onLoad, onProgress, onError */
  20298. {}
  20299. loadAsync(url, onProgress) {
  20300. const scope = this;
  20301. return new Promise(function (resolve, reject) {
  20302. scope.load(url, resolve, onProgress, reject);
  20303. });
  20304. }
  20305. parse()
  20306. /* data */
  20307. {}
  20308. setCrossOrigin(crossOrigin) {
  20309. this.crossOrigin = crossOrigin;
  20310. return this;
  20311. }
  20312. setWithCredentials(value) {
  20313. this.withCredentials = value;
  20314. return this;
  20315. }
  20316. setPath(path) {
  20317. this.path = path;
  20318. return this;
  20319. }
  20320. setResourcePath(resourcePath) {
  20321. this.resourcePath = resourcePath;
  20322. return this;
  20323. }
  20324. setRequestHeader(requestHeader) {
  20325. this.requestHeader = requestHeader;
  20326. return this;
  20327. }
  20328. }
  20329. const loading = {};
  20330. class FileLoader extends Loader {
  20331. constructor(manager) {
  20332. super(manager);
  20333. }
  20334. load(url, onLoad, onProgress, onError) {
  20335. if (url === undefined) url = '';
  20336. if (this.path !== undefined) url = this.path + url;
  20337. url = this.manager.resolveURL(url);
  20338. const scope = this;
  20339. const cached = Cache.get(url);
  20340. if (cached !== undefined) {
  20341. scope.manager.itemStart(url);
  20342. setTimeout(function () {
  20343. if (onLoad) onLoad(cached);
  20344. scope.manager.itemEnd(url);
  20345. }, 0);
  20346. return cached;
  20347. } // Check if request is duplicate
  20348. if (loading[url] !== undefined) {
  20349. loading[url].push({
  20350. onLoad: onLoad,
  20351. onProgress: onProgress,
  20352. onError: onError
  20353. });
  20354. return;
  20355. } // Check for data: URI
  20356. const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  20357. const dataUriRegexResult = url.match(dataUriRegex);
  20358. let request; // Safari can not handle Data URIs through XMLHttpRequest so process manually
  20359. if (dataUriRegexResult) {
  20360. const mimeType = dataUriRegexResult[1];
  20361. const isBase64 = !!dataUriRegexResult[2];
  20362. let data = dataUriRegexResult[3];
  20363. data = decodeURIComponent(data);
  20364. if (isBase64) data = atob(data);
  20365. try {
  20366. let response;
  20367. const responseType = (this.responseType || '').toLowerCase();
  20368. switch (responseType) {
  20369. case 'arraybuffer':
  20370. case 'blob':
  20371. const view = new Uint8Array(data.length);
  20372. for (let i = 0; i < data.length; i++) {
  20373. view[i] = data.charCodeAt(i);
  20374. }
  20375. if (responseType === 'blob') {
  20376. response = new Blob([view.buffer], {
  20377. type: mimeType
  20378. });
  20379. } else {
  20380. response = view.buffer;
  20381. }
  20382. break;
  20383. case 'document':
  20384. const parser = new DOMParser();
  20385. response = parser.parseFromString(data, mimeType);
  20386. break;
  20387. case 'json':
  20388. response = JSON.parse(data);
  20389. break;
  20390. default:
  20391. // 'text' or other
  20392. response = data;
  20393. break;
  20394. } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  20395. setTimeout(function () {
  20396. if (onLoad) onLoad(response);
  20397. scope.manager.itemEnd(url);
  20398. }, 0);
  20399. } catch (error) {
  20400. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  20401. setTimeout(function () {
  20402. if (onError) onError(error);
  20403. scope.manager.itemError(url);
  20404. scope.manager.itemEnd(url);
  20405. }, 0);
  20406. }
  20407. } else {
  20408. // Initialise array for duplicate requests
  20409. loading[url] = [];
  20410. loading[url].push({
  20411. onLoad: onLoad,
  20412. onProgress: onProgress,
  20413. onError: onError
  20414. });
  20415. request = new XMLHttpRequest();
  20416. request.open('GET', url, true);
  20417. request.addEventListener('load', function (event) {
  20418. const response = this.response;
  20419. const callbacks = loading[url];
  20420. delete loading[url];
  20421. if (this.status === 200 || this.status === 0) {
  20422. // Some browsers return HTTP Status 0 when using non-http protocol
  20423. // e.g. 'file://' or 'data://'. Handle as success.
  20424. if (this.status === 0) console.warn('THREE.FileLoader: HTTP Status 0 received.'); // Add to cache only on HTTP success, so that we do not cache
  20425. // error response bodies as proper responses to requests.
  20426. Cache.add(url, response);
  20427. for (let i = 0, il = callbacks.length; i < il; i++) {
  20428. const callback = callbacks[i];
  20429. if (callback.onLoad) callback.onLoad(response);
  20430. }
  20431. scope.manager.itemEnd(url);
  20432. } else {
  20433. for (let i = 0, il = callbacks.length; i < il; i++) {
  20434. const callback = callbacks[i];
  20435. if (callback.onError) callback.onError(event);
  20436. }
  20437. scope.manager.itemError(url);
  20438. scope.manager.itemEnd(url);
  20439. }
  20440. }, false);
  20441. request.addEventListener('progress', function (event) {
  20442. const callbacks = loading[url];
  20443. for (let i = 0, il = callbacks.length; i < il; i++) {
  20444. const callback = callbacks[i];
  20445. if (callback.onProgress) callback.onProgress(event);
  20446. }
  20447. }, false);
  20448. request.addEventListener('error', function (event) {
  20449. const callbacks = loading[url];
  20450. delete loading[url];
  20451. for (let i = 0, il = callbacks.length; i < il; i++) {
  20452. const callback = callbacks[i];
  20453. if (callback.onError) callback.onError(event);
  20454. }
  20455. scope.manager.itemError(url);
  20456. scope.manager.itemEnd(url);
  20457. }, false);
  20458. request.addEventListener('abort', function (event) {
  20459. const callbacks = loading[url];
  20460. delete loading[url];
  20461. for (let i = 0, il = callbacks.length; i < il; i++) {
  20462. const callback = callbacks[i];
  20463. if (callback.onError) callback.onError(event);
  20464. }
  20465. scope.manager.itemError(url);
  20466. scope.manager.itemEnd(url);
  20467. }, false);
  20468. if (this.responseType !== undefined) request.responseType = this.responseType;
  20469. if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
  20470. if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
  20471. for (const header in this.requestHeader) {
  20472. request.setRequestHeader(header, this.requestHeader[header]);
  20473. }
  20474. request.send(null);
  20475. }
  20476. scope.manager.itemStart(url);
  20477. return request;
  20478. }
  20479. setResponseType(value) {
  20480. this.responseType = value;
  20481. return this;
  20482. }
  20483. setMimeType(value) {
  20484. this.mimeType = value;
  20485. return this;
  20486. }
  20487. }
  20488. class AnimationLoader extends Loader {
  20489. constructor(manager) {
  20490. super(manager);
  20491. }
  20492. load(url, onLoad, onProgress, onError) {
  20493. const scope = this;
  20494. const loader = new FileLoader(this.manager);
  20495. loader.setPath(this.path);
  20496. loader.setRequestHeader(this.requestHeader);
  20497. loader.setWithCredentials(this.withCredentials);
  20498. loader.load(url, function (text) {
  20499. try {
  20500. onLoad(scope.parse(JSON.parse(text)));
  20501. } catch (e) {
  20502. if (onError) {
  20503. onError(e);
  20504. } else {
  20505. console.error(e);
  20506. }
  20507. scope.manager.itemError(url);
  20508. }
  20509. }, onProgress, onError);
  20510. }
  20511. parse(json) {
  20512. const animations = [];
  20513. for (let i = 0; i < json.length; i++) {
  20514. const clip = AnimationClip.parse(json[i]);
  20515. animations.push(clip);
  20516. }
  20517. return animations;
  20518. }
  20519. }
  20520. /**
  20521. * Abstract Base class to block based textures loader (dds, pvr, ...)
  20522. *
  20523. * Sub classes have to implement the parse() method which will be used in load().
  20524. */
  20525. class CompressedTextureLoader extends Loader {
  20526. constructor(manager) {
  20527. super(manager);
  20528. }
  20529. load(url, onLoad, onProgress, onError) {
  20530. const scope = this;
  20531. const images = [];
  20532. const texture = new CompressedTexture();
  20533. const loader = new FileLoader(this.manager);
  20534. loader.setPath(this.path);
  20535. loader.setResponseType('arraybuffer');
  20536. loader.setRequestHeader(this.requestHeader);
  20537. loader.setWithCredentials(scope.withCredentials);
  20538. let loaded = 0;
  20539. function loadTexture(i) {
  20540. loader.load(url[i], function (buffer) {
  20541. const texDatas = scope.parse(buffer, true);
  20542. images[i] = {
  20543. width: texDatas.width,
  20544. height: texDatas.height,
  20545. format: texDatas.format,
  20546. mipmaps: texDatas.mipmaps
  20547. };
  20548. loaded += 1;
  20549. if (loaded === 6) {
  20550. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  20551. texture.image = images;
  20552. texture.format = texDatas.format;
  20553. texture.needsUpdate = true;
  20554. if (onLoad) onLoad(texture);
  20555. }
  20556. }, onProgress, onError);
  20557. }
  20558. if (Array.isArray(url)) {
  20559. for (let i = 0, il = url.length; i < il; ++i) {
  20560. loadTexture(i);
  20561. }
  20562. } else {
  20563. // compressed cubemap texture stored in a single DDS file
  20564. loader.load(url, function (buffer) {
  20565. const texDatas = scope.parse(buffer, true);
  20566. if (texDatas.isCubemap) {
  20567. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  20568. for (let f = 0; f < faces; f++) {
  20569. images[f] = {
  20570. mipmaps: []
  20571. };
  20572. for (let i = 0; i < texDatas.mipmapCount; i++) {
  20573. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  20574. images[f].format = texDatas.format;
  20575. images[f].width = texDatas.width;
  20576. images[f].height = texDatas.height;
  20577. }
  20578. }
  20579. texture.image = images;
  20580. } else {
  20581. texture.image.width = texDatas.width;
  20582. texture.image.height = texDatas.height;
  20583. texture.mipmaps = texDatas.mipmaps;
  20584. }
  20585. if (texDatas.mipmapCount === 1) {
  20586. texture.minFilter = LinearFilter;
  20587. }
  20588. texture.format = texDatas.format;
  20589. texture.needsUpdate = true;
  20590. if (onLoad) onLoad(texture);
  20591. }, onProgress, onError);
  20592. }
  20593. return texture;
  20594. }
  20595. }
  20596. class ImageLoader extends Loader {
  20597. constructor(manager) {
  20598. super(manager);
  20599. }
  20600. load(url, onLoad, onProgress, onError) {
  20601. if (this.path !== undefined) url = this.path + url;
  20602. url = this.manager.resolveURL(url);
  20603. const scope = this;
  20604. const cached = Cache.get(url);
  20605. if (cached !== undefined) {
  20606. scope.manager.itemStart(url);
  20607. setTimeout(function () {
  20608. if (onLoad) onLoad(cached);
  20609. scope.manager.itemEnd(url);
  20610. }, 0);
  20611. return cached;
  20612. }
  20613. const image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
  20614. function onImageLoad() {
  20615. image.removeEventListener('load', onImageLoad, false);
  20616. image.removeEventListener('error', onImageError, false);
  20617. Cache.add(url, this);
  20618. if (onLoad) onLoad(this);
  20619. scope.manager.itemEnd(url);
  20620. }
  20621. function onImageError(event) {
  20622. image.removeEventListener('load', onImageLoad, false);
  20623. image.removeEventListener('error', onImageError, false);
  20624. if (onError) onError(event);
  20625. scope.manager.itemError(url);
  20626. scope.manager.itemEnd(url);
  20627. }
  20628. image.addEventListener('load', onImageLoad, false);
  20629. image.addEventListener('error', onImageError, false);
  20630. if (url.substr(0, 5) !== 'data:') {
  20631. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  20632. }
  20633. scope.manager.itemStart(url);
  20634. image.src = url;
  20635. return image;
  20636. }
  20637. }
  20638. class CubeTextureLoader extends Loader {
  20639. constructor(manager) {
  20640. super(manager);
  20641. }
  20642. load(urls, onLoad, onProgress, onError) {
  20643. const texture = new CubeTexture();
  20644. const loader = new ImageLoader(this.manager);
  20645. loader.setCrossOrigin(this.crossOrigin);
  20646. loader.setPath(this.path);
  20647. let loaded = 0;
  20648. function loadTexture(i) {
  20649. loader.load(urls[i], function (image) {
  20650. texture.images[i] = image;
  20651. loaded++;
  20652. if (loaded === 6) {
  20653. texture.needsUpdate = true;
  20654. if (onLoad) onLoad(texture);
  20655. }
  20656. }, undefined, onError);
  20657. }
  20658. for (let i = 0; i < urls.length; ++i) {
  20659. loadTexture(i);
  20660. }
  20661. return texture;
  20662. }
  20663. }
  20664. /**
  20665. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  20666. *
  20667. * Sub classes have to implement the parse() method which will be used in load().
  20668. */
  20669. class DataTextureLoader extends Loader {
  20670. constructor(manager) {
  20671. super(manager);
  20672. }
  20673. load(url, onLoad, onProgress, onError) {
  20674. const scope = this;
  20675. const texture = new DataTexture();
  20676. const loader = new FileLoader(this.manager);
  20677. loader.setResponseType('arraybuffer');
  20678. loader.setRequestHeader(this.requestHeader);
  20679. loader.setPath(this.path);
  20680. loader.setWithCredentials(scope.withCredentials);
  20681. loader.load(url, function (buffer) {
  20682. const texData = scope.parse(buffer);
  20683. if (!texData) return;
  20684. if (texData.image !== undefined) {
  20685. texture.image = texData.image;
  20686. } else if (texData.data !== undefined) {
  20687. texture.image.width = texData.width;
  20688. texture.image.height = texData.height;
  20689. texture.image.data = texData.data;
  20690. }
  20691. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  20692. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  20693. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  20694. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  20695. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  20696. if (texData.encoding !== undefined) {
  20697. texture.encoding = texData.encoding;
  20698. }
  20699. if (texData.flipY !== undefined) {
  20700. texture.flipY = texData.flipY;
  20701. }
  20702. if (texData.format !== undefined) {
  20703. texture.format = texData.format;
  20704. }
  20705. if (texData.type !== undefined) {
  20706. texture.type = texData.type;
  20707. }
  20708. if (texData.mipmaps !== undefined) {
  20709. texture.mipmaps = texData.mipmaps;
  20710. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  20711. }
  20712. if (texData.mipmapCount === 1) {
  20713. texture.minFilter = LinearFilter;
  20714. }
  20715. if (texData.generateMipmaps !== undefined) {
  20716. texture.generateMipmaps = texData.generateMipmaps;
  20717. }
  20718. texture.needsUpdate = true;
  20719. if (onLoad) onLoad(texture, texData);
  20720. }, onProgress, onError);
  20721. return texture;
  20722. }
  20723. }
  20724. class TextureLoader extends Loader {
  20725. constructor(manager) {
  20726. super(manager);
  20727. }
  20728. load(url, onLoad, onProgress, onError) {
  20729. const texture = new Texture();
  20730. const loader = new ImageLoader(this.manager);
  20731. loader.setCrossOrigin(this.crossOrigin);
  20732. loader.setPath(this.path);
  20733. loader.load(url, function (image) {
  20734. texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  20735. const isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;
  20736. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  20737. texture.needsUpdate = true;
  20738. if (onLoad !== undefined) {
  20739. onLoad(texture);
  20740. }
  20741. }, onProgress, onError);
  20742. return texture;
  20743. }
  20744. }
  20745. /**
  20746. * Extensible curve object.
  20747. *
  20748. * Some common of curve methods:
  20749. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  20750. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  20751. * .getPoints(), .getSpacedPoints()
  20752. * .getLength()
  20753. * .updateArcLengths()
  20754. *
  20755. * This following curves inherit from THREE.Curve:
  20756. *
  20757. * -- 2D curves --
  20758. * THREE.ArcCurve
  20759. * THREE.CubicBezierCurve
  20760. * THREE.EllipseCurve
  20761. * THREE.LineCurve
  20762. * THREE.QuadraticBezierCurve
  20763. * THREE.SplineCurve
  20764. *
  20765. * -- 3D curves --
  20766. * THREE.CatmullRomCurve3
  20767. * THREE.CubicBezierCurve3
  20768. * THREE.LineCurve3
  20769. * THREE.QuadraticBezierCurve3
  20770. *
  20771. * A series of curves can be represented as a THREE.CurvePath.
  20772. *
  20773. **/
  20774. class Curve {
  20775. constructor() {
  20776. this.type = 'Curve';
  20777. this.arcLengthDivisions = 200;
  20778. } // Virtual base class method to overwrite and implement in subclasses
  20779. // - t [0 .. 1]
  20780. getPoint()
  20781. /* t, optionalTarget */
  20782. {
  20783. console.warn('THREE.Curve: .getPoint() not implemented.');
  20784. return null;
  20785. } // Get point at relative position in curve according to arc length
  20786. // - u [0 .. 1]
  20787. getPointAt(u, optionalTarget) {
  20788. const t = this.getUtoTmapping(u);
  20789. return this.getPoint(t, optionalTarget);
  20790. } // Get sequence of points using getPoint( t )
  20791. getPoints(divisions = 5) {
  20792. const points = [];
  20793. for (let d = 0; d <= divisions; d++) {
  20794. points.push(this.getPoint(d / divisions));
  20795. }
  20796. return points;
  20797. } // Get sequence of points using getPointAt( u )
  20798. getSpacedPoints(divisions = 5) {
  20799. const points = [];
  20800. for (let d = 0; d <= divisions; d++) {
  20801. points.push(this.getPointAt(d / divisions));
  20802. }
  20803. return points;
  20804. } // Get total curve arc length
  20805. getLength() {
  20806. const lengths = this.getLengths();
  20807. return lengths[lengths.length - 1];
  20808. } // Get list of cumulative segment lengths
  20809. getLengths(divisions = this.arcLengthDivisions) {
  20810. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  20811. return this.cacheArcLengths;
  20812. }
  20813. this.needsUpdate = false;
  20814. const cache = [];
  20815. let current,
  20816. last = this.getPoint(0);
  20817. let sum = 0;
  20818. cache.push(0);
  20819. for (let p = 1; p <= divisions; p++) {
  20820. current = this.getPoint(p / divisions);
  20821. sum += current.distanceTo(last);
  20822. cache.push(sum);
  20823. last = current;
  20824. }
  20825. this.cacheArcLengths = cache;
  20826. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  20827. }
  20828. updateArcLengths() {
  20829. this.needsUpdate = true;
  20830. this.getLengths();
  20831. } // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  20832. getUtoTmapping(u, distance) {
  20833. const arcLengths = this.getLengths();
  20834. let i = 0;
  20835. const il = arcLengths.length;
  20836. let targetArcLength; // The targeted u distance value to get
  20837. if (distance) {
  20838. targetArcLength = distance;
  20839. } else {
  20840. targetArcLength = u * arcLengths[il - 1];
  20841. } // binary search for the index with largest value smaller than target u distance
  20842. let low = 0,
  20843. high = il - 1,
  20844. comparison;
  20845. while (low <= high) {
  20846. 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
  20847. comparison = arcLengths[i] - targetArcLength;
  20848. if (comparison < 0) {
  20849. low = i + 1;
  20850. } else if (comparison > 0) {
  20851. high = i - 1;
  20852. } else {
  20853. high = i;
  20854. break; // DONE
  20855. }
  20856. }
  20857. i = high;
  20858. if (arcLengths[i] === targetArcLength) {
  20859. return i / (il - 1);
  20860. } // we could get finer grain at lengths, or use simple interpolation between two points
  20861. const lengthBefore = arcLengths[i];
  20862. const lengthAfter = arcLengths[i + 1];
  20863. const segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  20864. const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  20865. const t = (i + segmentFraction) / (il - 1);
  20866. return t;
  20867. } // Returns a unit vector tangent at t
  20868. // In case any sub curve does not implement its tangent derivation,
  20869. // 2 points a small delta apart will be used to find its gradient
  20870. // which seems to give a reasonable approximation
  20871. getTangent(t, optionalTarget) {
  20872. const delta = 0.0001;
  20873. let t1 = t - delta;
  20874. let t2 = t + delta; // Capping in case of danger
  20875. if (t1 < 0) t1 = 0;
  20876. if (t2 > 1) t2 = 1;
  20877. const pt1 = this.getPoint(t1);
  20878. const pt2 = this.getPoint(t2);
  20879. const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
  20880. tangent.copy(pt2).sub(pt1).normalize();
  20881. return tangent;
  20882. }
  20883. getTangentAt(u, optionalTarget) {
  20884. const t = this.getUtoTmapping(u);
  20885. return this.getTangent(t, optionalTarget);
  20886. }
  20887. computeFrenetFrames(segments, closed) {
  20888. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20889. const normal = new Vector3();
  20890. const tangents = [];
  20891. const normals = [];
  20892. const binormals = [];
  20893. const vec = new Vector3();
  20894. const mat = new Matrix4(); // compute the tangent vectors for each segment on the curve
  20895. for (let i = 0; i <= segments; i++) {
  20896. const u = i / segments;
  20897. tangents[i] = this.getTangentAt(u, new Vector3());
  20898. tangents[i].normalize();
  20899. } // select an initial normal vector perpendicular to the first tangent vector,
  20900. // and in the direction of the minimum tangent xyz component
  20901. normals[0] = new Vector3();
  20902. binormals[0] = new Vector3();
  20903. let min = Number.MAX_VALUE;
  20904. const tx = Math.abs(tangents[0].x);
  20905. const ty = Math.abs(tangents[0].y);
  20906. const tz = Math.abs(tangents[0].z);
  20907. if (tx <= min) {
  20908. min = tx;
  20909. normal.set(1, 0, 0);
  20910. }
  20911. if (ty <= min) {
  20912. min = ty;
  20913. normal.set(0, 1, 0);
  20914. }
  20915. if (tz <= min) {
  20916. normal.set(0, 0, 1);
  20917. }
  20918. vec.crossVectors(tangents[0], normal).normalize();
  20919. normals[0].crossVectors(tangents[0], vec);
  20920. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  20921. for (let i = 1; i <= segments; i++) {
  20922. normals[i] = normals[i - 1].clone();
  20923. binormals[i] = binormals[i - 1].clone();
  20924. vec.crossVectors(tangents[i - 1], tangents[i]);
  20925. if (vec.length() > Number.EPSILON) {
  20926. vec.normalize();
  20927. const theta = Math.acos(clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  20928. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  20929. }
  20930. binormals[i].crossVectors(tangents[i], normals[i]);
  20931. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20932. if (closed === true) {
  20933. let theta = Math.acos(clamp(normals[0].dot(normals[segments]), -1, 1));
  20934. theta /= segments;
  20935. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  20936. theta = -theta;
  20937. }
  20938. for (let i = 1; i <= segments; i++) {
  20939. // twist a little...
  20940. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  20941. binormals[i].crossVectors(tangents[i], normals[i]);
  20942. }
  20943. }
  20944. return {
  20945. tangents: tangents,
  20946. normals: normals,
  20947. binormals: binormals
  20948. };
  20949. }
  20950. clone() {
  20951. return new this.constructor().copy(this);
  20952. }
  20953. copy(source) {
  20954. this.arcLengthDivisions = source.arcLengthDivisions;
  20955. return this;
  20956. }
  20957. toJSON() {
  20958. const data = {
  20959. metadata: {
  20960. version: 4.5,
  20961. type: 'Curve',
  20962. generator: 'Curve.toJSON'
  20963. }
  20964. };
  20965. data.arcLengthDivisions = this.arcLengthDivisions;
  20966. data.type = this.type;
  20967. return data;
  20968. }
  20969. fromJSON(json) {
  20970. this.arcLengthDivisions = json.arcLengthDivisions;
  20971. return this;
  20972. }
  20973. }
  20974. class EllipseCurve extends Curve {
  20975. constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) {
  20976. super();
  20977. this.type = 'EllipseCurve';
  20978. this.aX = aX;
  20979. this.aY = aY;
  20980. this.xRadius = xRadius;
  20981. this.yRadius = yRadius;
  20982. this.aStartAngle = aStartAngle;
  20983. this.aEndAngle = aEndAngle;
  20984. this.aClockwise = aClockwise;
  20985. this.aRotation = aRotation;
  20986. }
  20987. getPoint(t, optionalTarget) {
  20988. const point = optionalTarget || new Vector2();
  20989. const twoPi = Math.PI * 2;
  20990. let deltaAngle = this.aEndAngle - this.aStartAngle;
  20991. const samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  20992. while (deltaAngle < 0) deltaAngle += twoPi;
  20993. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  20994. if (deltaAngle < Number.EPSILON) {
  20995. if (samePoints) {
  20996. deltaAngle = 0;
  20997. } else {
  20998. deltaAngle = twoPi;
  20999. }
  21000. }
  21001. if (this.aClockwise === true && !samePoints) {
  21002. if (deltaAngle === twoPi) {
  21003. deltaAngle = -twoPi;
  21004. } else {
  21005. deltaAngle = deltaAngle - twoPi;
  21006. }
  21007. }
  21008. const angle = this.aStartAngle + t * deltaAngle;
  21009. let x = this.aX + this.xRadius * Math.cos(angle);
  21010. let y = this.aY + this.yRadius * Math.sin(angle);
  21011. if (this.aRotation !== 0) {
  21012. const cos = Math.cos(this.aRotation);
  21013. const sin = Math.sin(this.aRotation);
  21014. const tx = x - this.aX;
  21015. const ty = y - this.aY; // Rotate the point about the center of the ellipse.
  21016. x = tx * cos - ty * sin + this.aX;
  21017. y = tx * sin + ty * cos + this.aY;
  21018. }
  21019. return point.set(x, y);
  21020. }
  21021. copy(source) {
  21022. super.copy(source);
  21023. this.aX = source.aX;
  21024. this.aY = source.aY;
  21025. this.xRadius = source.xRadius;
  21026. this.yRadius = source.yRadius;
  21027. this.aStartAngle = source.aStartAngle;
  21028. this.aEndAngle = source.aEndAngle;
  21029. this.aClockwise = source.aClockwise;
  21030. this.aRotation = source.aRotation;
  21031. return this;
  21032. }
  21033. toJSON() {
  21034. const data = super.toJSON();
  21035. data.aX = this.aX;
  21036. data.aY = this.aY;
  21037. data.xRadius = this.xRadius;
  21038. data.yRadius = this.yRadius;
  21039. data.aStartAngle = this.aStartAngle;
  21040. data.aEndAngle = this.aEndAngle;
  21041. data.aClockwise = this.aClockwise;
  21042. data.aRotation = this.aRotation;
  21043. return data;
  21044. }
  21045. fromJSON(json) {
  21046. super.fromJSON(json);
  21047. this.aX = json.aX;
  21048. this.aY = json.aY;
  21049. this.xRadius = json.xRadius;
  21050. this.yRadius = json.yRadius;
  21051. this.aStartAngle = json.aStartAngle;
  21052. this.aEndAngle = json.aEndAngle;
  21053. this.aClockwise = json.aClockwise;
  21054. this.aRotation = json.aRotation;
  21055. return this;
  21056. }
  21057. }
  21058. EllipseCurve.prototype.isEllipseCurve = true;
  21059. class ArcCurve extends EllipseCurve {
  21060. constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  21061. super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  21062. this.type = 'ArcCurve';
  21063. }
  21064. }
  21065. ArcCurve.prototype.isArcCurve = true;
  21066. /**
  21067. * Centripetal CatmullRom Curve - which is useful for avoiding
  21068. * cusps and self-intersections in non-uniform catmull rom curves.
  21069. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  21070. *
  21071. * curve.type accepts centripetal(default), chordal and catmullrom
  21072. * curve.tension is used for catmullrom which defaults to 0.5
  21073. */
  21074. /*
  21075. Based on an optimized c++ solution in
  21076. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  21077. - http://ideone.com/NoEbVM
  21078. This CubicPoly class could be used for reusing some variables and calculations,
  21079. but for three.js curve use, it could be possible inlined and flatten into a single function call
  21080. which can be placed in CurveUtils.
  21081. */
  21082. function CubicPoly() {
  21083. let c0 = 0,
  21084. c1 = 0,
  21085. c2 = 0,
  21086. c3 = 0;
  21087. /*
  21088. * Compute coefficients for a cubic polynomial
  21089. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  21090. * such that
  21091. * p(0) = x0, p(1) = x1
  21092. * and
  21093. * p'(0) = t0, p'(1) = t1.
  21094. */
  21095. function init(x0, x1, t0, t1) {
  21096. c0 = x0;
  21097. c1 = t0;
  21098. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  21099. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  21100. }
  21101. return {
  21102. initCatmullRom: function (x0, x1, x2, x3, tension) {
  21103. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  21104. },
  21105. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  21106. // compute tangents when parameterized in [t1,t2]
  21107. let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  21108. let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  21109. t1 *= dt1;
  21110. t2 *= dt1;
  21111. init(x1, x2, t1, t2);
  21112. },
  21113. calc: function (t) {
  21114. const t2 = t * t;
  21115. const t3 = t2 * t;
  21116. return c0 + c1 * t + c2 * t2 + c3 * t3;
  21117. }
  21118. };
  21119. } //
  21120. const tmp = new Vector3();
  21121. const px = new CubicPoly(),
  21122. py = new CubicPoly(),
  21123. pz = new CubicPoly();
  21124. class CatmullRomCurve3 extends Curve {
  21125. constructor(points = [], closed = false, curveType = 'centripetal', tension = 0.5) {
  21126. super();
  21127. this.type = 'CatmullRomCurve3';
  21128. this.points = points;
  21129. this.closed = closed;
  21130. this.curveType = curveType;
  21131. this.tension = tension;
  21132. }
  21133. getPoint(t, optionalTarget = new Vector3()) {
  21134. const point = optionalTarget;
  21135. const points = this.points;
  21136. const l = points.length;
  21137. const p = (l - (this.closed ? 0 : 1)) * t;
  21138. let intPoint = Math.floor(p);
  21139. let weight = p - intPoint;
  21140. if (this.closed) {
  21141. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  21142. } else if (weight === 0 && intPoint === l - 1) {
  21143. intPoint = l - 2;
  21144. weight = 1;
  21145. }
  21146. let p0, p3; // 4 points (p1 & p2 defined below)
  21147. if (this.closed || intPoint > 0) {
  21148. p0 = points[(intPoint - 1) % l];
  21149. } else {
  21150. // extrapolate first point
  21151. tmp.subVectors(points[0], points[1]).add(points[0]);
  21152. p0 = tmp;
  21153. }
  21154. const p1 = points[intPoint % l];
  21155. const p2 = points[(intPoint + 1) % l];
  21156. if (this.closed || intPoint + 2 < l) {
  21157. p3 = points[(intPoint + 2) % l];
  21158. } else {
  21159. // extrapolate last point
  21160. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  21161. p3 = tmp;
  21162. }
  21163. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  21164. // init Centripetal / Chordal Catmull-Rom
  21165. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  21166. let dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  21167. let dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  21168. let dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  21169. if (dt1 < 1e-4) dt1 = 1.0;
  21170. if (dt0 < 1e-4) dt0 = dt1;
  21171. if (dt2 < 1e-4) dt2 = dt1;
  21172. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  21173. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  21174. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  21175. } else if (this.curveType === 'catmullrom') {
  21176. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  21177. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  21178. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  21179. }
  21180. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  21181. return point;
  21182. }
  21183. copy(source) {
  21184. super.copy(source);
  21185. this.points = [];
  21186. for (let i = 0, l = source.points.length; i < l; i++) {
  21187. const point = source.points[i];
  21188. this.points.push(point.clone());
  21189. }
  21190. this.closed = source.closed;
  21191. this.curveType = source.curveType;
  21192. this.tension = source.tension;
  21193. return this;
  21194. }
  21195. toJSON() {
  21196. const data = super.toJSON();
  21197. data.points = [];
  21198. for (let i = 0, l = this.points.length; i < l; i++) {
  21199. const point = this.points[i];
  21200. data.points.push(point.toArray());
  21201. }
  21202. data.closed = this.closed;
  21203. data.curveType = this.curveType;
  21204. data.tension = this.tension;
  21205. return data;
  21206. }
  21207. fromJSON(json) {
  21208. super.fromJSON(json);
  21209. this.points = [];
  21210. for (let i = 0, l = json.points.length; i < l; i++) {
  21211. const point = json.points[i];
  21212. this.points.push(new Vector3().fromArray(point));
  21213. }
  21214. this.closed = json.closed;
  21215. this.curveType = json.curveType;
  21216. this.tension = json.tension;
  21217. return this;
  21218. }
  21219. }
  21220. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  21221. /**
  21222. * Bezier Curves formulas obtained from
  21223. * http://en.wikipedia.org/wiki/Bézier_curve
  21224. */
  21225. function CatmullRom(t, p0, p1, p2, p3) {
  21226. const v0 = (p2 - p0) * 0.5;
  21227. const v1 = (p3 - p1) * 0.5;
  21228. const t2 = t * t;
  21229. const t3 = t * t2;
  21230. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  21231. } //
  21232. function QuadraticBezierP0(t, p) {
  21233. const k = 1 - t;
  21234. return k * k * p;
  21235. }
  21236. function QuadraticBezierP1(t, p) {
  21237. return 2 * (1 - t) * t * p;
  21238. }
  21239. function QuadraticBezierP2(t, p) {
  21240. return t * t * p;
  21241. }
  21242. function QuadraticBezier(t, p0, p1, p2) {
  21243. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  21244. } //
  21245. function CubicBezierP0(t, p) {
  21246. const k = 1 - t;
  21247. return k * k * k * p;
  21248. }
  21249. function CubicBezierP1(t, p) {
  21250. const k = 1 - t;
  21251. return 3 * k * k * t * p;
  21252. }
  21253. function CubicBezierP2(t, p) {
  21254. return 3 * (1 - t) * t * t * p;
  21255. }
  21256. function CubicBezierP3(t, p) {
  21257. return t * t * t * p;
  21258. }
  21259. function CubicBezier(t, p0, p1, p2, p3) {
  21260. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  21261. }
  21262. class CubicBezierCurve extends Curve {
  21263. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) {
  21264. super();
  21265. this.type = 'CubicBezierCurve';
  21266. this.v0 = v0;
  21267. this.v1 = v1;
  21268. this.v2 = v2;
  21269. this.v3 = v3;
  21270. }
  21271. getPoint(t, optionalTarget = new Vector2()) {
  21272. const point = optionalTarget;
  21273. const v0 = this.v0,
  21274. v1 = this.v1,
  21275. v2 = this.v2,
  21276. v3 = this.v3;
  21277. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  21278. return point;
  21279. }
  21280. copy(source) {
  21281. super.copy(source);
  21282. this.v0.copy(source.v0);
  21283. this.v1.copy(source.v1);
  21284. this.v2.copy(source.v2);
  21285. this.v3.copy(source.v3);
  21286. return this;
  21287. }
  21288. toJSON() {
  21289. const data = super.toJSON();
  21290. data.v0 = this.v0.toArray();
  21291. data.v1 = this.v1.toArray();
  21292. data.v2 = this.v2.toArray();
  21293. data.v3 = this.v3.toArray();
  21294. return data;
  21295. }
  21296. fromJSON(json) {
  21297. super.fromJSON(json);
  21298. this.v0.fromArray(json.v0);
  21299. this.v1.fromArray(json.v1);
  21300. this.v2.fromArray(json.v2);
  21301. this.v3.fromArray(json.v3);
  21302. return this;
  21303. }
  21304. }
  21305. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  21306. class CubicBezierCurve3 extends Curve {
  21307. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) {
  21308. super();
  21309. this.type = 'CubicBezierCurve3';
  21310. this.v0 = v0;
  21311. this.v1 = v1;
  21312. this.v2 = v2;
  21313. this.v3 = v3;
  21314. }
  21315. getPoint(t, optionalTarget = new Vector3()) {
  21316. const point = optionalTarget;
  21317. const v0 = this.v0,
  21318. v1 = this.v1,
  21319. v2 = this.v2,
  21320. v3 = this.v3;
  21321. 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));
  21322. return point;
  21323. }
  21324. copy(source) {
  21325. super.copy(source);
  21326. this.v0.copy(source.v0);
  21327. this.v1.copy(source.v1);
  21328. this.v2.copy(source.v2);
  21329. this.v3.copy(source.v3);
  21330. return this;
  21331. }
  21332. toJSON() {
  21333. const data = super.toJSON();
  21334. data.v0 = this.v0.toArray();
  21335. data.v1 = this.v1.toArray();
  21336. data.v2 = this.v2.toArray();
  21337. data.v3 = this.v3.toArray();
  21338. return data;
  21339. }
  21340. fromJSON(json) {
  21341. super.fromJSON(json);
  21342. this.v0.fromArray(json.v0);
  21343. this.v1.fromArray(json.v1);
  21344. this.v2.fromArray(json.v2);
  21345. this.v3.fromArray(json.v3);
  21346. return this;
  21347. }
  21348. }
  21349. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  21350. class LineCurve extends Curve {
  21351. constructor(v1 = new Vector2(), v2 = new Vector2()) {
  21352. super();
  21353. this.type = 'LineCurve';
  21354. this.v1 = v1;
  21355. this.v2 = v2;
  21356. }
  21357. getPoint(t, optionalTarget = new Vector2()) {
  21358. const point = optionalTarget;
  21359. if (t === 1) {
  21360. point.copy(this.v2);
  21361. } else {
  21362. point.copy(this.v2).sub(this.v1);
  21363. point.multiplyScalar(t).add(this.v1);
  21364. }
  21365. return point;
  21366. } // Line curve is linear, so we can overwrite default getPointAt
  21367. getPointAt(u, optionalTarget) {
  21368. return this.getPoint(u, optionalTarget);
  21369. }
  21370. getTangent(t, optionalTarget) {
  21371. const tangent = optionalTarget || new Vector2();
  21372. tangent.copy(this.v2).sub(this.v1).normalize();
  21373. return tangent;
  21374. }
  21375. copy(source) {
  21376. super.copy(source);
  21377. this.v1.copy(source.v1);
  21378. this.v2.copy(source.v2);
  21379. return this;
  21380. }
  21381. toJSON() {
  21382. const data = super.toJSON();
  21383. data.v1 = this.v1.toArray();
  21384. data.v2 = this.v2.toArray();
  21385. return data;
  21386. }
  21387. fromJSON(json) {
  21388. super.fromJSON(json);
  21389. this.v1.fromArray(json.v1);
  21390. this.v2.fromArray(json.v2);
  21391. return this;
  21392. }
  21393. }
  21394. LineCurve.prototype.isLineCurve = true;
  21395. class LineCurve3 extends Curve {
  21396. constructor(v1 = new Vector3(), v2 = new Vector3()) {
  21397. super();
  21398. this.type = 'LineCurve3';
  21399. this.isLineCurve3 = true;
  21400. this.v1 = v1;
  21401. this.v2 = v2;
  21402. }
  21403. getPoint(t, optionalTarget = new Vector3()) {
  21404. const point = optionalTarget;
  21405. if (t === 1) {
  21406. point.copy(this.v2);
  21407. } else {
  21408. point.copy(this.v2).sub(this.v1);
  21409. point.multiplyScalar(t).add(this.v1);
  21410. }
  21411. return point;
  21412. } // Line curve is linear, so we can overwrite default getPointAt
  21413. getPointAt(u, optionalTarget) {
  21414. return this.getPoint(u, optionalTarget);
  21415. }
  21416. copy(source) {
  21417. super.copy(source);
  21418. this.v1.copy(source.v1);
  21419. this.v2.copy(source.v2);
  21420. return this;
  21421. }
  21422. toJSON() {
  21423. const data = super.toJSON();
  21424. data.v1 = this.v1.toArray();
  21425. data.v2 = this.v2.toArray();
  21426. return data;
  21427. }
  21428. fromJSON(json) {
  21429. super.fromJSON(json);
  21430. this.v1.fromArray(json.v1);
  21431. this.v2.fromArray(json.v2);
  21432. return this;
  21433. }
  21434. }
  21435. class QuadraticBezierCurve extends Curve {
  21436. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) {
  21437. super();
  21438. this.type = 'QuadraticBezierCurve';
  21439. this.v0 = v0;
  21440. this.v1 = v1;
  21441. this.v2 = v2;
  21442. }
  21443. getPoint(t, optionalTarget = new Vector2()) {
  21444. const point = optionalTarget;
  21445. const v0 = this.v0,
  21446. v1 = this.v1,
  21447. v2 = this.v2;
  21448. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  21449. return point;
  21450. }
  21451. copy(source) {
  21452. super.copy(source);
  21453. this.v0.copy(source.v0);
  21454. this.v1.copy(source.v1);
  21455. this.v2.copy(source.v2);
  21456. return this;
  21457. }
  21458. toJSON() {
  21459. const data = super.toJSON();
  21460. data.v0 = this.v0.toArray();
  21461. data.v1 = this.v1.toArray();
  21462. data.v2 = this.v2.toArray();
  21463. return data;
  21464. }
  21465. fromJSON(json) {
  21466. super.fromJSON(json);
  21467. this.v0.fromArray(json.v0);
  21468. this.v1.fromArray(json.v1);
  21469. this.v2.fromArray(json.v2);
  21470. return this;
  21471. }
  21472. }
  21473. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  21474. class QuadraticBezierCurve3 extends Curve {
  21475. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) {
  21476. super();
  21477. this.type = 'QuadraticBezierCurve3';
  21478. this.v0 = v0;
  21479. this.v1 = v1;
  21480. this.v2 = v2;
  21481. }
  21482. getPoint(t, optionalTarget = new Vector3()) {
  21483. const point = optionalTarget;
  21484. const v0 = this.v0,
  21485. v1 = this.v1,
  21486. v2 = this.v2;
  21487. 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));
  21488. return point;
  21489. }
  21490. copy(source) {
  21491. super.copy(source);
  21492. this.v0.copy(source.v0);
  21493. this.v1.copy(source.v1);
  21494. this.v2.copy(source.v2);
  21495. return this;
  21496. }
  21497. toJSON() {
  21498. const data = super.toJSON();
  21499. data.v0 = this.v0.toArray();
  21500. data.v1 = this.v1.toArray();
  21501. data.v2 = this.v2.toArray();
  21502. return data;
  21503. }
  21504. fromJSON(json) {
  21505. super.fromJSON(json);
  21506. this.v0.fromArray(json.v0);
  21507. this.v1.fromArray(json.v1);
  21508. this.v2.fromArray(json.v2);
  21509. return this;
  21510. }
  21511. }
  21512. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  21513. class SplineCurve extends Curve {
  21514. constructor(points = []) {
  21515. super();
  21516. this.type = 'SplineCurve';
  21517. this.points = points;
  21518. }
  21519. getPoint(t, optionalTarget = new Vector2()) {
  21520. const point = optionalTarget;
  21521. const points = this.points;
  21522. const p = (points.length - 1) * t;
  21523. const intPoint = Math.floor(p);
  21524. const weight = p - intPoint;
  21525. const p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  21526. const p1 = points[intPoint];
  21527. const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  21528. const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  21529. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  21530. return point;
  21531. }
  21532. copy(source) {
  21533. super.copy(source);
  21534. this.points = [];
  21535. for (let i = 0, l = source.points.length; i < l; i++) {
  21536. const point = source.points[i];
  21537. this.points.push(point.clone());
  21538. }
  21539. return this;
  21540. }
  21541. toJSON() {
  21542. const data = super.toJSON();
  21543. data.points = [];
  21544. for (let i = 0, l = this.points.length; i < l; i++) {
  21545. const point = this.points[i];
  21546. data.points.push(point.toArray());
  21547. }
  21548. return data;
  21549. }
  21550. fromJSON(json) {
  21551. super.fromJSON(json);
  21552. this.points = [];
  21553. for (let i = 0, l = json.points.length; i < l; i++) {
  21554. const point = json.points[i];
  21555. this.points.push(new Vector2().fromArray(point));
  21556. }
  21557. return this;
  21558. }
  21559. }
  21560. SplineCurve.prototype.isSplineCurve = true;
  21561. var Curves = /*#__PURE__*/Object.freeze({
  21562. __proto__: null,
  21563. ArcCurve: ArcCurve,
  21564. CatmullRomCurve3: CatmullRomCurve3,
  21565. CubicBezierCurve: CubicBezierCurve,
  21566. CubicBezierCurve3: CubicBezierCurve3,
  21567. EllipseCurve: EllipseCurve,
  21568. LineCurve: LineCurve,
  21569. LineCurve3: LineCurve3,
  21570. QuadraticBezierCurve: QuadraticBezierCurve,
  21571. QuadraticBezierCurve3: QuadraticBezierCurve3,
  21572. SplineCurve: SplineCurve
  21573. });
  21574. /**************************************************************
  21575. * Curved Path - a curve path is simply a array of connected
  21576. * curves, but retains the api of a curve
  21577. **************************************************************/
  21578. class CurvePath extends Curve {
  21579. constructor() {
  21580. super();
  21581. this.type = 'CurvePath';
  21582. this.curves = [];
  21583. this.autoClose = false; // Automatically closes the path
  21584. }
  21585. add(curve) {
  21586. this.curves.push(curve);
  21587. }
  21588. closePath() {
  21589. // Add a line curve if start and end of lines are not connected
  21590. const startPoint = this.curves[0].getPoint(0);
  21591. const endPoint = this.curves[this.curves.length - 1].getPoint(1);
  21592. if (!startPoint.equals(endPoint)) {
  21593. this.curves.push(new LineCurve(endPoint, startPoint));
  21594. }
  21595. } // To get accurate point with reference to
  21596. // entire path distance at time t,
  21597. // following has to be done:
  21598. // 1. Length of each sub path have to be known
  21599. // 2. Locate and identify type of curve
  21600. // 3. Get t for the curve
  21601. // 4. Return curve.getPointAt(t')
  21602. getPoint(t) {
  21603. const d = t * this.getLength();
  21604. const curveLengths = this.getCurveLengths();
  21605. let i = 0; // To think about boundaries points.
  21606. while (i < curveLengths.length) {
  21607. if (curveLengths[i] >= d) {
  21608. const diff = curveLengths[i] - d;
  21609. const curve = this.curves[i];
  21610. const segmentLength = curve.getLength();
  21611. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  21612. return curve.getPointAt(u);
  21613. }
  21614. i++;
  21615. }
  21616. return null; // loop where sum != 0, sum > d , sum+1 <d
  21617. } // We cannot use the default THREE.Curve getPoint() with getLength() because in
  21618. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  21619. // getPoint() depends on getLength
  21620. getLength() {
  21621. const lens = this.getCurveLengths();
  21622. return lens[lens.length - 1];
  21623. } // cacheLengths must be recalculated.
  21624. updateArcLengths() {
  21625. this.needsUpdate = true;
  21626. this.cacheLengths = null;
  21627. this.getCurveLengths();
  21628. } // Compute lengths and cache them
  21629. // We cannot overwrite getLengths() because UtoT mapping uses it.
  21630. getCurveLengths() {
  21631. // We use cache values if curves and cache array are same length
  21632. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  21633. return this.cacheLengths;
  21634. } // Get length of sub-curve
  21635. // Push sums into cached array
  21636. const lengths = [];
  21637. let sums = 0;
  21638. for (let i = 0, l = this.curves.length; i < l; i++) {
  21639. sums += this.curves[i].getLength();
  21640. lengths.push(sums);
  21641. }
  21642. this.cacheLengths = lengths;
  21643. return lengths;
  21644. }
  21645. getSpacedPoints(divisions = 40) {
  21646. const points = [];
  21647. for (let i = 0; i <= divisions; i++) {
  21648. points.push(this.getPoint(i / divisions));
  21649. }
  21650. if (this.autoClose) {
  21651. points.push(points[0]);
  21652. }
  21653. return points;
  21654. }
  21655. getPoints(divisions = 12) {
  21656. const points = [];
  21657. let last;
  21658. for (let i = 0, curves = this.curves; i < curves.length; i++) {
  21659. const curve = curves[i];
  21660. const resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  21661. const pts = curve.getPoints(resolution);
  21662. for (let j = 0; j < pts.length; j++) {
  21663. const point = pts[j];
  21664. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  21665. points.push(point);
  21666. last = point;
  21667. }
  21668. }
  21669. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  21670. points.push(points[0]);
  21671. }
  21672. return points;
  21673. }
  21674. copy(source) {
  21675. super.copy(source);
  21676. this.curves = [];
  21677. for (let i = 0, l = source.curves.length; i < l; i++) {
  21678. const curve = source.curves[i];
  21679. this.curves.push(curve.clone());
  21680. }
  21681. this.autoClose = source.autoClose;
  21682. return this;
  21683. }
  21684. toJSON() {
  21685. const data = super.toJSON();
  21686. data.autoClose = this.autoClose;
  21687. data.curves = [];
  21688. for (let i = 0, l = this.curves.length; i < l; i++) {
  21689. const curve = this.curves[i];
  21690. data.curves.push(curve.toJSON());
  21691. }
  21692. return data;
  21693. }
  21694. fromJSON(json) {
  21695. super.fromJSON(json);
  21696. this.autoClose = json.autoClose;
  21697. this.curves = [];
  21698. for (let i = 0, l = json.curves.length; i < l; i++) {
  21699. const curve = json.curves[i];
  21700. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  21701. }
  21702. return this;
  21703. }
  21704. }
  21705. class Path extends CurvePath {
  21706. constructor(points) {
  21707. super();
  21708. this.type = 'Path';
  21709. this.currentPoint = new Vector2();
  21710. if (points) {
  21711. this.setFromPoints(points);
  21712. }
  21713. }
  21714. setFromPoints(points) {
  21715. this.moveTo(points[0].x, points[0].y);
  21716. for (let i = 1, l = points.length; i < l; i++) {
  21717. this.lineTo(points[i].x, points[i].y);
  21718. }
  21719. return this;
  21720. }
  21721. moveTo(x, y) {
  21722. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  21723. return this;
  21724. }
  21725. lineTo(x, y) {
  21726. const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  21727. this.curves.push(curve);
  21728. this.currentPoint.set(x, y);
  21729. return this;
  21730. }
  21731. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  21732. const curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  21733. this.curves.push(curve);
  21734. this.currentPoint.set(aX, aY);
  21735. return this;
  21736. }
  21737. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  21738. const curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  21739. this.curves.push(curve);
  21740. this.currentPoint.set(aX, aY);
  21741. return this;
  21742. }
  21743. splineThru(pts
  21744. /*Array of Vector*/
  21745. ) {
  21746. const npts = [this.currentPoint.clone()].concat(pts);
  21747. const curve = new SplineCurve(npts);
  21748. this.curves.push(curve);
  21749. this.currentPoint.copy(pts[pts.length - 1]);
  21750. return this;
  21751. }
  21752. arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  21753. const x0 = this.currentPoint.x;
  21754. const y0 = this.currentPoint.y;
  21755. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  21756. return this;
  21757. }
  21758. absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  21759. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  21760. return this;
  21761. }
  21762. ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  21763. const x0 = this.currentPoint.x;
  21764. const y0 = this.currentPoint.y;
  21765. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  21766. return this;
  21767. }
  21768. absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  21769. const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  21770. if (this.curves.length > 0) {
  21771. // if a previous curve is present, attempt to join
  21772. const firstPoint = curve.getPoint(0);
  21773. if (!firstPoint.equals(this.currentPoint)) {
  21774. this.lineTo(firstPoint.x, firstPoint.y);
  21775. }
  21776. }
  21777. this.curves.push(curve);
  21778. const lastPoint = curve.getPoint(1);
  21779. this.currentPoint.copy(lastPoint);
  21780. return this;
  21781. }
  21782. copy(source) {
  21783. super.copy(source);
  21784. this.currentPoint.copy(source.currentPoint);
  21785. return this;
  21786. }
  21787. toJSON() {
  21788. const data = super.toJSON();
  21789. data.currentPoint = this.currentPoint.toArray();
  21790. return data;
  21791. }
  21792. fromJSON(json) {
  21793. super.fromJSON(json);
  21794. this.currentPoint.fromArray(json.currentPoint);
  21795. return this;
  21796. }
  21797. }
  21798. class Shape extends Path {
  21799. constructor(points) {
  21800. super(points);
  21801. this.uuid = generateUUID();
  21802. this.type = 'Shape';
  21803. this.holes = [];
  21804. }
  21805. getPointsHoles(divisions) {
  21806. const holesPts = [];
  21807. for (let i = 0, l = this.holes.length; i < l; i++) {
  21808. holesPts[i] = this.holes[i].getPoints(divisions);
  21809. }
  21810. return holesPts;
  21811. } // get points of shape and holes (keypoints based on segments parameter)
  21812. extractPoints(divisions) {
  21813. return {
  21814. shape: this.getPoints(divisions),
  21815. holes: this.getPointsHoles(divisions)
  21816. };
  21817. }
  21818. copy(source) {
  21819. super.copy(source);
  21820. this.holes = [];
  21821. for (let i = 0, l = source.holes.length; i < l; i++) {
  21822. const hole = source.holes[i];
  21823. this.holes.push(hole.clone());
  21824. }
  21825. return this;
  21826. }
  21827. toJSON() {
  21828. const data = super.toJSON();
  21829. data.uuid = this.uuid;
  21830. data.holes = [];
  21831. for (let i = 0, l = this.holes.length; i < l; i++) {
  21832. const hole = this.holes[i];
  21833. data.holes.push(hole.toJSON());
  21834. }
  21835. return data;
  21836. }
  21837. fromJSON(json) {
  21838. super.fromJSON(json);
  21839. this.uuid = json.uuid;
  21840. this.holes = [];
  21841. for (let i = 0, l = json.holes.length; i < l; i++) {
  21842. const hole = json.holes[i];
  21843. this.holes.push(new Path().fromJSON(hole));
  21844. }
  21845. return this;
  21846. }
  21847. }
  21848. class Light extends Object3D {
  21849. constructor(color, intensity = 1) {
  21850. super();
  21851. this.type = 'Light';
  21852. this.color = new Color(color);
  21853. this.intensity = intensity;
  21854. }
  21855. dispose() {// Empty here in base class; some subclasses override.
  21856. }
  21857. copy(source) {
  21858. super.copy(source);
  21859. this.color.copy(source.color);
  21860. this.intensity = source.intensity;
  21861. return this;
  21862. }
  21863. toJSON(meta) {
  21864. const data = super.toJSON(meta);
  21865. data.object.color = this.color.getHex();
  21866. data.object.intensity = this.intensity;
  21867. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  21868. if (this.distance !== undefined) data.object.distance = this.distance;
  21869. if (this.angle !== undefined) data.object.angle = this.angle;
  21870. if (this.decay !== undefined) data.object.decay = this.decay;
  21871. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  21872. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  21873. return data;
  21874. }
  21875. }
  21876. Light.prototype.isLight = true;
  21877. class HemisphereLight extends Light {
  21878. constructor(skyColor, groundColor, intensity) {
  21879. super(skyColor, intensity);
  21880. this.type = 'HemisphereLight';
  21881. this.position.copy(Object3D.DefaultUp);
  21882. this.updateMatrix();
  21883. this.groundColor = new Color(groundColor);
  21884. }
  21885. copy(source) {
  21886. Light.prototype.copy.call(this, source);
  21887. this.groundColor.copy(source.groundColor);
  21888. return this;
  21889. }
  21890. }
  21891. HemisphereLight.prototype.isHemisphereLight = true;
  21892. const _projScreenMatrix$1 = /*@__PURE__*/new Matrix4();
  21893. const _lightPositionWorld$1 = /*@__PURE__*/new Vector3();
  21894. const _lookTarget$1 = /*@__PURE__*/new Vector3();
  21895. class LightShadow {
  21896. constructor(camera) {
  21897. this.camera = camera;
  21898. this.bias = 0;
  21899. this.normalBias = 0;
  21900. this.radius = 1;
  21901. this.mapSize = new Vector2(512, 512);
  21902. this.map = null;
  21903. this.mapPass = null;
  21904. this.matrix = new Matrix4();
  21905. this.autoUpdate = true;
  21906. this.needsUpdate = false;
  21907. this._frustum = new Frustum();
  21908. this._frameExtents = new Vector2(1, 1);
  21909. this._viewportCount = 1;
  21910. this._viewports = [new Vector4(0, 0, 1, 1)];
  21911. }
  21912. getViewportCount() {
  21913. return this._viewportCount;
  21914. }
  21915. getFrustum() {
  21916. return this._frustum;
  21917. }
  21918. updateMatrices(light) {
  21919. const shadowCamera = this.camera;
  21920. const shadowMatrix = this.matrix;
  21921. _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld);
  21922. shadowCamera.position.copy(_lightPositionWorld$1);
  21923. _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld);
  21924. shadowCamera.lookAt(_lookTarget$1);
  21925. shadowCamera.updateMatrixWorld();
  21926. _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  21927. this._frustum.setFromProjectionMatrix(_projScreenMatrix$1);
  21928. 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);
  21929. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  21930. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  21931. }
  21932. getViewport(viewportIndex) {
  21933. return this._viewports[viewportIndex];
  21934. }
  21935. getFrameExtents() {
  21936. return this._frameExtents;
  21937. }
  21938. dispose() {
  21939. if (this.map) {
  21940. this.map.dispose();
  21941. }
  21942. if (this.mapPass) {
  21943. this.mapPass.dispose();
  21944. }
  21945. }
  21946. copy(source) {
  21947. this.camera = source.camera.clone();
  21948. this.bias = source.bias;
  21949. this.radius = source.radius;
  21950. this.mapSize.copy(source.mapSize);
  21951. return this;
  21952. }
  21953. clone() {
  21954. return new this.constructor().copy(this);
  21955. }
  21956. toJSON() {
  21957. const object = {};
  21958. if (this.bias !== 0) object.bias = this.bias;
  21959. if (this.normalBias !== 0) object.normalBias = this.normalBias;
  21960. if (this.radius !== 1) object.radius = this.radius;
  21961. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  21962. object.camera = this.camera.toJSON(false).object;
  21963. delete object.camera.matrix;
  21964. return object;
  21965. }
  21966. }
  21967. class SpotLightShadow extends LightShadow {
  21968. constructor() {
  21969. super(new PerspectiveCamera(50, 1, 0.5, 500));
  21970. this.focus = 1;
  21971. }
  21972. updateMatrices(light) {
  21973. const camera = this.camera;
  21974. const fov = RAD2DEG * 2 * light.angle * this.focus;
  21975. const aspect = this.mapSize.width / this.mapSize.height;
  21976. const far = light.distance || camera.far;
  21977. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  21978. camera.fov = fov;
  21979. camera.aspect = aspect;
  21980. camera.far = far;
  21981. camera.updateProjectionMatrix();
  21982. }
  21983. super.updateMatrices(light);
  21984. }
  21985. copy(source) {
  21986. super.copy(source);
  21987. this.focus = source.focus;
  21988. return this;
  21989. }
  21990. }
  21991. SpotLightShadow.prototype.isSpotLightShadow = true;
  21992. class SpotLight extends Light {
  21993. constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1) {
  21994. super(color, intensity);
  21995. this.type = 'SpotLight';
  21996. this.position.copy(Object3D.DefaultUp);
  21997. this.updateMatrix();
  21998. this.target = new Object3D();
  21999. this.distance = distance;
  22000. this.angle = angle;
  22001. this.penumbra = penumbra;
  22002. this.decay = decay; // for physically correct lights, should be 2.
  22003. this.shadow = new SpotLightShadow();
  22004. }
  22005. get power() {
  22006. // intensity = power per solid angle.
  22007. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22008. return this.intensity * Math.PI;
  22009. }
  22010. set power(power) {
  22011. // intensity = power per solid angle.
  22012. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22013. this.intensity = power / Math.PI;
  22014. }
  22015. dispose() {
  22016. this.shadow.dispose();
  22017. }
  22018. copy(source) {
  22019. super.copy(source);
  22020. this.distance = source.distance;
  22021. this.angle = source.angle;
  22022. this.penumbra = source.penumbra;
  22023. this.decay = source.decay;
  22024. this.target = source.target.clone();
  22025. this.shadow = source.shadow.clone();
  22026. return this;
  22027. }
  22028. }
  22029. SpotLight.prototype.isSpotLight = true;
  22030. const _projScreenMatrix = /*@__PURE__*/new Matrix4();
  22031. const _lightPositionWorld = /*@__PURE__*/new Vector3();
  22032. const _lookTarget = /*@__PURE__*/new Vector3();
  22033. class PointLightShadow extends LightShadow {
  22034. constructor() {
  22035. super(new PerspectiveCamera(90, 1, 0.5, 500));
  22036. this._frameExtents = new Vector2(4, 2);
  22037. this._viewportCount = 6;
  22038. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  22039. // following orientation:
  22040. //
  22041. // xzXZ
  22042. // y Y
  22043. //
  22044. // X - Positive x direction
  22045. // x - Negative x direction
  22046. // Y - Positive y direction
  22047. // y - Negative y direction
  22048. // Z - Positive z direction
  22049. // z - Negative z direction
  22050. // positive X
  22051. new Vector4(2, 1, 1, 1), // negative X
  22052. new Vector4(0, 1, 1, 1), // positive Z
  22053. new Vector4(3, 1, 1, 1), // negative Z
  22054. new Vector4(1, 1, 1, 1), // positive Y
  22055. new Vector4(3, 0, 1, 1), // negative Y
  22056. new Vector4(1, 0, 1, 1)];
  22057. 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)];
  22058. 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)];
  22059. }
  22060. updateMatrices(light, viewportIndex = 0) {
  22061. const camera = this.camera;
  22062. const shadowMatrix = this.matrix;
  22063. const far = light.distance || camera.far;
  22064. if (far !== camera.far) {
  22065. camera.far = far;
  22066. camera.updateProjectionMatrix();
  22067. }
  22068. _lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  22069. camera.position.copy(_lightPositionWorld);
  22070. _lookTarget.copy(camera.position);
  22071. _lookTarget.add(this._cubeDirections[viewportIndex]);
  22072. camera.up.copy(this._cubeUps[viewportIndex]);
  22073. camera.lookAt(_lookTarget);
  22074. camera.updateMatrixWorld();
  22075. shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z);
  22076. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  22077. this._frustum.setFromProjectionMatrix(_projScreenMatrix);
  22078. }
  22079. }
  22080. PointLightShadow.prototype.isPointLightShadow = true;
  22081. class PointLight extends Light {
  22082. constructor(color, intensity, distance = 0, decay = 1) {
  22083. super(color, intensity);
  22084. this.type = 'PointLight';
  22085. this.distance = distance;
  22086. this.decay = decay; // for physically correct lights, should be 2.
  22087. this.shadow = new PointLightShadow();
  22088. }
  22089. get power() {
  22090. // intensity = power per solid angle.
  22091. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22092. return this.intensity * 4 * Math.PI;
  22093. }
  22094. set power(power) {
  22095. // intensity = power per solid angle.
  22096. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22097. this.intensity = power / (4 * Math.PI);
  22098. }
  22099. dispose() {
  22100. this.shadow.dispose();
  22101. }
  22102. copy(source) {
  22103. super.copy(source);
  22104. this.distance = source.distance;
  22105. this.decay = source.decay;
  22106. this.shadow = source.shadow.clone();
  22107. return this;
  22108. }
  22109. }
  22110. PointLight.prototype.isPointLight = true;
  22111. class OrthographicCamera extends Camera {
  22112. constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) {
  22113. super();
  22114. this.type = 'OrthographicCamera';
  22115. this.zoom = 1;
  22116. this.view = null;
  22117. this.left = left;
  22118. this.right = right;
  22119. this.top = top;
  22120. this.bottom = bottom;
  22121. this.near = near;
  22122. this.far = far;
  22123. this.updateProjectionMatrix();
  22124. }
  22125. copy(source, recursive) {
  22126. super.copy(source, recursive);
  22127. this.left = source.left;
  22128. this.right = source.right;
  22129. this.top = source.top;
  22130. this.bottom = source.bottom;
  22131. this.near = source.near;
  22132. this.far = source.far;
  22133. this.zoom = source.zoom;
  22134. this.view = source.view === null ? null : Object.assign({}, source.view);
  22135. return this;
  22136. }
  22137. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  22138. if (this.view === null) {
  22139. this.view = {
  22140. enabled: true,
  22141. fullWidth: 1,
  22142. fullHeight: 1,
  22143. offsetX: 0,
  22144. offsetY: 0,
  22145. width: 1,
  22146. height: 1
  22147. };
  22148. }
  22149. this.view.enabled = true;
  22150. this.view.fullWidth = fullWidth;
  22151. this.view.fullHeight = fullHeight;
  22152. this.view.offsetX = x;
  22153. this.view.offsetY = y;
  22154. this.view.width = width;
  22155. this.view.height = height;
  22156. this.updateProjectionMatrix();
  22157. }
  22158. clearViewOffset() {
  22159. if (this.view !== null) {
  22160. this.view.enabled = false;
  22161. }
  22162. this.updateProjectionMatrix();
  22163. }
  22164. updateProjectionMatrix() {
  22165. const dx = (this.right - this.left) / (2 * this.zoom);
  22166. const dy = (this.top - this.bottom) / (2 * this.zoom);
  22167. const cx = (this.right + this.left) / 2;
  22168. const cy = (this.top + this.bottom) / 2;
  22169. let left = cx - dx;
  22170. let right = cx + dx;
  22171. let top = cy + dy;
  22172. let bottom = cy - dy;
  22173. if (this.view !== null && this.view.enabled) {
  22174. const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  22175. const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  22176. left += scaleW * this.view.offsetX;
  22177. right = left + scaleW * this.view.width;
  22178. top -= scaleH * this.view.offsetY;
  22179. bottom = top - scaleH * this.view.height;
  22180. }
  22181. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  22182. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  22183. }
  22184. toJSON(meta) {
  22185. const data = super.toJSON(meta);
  22186. data.object.zoom = this.zoom;
  22187. data.object.left = this.left;
  22188. data.object.right = this.right;
  22189. data.object.top = this.top;
  22190. data.object.bottom = this.bottom;
  22191. data.object.near = this.near;
  22192. data.object.far = this.far;
  22193. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  22194. return data;
  22195. }
  22196. }
  22197. OrthographicCamera.prototype.isOrthographicCamera = true;
  22198. class DirectionalLightShadow extends LightShadow {
  22199. constructor() {
  22200. super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  22201. }
  22202. }
  22203. DirectionalLightShadow.prototype.isDirectionalLightShadow = true;
  22204. class DirectionalLight extends Light {
  22205. constructor(color, intensity) {
  22206. super(color, intensity);
  22207. this.type = 'DirectionalLight';
  22208. this.position.copy(Object3D.DefaultUp);
  22209. this.updateMatrix();
  22210. this.target = new Object3D();
  22211. this.shadow = new DirectionalLightShadow();
  22212. }
  22213. dispose() {
  22214. this.shadow.dispose();
  22215. }
  22216. copy(source) {
  22217. super.copy(source);
  22218. this.target = source.target.clone();
  22219. this.shadow = source.shadow.clone();
  22220. return this;
  22221. }
  22222. }
  22223. DirectionalLight.prototype.isDirectionalLight = true;
  22224. class AmbientLight extends Light {
  22225. constructor(color, intensity) {
  22226. super(color, intensity);
  22227. this.type = 'AmbientLight';
  22228. }
  22229. }
  22230. AmbientLight.prototype.isAmbientLight = true;
  22231. class RectAreaLight extends Light {
  22232. constructor(color, intensity, width = 10, height = 10) {
  22233. super(color, intensity);
  22234. this.type = 'RectAreaLight';
  22235. this.width = width;
  22236. this.height = height;
  22237. }
  22238. copy(source) {
  22239. super.copy(source);
  22240. this.width = source.width;
  22241. this.height = source.height;
  22242. return this;
  22243. }
  22244. toJSON(meta) {
  22245. const data = super.toJSON(meta);
  22246. data.object.width = this.width;
  22247. data.object.height = this.height;
  22248. return data;
  22249. }
  22250. }
  22251. RectAreaLight.prototype.isRectAreaLight = true;
  22252. /**
  22253. * Primary reference:
  22254. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  22255. *
  22256. * Secondary reference:
  22257. * https://www.ppsloan.org/publications/StupidSH36.pdf
  22258. */
  22259. // 3-band SH defined by 9 coefficients
  22260. class SphericalHarmonics3 {
  22261. constructor() {
  22262. this.coefficients = [];
  22263. for (let i = 0; i < 9; i++) {
  22264. this.coefficients.push(new Vector3());
  22265. }
  22266. }
  22267. set(coefficients) {
  22268. for (let i = 0; i < 9; i++) {
  22269. this.coefficients[i].copy(coefficients[i]);
  22270. }
  22271. return this;
  22272. }
  22273. zero() {
  22274. for (let i = 0; i < 9; i++) {
  22275. this.coefficients[i].set(0, 0, 0);
  22276. }
  22277. return this;
  22278. } // get the radiance in the direction of the normal
  22279. // target is a Vector3
  22280. getAt(normal, target) {
  22281. // normal is assumed to be unit length
  22282. const x = normal.x,
  22283. y = normal.y,
  22284. z = normal.z;
  22285. const coeff = this.coefficients; // band 0
  22286. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  22287. target.addScaledVector(coeff[1], 0.488603 * y);
  22288. target.addScaledVector(coeff[2], 0.488603 * z);
  22289. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  22290. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  22291. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  22292. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  22293. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  22294. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  22295. return target;
  22296. } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  22297. // target is a Vector3
  22298. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  22299. getIrradianceAt(normal, target) {
  22300. // normal is assumed to be unit length
  22301. const x = normal.x,
  22302. y = normal.y,
  22303. z = normal.z;
  22304. const coeff = this.coefficients; // band 0
  22305. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  22306. // band 1
  22307. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  22308. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  22309. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  22310. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  22311. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  22312. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  22313. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  22314. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  22315. return target;
  22316. }
  22317. add(sh) {
  22318. for (let i = 0; i < 9; i++) {
  22319. this.coefficients[i].add(sh.coefficients[i]);
  22320. }
  22321. return this;
  22322. }
  22323. addScaledSH(sh, s) {
  22324. for (let i = 0; i < 9; i++) {
  22325. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  22326. }
  22327. return this;
  22328. }
  22329. scale(s) {
  22330. for (let i = 0; i < 9; i++) {
  22331. this.coefficients[i].multiplyScalar(s);
  22332. }
  22333. return this;
  22334. }
  22335. lerp(sh, alpha) {
  22336. for (let i = 0; i < 9; i++) {
  22337. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  22338. }
  22339. return this;
  22340. }
  22341. equals(sh) {
  22342. for (let i = 0; i < 9; i++) {
  22343. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  22344. return false;
  22345. }
  22346. }
  22347. return true;
  22348. }
  22349. copy(sh) {
  22350. return this.set(sh.coefficients);
  22351. }
  22352. clone() {
  22353. return new this.constructor().copy(this);
  22354. }
  22355. fromArray(array, offset = 0) {
  22356. const coefficients = this.coefficients;
  22357. for (let i = 0; i < 9; i++) {
  22358. coefficients[i].fromArray(array, offset + i * 3);
  22359. }
  22360. return this;
  22361. }
  22362. toArray(array = [], offset = 0) {
  22363. const coefficients = this.coefficients;
  22364. for (let i = 0; i < 9; i++) {
  22365. coefficients[i].toArray(array, offset + i * 3);
  22366. }
  22367. return array;
  22368. } // evaluate the basis functions
  22369. // shBasis is an Array[ 9 ]
  22370. static getBasisAt(normal, shBasis) {
  22371. // normal is assumed to be unit length
  22372. const x = normal.x,
  22373. y = normal.y,
  22374. z = normal.z; // band 0
  22375. shBasis[0] = 0.282095; // band 1
  22376. shBasis[1] = 0.488603 * y;
  22377. shBasis[2] = 0.488603 * z;
  22378. shBasis[3] = 0.488603 * x; // band 2
  22379. shBasis[4] = 1.092548 * x * y;
  22380. shBasis[5] = 1.092548 * y * z;
  22381. shBasis[6] = 0.315392 * (3 * z * z - 1);
  22382. shBasis[7] = 1.092548 * x * z;
  22383. shBasis[8] = 0.546274 * (x * x - y * y);
  22384. }
  22385. }
  22386. SphericalHarmonics3.prototype.isSphericalHarmonics3 = true;
  22387. class LightProbe extends Light {
  22388. constructor(sh = new SphericalHarmonics3(), intensity = 1) {
  22389. super(undefined, intensity);
  22390. this.sh = sh;
  22391. }
  22392. copy(source) {
  22393. super.copy(source);
  22394. this.sh.copy(source.sh);
  22395. return this;
  22396. }
  22397. fromJSON(json) {
  22398. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  22399. this.sh.fromArray(json.sh);
  22400. return this;
  22401. }
  22402. toJSON(meta) {
  22403. const data = super.toJSON(meta);
  22404. data.object.sh = this.sh.toArray();
  22405. return data;
  22406. }
  22407. }
  22408. LightProbe.prototype.isLightProbe = true;
  22409. class MaterialLoader extends Loader {
  22410. constructor(manager) {
  22411. super(manager);
  22412. this.textures = {};
  22413. }
  22414. load(url, onLoad, onProgress, onError) {
  22415. const scope = this;
  22416. const loader = new FileLoader(scope.manager);
  22417. loader.setPath(scope.path);
  22418. loader.setRequestHeader(scope.requestHeader);
  22419. loader.setWithCredentials(scope.withCredentials);
  22420. loader.load(url, function (text) {
  22421. try {
  22422. onLoad(scope.parse(JSON.parse(text)));
  22423. } catch (e) {
  22424. if (onError) {
  22425. onError(e);
  22426. } else {
  22427. console.error(e);
  22428. }
  22429. scope.manager.itemError(url);
  22430. }
  22431. }, onProgress, onError);
  22432. }
  22433. parse(json) {
  22434. const textures = this.textures;
  22435. function getTexture(name) {
  22436. if (textures[name] === undefined) {
  22437. console.warn('THREE.MaterialLoader: Undefined texture', name);
  22438. }
  22439. return textures[name];
  22440. }
  22441. const material = new Materials[json.type]();
  22442. if (json.uuid !== undefined) material.uuid = json.uuid;
  22443. if (json.name !== undefined) material.name = json.name;
  22444. if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
  22445. if (json.roughness !== undefined) material.roughness = json.roughness;
  22446. if (json.metalness !== undefined) material.metalness = json.metalness;
  22447. if (json.sheen !== undefined) material.sheen = new Color().setHex(json.sheen);
  22448. if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
  22449. if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
  22450. if (json.shininess !== undefined) material.shininess = json.shininess;
  22451. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  22452. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  22453. if (json.fog !== undefined) material.fog = json.fog;
  22454. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  22455. if (json.blending !== undefined) material.blending = json.blending;
  22456. if (json.combine !== undefined) material.combine = json.combine;
  22457. if (json.side !== undefined) material.side = json.side;
  22458. if (json.shadowSide !== undefined) material.shadowSide = json.shadowSide;
  22459. if (json.opacity !== undefined) material.opacity = json.opacity;
  22460. if (json.transparent !== undefined) material.transparent = json.transparent;
  22461. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  22462. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  22463. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  22464. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  22465. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  22466. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  22467. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  22468. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  22469. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  22470. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  22471. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  22472. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  22473. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  22474. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  22475. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  22476. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  22477. if (json.rotation !== undefined) material.rotation = json.rotation;
  22478. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  22479. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  22480. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  22481. if (json.scale !== undefined) material.scale = json.scale;
  22482. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  22483. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  22484. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  22485. if (json.skinning !== undefined) material.skinning = json.skinning;
  22486. if (json.morphTargets !== undefined) material.morphTargets = json.morphTargets;
  22487. if (json.morphNormals !== undefined) material.morphNormals = json.morphNormals;
  22488. if (json.dithering !== undefined) material.dithering = json.dithering;
  22489. if (json.alphaToCoverage !== undefined) material.alphaToCoverage = json.alphaToCoverage;
  22490. if (json.premultipliedAlpha !== undefined) material.premultipliedAlpha = json.premultipliedAlpha;
  22491. if (json.vertexTangents !== undefined) material.vertexTangents = json.vertexTangents;
  22492. if (json.visible !== undefined) material.visible = json.visible;
  22493. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  22494. if (json.userData !== undefined) material.userData = json.userData;
  22495. if (json.vertexColors !== undefined) {
  22496. if (typeof json.vertexColors === 'number') {
  22497. material.vertexColors = json.vertexColors > 0 ? true : false;
  22498. } else {
  22499. material.vertexColors = json.vertexColors;
  22500. }
  22501. } // Shader Material
  22502. if (json.uniforms !== undefined) {
  22503. for (const name in json.uniforms) {
  22504. const uniform = json.uniforms[name];
  22505. material.uniforms[name] = {};
  22506. switch (uniform.type) {
  22507. case 't':
  22508. material.uniforms[name].value = getTexture(uniform.value);
  22509. break;
  22510. case 'c':
  22511. material.uniforms[name].value = new Color().setHex(uniform.value);
  22512. break;
  22513. case 'v2':
  22514. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  22515. break;
  22516. case 'v3':
  22517. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  22518. break;
  22519. case 'v4':
  22520. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  22521. break;
  22522. case 'm3':
  22523. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  22524. break;
  22525. case 'm4':
  22526. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  22527. break;
  22528. default:
  22529. material.uniforms[name].value = uniform.value;
  22530. }
  22531. }
  22532. }
  22533. if (json.defines !== undefined) material.defines = json.defines;
  22534. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  22535. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  22536. if (json.extensions !== undefined) {
  22537. for (const key in json.extensions) {
  22538. material.extensions[key] = json.extensions[key];
  22539. }
  22540. } // Deprecated
  22541. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  22542. // for PointsMaterial
  22543. if (json.size !== undefined) material.size = json.size;
  22544. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  22545. if (json.map !== undefined) material.map = getTexture(json.map);
  22546. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  22547. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  22548. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  22549. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  22550. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  22551. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  22552. if (json.normalScale !== undefined) {
  22553. let normalScale = json.normalScale;
  22554. if (Array.isArray(normalScale) === false) {
  22555. // Blender exporter used to export a scalar. See #7459
  22556. normalScale = [normalScale, normalScale];
  22557. }
  22558. material.normalScale = new Vector2().fromArray(normalScale);
  22559. }
  22560. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  22561. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  22562. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  22563. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  22564. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  22565. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  22566. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  22567. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  22568. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  22569. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  22570. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  22571. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  22572. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  22573. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  22574. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  22575. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  22576. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  22577. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  22578. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  22579. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  22580. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  22581. if (json.transmission !== undefined) material.transmission = json.transmission;
  22582. if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
  22583. return material;
  22584. }
  22585. setTextures(value) {
  22586. this.textures = value;
  22587. return this;
  22588. }
  22589. }
  22590. class LoaderUtils {
  22591. static decodeText(array) {
  22592. if (typeof TextDecoder !== 'undefined') {
  22593. return new TextDecoder().decode(array);
  22594. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  22595. // throws a "maximum call stack size exceeded" error for large arrays.
  22596. let s = '';
  22597. for (let i = 0, il = array.length; i < il; i++) {
  22598. // Implicitly assumes little-endian.
  22599. s += String.fromCharCode(array[i]);
  22600. }
  22601. try {
  22602. // merges multi-byte utf-8 characters.
  22603. return decodeURIComponent(escape(s));
  22604. } catch (e) {
  22605. // see #16358
  22606. return s;
  22607. }
  22608. }
  22609. static extractUrlBase(url) {
  22610. const index = url.lastIndexOf('/');
  22611. if (index === -1) return './';
  22612. return url.substr(0, index + 1);
  22613. }
  22614. }
  22615. class InstancedBufferGeometry extends BufferGeometry {
  22616. constructor() {
  22617. super();
  22618. this.type = 'InstancedBufferGeometry';
  22619. this.instanceCount = Infinity;
  22620. }
  22621. copy(source) {
  22622. super.copy(source);
  22623. this.instanceCount = source.instanceCount;
  22624. return this;
  22625. }
  22626. clone() {
  22627. return new this.constructor().copy(this);
  22628. }
  22629. toJSON() {
  22630. const data = super.toJSON(this);
  22631. data.instanceCount = this.instanceCount;
  22632. data.isInstancedBufferGeometry = true;
  22633. return data;
  22634. }
  22635. }
  22636. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  22637. class InstancedBufferAttribute extends BufferAttribute {
  22638. constructor(array, itemSize, normalized, meshPerAttribute) {
  22639. if (typeof normalized === 'number') {
  22640. meshPerAttribute = normalized;
  22641. normalized = false;
  22642. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  22643. }
  22644. super(array, itemSize, normalized);
  22645. this.meshPerAttribute = meshPerAttribute || 1;
  22646. }
  22647. copy(source) {
  22648. super.copy(source);
  22649. this.meshPerAttribute = source.meshPerAttribute;
  22650. return this;
  22651. }
  22652. toJSON() {
  22653. const data = super.toJSON();
  22654. data.meshPerAttribute = this.meshPerAttribute;
  22655. data.isInstancedBufferAttribute = true;
  22656. return data;
  22657. }
  22658. }
  22659. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  22660. class BufferGeometryLoader extends Loader {
  22661. constructor(manager) {
  22662. super(manager);
  22663. }
  22664. load(url, onLoad, onProgress, onError) {
  22665. const scope = this;
  22666. const loader = new FileLoader(scope.manager);
  22667. loader.setPath(scope.path);
  22668. loader.setRequestHeader(scope.requestHeader);
  22669. loader.setWithCredentials(scope.withCredentials);
  22670. loader.load(url, function (text) {
  22671. try {
  22672. onLoad(scope.parse(JSON.parse(text)));
  22673. } catch (e) {
  22674. if (onError) {
  22675. onError(e);
  22676. } else {
  22677. console.error(e);
  22678. }
  22679. scope.manager.itemError(url);
  22680. }
  22681. }, onProgress, onError);
  22682. }
  22683. parse(json) {
  22684. const interleavedBufferMap = {};
  22685. const arrayBufferMap = {};
  22686. function getInterleavedBuffer(json, uuid) {
  22687. if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
  22688. const interleavedBuffers = json.interleavedBuffers;
  22689. const interleavedBuffer = interleavedBuffers[uuid];
  22690. const buffer = getArrayBuffer(json, interleavedBuffer.buffer);
  22691. const array = getTypedArray(interleavedBuffer.type, buffer);
  22692. const ib = new InterleavedBuffer(array, interleavedBuffer.stride);
  22693. ib.uuid = interleavedBuffer.uuid;
  22694. interleavedBufferMap[uuid] = ib;
  22695. return ib;
  22696. }
  22697. function getArrayBuffer(json, uuid) {
  22698. if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
  22699. const arrayBuffers = json.arrayBuffers;
  22700. const arrayBuffer = arrayBuffers[uuid];
  22701. const ab = new Uint32Array(arrayBuffer).buffer;
  22702. arrayBufferMap[uuid] = ab;
  22703. return ab;
  22704. }
  22705. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  22706. const index = json.data.index;
  22707. if (index !== undefined) {
  22708. const typedArray = getTypedArray(index.type, index.array);
  22709. geometry.setIndex(new BufferAttribute(typedArray, 1));
  22710. }
  22711. const attributes = json.data.attributes;
  22712. for (const key in attributes) {
  22713. const attribute = attributes[key];
  22714. let bufferAttribute;
  22715. if (attribute.isInterleavedBufferAttribute) {
  22716. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  22717. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  22718. } else {
  22719. const typedArray = getTypedArray(attribute.type, attribute.array);
  22720. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  22721. bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  22722. }
  22723. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  22724. if (attribute.usage !== undefined) bufferAttribute.setUsage(attribute.usage);
  22725. if (attribute.updateRange !== undefined) {
  22726. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  22727. bufferAttribute.updateRange.count = attribute.updateRange.count;
  22728. }
  22729. geometry.setAttribute(key, bufferAttribute);
  22730. }
  22731. const morphAttributes = json.data.morphAttributes;
  22732. if (morphAttributes) {
  22733. for (const key in morphAttributes) {
  22734. const attributeArray = morphAttributes[key];
  22735. const array = [];
  22736. for (let i = 0, il = attributeArray.length; i < il; i++) {
  22737. const attribute = attributeArray[i];
  22738. let bufferAttribute;
  22739. if (attribute.isInterleavedBufferAttribute) {
  22740. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  22741. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  22742. } else {
  22743. const typedArray = getTypedArray(attribute.type, attribute.array);
  22744. bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  22745. }
  22746. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  22747. array.push(bufferAttribute);
  22748. }
  22749. geometry.morphAttributes[key] = array;
  22750. }
  22751. }
  22752. const morphTargetsRelative = json.data.morphTargetsRelative;
  22753. if (morphTargetsRelative) {
  22754. geometry.morphTargetsRelative = true;
  22755. }
  22756. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  22757. if (groups !== undefined) {
  22758. for (let i = 0, n = groups.length; i !== n; ++i) {
  22759. const group = groups[i];
  22760. geometry.addGroup(group.start, group.count, group.materialIndex);
  22761. }
  22762. }
  22763. const boundingSphere = json.data.boundingSphere;
  22764. if (boundingSphere !== undefined) {
  22765. const center = new Vector3();
  22766. if (boundingSphere.center !== undefined) {
  22767. center.fromArray(boundingSphere.center);
  22768. }
  22769. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  22770. }
  22771. if (json.name) geometry.name = json.name;
  22772. if (json.userData) geometry.userData = json.userData;
  22773. return geometry;
  22774. }
  22775. }
  22776. class ObjectLoader extends Loader {
  22777. constructor(manager) {
  22778. super(manager);
  22779. }
  22780. load(url, onLoad, onProgress, onError) {
  22781. const scope = this;
  22782. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  22783. this.resourcePath = this.resourcePath || path;
  22784. const loader = new FileLoader(this.manager);
  22785. loader.setPath(this.path);
  22786. loader.setRequestHeader(this.requestHeader);
  22787. loader.setWithCredentials(this.withCredentials);
  22788. loader.load(url, function (text) {
  22789. let json = null;
  22790. try {
  22791. json = JSON.parse(text);
  22792. } catch (error) {
  22793. if (onError !== undefined) onError(error);
  22794. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  22795. return;
  22796. }
  22797. const metadata = json.metadata;
  22798. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  22799. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  22800. return;
  22801. }
  22802. scope.parse(json, onLoad);
  22803. }, onProgress, onError);
  22804. }
  22805. parse(json, onLoad) {
  22806. const animations = this.parseAnimations(json.animations);
  22807. const shapes = this.parseShapes(json.shapes);
  22808. const geometries = this.parseGeometries(json.geometries, shapes);
  22809. const images = this.parseImages(json.images, function () {
  22810. if (onLoad !== undefined) onLoad(object);
  22811. });
  22812. const textures = this.parseTextures(json.textures, images);
  22813. const materials = this.parseMaterials(json.materials, textures);
  22814. const object = this.parseObject(json.object, geometries, materials, animations);
  22815. const skeletons = this.parseSkeletons(json.skeletons, object);
  22816. this.bindSkeletons(object, skeletons); //
  22817. if (onLoad !== undefined) {
  22818. let hasImages = false;
  22819. for (const uuid in images) {
  22820. if (images[uuid] instanceof HTMLImageElement) {
  22821. hasImages = true;
  22822. break;
  22823. }
  22824. }
  22825. if (hasImages === false) onLoad(object);
  22826. }
  22827. return object;
  22828. }
  22829. parseShapes(json) {
  22830. const shapes = {};
  22831. if (json !== undefined) {
  22832. for (let i = 0, l = json.length; i < l; i++) {
  22833. const shape = new Shape().fromJSON(json[i]);
  22834. shapes[shape.uuid] = shape;
  22835. }
  22836. }
  22837. return shapes;
  22838. }
  22839. parseSkeletons(json, object) {
  22840. const skeletons = {};
  22841. const bones = {}; // generate bone lookup table
  22842. object.traverse(function (child) {
  22843. if (child.isBone) bones[child.uuid] = child;
  22844. }); // create skeletons
  22845. if (json !== undefined) {
  22846. for (let i = 0, l = json.length; i < l; i++) {
  22847. const skeleton = new Skeleton().fromJSON(json[i], bones);
  22848. skeletons[skeleton.uuid] = skeleton;
  22849. }
  22850. }
  22851. return skeletons;
  22852. }
  22853. parseGeometries(json, shapes) {
  22854. const geometries = {};
  22855. let geometryShapes;
  22856. if (json !== undefined) {
  22857. const bufferGeometryLoader = new BufferGeometryLoader();
  22858. for (let i = 0, l = json.length; i < l; i++) {
  22859. let geometry;
  22860. const data = json[i];
  22861. switch (data.type) {
  22862. case 'PlaneGeometry':
  22863. case 'PlaneBufferGeometry':
  22864. geometry = new Geometries[data.type](data.width, data.height, data.widthSegments, data.heightSegments);
  22865. break;
  22866. case 'BoxGeometry':
  22867. case 'BoxBufferGeometry':
  22868. geometry = new Geometries[data.type](data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  22869. break;
  22870. case 'CircleGeometry':
  22871. case 'CircleBufferGeometry':
  22872. geometry = new Geometries[data.type](data.radius, data.segments, data.thetaStart, data.thetaLength);
  22873. break;
  22874. case 'CylinderGeometry':
  22875. case 'CylinderBufferGeometry':
  22876. geometry = new Geometries[data.type](data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  22877. break;
  22878. case 'ConeGeometry':
  22879. case 'ConeBufferGeometry':
  22880. geometry = new Geometries[data.type](data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  22881. break;
  22882. case 'SphereGeometry':
  22883. case 'SphereBufferGeometry':
  22884. geometry = new Geometries[data.type](data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  22885. break;
  22886. case 'DodecahedronGeometry':
  22887. case 'DodecahedronBufferGeometry':
  22888. case 'IcosahedronGeometry':
  22889. case 'IcosahedronBufferGeometry':
  22890. case 'OctahedronGeometry':
  22891. case 'OctahedronBufferGeometry':
  22892. case 'TetrahedronGeometry':
  22893. case 'TetrahedronBufferGeometry':
  22894. geometry = new Geometries[data.type](data.radius, data.detail);
  22895. break;
  22896. case 'RingGeometry':
  22897. case 'RingBufferGeometry':
  22898. geometry = new Geometries[data.type](data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  22899. break;
  22900. case 'TorusGeometry':
  22901. case 'TorusBufferGeometry':
  22902. geometry = new Geometries[data.type](data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  22903. break;
  22904. case 'TorusKnotGeometry':
  22905. case 'TorusKnotBufferGeometry':
  22906. geometry = new Geometries[data.type](data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  22907. break;
  22908. case 'TubeGeometry':
  22909. case 'TubeBufferGeometry':
  22910. // This only works for built-in curves (e.g. CatmullRomCurve3).
  22911. // User defined curves or instances of CurvePath will not be deserialized.
  22912. geometry = new Geometries[data.type](new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  22913. break;
  22914. case 'LatheGeometry':
  22915. case 'LatheBufferGeometry':
  22916. geometry = new Geometries[data.type](data.points, data.segments, data.phiStart, data.phiLength);
  22917. break;
  22918. case 'PolyhedronGeometry':
  22919. case 'PolyhedronBufferGeometry':
  22920. geometry = new Geometries[data.type](data.vertices, data.indices, data.radius, data.details);
  22921. break;
  22922. case 'ShapeGeometry':
  22923. case 'ShapeBufferGeometry':
  22924. geometryShapes = [];
  22925. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  22926. const shape = shapes[data.shapes[j]];
  22927. geometryShapes.push(shape);
  22928. }
  22929. geometry = new Geometries[data.type](geometryShapes, data.curveSegments);
  22930. break;
  22931. case 'ExtrudeGeometry':
  22932. case 'ExtrudeBufferGeometry':
  22933. geometryShapes = [];
  22934. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  22935. const shape = shapes[data.shapes[j]];
  22936. geometryShapes.push(shape);
  22937. }
  22938. const extrudePath = data.options.extrudePath;
  22939. if (extrudePath !== undefined) {
  22940. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  22941. }
  22942. geometry = new Geometries[data.type](geometryShapes, data.options);
  22943. break;
  22944. case 'BufferGeometry':
  22945. case 'InstancedBufferGeometry':
  22946. geometry = bufferGeometryLoader.parse(data);
  22947. break;
  22948. case 'Geometry':
  22949. console.error('THREE.ObjectLoader: Loading "Geometry" is not supported anymore.');
  22950. break;
  22951. default:
  22952. console.warn('THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"');
  22953. continue;
  22954. }
  22955. geometry.uuid = data.uuid;
  22956. if (data.name !== undefined) geometry.name = data.name;
  22957. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  22958. geometries[data.uuid] = geometry;
  22959. }
  22960. }
  22961. return geometries;
  22962. }
  22963. parseMaterials(json, textures) {
  22964. const cache = {}; // MultiMaterial
  22965. const materials = {};
  22966. if (json !== undefined) {
  22967. const loader = new MaterialLoader();
  22968. loader.setTextures(textures);
  22969. for (let i = 0, l = json.length; i < l; i++) {
  22970. const data = json[i];
  22971. if (data.type === 'MultiMaterial') {
  22972. // Deprecated
  22973. const array = [];
  22974. for (let j = 0; j < data.materials.length; j++) {
  22975. const material = data.materials[j];
  22976. if (cache[material.uuid] === undefined) {
  22977. cache[material.uuid] = loader.parse(material);
  22978. }
  22979. array.push(cache[material.uuid]);
  22980. }
  22981. materials[data.uuid] = array;
  22982. } else {
  22983. if (cache[data.uuid] === undefined) {
  22984. cache[data.uuid] = loader.parse(data);
  22985. }
  22986. materials[data.uuid] = cache[data.uuid];
  22987. }
  22988. }
  22989. }
  22990. return materials;
  22991. }
  22992. parseAnimations(json) {
  22993. const animations = {};
  22994. if (json !== undefined) {
  22995. for (let i = 0; i < json.length; i++) {
  22996. const data = json[i];
  22997. const clip = AnimationClip.parse(data);
  22998. animations[clip.uuid] = clip;
  22999. }
  23000. }
  23001. return animations;
  23002. }
  23003. parseImages(json, onLoad) {
  23004. const scope = this;
  23005. const images = {};
  23006. let loader;
  23007. function loadImage(url) {
  23008. scope.manager.itemStart(url);
  23009. return loader.load(url, function () {
  23010. scope.manager.itemEnd(url);
  23011. }, undefined, function () {
  23012. scope.manager.itemError(url);
  23013. scope.manager.itemEnd(url);
  23014. });
  23015. }
  23016. function deserializeImage(image) {
  23017. if (typeof image === 'string') {
  23018. const url = image;
  23019. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  23020. return loadImage(path);
  23021. } else {
  23022. if (image.data) {
  23023. return {
  23024. data: getTypedArray(image.type, image.data),
  23025. width: image.width,
  23026. height: image.height
  23027. };
  23028. } else {
  23029. return null;
  23030. }
  23031. }
  23032. }
  23033. if (json !== undefined && json.length > 0) {
  23034. const manager = new LoadingManager(onLoad);
  23035. loader = new ImageLoader(manager);
  23036. loader.setCrossOrigin(this.crossOrigin);
  23037. for (let i = 0, il = json.length; i < il; i++) {
  23038. const image = json[i];
  23039. const url = image.url;
  23040. if (Array.isArray(url)) {
  23041. // load array of images e.g CubeTexture
  23042. images[image.uuid] = [];
  23043. for (let j = 0, jl = url.length; j < jl; j++) {
  23044. const currentUrl = url[j];
  23045. const deserializedImage = deserializeImage(currentUrl);
  23046. if (deserializedImage !== null) {
  23047. if (deserializedImage instanceof HTMLImageElement) {
  23048. images[image.uuid].push(deserializedImage);
  23049. } else {
  23050. // special case: handle array of data textures for cube textures
  23051. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  23052. }
  23053. }
  23054. }
  23055. } else {
  23056. // load single image
  23057. const deserializedImage = deserializeImage(image.url);
  23058. if (deserializedImage !== null) {
  23059. images[image.uuid] = deserializedImage;
  23060. }
  23061. }
  23062. }
  23063. }
  23064. return images;
  23065. }
  23066. parseTextures(json, images) {
  23067. function parseConstant(value, type) {
  23068. if (typeof value === 'number') return value;
  23069. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  23070. return type[value];
  23071. }
  23072. const textures = {};
  23073. if (json !== undefined) {
  23074. for (let i = 0, l = json.length; i < l; i++) {
  23075. const data = json[i];
  23076. if (data.image === undefined) {
  23077. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  23078. }
  23079. if (images[data.image] === undefined) {
  23080. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  23081. }
  23082. let texture;
  23083. const image = images[data.image];
  23084. if (Array.isArray(image)) {
  23085. texture = new CubeTexture(image);
  23086. if (image.length === 6) texture.needsUpdate = true;
  23087. } else {
  23088. if (image && image.data) {
  23089. texture = new DataTexture(image.data, image.width, image.height);
  23090. } else {
  23091. texture = new Texture(image);
  23092. }
  23093. if (image) texture.needsUpdate = true; // textures can have undefined image data
  23094. }
  23095. texture.uuid = data.uuid;
  23096. if (data.name !== undefined) texture.name = data.name;
  23097. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  23098. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  23099. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  23100. if (data.center !== undefined) texture.center.fromArray(data.center);
  23101. if (data.rotation !== undefined) texture.rotation = data.rotation;
  23102. if (data.wrap !== undefined) {
  23103. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  23104. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  23105. }
  23106. if (data.format !== undefined) texture.format = data.format;
  23107. if (data.type !== undefined) texture.type = data.type;
  23108. if (data.encoding !== undefined) texture.encoding = data.encoding;
  23109. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  23110. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  23111. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  23112. if (data.flipY !== undefined) texture.flipY = data.flipY;
  23113. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  23114. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  23115. textures[data.uuid] = texture;
  23116. }
  23117. }
  23118. return textures;
  23119. }
  23120. parseObject(data, geometries, materials, animations) {
  23121. let object;
  23122. function getGeometry(name) {
  23123. if (geometries[name] === undefined) {
  23124. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  23125. }
  23126. return geometries[name];
  23127. }
  23128. function getMaterial(name) {
  23129. if (name === undefined) return undefined;
  23130. if (Array.isArray(name)) {
  23131. const array = [];
  23132. for (let i = 0, l = name.length; i < l; i++) {
  23133. const uuid = name[i];
  23134. if (materials[uuid] === undefined) {
  23135. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  23136. }
  23137. array.push(materials[uuid]);
  23138. }
  23139. return array;
  23140. }
  23141. if (materials[name] === undefined) {
  23142. console.warn('THREE.ObjectLoader: Undefined material', name);
  23143. }
  23144. return materials[name];
  23145. }
  23146. let geometry, material;
  23147. switch (data.type) {
  23148. case 'Scene':
  23149. object = new Scene();
  23150. if (data.background !== undefined) {
  23151. if (Number.isInteger(data.background)) {
  23152. object.background = new Color(data.background);
  23153. }
  23154. }
  23155. if (data.fog !== undefined) {
  23156. if (data.fog.type === 'Fog') {
  23157. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  23158. } else if (data.fog.type === 'FogExp2') {
  23159. object.fog = new FogExp2(data.fog.color, data.fog.density);
  23160. }
  23161. }
  23162. break;
  23163. case 'PerspectiveCamera':
  23164. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  23165. if (data.focus !== undefined) object.focus = data.focus;
  23166. if (data.zoom !== undefined) object.zoom = data.zoom;
  23167. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  23168. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  23169. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  23170. break;
  23171. case 'OrthographicCamera':
  23172. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  23173. if (data.zoom !== undefined) object.zoom = data.zoom;
  23174. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  23175. break;
  23176. case 'AmbientLight':
  23177. object = new AmbientLight(data.color, data.intensity);
  23178. break;
  23179. case 'DirectionalLight':
  23180. object = new DirectionalLight(data.color, data.intensity);
  23181. break;
  23182. case 'PointLight':
  23183. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  23184. break;
  23185. case 'RectAreaLight':
  23186. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  23187. break;
  23188. case 'SpotLight':
  23189. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  23190. break;
  23191. case 'HemisphereLight':
  23192. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  23193. break;
  23194. case 'LightProbe':
  23195. object = new LightProbe().fromJSON(data);
  23196. break;
  23197. case 'SkinnedMesh':
  23198. geometry = getGeometry(data.geometry);
  23199. material = getMaterial(data.material);
  23200. object = new SkinnedMesh(geometry, material);
  23201. if (data.bindMode !== undefined) object.bindMode = data.bindMode;
  23202. if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
  23203. if (data.skeleton !== undefined) object.skeleton = data.skeleton;
  23204. break;
  23205. case 'Mesh':
  23206. geometry = getGeometry(data.geometry);
  23207. material = getMaterial(data.material);
  23208. object = new Mesh(geometry, material);
  23209. break;
  23210. case 'InstancedMesh':
  23211. geometry = getGeometry(data.geometry);
  23212. material = getMaterial(data.material);
  23213. const count = data.count;
  23214. const instanceMatrix = data.instanceMatrix;
  23215. const instanceColor = data.instanceColor;
  23216. object = new InstancedMesh(geometry, material, count);
  23217. object.instanceMatrix = new BufferAttribute(new Float32Array(instanceMatrix.array), 16);
  23218. if (instanceColor !== undefined) object.instanceColor = new BufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize);
  23219. break;
  23220. case 'LOD':
  23221. object = new LOD();
  23222. break;
  23223. case 'Line':
  23224. object = new Line(getGeometry(data.geometry), getMaterial(data.material));
  23225. break;
  23226. case 'LineLoop':
  23227. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  23228. break;
  23229. case 'LineSegments':
  23230. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  23231. break;
  23232. case 'PointCloud':
  23233. case 'Points':
  23234. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  23235. break;
  23236. case 'Sprite':
  23237. object = new Sprite(getMaterial(data.material));
  23238. break;
  23239. case 'Group':
  23240. object = new Group();
  23241. break;
  23242. case 'Bone':
  23243. object = new Bone();
  23244. break;
  23245. default:
  23246. object = new Object3D();
  23247. }
  23248. object.uuid = data.uuid;
  23249. if (data.name !== undefined) object.name = data.name;
  23250. if (data.matrix !== undefined) {
  23251. object.matrix.fromArray(data.matrix);
  23252. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  23253. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  23254. } else {
  23255. if (data.position !== undefined) object.position.fromArray(data.position);
  23256. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  23257. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  23258. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  23259. }
  23260. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  23261. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  23262. if (data.shadow) {
  23263. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  23264. if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
  23265. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  23266. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  23267. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  23268. }
  23269. if (data.visible !== undefined) object.visible = data.visible;
  23270. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  23271. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  23272. if (data.userData !== undefined) object.userData = data.userData;
  23273. if (data.layers !== undefined) object.layers.mask = data.layers;
  23274. if (data.children !== undefined) {
  23275. const children = data.children;
  23276. for (let i = 0; i < children.length; i++) {
  23277. object.add(this.parseObject(children[i], geometries, materials, animations));
  23278. }
  23279. }
  23280. if (data.animations !== undefined) {
  23281. const objectAnimations = data.animations;
  23282. for (let i = 0; i < objectAnimations.length; i++) {
  23283. const uuid = objectAnimations[i];
  23284. object.animations.push(animations[uuid]);
  23285. }
  23286. }
  23287. if (data.type === 'LOD') {
  23288. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  23289. const levels = data.levels;
  23290. for (let l = 0; l < levels.length; l++) {
  23291. const level = levels[l];
  23292. const child = object.getObjectByProperty('uuid', level.object);
  23293. if (child !== undefined) {
  23294. object.addLevel(child, level.distance);
  23295. }
  23296. }
  23297. }
  23298. return object;
  23299. }
  23300. bindSkeletons(object, skeletons) {
  23301. if (Object.keys(skeletons).length === 0) return;
  23302. object.traverse(function (child) {
  23303. if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
  23304. const skeleton = skeletons[child.skeleton];
  23305. if (skeleton === undefined) {
  23306. console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
  23307. } else {
  23308. child.bind(skeleton, child.bindMatrix);
  23309. }
  23310. }
  23311. });
  23312. }
  23313. /* DEPRECATED */
  23314. setTexturePath(value) {
  23315. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  23316. return this.setResourcePath(value);
  23317. }
  23318. }
  23319. const TEXTURE_MAPPING = {
  23320. UVMapping: UVMapping,
  23321. CubeReflectionMapping: CubeReflectionMapping,
  23322. CubeRefractionMapping: CubeRefractionMapping,
  23323. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  23324. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  23325. CubeUVReflectionMapping: CubeUVReflectionMapping,
  23326. CubeUVRefractionMapping: CubeUVRefractionMapping
  23327. };
  23328. const TEXTURE_WRAPPING = {
  23329. RepeatWrapping: RepeatWrapping,
  23330. ClampToEdgeWrapping: ClampToEdgeWrapping,
  23331. MirroredRepeatWrapping: MirroredRepeatWrapping
  23332. };
  23333. const TEXTURE_FILTER = {
  23334. NearestFilter: NearestFilter,
  23335. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  23336. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  23337. LinearFilter: LinearFilter,
  23338. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  23339. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  23340. };
  23341. class ImageBitmapLoader extends Loader {
  23342. constructor(manager) {
  23343. super(manager);
  23344. if (typeof createImageBitmap === 'undefined') {
  23345. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  23346. }
  23347. if (typeof fetch === 'undefined') {
  23348. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  23349. }
  23350. this.options = {
  23351. premultiplyAlpha: 'none'
  23352. };
  23353. }
  23354. setOptions(options) {
  23355. this.options = options;
  23356. return this;
  23357. }
  23358. load(url, onLoad, onProgress, onError) {
  23359. if (url === undefined) url = '';
  23360. if (this.path !== undefined) url = this.path + url;
  23361. url = this.manager.resolveURL(url);
  23362. const scope = this;
  23363. const cached = Cache.get(url);
  23364. if (cached !== undefined) {
  23365. scope.manager.itemStart(url);
  23366. setTimeout(function () {
  23367. if (onLoad) onLoad(cached);
  23368. scope.manager.itemEnd(url);
  23369. }, 0);
  23370. return cached;
  23371. }
  23372. const fetchOptions = {};
  23373. fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
  23374. fetchOptions.headers = this.requestHeader;
  23375. fetch(url, fetchOptions).then(function (res) {
  23376. return res.blob();
  23377. }).then(function (blob) {
  23378. return createImageBitmap(blob, Object.assign(scope.options, {
  23379. colorSpaceConversion: 'none'
  23380. }));
  23381. }).then(function (imageBitmap) {
  23382. Cache.add(url, imageBitmap);
  23383. if (onLoad) onLoad(imageBitmap);
  23384. scope.manager.itemEnd(url);
  23385. }).catch(function (e) {
  23386. if (onError) onError(e);
  23387. scope.manager.itemError(url);
  23388. scope.manager.itemEnd(url);
  23389. });
  23390. scope.manager.itemStart(url);
  23391. }
  23392. }
  23393. ImageBitmapLoader.prototype.isImageBitmapLoader = true;
  23394. class ShapePath {
  23395. constructor() {
  23396. this.type = 'ShapePath';
  23397. this.color = new Color();
  23398. this.subPaths = [];
  23399. this.currentPath = null;
  23400. }
  23401. moveTo(x, y) {
  23402. this.currentPath = new Path();
  23403. this.subPaths.push(this.currentPath);
  23404. this.currentPath.moveTo(x, y);
  23405. return this;
  23406. }
  23407. lineTo(x, y) {
  23408. this.currentPath.lineTo(x, y);
  23409. return this;
  23410. }
  23411. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  23412. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  23413. return this;
  23414. }
  23415. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  23416. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  23417. return this;
  23418. }
  23419. splineThru(pts) {
  23420. this.currentPath.splineThru(pts);
  23421. return this;
  23422. }
  23423. toShapes(isCCW, noHoles) {
  23424. function toShapesNoHoles(inSubpaths) {
  23425. const shapes = [];
  23426. for (let i = 0, l = inSubpaths.length; i < l; i++) {
  23427. const tmpPath = inSubpaths[i];
  23428. const tmpShape = new Shape();
  23429. tmpShape.curves = tmpPath.curves;
  23430. shapes.push(tmpShape);
  23431. }
  23432. return shapes;
  23433. }
  23434. function isPointInsidePolygon(inPt, inPolygon) {
  23435. const polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  23436. // toggling of inside/outside at every single! intersection point of an edge
  23437. // with the horizontal line through inPt, left of inPt
  23438. // not counting lowerY endpoints of edges and whole edges on that line
  23439. let inside = false;
  23440. for (let p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  23441. let edgeLowPt = inPolygon[p];
  23442. let edgeHighPt = inPolygon[q];
  23443. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  23444. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  23445. if (Math.abs(edgeDy) > Number.EPSILON) {
  23446. // not parallel
  23447. if (edgeDy < 0) {
  23448. edgeLowPt = inPolygon[q];
  23449. edgeDx = -edgeDx;
  23450. edgeHighPt = inPolygon[p];
  23451. edgeDy = -edgeDy;
  23452. }
  23453. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  23454. if (inPt.y === edgeLowPt.y) {
  23455. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  23456. // continue; // no intersection or edgeLowPt => doesn't count !!!
  23457. } else {
  23458. const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  23459. if (perpEdge === 0) return true; // inPt is on contour ?
  23460. if (perpEdge < 0) continue;
  23461. inside = !inside; // true intersection left of inPt
  23462. }
  23463. } else {
  23464. // parallel or collinear
  23465. if (inPt.y !== edgeLowPt.y) continue; // parallel
  23466. // edge lies on the same horizontal line as inPt
  23467. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  23468. // continue;
  23469. }
  23470. }
  23471. return inside;
  23472. }
  23473. const isClockWise = ShapeUtils.isClockWise;
  23474. const subPaths = this.subPaths;
  23475. if (subPaths.length === 0) return [];
  23476. if (noHoles === true) return toShapesNoHoles(subPaths);
  23477. let solid, tmpPath, tmpShape;
  23478. const shapes = [];
  23479. if (subPaths.length === 1) {
  23480. tmpPath = subPaths[0];
  23481. tmpShape = new Shape();
  23482. tmpShape.curves = tmpPath.curves;
  23483. shapes.push(tmpShape);
  23484. return shapes;
  23485. }
  23486. let holesFirst = !isClockWise(subPaths[0].getPoints());
  23487. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  23488. const betterShapeHoles = [];
  23489. const newShapes = [];
  23490. let newShapeHoles = [];
  23491. let mainIdx = 0;
  23492. let tmpPoints;
  23493. newShapes[mainIdx] = undefined;
  23494. newShapeHoles[mainIdx] = [];
  23495. for (let i = 0, l = subPaths.length; i < l; i++) {
  23496. tmpPath = subPaths[i];
  23497. tmpPoints = tmpPath.getPoints();
  23498. solid = isClockWise(tmpPoints);
  23499. solid = isCCW ? !solid : solid;
  23500. if (solid) {
  23501. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  23502. newShapes[mainIdx] = {
  23503. s: new Shape(),
  23504. p: tmpPoints
  23505. };
  23506. newShapes[mainIdx].s.curves = tmpPath.curves;
  23507. if (holesFirst) mainIdx++;
  23508. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  23509. } else {
  23510. newShapeHoles[mainIdx].push({
  23511. h: tmpPath,
  23512. p: tmpPoints[0]
  23513. }); //console.log('ccw', i);
  23514. }
  23515. } // only Holes? -> probably all Shapes with wrong orientation
  23516. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  23517. if (newShapes.length > 1) {
  23518. let ambiguous = false;
  23519. const toChange = [];
  23520. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  23521. betterShapeHoles[sIdx] = [];
  23522. }
  23523. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  23524. const sho = newShapeHoles[sIdx];
  23525. for (let hIdx = 0; hIdx < sho.length; hIdx++) {
  23526. const ho = sho[hIdx];
  23527. let hole_unassigned = true;
  23528. for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  23529. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  23530. if (sIdx !== s2Idx) toChange.push({
  23531. froms: sIdx,
  23532. tos: s2Idx,
  23533. hole: hIdx
  23534. });
  23535. if (hole_unassigned) {
  23536. hole_unassigned = false;
  23537. betterShapeHoles[s2Idx].push(ho);
  23538. } else {
  23539. ambiguous = true;
  23540. }
  23541. }
  23542. }
  23543. if (hole_unassigned) {
  23544. betterShapeHoles[sIdx].push(ho);
  23545. }
  23546. }
  23547. } // console.log("ambiguous: ", ambiguous);
  23548. if (toChange.length > 0) {
  23549. // console.log("to change: ", toChange);
  23550. if (!ambiguous) newShapeHoles = betterShapeHoles;
  23551. }
  23552. }
  23553. let tmpHoles;
  23554. for (let i = 0, il = newShapes.length; i < il; i++) {
  23555. tmpShape = newShapes[i].s;
  23556. shapes.push(tmpShape);
  23557. tmpHoles = newShapeHoles[i];
  23558. for (let j = 0, jl = tmpHoles.length; j < jl; j++) {
  23559. tmpShape.holes.push(tmpHoles[j].h);
  23560. }
  23561. } //console.log("shape", shapes);
  23562. return shapes;
  23563. }
  23564. }
  23565. class Font {
  23566. constructor(data) {
  23567. this.type = 'Font';
  23568. this.data = data;
  23569. }
  23570. generateShapes(text, size = 100) {
  23571. const shapes = [];
  23572. const paths = createPaths(text, size, this.data);
  23573. for (let p = 0, pl = paths.length; p < pl; p++) {
  23574. Array.prototype.push.apply(shapes, paths[p].toShapes());
  23575. }
  23576. return shapes;
  23577. }
  23578. }
  23579. function createPaths(text, size, data) {
  23580. const chars = Array.from(text);
  23581. const scale = size / data.resolution;
  23582. const line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
  23583. const paths = [];
  23584. let offsetX = 0,
  23585. offsetY = 0;
  23586. for (let i = 0; i < chars.length; i++) {
  23587. const char = chars[i];
  23588. if (char === '\n') {
  23589. offsetX = 0;
  23590. offsetY -= line_height;
  23591. } else {
  23592. const ret = createPath(char, scale, offsetX, offsetY, data);
  23593. offsetX += ret.offsetX;
  23594. paths.push(ret.path);
  23595. }
  23596. }
  23597. return paths;
  23598. }
  23599. function createPath(char, scale, offsetX, offsetY, data) {
  23600. const glyph = data.glyphs[char] || data.glyphs['?'];
  23601. if (!glyph) {
  23602. console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
  23603. return;
  23604. }
  23605. const path = new ShapePath();
  23606. let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  23607. if (glyph.o) {
  23608. const outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
  23609. for (let i = 0, l = outline.length; i < l;) {
  23610. const action = outline[i++];
  23611. switch (action) {
  23612. case 'm':
  23613. // moveTo
  23614. x = outline[i++] * scale + offsetX;
  23615. y = outline[i++] * scale + offsetY;
  23616. path.moveTo(x, y);
  23617. break;
  23618. case 'l':
  23619. // lineTo
  23620. x = outline[i++] * scale + offsetX;
  23621. y = outline[i++] * scale + offsetY;
  23622. path.lineTo(x, y);
  23623. break;
  23624. case 'q':
  23625. // quadraticCurveTo
  23626. cpx = outline[i++] * scale + offsetX;
  23627. cpy = outline[i++] * scale + offsetY;
  23628. cpx1 = outline[i++] * scale + offsetX;
  23629. cpy1 = outline[i++] * scale + offsetY;
  23630. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  23631. break;
  23632. case 'b':
  23633. // bezierCurveTo
  23634. cpx = outline[i++] * scale + offsetX;
  23635. cpy = outline[i++] * scale + offsetY;
  23636. cpx1 = outline[i++] * scale + offsetX;
  23637. cpy1 = outline[i++] * scale + offsetY;
  23638. cpx2 = outline[i++] * scale + offsetX;
  23639. cpy2 = outline[i++] * scale + offsetY;
  23640. path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
  23641. break;
  23642. }
  23643. }
  23644. }
  23645. return {
  23646. offsetX: glyph.ha * scale,
  23647. path: path
  23648. };
  23649. }
  23650. Font.prototype.isFont = true;
  23651. class FontLoader extends Loader {
  23652. constructor(manager) {
  23653. super(manager);
  23654. }
  23655. load(url, onLoad, onProgress, onError) {
  23656. const scope = this;
  23657. const loader = new FileLoader(this.manager);
  23658. loader.setPath(this.path);
  23659. loader.setRequestHeader(this.requestHeader);
  23660. loader.setWithCredentials(scope.withCredentials);
  23661. loader.load(url, function (text) {
  23662. let json;
  23663. try {
  23664. json = JSON.parse(text);
  23665. } catch (e) {
  23666. console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
  23667. json = JSON.parse(text.substring(65, text.length - 2));
  23668. }
  23669. const font = scope.parse(json);
  23670. if (onLoad) onLoad(font);
  23671. }, onProgress, onError);
  23672. }
  23673. parse(json) {
  23674. return new Font(json);
  23675. }
  23676. }
  23677. let _context;
  23678. const AudioContext = {
  23679. getContext: function () {
  23680. if (_context === undefined) {
  23681. _context = new (window.AudioContext || window.webkitAudioContext)();
  23682. }
  23683. return _context;
  23684. },
  23685. setContext: function (value) {
  23686. _context = value;
  23687. }
  23688. };
  23689. class AudioLoader extends Loader {
  23690. constructor(manager) {
  23691. super(manager);
  23692. }
  23693. load(url, onLoad, onProgress, onError) {
  23694. const scope = this;
  23695. const loader = new FileLoader(this.manager);
  23696. loader.setResponseType('arraybuffer');
  23697. loader.setPath(this.path);
  23698. loader.setRequestHeader(this.requestHeader);
  23699. loader.setWithCredentials(this.withCredentials);
  23700. loader.load(url, function (buffer) {
  23701. try {
  23702. // Create a copy of the buffer. The `decodeAudioData` method
  23703. // detaches the buffer when complete, preventing reuse.
  23704. const bufferCopy = buffer.slice(0);
  23705. const context = AudioContext.getContext();
  23706. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  23707. onLoad(audioBuffer);
  23708. });
  23709. } catch (e) {
  23710. if (onError) {
  23711. onError(e);
  23712. } else {
  23713. console.error(e);
  23714. }
  23715. scope.manager.itemError(url);
  23716. }
  23717. }, onProgress, onError);
  23718. }
  23719. }
  23720. class HemisphereLightProbe extends LightProbe {
  23721. constructor(skyColor, groundColor, intensity = 1) {
  23722. super(undefined, intensity);
  23723. const color1 = new Color().set(skyColor);
  23724. const color2 = new Color().set(groundColor);
  23725. const sky = new Vector3(color1.r, color1.g, color1.b);
  23726. const ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  23727. const c0 = Math.sqrt(Math.PI);
  23728. const c1 = c0 * Math.sqrt(0.75);
  23729. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  23730. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  23731. }
  23732. }
  23733. HemisphereLightProbe.prototype.isHemisphereLightProbe = true;
  23734. class AmbientLightProbe extends LightProbe {
  23735. constructor(color, intensity = 1) {
  23736. super(undefined, intensity);
  23737. const color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  23738. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  23739. }
  23740. }
  23741. AmbientLightProbe.prototype.isAmbientLightProbe = true;
  23742. const _eyeRight = /*@__PURE__*/new Matrix4();
  23743. const _eyeLeft = /*@__PURE__*/new Matrix4();
  23744. class StereoCamera {
  23745. constructor() {
  23746. this.type = 'StereoCamera';
  23747. this.aspect = 1;
  23748. this.eyeSep = 0.064;
  23749. this.cameraL = new PerspectiveCamera();
  23750. this.cameraL.layers.enable(1);
  23751. this.cameraL.matrixAutoUpdate = false;
  23752. this.cameraR = new PerspectiveCamera();
  23753. this.cameraR.layers.enable(2);
  23754. this.cameraR.matrixAutoUpdate = false;
  23755. this._cache = {
  23756. focus: null,
  23757. fov: null,
  23758. aspect: null,
  23759. near: null,
  23760. far: null,
  23761. zoom: null,
  23762. eyeSep: null
  23763. };
  23764. }
  23765. update(camera) {
  23766. const cache = this._cache;
  23767. 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;
  23768. if (needsUpdate) {
  23769. cache.focus = camera.focus;
  23770. cache.fov = camera.fov;
  23771. cache.aspect = camera.aspect * this.aspect;
  23772. cache.near = camera.near;
  23773. cache.far = camera.far;
  23774. cache.zoom = camera.zoom;
  23775. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  23776. // http://paulbourke.net/stereographics/stereorender/
  23777. const projectionMatrix = camera.projectionMatrix.clone();
  23778. const eyeSepHalf = cache.eyeSep / 2;
  23779. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  23780. const ymax = cache.near * Math.tan(DEG2RAD * cache.fov * 0.5) / cache.zoom;
  23781. let xmin, xmax; // translate xOffset
  23782. _eyeLeft.elements[12] = -eyeSepHalf;
  23783. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  23784. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  23785. xmax = ymax * cache.aspect + eyeSepOnProjection;
  23786. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  23787. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  23788. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  23789. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  23790. xmax = ymax * cache.aspect - eyeSepOnProjection;
  23791. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  23792. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  23793. this.cameraR.projectionMatrix.copy(projectionMatrix);
  23794. }
  23795. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  23796. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  23797. }
  23798. }
  23799. class Clock {
  23800. constructor(autoStart = true) {
  23801. this.autoStart = autoStart;
  23802. this.startTime = 0;
  23803. this.oldTime = 0;
  23804. this.elapsedTime = 0;
  23805. this.running = false;
  23806. }
  23807. start() {
  23808. this.startTime = now();
  23809. this.oldTime = this.startTime;
  23810. this.elapsedTime = 0;
  23811. this.running = true;
  23812. }
  23813. stop() {
  23814. this.getElapsedTime();
  23815. this.running = false;
  23816. this.autoStart = false;
  23817. }
  23818. getElapsedTime() {
  23819. this.getDelta();
  23820. return this.elapsedTime;
  23821. }
  23822. getDelta() {
  23823. let diff = 0;
  23824. if (this.autoStart && !this.running) {
  23825. this.start();
  23826. return 0;
  23827. }
  23828. if (this.running) {
  23829. const newTime = now();
  23830. diff = (newTime - this.oldTime) / 1000;
  23831. this.oldTime = newTime;
  23832. this.elapsedTime += diff;
  23833. }
  23834. return diff;
  23835. }
  23836. }
  23837. function now() {
  23838. return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  23839. }
  23840. const _position$1 = /*@__PURE__*/new Vector3();
  23841. const _quaternion$1 = /*@__PURE__*/new Quaternion();
  23842. const _scale$1 = /*@__PURE__*/new Vector3();
  23843. const _orientation$1 = /*@__PURE__*/new Vector3();
  23844. class AudioListener extends Object3D {
  23845. constructor() {
  23846. super();
  23847. this.type = 'AudioListener';
  23848. this.context = AudioContext.getContext();
  23849. this.gain = this.context.createGain();
  23850. this.gain.connect(this.context.destination);
  23851. this.filter = null;
  23852. this.timeDelta = 0; // private
  23853. this._clock = new Clock();
  23854. }
  23855. getInput() {
  23856. return this.gain;
  23857. }
  23858. removeFilter() {
  23859. if (this.filter !== null) {
  23860. this.gain.disconnect(this.filter);
  23861. this.filter.disconnect(this.context.destination);
  23862. this.gain.connect(this.context.destination);
  23863. this.filter = null;
  23864. }
  23865. return this;
  23866. }
  23867. getFilter() {
  23868. return this.filter;
  23869. }
  23870. setFilter(value) {
  23871. if (this.filter !== null) {
  23872. this.gain.disconnect(this.filter);
  23873. this.filter.disconnect(this.context.destination);
  23874. } else {
  23875. this.gain.disconnect(this.context.destination);
  23876. }
  23877. this.filter = value;
  23878. this.gain.connect(this.filter);
  23879. this.filter.connect(this.context.destination);
  23880. return this;
  23881. }
  23882. getMasterVolume() {
  23883. return this.gain.gain.value;
  23884. }
  23885. setMasterVolume(value) {
  23886. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  23887. return this;
  23888. }
  23889. updateMatrixWorld(force) {
  23890. super.updateMatrixWorld(force);
  23891. const listener = this.context.listener;
  23892. const up = this.up;
  23893. this.timeDelta = this._clock.getDelta();
  23894. this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1);
  23895. _orientation$1.set(0, 0, -1).applyQuaternion(_quaternion$1);
  23896. if (listener.positionX) {
  23897. // code path for Chrome (see #14393)
  23898. const endTime = this.context.currentTime + this.timeDelta;
  23899. listener.positionX.linearRampToValueAtTime(_position$1.x, endTime);
  23900. listener.positionY.linearRampToValueAtTime(_position$1.y, endTime);
  23901. listener.positionZ.linearRampToValueAtTime(_position$1.z, endTime);
  23902. listener.forwardX.linearRampToValueAtTime(_orientation$1.x, endTime);
  23903. listener.forwardY.linearRampToValueAtTime(_orientation$1.y, endTime);
  23904. listener.forwardZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  23905. listener.upX.linearRampToValueAtTime(up.x, endTime);
  23906. listener.upY.linearRampToValueAtTime(up.y, endTime);
  23907. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  23908. } else {
  23909. listener.setPosition(_position$1.x, _position$1.y, _position$1.z);
  23910. listener.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z);
  23911. }
  23912. }
  23913. }
  23914. class Audio extends Object3D {
  23915. constructor(listener) {
  23916. super();
  23917. this.type = 'Audio';
  23918. this.listener = listener;
  23919. this.context = listener.context;
  23920. this.gain = this.context.createGain();
  23921. this.gain.connect(listener.getInput());
  23922. this.autoplay = false;
  23923. this.buffer = null;
  23924. this.detune = 0;
  23925. this.loop = false;
  23926. this.loopStart = 0;
  23927. this.loopEnd = 0;
  23928. this.offset = 0;
  23929. this.duration = undefined;
  23930. this.playbackRate = 1;
  23931. this.isPlaying = false;
  23932. this.hasPlaybackControl = true;
  23933. this.source = null;
  23934. this.sourceType = 'empty';
  23935. this._startedAt = 0;
  23936. this._progress = 0;
  23937. this._connected = false;
  23938. this.filters = [];
  23939. }
  23940. getOutput() {
  23941. return this.gain;
  23942. }
  23943. setNodeSource(audioNode) {
  23944. this.hasPlaybackControl = false;
  23945. this.sourceType = 'audioNode';
  23946. this.source = audioNode;
  23947. this.connect();
  23948. return this;
  23949. }
  23950. setMediaElementSource(mediaElement) {
  23951. this.hasPlaybackControl = false;
  23952. this.sourceType = 'mediaNode';
  23953. this.source = this.context.createMediaElementSource(mediaElement);
  23954. this.connect();
  23955. return this;
  23956. }
  23957. setMediaStreamSource(mediaStream) {
  23958. this.hasPlaybackControl = false;
  23959. this.sourceType = 'mediaStreamNode';
  23960. this.source = this.context.createMediaStreamSource(mediaStream);
  23961. this.connect();
  23962. return this;
  23963. }
  23964. setBuffer(audioBuffer) {
  23965. this.buffer = audioBuffer;
  23966. this.sourceType = 'buffer';
  23967. if (this.autoplay) this.play();
  23968. return this;
  23969. }
  23970. play(delay = 0) {
  23971. if (this.isPlaying === true) {
  23972. console.warn('THREE.Audio: Audio is already playing.');
  23973. return;
  23974. }
  23975. if (this.hasPlaybackControl === false) {
  23976. console.warn('THREE.Audio: this Audio has no playback control.');
  23977. return;
  23978. }
  23979. this._startedAt = this.context.currentTime + delay;
  23980. const source = this.context.createBufferSource();
  23981. source.buffer = this.buffer;
  23982. source.loop = this.loop;
  23983. source.loopStart = this.loopStart;
  23984. source.loopEnd = this.loopEnd;
  23985. source.onended = this.onEnded.bind(this);
  23986. source.start(this._startedAt, this._progress + this.offset, this.duration);
  23987. this.isPlaying = true;
  23988. this.source = source;
  23989. this.setDetune(this.detune);
  23990. this.setPlaybackRate(this.playbackRate);
  23991. return this.connect();
  23992. }
  23993. pause() {
  23994. if (this.hasPlaybackControl === false) {
  23995. console.warn('THREE.Audio: this Audio has no playback control.');
  23996. return;
  23997. }
  23998. if (this.isPlaying === true) {
  23999. // update current progress
  24000. this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  24001. if (this.loop === true) {
  24002. // ensure _progress does not exceed duration with looped audios
  24003. this._progress = this._progress % (this.duration || this.buffer.duration);
  24004. }
  24005. this.source.stop();
  24006. this.source.onended = null;
  24007. this.isPlaying = false;
  24008. }
  24009. return this;
  24010. }
  24011. stop() {
  24012. if (this.hasPlaybackControl === false) {
  24013. console.warn('THREE.Audio: this Audio has no playback control.');
  24014. return;
  24015. }
  24016. this._progress = 0;
  24017. this.source.stop();
  24018. this.source.onended = null;
  24019. this.isPlaying = false;
  24020. return this;
  24021. }
  24022. connect() {
  24023. if (this.filters.length > 0) {
  24024. this.source.connect(this.filters[0]);
  24025. for (let i = 1, l = this.filters.length; i < l; i++) {
  24026. this.filters[i - 1].connect(this.filters[i]);
  24027. }
  24028. this.filters[this.filters.length - 1].connect(this.getOutput());
  24029. } else {
  24030. this.source.connect(this.getOutput());
  24031. }
  24032. this._connected = true;
  24033. return this;
  24034. }
  24035. disconnect() {
  24036. if (this.filters.length > 0) {
  24037. this.source.disconnect(this.filters[0]);
  24038. for (let i = 1, l = this.filters.length; i < l; i++) {
  24039. this.filters[i - 1].disconnect(this.filters[i]);
  24040. }
  24041. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  24042. } else {
  24043. this.source.disconnect(this.getOutput());
  24044. }
  24045. this._connected = false;
  24046. return this;
  24047. }
  24048. getFilters() {
  24049. return this.filters;
  24050. }
  24051. setFilters(value) {
  24052. if (!value) value = [];
  24053. if (this._connected === true) {
  24054. this.disconnect();
  24055. this.filters = value.slice();
  24056. this.connect();
  24057. } else {
  24058. this.filters = value.slice();
  24059. }
  24060. return this;
  24061. }
  24062. setDetune(value) {
  24063. this.detune = value;
  24064. if (this.source.detune === undefined) return; // only set detune when available
  24065. if (this.isPlaying === true) {
  24066. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  24067. }
  24068. return this;
  24069. }
  24070. getDetune() {
  24071. return this.detune;
  24072. }
  24073. getFilter() {
  24074. return this.getFilters()[0];
  24075. }
  24076. setFilter(filter) {
  24077. return this.setFilters(filter ? [filter] : []);
  24078. }
  24079. setPlaybackRate(value) {
  24080. if (this.hasPlaybackControl === false) {
  24081. console.warn('THREE.Audio: this Audio has no playback control.');
  24082. return;
  24083. }
  24084. this.playbackRate = value;
  24085. if (this.isPlaying === true) {
  24086. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  24087. }
  24088. return this;
  24089. }
  24090. getPlaybackRate() {
  24091. return this.playbackRate;
  24092. }
  24093. onEnded() {
  24094. this.isPlaying = false;
  24095. }
  24096. getLoop() {
  24097. if (this.hasPlaybackControl === false) {
  24098. console.warn('THREE.Audio: this Audio has no playback control.');
  24099. return false;
  24100. }
  24101. return this.loop;
  24102. }
  24103. setLoop(value) {
  24104. if (this.hasPlaybackControl === false) {
  24105. console.warn('THREE.Audio: this Audio has no playback control.');
  24106. return;
  24107. }
  24108. this.loop = value;
  24109. if (this.isPlaying === true) {
  24110. this.source.loop = this.loop;
  24111. }
  24112. return this;
  24113. }
  24114. setLoopStart(value) {
  24115. this.loopStart = value;
  24116. return this;
  24117. }
  24118. setLoopEnd(value) {
  24119. this.loopEnd = value;
  24120. return this;
  24121. }
  24122. getVolume() {
  24123. return this.gain.gain.value;
  24124. }
  24125. setVolume(value) {
  24126. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  24127. return this;
  24128. }
  24129. }
  24130. const _position = /*@__PURE__*/new Vector3();
  24131. const _quaternion = /*@__PURE__*/new Quaternion();
  24132. const _scale = /*@__PURE__*/new Vector3();
  24133. const _orientation = /*@__PURE__*/new Vector3();
  24134. class PositionalAudio extends Audio {
  24135. constructor(listener) {
  24136. super(listener);
  24137. this.panner = this.context.createPanner();
  24138. this.panner.panningModel = 'HRTF';
  24139. this.panner.connect(this.gain);
  24140. }
  24141. getOutput() {
  24142. return this.panner;
  24143. }
  24144. getRefDistance() {
  24145. return this.panner.refDistance;
  24146. }
  24147. setRefDistance(value) {
  24148. this.panner.refDistance = value;
  24149. return this;
  24150. }
  24151. getRolloffFactor() {
  24152. return this.panner.rolloffFactor;
  24153. }
  24154. setRolloffFactor(value) {
  24155. this.panner.rolloffFactor = value;
  24156. return this;
  24157. }
  24158. getDistanceModel() {
  24159. return this.panner.distanceModel;
  24160. }
  24161. setDistanceModel(value) {
  24162. this.panner.distanceModel = value;
  24163. return this;
  24164. }
  24165. getMaxDistance() {
  24166. return this.panner.maxDistance;
  24167. }
  24168. setMaxDistance(value) {
  24169. this.panner.maxDistance = value;
  24170. return this;
  24171. }
  24172. setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  24173. this.panner.coneInnerAngle = coneInnerAngle;
  24174. this.panner.coneOuterAngle = coneOuterAngle;
  24175. this.panner.coneOuterGain = coneOuterGain;
  24176. return this;
  24177. }
  24178. updateMatrixWorld(force) {
  24179. super.updateMatrixWorld(force);
  24180. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  24181. this.matrixWorld.decompose(_position, _quaternion, _scale);
  24182. _orientation.set(0, 0, 1).applyQuaternion(_quaternion);
  24183. const panner = this.panner;
  24184. if (panner.positionX) {
  24185. // code path for Chrome and Firefox (see #14393)
  24186. const endTime = this.context.currentTime + this.listener.timeDelta;
  24187. panner.positionX.linearRampToValueAtTime(_position.x, endTime);
  24188. panner.positionY.linearRampToValueAtTime(_position.y, endTime);
  24189. panner.positionZ.linearRampToValueAtTime(_position.z, endTime);
  24190. panner.orientationX.linearRampToValueAtTime(_orientation.x, endTime);
  24191. panner.orientationY.linearRampToValueAtTime(_orientation.y, endTime);
  24192. panner.orientationZ.linearRampToValueAtTime(_orientation.z, endTime);
  24193. } else {
  24194. panner.setPosition(_position.x, _position.y, _position.z);
  24195. panner.setOrientation(_orientation.x, _orientation.y, _orientation.z);
  24196. }
  24197. }
  24198. }
  24199. class AudioAnalyser {
  24200. constructor(audio, fftSize = 2048) {
  24201. this.analyser = audio.context.createAnalyser();
  24202. this.analyser.fftSize = fftSize;
  24203. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  24204. audio.getOutput().connect(this.analyser);
  24205. }
  24206. getFrequencyData() {
  24207. this.analyser.getByteFrequencyData(this.data);
  24208. return this.data;
  24209. }
  24210. getAverageFrequency() {
  24211. let value = 0;
  24212. const data = this.getFrequencyData();
  24213. for (let i = 0; i < data.length; i++) {
  24214. value += data[i];
  24215. }
  24216. return value / data.length;
  24217. }
  24218. }
  24219. class PropertyMixer {
  24220. constructor(binding, typeName, valueSize) {
  24221. this.binding = binding;
  24222. this.valueSize = valueSize;
  24223. let mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  24224. //
  24225. // interpolators can use .buffer as their .result
  24226. // the data then goes to 'incoming'
  24227. //
  24228. // 'accu0' and 'accu1' are used frame-interleaved for
  24229. // the cumulative result and are compared to detect
  24230. // changes
  24231. //
  24232. // 'orig' stores the original state of the property
  24233. //
  24234. // 'add' is used for additive cumulative results
  24235. //
  24236. // 'work' is optional and is only present for quaternion types. It is used
  24237. // to store intermediate quaternion multiplication results
  24238. switch (typeName) {
  24239. case 'quaternion':
  24240. mixFunction = this._slerp;
  24241. mixFunctionAdditive = this._slerpAdditive;
  24242. setIdentity = this._setAdditiveIdentityQuaternion;
  24243. this.buffer = new Float64Array(valueSize * 6);
  24244. this._workIndex = 5;
  24245. break;
  24246. case 'string':
  24247. case 'bool':
  24248. mixFunction = this._select; // Use the regular mix function and for additive on these types,
  24249. // additive is not relevant for non-numeric types
  24250. mixFunctionAdditive = this._select;
  24251. setIdentity = this._setAdditiveIdentityOther;
  24252. this.buffer = new Array(valueSize * 5);
  24253. break;
  24254. default:
  24255. mixFunction = this._lerp;
  24256. mixFunctionAdditive = this._lerpAdditive;
  24257. setIdentity = this._setAdditiveIdentityNumeric;
  24258. this.buffer = new Float64Array(valueSize * 5);
  24259. }
  24260. this._mixBufferRegion = mixFunction;
  24261. this._mixBufferRegionAdditive = mixFunctionAdditive;
  24262. this._setIdentity = setIdentity;
  24263. this._origIndex = 3;
  24264. this._addIndex = 4;
  24265. this.cumulativeWeight = 0;
  24266. this.cumulativeWeightAdditive = 0;
  24267. this.useCount = 0;
  24268. this.referenceCount = 0;
  24269. } // accumulate data in the 'incoming' region into 'accu<i>'
  24270. accumulate(accuIndex, weight) {
  24271. // note: happily accumulating nothing when weight = 0, the caller knows
  24272. // the weight and shouldn't have made the call in the first place
  24273. const buffer = this.buffer,
  24274. stride = this.valueSize,
  24275. offset = accuIndex * stride + stride;
  24276. let currentWeight = this.cumulativeWeight;
  24277. if (currentWeight === 0) {
  24278. // accuN := incoming * weight
  24279. for (let i = 0; i !== stride; ++i) {
  24280. buffer[offset + i] = buffer[i];
  24281. }
  24282. currentWeight = weight;
  24283. } else {
  24284. // accuN := accuN + incoming * weight
  24285. currentWeight += weight;
  24286. const mix = weight / currentWeight;
  24287. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  24288. }
  24289. this.cumulativeWeight = currentWeight;
  24290. } // accumulate data in the 'incoming' region into 'add'
  24291. accumulateAdditive(weight) {
  24292. const buffer = this.buffer,
  24293. stride = this.valueSize,
  24294. offset = stride * this._addIndex;
  24295. if (this.cumulativeWeightAdditive === 0) {
  24296. // add = identity
  24297. this._setIdentity();
  24298. } // add := add + incoming * weight
  24299. this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
  24300. this.cumulativeWeightAdditive += weight;
  24301. } // apply the state of 'accu<i>' to the binding when accus differ
  24302. apply(accuIndex) {
  24303. const stride = this.valueSize,
  24304. buffer = this.buffer,
  24305. offset = accuIndex * stride + stride,
  24306. weight = this.cumulativeWeight,
  24307. weightAdditive = this.cumulativeWeightAdditive,
  24308. binding = this.binding;
  24309. this.cumulativeWeight = 0;
  24310. this.cumulativeWeightAdditive = 0;
  24311. if (weight < 1) {
  24312. // accuN := accuN + original * ( 1 - cumulativeWeight )
  24313. const originalValueOffset = stride * this._origIndex;
  24314. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  24315. }
  24316. if (weightAdditive > 0) {
  24317. // accuN := accuN + additive accuN
  24318. this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
  24319. }
  24320. for (let i = stride, e = stride + stride; i !== e; ++i) {
  24321. if (buffer[i] !== buffer[i + stride]) {
  24322. // value has changed -> update scene graph
  24323. binding.setValue(buffer, offset);
  24324. break;
  24325. }
  24326. }
  24327. } // remember the state of the bound property and copy it to both accus
  24328. saveOriginalState() {
  24329. const binding = this.binding;
  24330. const buffer = this.buffer,
  24331. stride = this.valueSize,
  24332. originalValueOffset = stride * this._origIndex;
  24333. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  24334. for (let i = stride, e = originalValueOffset; i !== e; ++i) {
  24335. buffer[i] = buffer[originalValueOffset + i % stride];
  24336. } // Add to identity for additive
  24337. this._setIdentity();
  24338. this.cumulativeWeight = 0;
  24339. this.cumulativeWeightAdditive = 0;
  24340. } // apply the state previously taken via 'saveOriginalState' to the binding
  24341. restoreOriginalState() {
  24342. const originalValueOffset = this.valueSize * 3;
  24343. this.binding.setValue(this.buffer, originalValueOffset);
  24344. }
  24345. _setAdditiveIdentityNumeric() {
  24346. const startIndex = this._addIndex * this.valueSize;
  24347. const endIndex = startIndex + this.valueSize;
  24348. for (let i = startIndex; i < endIndex; i++) {
  24349. this.buffer[i] = 0;
  24350. }
  24351. }
  24352. _setAdditiveIdentityQuaternion() {
  24353. this._setAdditiveIdentityNumeric();
  24354. this.buffer[this._addIndex * this.valueSize + 3] = 1;
  24355. }
  24356. _setAdditiveIdentityOther() {
  24357. const startIndex = this._origIndex * this.valueSize;
  24358. const targetIndex = this._addIndex * this.valueSize;
  24359. for (let i = 0; i < this.valueSize; i++) {
  24360. this.buffer[targetIndex + i] = this.buffer[startIndex + i];
  24361. }
  24362. } // mix functions
  24363. _select(buffer, dstOffset, srcOffset, t, stride) {
  24364. if (t >= 0.5) {
  24365. for (let i = 0; i !== stride; ++i) {
  24366. buffer[dstOffset + i] = buffer[srcOffset + i];
  24367. }
  24368. }
  24369. }
  24370. _slerp(buffer, dstOffset, srcOffset, t) {
  24371. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  24372. }
  24373. _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  24374. const workOffset = this._workIndex * stride; // Store result in intermediate buffer offset
  24375. Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
  24376. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
  24377. }
  24378. _lerp(buffer, dstOffset, srcOffset, t, stride) {
  24379. const s = 1 - t;
  24380. for (let i = 0; i !== stride; ++i) {
  24381. const j = dstOffset + i;
  24382. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  24383. }
  24384. }
  24385. _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  24386. for (let i = 0; i !== stride; ++i) {
  24387. const j = dstOffset + i;
  24388. buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
  24389. }
  24390. }
  24391. }
  24392. // Characters [].:/ are reserved for track binding syntax.
  24393. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  24394. const _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  24395. // only latin characters, and the unicode \p{L} is not yet supported. So
  24396. // instead, we exclude reserved characters and match everything else.
  24397. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  24398. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  24399. // be matched to parse the rest of the track name.
  24400. const _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  24401. const _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  24402. // characters. Accessor may contain any character except closing bracket.
  24403. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  24404. // contain any non-bracket characters.
  24405. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  24406. const _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  24407. const _supportedObjectNames = ['material', 'materials', 'bones'];
  24408. class Composite {
  24409. constructor(targetGroup, path, optionalParsedPath) {
  24410. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  24411. this._targetGroup = targetGroup;
  24412. this._bindings = targetGroup.subscribe_(path, parsedPath);
  24413. }
  24414. getValue(array, offset) {
  24415. this.bind(); // bind all binding
  24416. const firstValidIndex = this._targetGroup.nCachedObjects_,
  24417. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  24418. if (binding !== undefined) binding.getValue(array, offset);
  24419. }
  24420. setValue(array, offset) {
  24421. const bindings = this._bindings;
  24422. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  24423. bindings[i].setValue(array, offset);
  24424. }
  24425. }
  24426. bind() {
  24427. const bindings = this._bindings;
  24428. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  24429. bindings[i].bind();
  24430. }
  24431. }
  24432. unbind() {
  24433. const bindings = this._bindings;
  24434. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  24435. bindings[i].unbind();
  24436. }
  24437. }
  24438. } // Note: This class uses a State pattern on a per-method basis:
  24439. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  24440. // prototype version of these methods with one that represents
  24441. // the bound state. When the property is not found, the methods
  24442. // become no-ops.
  24443. class PropertyBinding {
  24444. constructor(rootNode, path, parsedPath) {
  24445. this.path = path;
  24446. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  24447. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  24448. this.rootNode = rootNode; // initial state of these methods that calls 'bind'
  24449. this.getValue = this._getValue_unbound;
  24450. this.setValue = this._setValue_unbound;
  24451. }
  24452. static create(root, path, parsedPath) {
  24453. if (!(root && root.isAnimationObjectGroup)) {
  24454. return new PropertyBinding(root, path, parsedPath);
  24455. } else {
  24456. return new PropertyBinding.Composite(root, path, parsedPath);
  24457. }
  24458. }
  24459. /**
  24460. * Replaces spaces with underscores and removes unsupported characters from
  24461. * node names, to ensure compatibility with parseTrackName().
  24462. *
  24463. * @param {string} name Node name to be sanitized.
  24464. * @return {string}
  24465. */
  24466. static sanitizeNodeName(name) {
  24467. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  24468. }
  24469. static parseTrackName(trackName) {
  24470. const matches = _trackRe.exec(trackName);
  24471. if (!matches) {
  24472. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  24473. }
  24474. const results = {
  24475. // directoryName: matches[ 1 ], // (tschw) currently unused
  24476. nodeName: matches[2],
  24477. objectName: matches[3],
  24478. objectIndex: matches[4],
  24479. propertyName: matches[5],
  24480. // required
  24481. propertyIndex: matches[6]
  24482. };
  24483. const lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  24484. if (lastDot !== undefined && lastDot !== -1) {
  24485. const objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
  24486. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  24487. // 'bar' could be the objectName, or part of a nodeName (which can
  24488. // include '.' characters).
  24489. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  24490. results.nodeName = results.nodeName.substring(0, lastDot);
  24491. results.objectName = objectName;
  24492. }
  24493. }
  24494. if (results.propertyName === null || results.propertyName.length === 0) {
  24495. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  24496. }
  24497. return results;
  24498. }
  24499. static findNode(root, nodeName) {
  24500. if (!nodeName || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  24501. return root;
  24502. } // search into skeleton bones.
  24503. if (root.skeleton) {
  24504. const bone = root.skeleton.getBoneByName(nodeName);
  24505. if (bone !== undefined) {
  24506. return bone;
  24507. }
  24508. } // search into node subtree.
  24509. if (root.children) {
  24510. const searchNodeSubtree = function (children) {
  24511. for (let i = 0; i < children.length; i++) {
  24512. const childNode = children[i];
  24513. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  24514. return childNode;
  24515. }
  24516. const result = searchNodeSubtree(childNode.children);
  24517. if (result) return result;
  24518. }
  24519. return null;
  24520. };
  24521. const subTreeNode = searchNodeSubtree(root.children);
  24522. if (subTreeNode) {
  24523. return subTreeNode;
  24524. }
  24525. }
  24526. return null;
  24527. } // these are used to "bind" a nonexistent property
  24528. _getValue_unavailable() {}
  24529. _setValue_unavailable() {} // Getters
  24530. _getValue_direct(buffer, offset) {
  24531. buffer[offset] = this.node[this.propertyName];
  24532. }
  24533. _getValue_array(buffer, offset) {
  24534. const source = this.resolvedProperty;
  24535. for (let i = 0, n = source.length; i !== n; ++i) {
  24536. buffer[offset++] = source[i];
  24537. }
  24538. }
  24539. _getValue_arrayElement(buffer, offset) {
  24540. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  24541. }
  24542. _getValue_toArray(buffer, offset) {
  24543. this.resolvedProperty.toArray(buffer, offset);
  24544. } // Direct
  24545. _setValue_direct(buffer, offset) {
  24546. this.targetObject[this.propertyName] = buffer[offset];
  24547. }
  24548. _setValue_direct_setNeedsUpdate(buffer, offset) {
  24549. this.targetObject[this.propertyName] = buffer[offset];
  24550. this.targetObject.needsUpdate = true;
  24551. }
  24552. _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  24553. this.targetObject[this.propertyName] = buffer[offset];
  24554. this.targetObject.matrixWorldNeedsUpdate = true;
  24555. } // EntireArray
  24556. _setValue_array(buffer, offset) {
  24557. const dest = this.resolvedProperty;
  24558. for (let i = 0, n = dest.length; i !== n; ++i) {
  24559. dest[i] = buffer[offset++];
  24560. }
  24561. }
  24562. _setValue_array_setNeedsUpdate(buffer, offset) {
  24563. const dest = this.resolvedProperty;
  24564. for (let i = 0, n = dest.length; i !== n; ++i) {
  24565. dest[i] = buffer[offset++];
  24566. }
  24567. this.targetObject.needsUpdate = true;
  24568. }
  24569. _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  24570. const dest = this.resolvedProperty;
  24571. for (let i = 0, n = dest.length; i !== n; ++i) {
  24572. dest[i] = buffer[offset++];
  24573. }
  24574. this.targetObject.matrixWorldNeedsUpdate = true;
  24575. } // ArrayElement
  24576. _setValue_arrayElement(buffer, offset) {
  24577. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  24578. }
  24579. _setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  24580. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  24581. this.targetObject.needsUpdate = true;
  24582. }
  24583. _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  24584. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  24585. this.targetObject.matrixWorldNeedsUpdate = true;
  24586. } // HasToFromArray
  24587. _setValue_fromArray(buffer, offset) {
  24588. this.resolvedProperty.fromArray(buffer, offset);
  24589. }
  24590. _setValue_fromArray_setNeedsUpdate(buffer, offset) {
  24591. this.resolvedProperty.fromArray(buffer, offset);
  24592. this.targetObject.needsUpdate = true;
  24593. }
  24594. _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  24595. this.resolvedProperty.fromArray(buffer, offset);
  24596. this.targetObject.matrixWorldNeedsUpdate = true;
  24597. }
  24598. _getValue_unbound(targetArray, offset) {
  24599. this.bind();
  24600. this.getValue(targetArray, offset);
  24601. }
  24602. _setValue_unbound(sourceArray, offset) {
  24603. this.bind();
  24604. this.setValue(sourceArray, offset);
  24605. } // create getter / setter pair for a property in the scene graph
  24606. bind() {
  24607. let targetObject = this.node;
  24608. const parsedPath = this.parsedPath;
  24609. const objectName = parsedPath.objectName;
  24610. const propertyName = parsedPath.propertyName;
  24611. let propertyIndex = parsedPath.propertyIndex;
  24612. if (!targetObject) {
  24613. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  24614. this.node = targetObject;
  24615. } // set fail state so we can just 'return' on error
  24616. this.getValue = this._getValue_unavailable;
  24617. this.setValue = this._setValue_unavailable; // ensure there is a value node
  24618. if (!targetObject) {
  24619. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  24620. return;
  24621. }
  24622. if (objectName) {
  24623. let objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  24624. switch (objectName) {
  24625. case 'materials':
  24626. if (!targetObject.material) {
  24627. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  24628. return;
  24629. }
  24630. if (!targetObject.material.materials) {
  24631. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  24632. return;
  24633. }
  24634. targetObject = targetObject.material.materials;
  24635. break;
  24636. case 'bones':
  24637. if (!targetObject.skeleton) {
  24638. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  24639. return;
  24640. } // potential future optimization: skip this if propertyIndex is already an integer
  24641. // and convert the integer string to a true integer.
  24642. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  24643. for (let i = 0; i < targetObject.length; i++) {
  24644. if (targetObject[i].name === objectIndex) {
  24645. objectIndex = i;
  24646. break;
  24647. }
  24648. }
  24649. break;
  24650. default:
  24651. if (targetObject[objectName] === undefined) {
  24652. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  24653. return;
  24654. }
  24655. targetObject = targetObject[objectName];
  24656. }
  24657. if (objectIndex !== undefined) {
  24658. if (targetObject[objectIndex] === undefined) {
  24659. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  24660. return;
  24661. }
  24662. targetObject = targetObject[objectIndex];
  24663. }
  24664. } // resolve property
  24665. const nodeProperty = targetObject[propertyName];
  24666. if (nodeProperty === undefined) {
  24667. const nodeName = parsedPath.nodeName;
  24668. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  24669. return;
  24670. } // determine versioning scheme
  24671. let versioning = this.Versioning.None;
  24672. this.targetObject = targetObject;
  24673. if (targetObject.needsUpdate !== undefined) {
  24674. // material
  24675. versioning = this.Versioning.NeedsUpdate;
  24676. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  24677. // node transform
  24678. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  24679. } // determine how the property gets bound
  24680. let bindingType = this.BindingType.Direct;
  24681. if (propertyIndex !== undefined) {
  24682. // access a sub element of the property array (only primitives are supported right now)
  24683. if (propertyName === 'morphTargetInfluences') {
  24684. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  24685. // support resolving morphTarget names into indices.
  24686. if (!targetObject.geometry) {
  24687. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  24688. return;
  24689. }
  24690. if (targetObject.geometry.isBufferGeometry) {
  24691. if (!targetObject.geometry.morphAttributes) {
  24692. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  24693. return;
  24694. }
  24695. if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
  24696. propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
  24697. }
  24698. } else {
  24699. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this);
  24700. return;
  24701. }
  24702. }
  24703. bindingType = this.BindingType.ArrayElement;
  24704. this.resolvedProperty = nodeProperty;
  24705. this.propertyIndex = propertyIndex;
  24706. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  24707. // must use copy for Object3D.Euler/Quaternion
  24708. bindingType = this.BindingType.HasFromToArray;
  24709. this.resolvedProperty = nodeProperty;
  24710. } else if (Array.isArray(nodeProperty)) {
  24711. bindingType = this.BindingType.EntireArray;
  24712. this.resolvedProperty = nodeProperty;
  24713. } else {
  24714. this.propertyName = propertyName;
  24715. } // select getter / setter
  24716. this.getValue = this.GetterByBindingType[bindingType];
  24717. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  24718. }
  24719. unbind() {
  24720. this.node = null; // back to the prototype version of getValue / setValue
  24721. // note: avoiding to mutate the shape of 'this' via 'delete'
  24722. this.getValue = this._getValue_unbound;
  24723. this.setValue = this._setValue_unbound;
  24724. }
  24725. }
  24726. PropertyBinding.Composite = Composite;
  24727. PropertyBinding.prototype.BindingType = {
  24728. Direct: 0,
  24729. EntireArray: 1,
  24730. ArrayElement: 2,
  24731. HasFromToArray: 3
  24732. };
  24733. PropertyBinding.prototype.Versioning = {
  24734. None: 0,
  24735. NeedsUpdate: 1,
  24736. MatrixWorldNeedsUpdate: 2
  24737. };
  24738. PropertyBinding.prototype.GetterByBindingType = [PropertyBinding.prototype._getValue_direct, PropertyBinding.prototype._getValue_array, PropertyBinding.prototype._getValue_arrayElement, PropertyBinding.prototype._getValue_toArray];
  24739. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [[// Direct
  24740. PropertyBinding.prototype._setValue_direct, PropertyBinding.prototype._setValue_direct_setNeedsUpdate, PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate], [// EntireArray
  24741. PropertyBinding.prototype._setValue_array, PropertyBinding.prototype._setValue_array_setNeedsUpdate, PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate], [// ArrayElement
  24742. PropertyBinding.prototype._setValue_arrayElement, PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate], [// HasToFromArray
  24743. PropertyBinding.prototype._setValue_fromArray, PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];
  24744. /**
  24745. *
  24746. * A group of objects that receives a shared animation state.
  24747. *
  24748. * Usage:
  24749. *
  24750. * - Add objects you would otherwise pass as 'root' to the
  24751. * constructor or the .clipAction method of AnimationMixer.
  24752. *
  24753. * - Instead pass this object as 'root'.
  24754. *
  24755. * - You can also add and remove objects later when the mixer
  24756. * is running.
  24757. *
  24758. * Note:
  24759. *
  24760. * Objects of this class appear as one object to the mixer,
  24761. * so cache control of the individual objects must be done
  24762. * on the group.
  24763. *
  24764. * Limitation:
  24765. *
  24766. * - The animated properties must be compatible among the
  24767. * all objects in the group.
  24768. *
  24769. * - A single property can either be controlled through a
  24770. * target group or directly, but not both.
  24771. */
  24772. class AnimationObjectGroup {
  24773. constructor() {
  24774. this.uuid = generateUUID(); // cached objects followed by the active ones
  24775. this._objects = Array.prototype.slice.call(arguments);
  24776. this.nCachedObjects_ = 0; // threshold
  24777. // note: read by PropertyBinding.Composite
  24778. const indices = {};
  24779. this._indicesByUUID = indices; // for bookkeeping
  24780. for (let i = 0, n = arguments.length; i !== n; ++i) {
  24781. indices[arguments[i].uuid] = i;
  24782. }
  24783. this._paths = []; // inside: string
  24784. this._parsedPaths = []; // inside: { we don't care, here }
  24785. this._bindings = []; // inside: Array< PropertyBinding >
  24786. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  24787. const scope = this;
  24788. this.stats = {
  24789. objects: {
  24790. get total() {
  24791. return scope._objects.length;
  24792. },
  24793. get inUse() {
  24794. return this.total - scope.nCachedObjects_;
  24795. }
  24796. },
  24797. get bindingsPerObject() {
  24798. return scope._bindings.length;
  24799. }
  24800. };
  24801. }
  24802. add() {
  24803. const objects = this._objects,
  24804. indicesByUUID = this._indicesByUUID,
  24805. paths = this._paths,
  24806. parsedPaths = this._parsedPaths,
  24807. bindings = this._bindings,
  24808. nBindings = bindings.length;
  24809. let knownObject = undefined,
  24810. nObjects = objects.length,
  24811. nCachedObjects = this.nCachedObjects_;
  24812. for (let i = 0, n = arguments.length; i !== n; ++i) {
  24813. const object = arguments[i],
  24814. uuid = object.uuid;
  24815. let index = indicesByUUID[uuid];
  24816. if (index === undefined) {
  24817. // unknown object -> add it to the ACTIVE region
  24818. index = nObjects++;
  24819. indicesByUUID[uuid] = index;
  24820. objects.push(object); // accounting is done, now do the same for all bindings
  24821. for (let j = 0, m = nBindings; j !== m; ++j) {
  24822. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  24823. }
  24824. } else if (index < nCachedObjects) {
  24825. knownObject = objects[index]; // move existing object to the ACTIVE region
  24826. const firstActiveIndex = --nCachedObjects,
  24827. lastCachedObject = objects[firstActiveIndex];
  24828. indicesByUUID[lastCachedObject.uuid] = index;
  24829. objects[index] = lastCachedObject;
  24830. indicesByUUID[uuid] = firstActiveIndex;
  24831. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  24832. for (let j = 0, m = nBindings; j !== m; ++j) {
  24833. const bindingsForPath = bindings[j],
  24834. lastCached = bindingsForPath[firstActiveIndex];
  24835. let binding = bindingsForPath[index];
  24836. bindingsForPath[index] = lastCached;
  24837. if (binding === undefined) {
  24838. // since we do not bother to create new bindings
  24839. // for objects that are cached, the binding may
  24840. // or may not exist
  24841. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  24842. }
  24843. bindingsForPath[firstActiveIndex] = binding;
  24844. }
  24845. } else if (objects[index] !== knownObject) {
  24846. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  24847. } // else the object is already where we want it to be
  24848. } // for arguments
  24849. this.nCachedObjects_ = nCachedObjects;
  24850. }
  24851. remove() {
  24852. const objects = this._objects,
  24853. indicesByUUID = this._indicesByUUID,
  24854. bindings = this._bindings,
  24855. nBindings = bindings.length;
  24856. let nCachedObjects = this.nCachedObjects_;
  24857. for (let i = 0, n = arguments.length; i !== n; ++i) {
  24858. const object = arguments[i],
  24859. uuid = object.uuid,
  24860. index = indicesByUUID[uuid];
  24861. if (index !== undefined && index >= nCachedObjects) {
  24862. // move existing object into the CACHED region
  24863. const lastCachedIndex = nCachedObjects++,
  24864. firstActiveObject = objects[lastCachedIndex];
  24865. indicesByUUID[firstActiveObject.uuid] = index;
  24866. objects[index] = firstActiveObject;
  24867. indicesByUUID[uuid] = lastCachedIndex;
  24868. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  24869. for (let j = 0, m = nBindings; j !== m; ++j) {
  24870. const bindingsForPath = bindings[j],
  24871. firstActive = bindingsForPath[lastCachedIndex],
  24872. binding = bindingsForPath[index];
  24873. bindingsForPath[index] = firstActive;
  24874. bindingsForPath[lastCachedIndex] = binding;
  24875. }
  24876. }
  24877. } // for arguments
  24878. this.nCachedObjects_ = nCachedObjects;
  24879. } // remove & forget
  24880. uncache() {
  24881. const objects = this._objects,
  24882. indicesByUUID = this._indicesByUUID,
  24883. bindings = this._bindings,
  24884. nBindings = bindings.length;
  24885. let nCachedObjects = this.nCachedObjects_,
  24886. nObjects = objects.length;
  24887. for (let i = 0, n = arguments.length; i !== n; ++i) {
  24888. const object = arguments[i],
  24889. uuid = object.uuid,
  24890. index = indicesByUUID[uuid];
  24891. if (index !== undefined) {
  24892. delete indicesByUUID[uuid];
  24893. if (index < nCachedObjects) {
  24894. // object is cached, shrink the CACHED region
  24895. const firstActiveIndex = --nCachedObjects,
  24896. lastCachedObject = objects[firstActiveIndex],
  24897. lastIndex = --nObjects,
  24898. lastObject = objects[lastIndex]; // last cached object takes this object's place
  24899. indicesByUUID[lastCachedObject.uuid] = index;
  24900. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  24901. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  24902. objects[firstActiveIndex] = lastObject;
  24903. objects.pop(); // accounting is done, now do the same for all bindings
  24904. for (let j = 0, m = nBindings; j !== m; ++j) {
  24905. const bindingsForPath = bindings[j],
  24906. lastCached = bindingsForPath[firstActiveIndex],
  24907. last = bindingsForPath[lastIndex];
  24908. bindingsForPath[index] = lastCached;
  24909. bindingsForPath[firstActiveIndex] = last;
  24910. bindingsForPath.pop();
  24911. }
  24912. } else {
  24913. // object is active, just swap with the last and pop
  24914. const lastIndex = --nObjects,
  24915. lastObject = objects[lastIndex];
  24916. if (lastIndex > 0) {
  24917. indicesByUUID[lastObject.uuid] = index;
  24918. }
  24919. objects[index] = lastObject;
  24920. objects.pop(); // accounting is done, now do the same for all bindings
  24921. for (let j = 0, m = nBindings; j !== m; ++j) {
  24922. const bindingsForPath = bindings[j];
  24923. bindingsForPath[index] = bindingsForPath[lastIndex];
  24924. bindingsForPath.pop();
  24925. }
  24926. } // cached or active
  24927. } // if object is known
  24928. } // for arguments
  24929. this.nCachedObjects_ = nCachedObjects;
  24930. } // Internal interface used by befriended PropertyBinding.Composite:
  24931. subscribe_(path, parsedPath) {
  24932. // returns an array of bindings for the given path that is changed
  24933. // according to the contained objects in the group
  24934. const indicesByPath = this._bindingsIndicesByPath;
  24935. let index = indicesByPath[path];
  24936. const bindings = this._bindings;
  24937. if (index !== undefined) return bindings[index];
  24938. const paths = this._paths,
  24939. parsedPaths = this._parsedPaths,
  24940. objects = this._objects,
  24941. nObjects = objects.length,
  24942. nCachedObjects = this.nCachedObjects_,
  24943. bindingsForPath = new Array(nObjects);
  24944. index = bindings.length;
  24945. indicesByPath[path] = index;
  24946. paths.push(path);
  24947. parsedPaths.push(parsedPath);
  24948. bindings.push(bindingsForPath);
  24949. for (let i = nCachedObjects, n = objects.length; i !== n; ++i) {
  24950. const object = objects[i];
  24951. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  24952. }
  24953. return bindingsForPath;
  24954. }
  24955. unsubscribe_(path) {
  24956. // tells the group to forget about a property path and no longer
  24957. // update the array previously obtained with 'subscribe_'
  24958. const indicesByPath = this._bindingsIndicesByPath,
  24959. index = indicesByPath[path];
  24960. if (index !== undefined) {
  24961. const paths = this._paths,
  24962. parsedPaths = this._parsedPaths,
  24963. bindings = this._bindings,
  24964. lastBindingsIndex = bindings.length - 1,
  24965. lastBindings = bindings[lastBindingsIndex],
  24966. lastBindingsPath = path[lastBindingsIndex];
  24967. indicesByPath[lastBindingsPath] = index;
  24968. bindings[index] = lastBindings;
  24969. bindings.pop();
  24970. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  24971. parsedPaths.pop();
  24972. paths[index] = paths[lastBindingsIndex];
  24973. paths.pop();
  24974. }
  24975. }
  24976. }
  24977. AnimationObjectGroup.prototype.isAnimationObjectGroup = true;
  24978. class AnimationAction {
  24979. constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) {
  24980. this._mixer = mixer;
  24981. this._clip = clip;
  24982. this._localRoot = localRoot;
  24983. this.blendMode = blendMode;
  24984. const tracks = clip.tracks,
  24985. nTracks = tracks.length,
  24986. interpolants = new Array(nTracks);
  24987. const interpolantSettings = {
  24988. endingStart: ZeroCurvatureEnding,
  24989. endingEnd: ZeroCurvatureEnding
  24990. };
  24991. for (let i = 0; i !== nTracks; ++i) {
  24992. const interpolant = tracks[i].createInterpolant(null);
  24993. interpolants[i] = interpolant;
  24994. interpolant.settings = interpolantSettings;
  24995. }
  24996. this._interpolantSettings = interpolantSettings;
  24997. this._interpolants = interpolants; // bound by the mixer
  24998. // inside: PropertyMixer (managed by the mixer)
  24999. this._propertyBindings = new Array(nTracks);
  25000. this._cacheIndex = null; // for the memory manager
  25001. this._byClipCacheIndex = null; // for the memory manager
  25002. this._timeScaleInterpolant = null;
  25003. this._weightInterpolant = null;
  25004. this.loop = LoopRepeat;
  25005. this._loopCount = -1; // global mixer time when the action is to be started
  25006. // it's set back to 'null' upon start of the action
  25007. this._startTime = null; // scaled local time of the action
  25008. // gets clamped or wrapped to 0..clip.duration according to loop
  25009. this.time = 0;
  25010. this.timeScale = 1;
  25011. this._effectiveTimeScale = 1;
  25012. this.weight = 1;
  25013. this._effectiveWeight = 1;
  25014. this.repetitions = Infinity; // no. of repetitions when looping
  25015. this.paused = false; // true -> zero effective time scale
  25016. this.enabled = true; // false -> zero effective weight
  25017. this.clampWhenFinished = false; // keep feeding the last frame?
  25018. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  25019. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  25020. } // State & Scheduling
  25021. play() {
  25022. this._mixer._activateAction(this);
  25023. return this;
  25024. }
  25025. stop() {
  25026. this._mixer._deactivateAction(this);
  25027. return this.reset();
  25028. }
  25029. reset() {
  25030. this.paused = false;
  25031. this.enabled = true;
  25032. this.time = 0; // restart clip
  25033. this._loopCount = -1; // forget previous loops
  25034. this._startTime = null; // forget scheduling
  25035. return this.stopFading().stopWarping();
  25036. }
  25037. isRunning() {
  25038. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  25039. } // return true when play has been called
  25040. isScheduled() {
  25041. return this._mixer._isActiveAction(this);
  25042. }
  25043. startAt(time) {
  25044. this._startTime = time;
  25045. return this;
  25046. }
  25047. setLoop(mode, repetitions) {
  25048. this.loop = mode;
  25049. this.repetitions = repetitions;
  25050. return this;
  25051. } // Weight
  25052. // set the weight stopping any scheduled fading
  25053. // although .enabled = false yields an effective weight of zero, this
  25054. // method does *not* change .enabled, because it would be confusing
  25055. setEffectiveWeight(weight) {
  25056. this.weight = weight; // note: same logic as when updated at runtime
  25057. this._effectiveWeight = this.enabled ? weight : 0;
  25058. return this.stopFading();
  25059. } // return the weight considering fading and .enabled
  25060. getEffectiveWeight() {
  25061. return this._effectiveWeight;
  25062. }
  25063. fadeIn(duration) {
  25064. return this._scheduleFading(duration, 0, 1);
  25065. }
  25066. fadeOut(duration) {
  25067. return this._scheduleFading(duration, 1, 0);
  25068. }
  25069. crossFadeFrom(fadeOutAction, duration, warp) {
  25070. fadeOutAction.fadeOut(duration);
  25071. this.fadeIn(duration);
  25072. if (warp) {
  25073. const fadeInDuration = this._clip.duration,
  25074. fadeOutDuration = fadeOutAction._clip.duration,
  25075. startEndRatio = fadeOutDuration / fadeInDuration,
  25076. endStartRatio = fadeInDuration / fadeOutDuration;
  25077. fadeOutAction.warp(1.0, startEndRatio, duration);
  25078. this.warp(endStartRatio, 1.0, duration);
  25079. }
  25080. return this;
  25081. }
  25082. crossFadeTo(fadeInAction, duration, warp) {
  25083. return fadeInAction.crossFadeFrom(this, duration, warp);
  25084. }
  25085. stopFading() {
  25086. const weightInterpolant = this._weightInterpolant;
  25087. if (weightInterpolant !== null) {
  25088. this._weightInterpolant = null;
  25089. this._mixer._takeBackControlInterpolant(weightInterpolant);
  25090. }
  25091. return this;
  25092. } // Time Scale Control
  25093. // set the time scale stopping any scheduled warping
  25094. // although .paused = true yields an effective time scale of zero, this
  25095. // method does *not* change .paused, because it would be confusing
  25096. setEffectiveTimeScale(timeScale) {
  25097. this.timeScale = timeScale;
  25098. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  25099. return this.stopWarping();
  25100. } // return the time scale considering warping and .paused
  25101. getEffectiveTimeScale() {
  25102. return this._effectiveTimeScale;
  25103. }
  25104. setDuration(duration) {
  25105. this.timeScale = this._clip.duration / duration;
  25106. return this.stopWarping();
  25107. }
  25108. syncWith(action) {
  25109. this.time = action.time;
  25110. this.timeScale = action.timeScale;
  25111. return this.stopWarping();
  25112. }
  25113. halt(duration) {
  25114. return this.warp(this._effectiveTimeScale, 0, duration);
  25115. }
  25116. warp(startTimeScale, endTimeScale, duration) {
  25117. const mixer = this._mixer,
  25118. now = mixer.time,
  25119. timeScale = this.timeScale;
  25120. let interpolant = this._timeScaleInterpolant;
  25121. if (interpolant === null) {
  25122. interpolant = mixer._lendControlInterpolant();
  25123. this._timeScaleInterpolant = interpolant;
  25124. }
  25125. const times = interpolant.parameterPositions,
  25126. values = interpolant.sampleValues;
  25127. times[0] = now;
  25128. times[1] = now + duration;
  25129. values[0] = startTimeScale / timeScale;
  25130. values[1] = endTimeScale / timeScale;
  25131. return this;
  25132. }
  25133. stopWarping() {
  25134. const timeScaleInterpolant = this._timeScaleInterpolant;
  25135. if (timeScaleInterpolant !== null) {
  25136. this._timeScaleInterpolant = null;
  25137. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  25138. }
  25139. return this;
  25140. } // Object Accessors
  25141. getMixer() {
  25142. return this._mixer;
  25143. }
  25144. getClip() {
  25145. return this._clip;
  25146. }
  25147. getRoot() {
  25148. return this._localRoot || this._mixer._root;
  25149. } // Interna
  25150. _update(time, deltaTime, timeDirection, accuIndex) {
  25151. // called by the mixer
  25152. if (!this.enabled) {
  25153. // call ._updateWeight() to update ._effectiveWeight
  25154. this._updateWeight(time);
  25155. return;
  25156. }
  25157. const startTime = this._startTime;
  25158. if (startTime !== null) {
  25159. // check for scheduled start of action
  25160. const timeRunning = (time - startTime) * timeDirection;
  25161. if (timeRunning < 0 || timeDirection === 0) {
  25162. return; // yet to come / don't decide when delta = 0
  25163. } // start
  25164. this._startTime = null; // unschedule
  25165. deltaTime = timeDirection * timeRunning;
  25166. } // apply time scale and advance time
  25167. deltaTime *= this._updateTimeScale(time);
  25168. const clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  25169. // an effective weight of 0
  25170. const weight = this._updateWeight(time);
  25171. if (weight > 0) {
  25172. const interpolants = this._interpolants;
  25173. const propertyMixers = this._propertyBindings;
  25174. switch (this.blendMode) {
  25175. case AdditiveAnimationBlendMode:
  25176. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  25177. interpolants[j].evaluate(clipTime);
  25178. propertyMixers[j].accumulateAdditive(weight);
  25179. }
  25180. break;
  25181. case NormalAnimationBlendMode:
  25182. default:
  25183. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  25184. interpolants[j].evaluate(clipTime);
  25185. propertyMixers[j].accumulate(accuIndex, weight);
  25186. }
  25187. }
  25188. }
  25189. }
  25190. _updateWeight(time) {
  25191. let weight = 0;
  25192. if (this.enabled) {
  25193. weight = this.weight;
  25194. const interpolant = this._weightInterpolant;
  25195. if (interpolant !== null) {
  25196. const interpolantValue = interpolant.evaluate(time)[0];
  25197. weight *= interpolantValue;
  25198. if (time > interpolant.parameterPositions[1]) {
  25199. this.stopFading();
  25200. if (interpolantValue === 0) {
  25201. // faded out, disable
  25202. this.enabled = false;
  25203. }
  25204. }
  25205. }
  25206. }
  25207. this._effectiveWeight = weight;
  25208. return weight;
  25209. }
  25210. _updateTimeScale(time) {
  25211. let timeScale = 0;
  25212. if (!this.paused) {
  25213. timeScale = this.timeScale;
  25214. const interpolant = this._timeScaleInterpolant;
  25215. if (interpolant !== null) {
  25216. const interpolantValue = interpolant.evaluate(time)[0];
  25217. timeScale *= interpolantValue;
  25218. if (time > interpolant.parameterPositions[1]) {
  25219. this.stopWarping();
  25220. if (timeScale === 0) {
  25221. // motion has halted, pause
  25222. this.paused = true;
  25223. } else {
  25224. // warp done - apply final time scale
  25225. this.timeScale = timeScale;
  25226. }
  25227. }
  25228. }
  25229. }
  25230. this._effectiveTimeScale = timeScale;
  25231. return timeScale;
  25232. }
  25233. _updateTime(deltaTime) {
  25234. const duration = this._clip.duration;
  25235. const loop = this.loop;
  25236. let time = this.time + deltaTime;
  25237. let loopCount = this._loopCount;
  25238. const pingPong = loop === LoopPingPong;
  25239. if (deltaTime === 0) {
  25240. if (loopCount === -1) return time;
  25241. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  25242. }
  25243. if (loop === LoopOnce) {
  25244. if (loopCount === -1) {
  25245. // just started
  25246. this._loopCount = 0;
  25247. this._setEndings(true, true, false);
  25248. }
  25249. handle_stop: {
  25250. if (time >= duration) {
  25251. time = duration;
  25252. } else if (time < 0) {
  25253. time = 0;
  25254. } else {
  25255. this.time = time;
  25256. break handle_stop;
  25257. }
  25258. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  25259. this.time = time;
  25260. this._mixer.dispatchEvent({
  25261. type: 'finished',
  25262. action: this,
  25263. direction: deltaTime < 0 ? -1 : 1
  25264. });
  25265. }
  25266. } else {
  25267. // repetitive Repeat or PingPong
  25268. if (loopCount === -1) {
  25269. // just started
  25270. if (deltaTime >= 0) {
  25271. loopCount = 0;
  25272. this._setEndings(true, this.repetitions === 0, pingPong);
  25273. } else {
  25274. // when looping in reverse direction, the initial
  25275. // transition through zero counts as a repetition,
  25276. // so leave loopCount at -1
  25277. this._setEndings(this.repetitions === 0, true, pingPong);
  25278. }
  25279. }
  25280. if (time >= duration || time < 0) {
  25281. // wrap around
  25282. const loopDelta = Math.floor(time / duration); // signed
  25283. time -= duration * loopDelta;
  25284. loopCount += Math.abs(loopDelta);
  25285. const pending = this.repetitions - loopCount;
  25286. if (pending <= 0) {
  25287. // have to stop (switch state, clamp time, fire event)
  25288. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  25289. time = deltaTime > 0 ? duration : 0;
  25290. this.time = time;
  25291. this._mixer.dispatchEvent({
  25292. type: 'finished',
  25293. action: this,
  25294. direction: deltaTime > 0 ? 1 : -1
  25295. });
  25296. } else {
  25297. // keep running
  25298. if (pending === 1) {
  25299. // entering the last round
  25300. const atStart = deltaTime < 0;
  25301. this._setEndings(atStart, !atStart, pingPong);
  25302. } else {
  25303. this._setEndings(false, false, pingPong);
  25304. }
  25305. this._loopCount = loopCount;
  25306. this.time = time;
  25307. this._mixer.dispatchEvent({
  25308. type: 'loop',
  25309. action: this,
  25310. loopDelta: loopDelta
  25311. });
  25312. }
  25313. } else {
  25314. this.time = time;
  25315. }
  25316. if (pingPong && (loopCount & 1) === 1) {
  25317. // invert time for the "pong round"
  25318. return duration - time;
  25319. }
  25320. }
  25321. return time;
  25322. }
  25323. _setEndings(atStart, atEnd, pingPong) {
  25324. const settings = this._interpolantSettings;
  25325. if (pingPong) {
  25326. settings.endingStart = ZeroSlopeEnding;
  25327. settings.endingEnd = ZeroSlopeEnding;
  25328. } else {
  25329. // assuming for LoopOnce atStart == atEnd == true
  25330. if (atStart) {
  25331. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  25332. } else {
  25333. settings.endingStart = WrapAroundEnding;
  25334. }
  25335. if (atEnd) {
  25336. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  25337. } else {
  25338. settings.endingEnd = WrapAroundEnding;
  25339. }
  25340. }
  25341. }
  25342. _scheduleFading(duration, weightNow, weightThen) {
  25343. const mixer = this._mixer,
  25344. now = mixer.time;
  25345. let interpolant = this._weightInterpolant;
  25346. if (interpolant === null) {
  25347. interpolant = mixer._lendControlInterpolant();
  25348. this._weightInterpolant = interpolant;
  25349. }
  25350. const times = interpolant.parameterPositions,
  25351. values = interpolant.sampleValues;
  25352. times[0] = now;
  25353. values[0] = weightNow;
  25354. times[1] = now + duration;
  25355. values[1] = weightThen;
  25356. return this;
  25357. }
  25358. }
  25359. class AnimationMixer extends EventDispatcher {
  25360. constructor(root) {
  25361. super();
  25362. this._root = root;
  25363. this._initMemoryManager();
  25364. this._accuIndex = 0;
  25365. this.time = 0;
  25366. this.timeScale = 1.0;
  25367. }
  25368. _bindAction(action, prototypeAction) {
  25369. const root = action._localRoot || this._root,
  25370. tracks = action._clip.tracks,
  25371. nTracks = tracks.length,
  25372. bindings = action._propertyBindings,
  25373. interpolants = action._interpolants,
  25374. rootUuid = root.uuid,
  25375. bindingsByRoot = this._bindingsByRootAndName;
  25376. let bindingsByName = bindingsByRoot[rootUuid];
  25377. if (bindingsByName === undefined) {
  25378. bindingsByName = {};
  25379. bindingsByRoot[rootUuid] = bindingsByName;
  25380. }
  25381. for (let i = 0; i !== nTracks; ++i) {
  25382. const track = tracks[i],
  25383. trackName = track.name;
  25384. let binding = bindingsByName[trackName];
  25385. if (binding !== undefined) {
  25386. bindings[i] = binding;
  25387. } else {
  25388. binding = bindings[i];
  25389. if (binding !== undefined) {
  25390. // existing binding, make sure the cache knows
  25391. if (binding._cacheIndex === null) {
  25392. ++binding.referenceCount;
  25393. this._addInactiveBinding(binding, rootUuid, trackName);
  25394. }
  25395. continue;
  25396. }
  25397. const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  25398. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  25399. ++binding.referenceCount;
  25400. this._addInactiveBinding(binding, rootUuid, trackName);
  25401. bindings[i] = binding;
  25402. }
  25403. interpolants[i].resultBuffer = binding.buffer;
  25404. }
  25405. }
  25406. _activateAction(action) {
  25407. if (!this._isActiveAction(action)) {
  25408. if (action._cacheIndex === null) {
  25409. // this action has been forgotten by the cache, but the user
  25410. // appears to be still using it -> rebind
  25411. const rootUuid = (action._localRoot || this._root).uuid,
  25412. clipUuid = action._clip.uuid,
  25413. actionsForClip = this._actionsByClip[clipUuid];
  25414. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  25415. this._addInactiveAction(action, clipUuid, rootUuid);
  25416. }
  25417. const bindings = action._propertyBindings; // increment reference counts / sort out state
  25418. for (let i = 0, n = bindings.length; i !== n; ++i) {
  25419. const binding = bindings[i];
  25420. if (binding.useCount++ === 0) {
  25421. this._lendBinding(binding);
  25422. binding.saveOriginalState();
  25423. }
  25424. }
  25425. this._lendAction(action);
  25426. }
  25427. }
  25428. _deactivateAction(action) {
  25429. if (this._isActiveAction(action)) {
  25430. const bindings = action._propertyBindings; // decrement reference counts / sort out state
  25431. for (let i = 0, n = bindings.length; i !== n; ++i) {
  25432. const binding = bindings[i];
  25433. if (--binding.useCount === 0) {
  25434. binding.restoreOriginalState();
  25435. this._takeBackBinding(binding);
  25436. }
  25437. }
  25438. this._takeBackAction(action);
  25439. }
  25440. } // Memory manager
  25441. _initMemoryManager() {
  25442. this._actions = []; // 'nActiveActions' followed by inactive ones
  25443. this._nActiveActions = 0;
  25444. this._actionsByClip = {}; // inside:
  25445. // {
  25446. // knownActions: Array< AnimationAction > - used as prototypes
  25447. // actionByRoot: AnimationAction - lookup
  25448. // }
  25449. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  25450. this._nActiveBindings = 0;
  25451. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  25452. this._controlInterpolants = []; // same game as above
  25453. this._nActiveControlInterpolants = 0;
  25454. const scope = this;
  25455. this.stats = {
  25456. actions: {
  25457. get total() {
  25458. return scope._actions.length;
  25459. },
  25460. get inUse() {
  25461. return scope._nActiveActions;
  25462. }
  25463. },
  25464. bindings: {
  25465. get total() {
  25466. return scope._bindings.length;
  25467. },
  25468. get inUse() {
  25469. return scope._nActiveBindings;
  25470. }
  25471. },
  25472. controlInterpolants: {
  25473. get total() {
  25474. return scope._controlInterpolants.length;
  25475. },
  25476. get inUse() {
  25477. return scope._nActiveControlInterpolants;
  25478. }
  25479. }
  25480. };
  25481. } // Memory management for AnimationAction objects
  25482. _isActiveAction(action) {
  25483. const index = action._cacheIndex;
  25484. return index !== null && index < this._nActiveActions;
  25485. }
  25486. _addInactiveAction(action, clipUuid, rootUuid) {
  25487. const actions = this._actions,
  25488. actionsByClip = this._actionsByClip;
  25489. let actionsForClip = actionsByClip[clipUuid];
  25490. if (actionsForClip === undefined) {
  25491. actionsForClip = {
  25492. knownActions: [action],
  25493. actionByRoot: {}
  25494. };
  25495. action._byClipCacheIndex = 0;
  25496. actionsByClip[clipUuid] = actionsForClip;
  25497. } else {
  25498. const knownActions = actionsForClip.knownActions;
  25499. action._byClipCacheIndex = knownActions.length;
  25500. knownActions.push(action);
  25501. }
  25502. action._cacheIndex = actions.length;
  25503. actions.push(action);
  25504. actionsForClip.actionByRoot[rootUuid] = action;
  25505. }
  25506. _removeInactiveAction(action) {
  25507. const actions = this._actions,
  25508. lastInactiveAction = actions[actions.length - 1],
  25509. cacheIndex = action._cacheIndex;
  25510. lastInactiveAction._cacheIndex = cacheIndex;
  25511. actions[cacheIndex] = lastInactiveAction;
  25512. actions.pop();
  25513. action._cacheIndex = null;
  25514. const clipUuid = action._clip.uuid,
  25515. actionsByClip = this._actionsByClip,
  25516. actionsForClip = actionsByClip[clipUuid],
  25517. knownActionsForClip = actionsForClip.knownActions,
  25518. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  25519. byClipCacheIndex = action._byClipCacheIndex;
  25520. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  25521. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  25522. knownActionsForClip.pop();
  25523. action._byClipCacheIndex = null;
  25524. const actionByRoot = actionsForClip.actionByRoot,
  25525. rootUuid = (action._localRoot || this._root).uuid;
  25526. delete actionByRoot[rootUuid];
  25527. if (knownActionsForClip.length === 0) {
  25528. delete actionsByClip[clipUuid];
  25529. }
  25530. this._removeInactiveBindingsForAction(action);
  25531. }
  25532. _removeInactiveBindingsForAction(action) {
  25533. const bindings = action._propertyBindings;
  25534. for (let i = 0, n = bindings.length; i !== n; ++i) {
  25535. const binding = bindings[i];
  25536. if (--binding.referenceCount === 0) {
  25537. this._removeInactiveBinding(binding);
  25538. }
  25539. }
  25540. }
  25541. _lendAction(action) {
  25542. // [ active actions | inactive actions ]
  25543. // [ active actions >| inactive actions ]
  25544. // s a
  25545. // <-swap->
  25546. // a s
  25547. const actions = this._actions,
  25548. prevIndex = action._cacheIndex,
  25549. lastActiveIndex = this._nActiveActions++,
  25550. firstInactiveAction = actions[lastActiveIndex];
  25551. action._cacheIndex = lastActiveIndex;
  25552. actions[lastActiveIndex] = action;
  25553. firstInactiveAction._cacheIndex = prevIndex;
  25554. actions[prevIndex] = firstInactiveAction;
  25555. }
  25556. _takeBackAction(action) {
  25557. // [ active actions | inactive actions ]
  25558. // [ active actions |< inactive actions ]
  25559. // a s
  25560. // <-swap->
  25561. // s a
  25562. const actions = this._actions,
  25563. prevIndex = action._cacheIndex,
  25564. firstInactiveIndex = --this._nActiveActions,
  25565. lastActiveAction = actions[firstInactiveIndex];
  25566. action._cacheIndex = firstInactiveIndex;
  25567. actions[firstInactiveIndex] = action;
  25568. lastActiveAction._cacheIndex = prevIndex;
  25569. actions[prevIndex] = lastActiveAction;
  25570. } // Memory management for PropertyMixer objects
  25571. _addInactiveBinding(binding, rootUuid, trackName) {
  25572. const bindingsByRoot = this._bindingsByRootAndName,
  25573. bindings = this._bindings;
  25574. let bindingByName = bindingsByRoot[rootUuid];
  25575. if (bindingByName === undefined) {
  25576. bindingByName = {};
  25577. bindingsByRoot[rootUuid] = bindingByName;
  25578. }
  25579. bindingByName[trackName] = binding;
  25580. binding._cacheIndex = bindings.length;
  25581. bindings.push(binding);
  25582. }
  25583. _removeInactiveBinding(binding) {
  25584. const bindings = this._bindings,
  25585. propBinding = binding.binding,
  25586. rootUuid = propBinding.rootNode.uuid,
  25587. trackName = propBinding.path,
  25588. bindingsByRoot = this._bindingsByRootAndName,
  25589. bindingByName = bindingsByRoot[rootUuid],
  25590. lastInactiveBinding = bindings[bindings.length - 1],
  25591. cacheIndex = binding._cacheIndex;
  25592. lastInactiveBinding._cacheIndex = cacheIndex;
  25593. bindings[cacheIndex] = lastInactiveBinding;
  25594. bindings.pop();
  25595. delete bindingByName[trackName];
  25596. if (Object.keys(bindingByName).length === 0) {
  25597. delete bindingsByRoot[rootUuid];
  25598. }
  25599. }
  25600. _lendBinding(binding) {
  25601. const bindings = this._bindings,
  25602. prevIndex = binding._cacheIndex,
  25603. lastActiveIndex = this._nActiveBindings++,
  25604. firstInactiveBinding = bindings[lastActiveIndex];
  25605. binding._cacheIndex = lastActiveIndex;
  25606. bindings[lastActiveIndex] = binding;
  25607. firstInactiveBinding._cacheIndex = prevIndex;
  25608. bindings[prevIndex] = firstInactiveBinding;
  25609. }
  25610. _takeBackBinding(binding) {
  25611. const bindings = this._bindings,
  25612. prevIndex = binding._cacheIndex,
  25613. firstInactiveIndex = --this._nActiveBindings,
  25614. lastActiveBinding = bindings[firstInactiveIndex];
  25615. binding._cacheIndex = firstInactiveIndex;
  25616. bindings[firstInactiveIndex] = binding;
  25617. lastActiveBinding._cacheIndex = prevIndex;
  25618. bindings[prevIndex] = lastActiveBinding;
  25619. } // Memory management of Interpolants for weight and time scale
  25620. _lendControlInterpolant() {
  25621. const interpolants = this._controlInterpolants,
  25622. lastActiveIndex = this._nActiveControlInterpolants++;
  25623. let interpolant = interpolants[lastActiveIndex];
  25624. if (interpolant === undefined) {
  25625. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  25626. interpolant.__cacheIndex = lastActiveIndex;
  25627. interpolants[lastActiveIndex] = interpolant;
  25628. }
  25629. return interpolant;
  25630. }
  25631. _takeBackControlInterpolant(interpolant) {
  25632. const interpolants = this._controlInterpolants,
  25633. prevIndex = interpolant.__cacheIndex,
  25634. firstInactiveIndex = --this._nActiveControlInterpolants,
  25635. lastActiveInterpolant = interpolants[firstInactiveIndex];
  25636. interpolant.__cacheIndex = firstInactiveIndex;
  25637. interpolants[firstInactiveIndex] = interpolant;
  25638. lastActiveInterpolant.__cacheIndex = prevIndex;
  25639. interpolants[prevIndex] = lastActiveInterpolant;
  25640. } // return an action for a clip optionally using a custom root target
  25641. // object (this method allocates a lot of dynamic memory in case a
  25642. // previously unknown clip/root combination is specified)
  25643. clipAction(clip, optionalRoot, blendMode) {
  25644. const root = optionalRoot || this._root,
  25645. rootUuid = root.uuid;
  25646. let clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
  25647. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  25648. const actionsForClip = this._actionsByClip[clipUuid];
  25649. let prototypeAction = null;
  25650. if (blendMode === undefined) {
  25651. if (clipObject !== null) {
  25652. blendMode = clipObject.blendMode;
  25653. } else {
  25654. blendMode = NormalAnimationBlendMode;
  25655. }
  25656. }
  25657. if (actionsForClip !== undefined) {
  25658. const existingAction = actionsForClip.actionByRoot[rootUuid];
  25659. if (existingAction !== undefined && existingAction.blendMode === blendMode) {
  25660. return existingAction;
  25661. } // we know the clip, so we don't have to parse all
  25662. // the bindings again but can just copy
  25663. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  25664. if (clipObject === null) clipObject = prototypeAction._clip;
  25665. } // clip must be known when specified via string
  25666. if (clipObject === null) return null; // allocate all resources required to run it
  25667. const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
  25668. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  25669. this._addInactiveAction(newAction, clipUuid, rootUuid);
  25670. return newAction;
  25671. } // get an existing action
  25672. existingAction(clip, optionalRoot) {
  25673. const root = optionalRoot || this._root,
  25674. rootUuid = root.uuid,
  25675. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  25676. clipUuid = clipObject ? clipObject.uuid : clip,
  25677. actionsForClip = this._actionsByClip[clipUuid];
  25678. if (actionsForClip !== undefined) {
  25679. return actionsForClip.actionByRoot[rootUuid] || null;
  25680. }
  25681. return null;
  25682. } // deactivates all previously scheduled actions
  25683. stopAllAction() {
  25684. const actions = this._actions,
  25685. nActions = this._nActiveActions;
  25686. for (let i = nActions - 1; i >= 0; --i) {
  25687. actions[i].stop();
  25688. }
  25689. return this;
  25690. } // advance the time and update apply the animation
  25691. update(deltaTime) {
  25692. deltaTime *= this.timeScale;
  25693. const actions = this._actions,
  25694. nActions = this._nActiveActions,
  25695. time = this.time += deltaTime,
  25696. timeDirection = Math.sign(deltaTime),
  25697. accuIndex = this._accuIndex ^= 1; // run active actions
  25698. for (let i = 0; i !== nActions; ++i) {
  25699. const action = actions[i];
  25700. action._update(time, deltaTime, timeDirection, accuIndex);
  25701. } // update scene graph
  25702. const bindings = this._bindings,
  25703. nBindings = this._nActiveBindings;
  25704. for (let i = 0; i !== nBindings; ++i) {
  25705. bindings[i].apply(accuIndex);
  25706. }
  25707. return this;
  25708. } // Allows you to seek to a specific time in an animation.
  25709. setTime(timeInSeconds) {
  25710. this.time = 0; // Zero out time attribute for AnimationMixer object;
  25711. for (let i = 0; i < this._actions.length; i++) {
  25712. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  25713. }
  25714. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  25715. } // return this mixer's root target object
  25716. getRoot() {
  25717. return this._root;
  25718. } // free all resources specific to a particular clip
  25719. uncacheClip(clip) {
  25720. const actions = this._actions,
  25721. clipUuid = clip.uuid,
  25722. actionsByClip = this._actionsByClip,
  25723. actionsForClip = actionsByClip[clipUuid];
  25724. if (actionsForClip !== undefined) {
  25725. // note: just calling _removeInactiveAction would mess up the
  25726. // iteration state and also require updating the state we can
  25727. // just throw away
  25728. const actionsToRemove = actionsForClip.knownActions;
  25729. for (let i = 0, n = actionsToRemove.length; i !== n; ++i) {
  25730. const action = actionsToRemove[i];
  25731. this._deactivateAction(action);
  25732. const cacheIndex = action._cacheIndex,
  25733. lastInactiveAction = actions[actions.length - 1];
  25734. action._cacheIndex = null;
  25735. action._byClipCacheIndex = null;
  25736. lastInactiveAction._cacheIndex = cacheIndex;
  25737. actions[cacheIndex] = lastInactiveAction;
  25738. actions.pop();
  25739. this._removeInactiveBindingsForAction(action);
  25740. }
  25741. delete actionsByClip[clipUuid];
  25742. }
  25743. } // free all resources specific to a particular root target object
  25744. uncacheRoot(root) {
  25745. const rootUuid = root.uuid,
  25746. actionsByClip = this._actionsByClip;
  25747. for (const clipUuid in actionsByClip) {
  25748. const actionByRoot = actionsByClip[clipUuid].actionByRoot,
  25749. action = actionByRoot[rootUuid];
  25750. if (action !== undefined) {
  25751. this._deactivateAction(action);
  25752. this._removeInactiveAction(action);
  25753. }
  25754. }
  25755. const bindingsByRoot = this._bindingsByRootAndName,
  25756. bindingByName = bindingsByRoot[rootUuid];
  25757. if (bindingByName !== undefined) {
  25758. for (const trackName in bindingByName) {
  25759. const binding = bindingByName[trackName];
  25760. binding.restoreOriginalState();
  25761. this._removeInactiveBinding(binding);
  25762. }
  25763. }
  25764. } // remove a targeted clip from the cache
  25765. uncacheAction(clip, optionalRoot) {
  25766. const action = this.existingAction(clip, optionalRoot);
  25767. if (action !== null) {
  25768. this._deactivateAction(action);
  25769. this._removeInactiveAction(action);
  25770. }
  25771. }
  25772. }
  25773. AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array(1);
  25774. class Uniform {
  25775. constructor(value) {
  25776. if (typeof value === 'string') {
  25777. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  25778. value = arguments[1];
  25779. }
  25780. this.value = value;
  25781. }
  25782. clone() {
  25783. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  25784. }
  25785. }
  25786. class InstancedInterleavedBuffer extends InterleavedBuffer {
  25787. constructor(array, stride, meshPerAttribute = 1) {
  25788. super(array, stride);
  25789. this.meshPerAttribute = meshPerAttribute || 1;
  25790. }
  25791. copy(source) {
  25792. super.copy(source);
  25793. this.meshPerAttribute = source.meshPerAttribute;
  25794. return this;
  25795. }
  25796. clone(data) {
  25797. const ib = super.clone(data);
  25798. ib.meshPerAttribute = this.meshPerAttribute;
  25799. return ib;
  25800. }
  25801. toJSON(data) {
  25802. const json = super.toJSON(data);
  25803. json.isInstancedInterleavedBuffer = true;
  25804. json.meshPerAttribute = this.meshPerAttribute;
  25805. return json;
  25806. }
  25807. }
  25808. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  25809. class GLBufferAttribute {
  25810. constructor(buffer, type, itemSize, elementSize, count) {
  25811. this.buffer = buffer;
  25812. this.type = type;
  25813. this.itemSize = itemSize;
  25814. this.elementSize = elementSize;
  25815. this.count = count;
  25816. this.version = 0;
  25817. }
  25818. set needsUpdate(value) {
  25819. if (value === true) this.version++;
  25820. }
  25821. setBuffer(buffer) {
  25822. this.buffer = buffer;
  25823. return this;
  25824. }
  25825. setType(type, elementSize) {
  25826. this.type = type;
  25827. this.elementSize = elementSize;
  25828. return this;
  25829. }
  25830. setItemSize(itemSize) {
  25831. this.itemSize = itemSize;
  25832. return this;
  25833. }
  25834. setCount(count) {
  25835. this.count = count;
  25836. return this;
  25837. }
  25838. }
  25839. GLBufferAttribute.prototype.isGLBufferAttribute = true;
  25840. class Raycaster {
  25841. constructor(origin, direction, near = 0, far = Infinity) {
  25842. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  25843. this.near = near;
  25844. this.far = far;
  25845. this.camera = null;
  25846. this.layers = new Layers();
  25847. this.params = {
  25848. Mesh: {},
  25849. Line: {
  25850. threshold: 1
  25851. },
  25852. LOD: {},
  25853. Points: {
  25854. threshold: 1
  25855. },
  25856. Sprite: {}
  25857. };
  25858. }
  25859. set(origin, direction) {
  25860. // direction is assumed to be normalized (for accurate distance calculations)
  25861. this.ray.set(origin, direction);
  25862. }
  25863. setFromCamera(coords, camera) {
  25864. if (camera && camera.isPerspectiveCamera) {
  25865. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  25866. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  25867. this.camera = camera;
  25868. } else if (camera && camera.isOrthographicCamera) {
  25869. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  25870. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  25871. this.camera = camera;
  25872. } else {
  25873. console.error('THREE.Raycaster: Unsupported camera type: ' + camera.type);
  25874. }
  25875. }
  25876. intersectObject(object, recursive = false, intersects = []) {
  25877. intersectObject(object, this, intersects, recursive);
  25878. intersects.sort(ascSort);
  25879. return intersects;
  25880. }
  25881. intersectObjects(objects, recursive = false, intersects = []) {
  25882. for (let i = 0, l = objects.length; i < l; i++) {
  25883. intersectObject(objects[i], this, intersects, recursive);
  25884. }
  25885. intersects.sort(ascSort);
  25886. return intersects;
  25887. }
  25888. }
  25889. function ascSort(a, b) {
  25890. return a.distance - b.distance;
  25891. }
  25892. function intersectObject(object, raycaster, intersects, recursive) {
  25893. if (object.layers.test(raycaster.layers)) {
  25894. object.raycast(raycaster, intersects);
  25895. }
  25896. if (recursive === true) {
  25897. const children = object.children;
  25898. for (let i = 0, l = children.length; i < l; i++) {
  25899. intersectObject(children[i], raycaster, intersects, true);
  25900. }
  25901. }
  25902. }
  25903. /**
  25904. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  25905. *
  25906. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  25907. * The azimuthal angle (theta) is measured from the positive z-axis.
  25908. */
  25909. class Spherical {
  25910. constructor(radius = 1, phi = 0, theta = 0) {
  25911. this.radius = radius;
  25912. this.phi = phi; // polar angle
  25913. this.theta = theta; // azimuthal angle
  25914. return this;
  25915. }
  25916. set(radius, phi, theta) {
  25917. this.radius = radius;
  25918. this.phi = phi;
  25919. this.theta = theta;
  25920. return this;
  25921. }
  25922. copy(other) {
  25923. this.radius = other.radius;
  25924. this.phi = other.phi;
  25925. this.theta = other.theta;
  25926. return this;
  25927. } // restrict phi to be betwee EPS and PI-EPS
  25928. makeSafe() {
  25929. const EPS = 0.000001;
  25930. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  25931. return this;
  25932. }
  25933. setFromVector3(v) {
  25934. return this.setFromCartesianCoords(v.x, v.y, v.z);
  25935. }
  25936. setFromCartesianCoords(x, y, z) {
  25937. this.radius = Math.sqrt(x * x + y * y + z * z);
  25938. if (this.radius === 0) {
  25939. this.theta = 0;
  25940. this.phi = 0;
  25941. } else {
  25942. this.theta = Math.atan2(x, z);
  25943. this.phi = Math.acos(clamp(y / this.radius, -1, 1));
  25944. }
  25945. return this;
  25946. }
  25947. clone() {
  25948. return new this.constructor().copy(this);
  25949. }
  25950. }
  25951. /**
  25952. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  25953. */
  25954. class Cylindrical {
  25955. constructor(radius = 1, theta = 0, y = 0) {
  25956. this.radius = radius; // distance from the origin to a point in the x-z plane
  25957. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  25958. this.y = y; // height above the x-z plane
  25959. return this;
  25960. }
  25961. set(radius, theta, y) {
  25962. this.radius = radius;
  25963. this.theta = theta;
  25964. this.y = y;
  25965. return this;
  25966. }
  25967. copy(other) {
  25968. this.radius = other.radius;
  25969. this.theta = other.theta;
  25970. this.y = other.y;
  25971. return this;
  25972. }
  25973. setFromVector3(v) {
  25974. return this.setFromCartesianCoords(v.x, v.y, v.z);
  25975. }
  25976. setFromCartesianCoords(x, y, z) {
  25977. this.radius = Math.sqrt(x * x + z * z);
  25978. this.theta = Math.atan2(x, z);
  25979. this.y = y;
  25980. return this;
  25981. }
  25982. clone() {
  25983. return new this.constructor().copy(this);
  25984. }
  25985. }
  25986. const _vector$4 = /*@__PURE__*/new Vector2();
  25987. class Box2 {
  25988. constructor(min = new Vector2(+Infinity, +Infinity), max = new Vector2(-Infinity, -Infinity)) {
  25989. this.min = min;
  25990. this.max = max;
  25991. }
  25992. set(min, max) {
  25993. this.min.copy(min);
  25994. this.max.copy(max);
  25995. return this;
  25996. }
  25997. setFromPoints(points) {
  25998. this.makeEmpty();
  25999. for (let i = 0, il = points.length; i < il; i++) {
  26000. this.expandByPoint(points[i]);
  26001. }
  26002. return this;
  26003. }
  26004. setFromCenterAndSize(center, size) {
  26005. const halfSize = _vector$4.copy(size).multiplyScalar(0.5);
  26006. this.min.copy(center).sub(halfSize);
  26007. this.max.copy(center).add(halfSize);
  26008. return this;
  26009. }
  26010. clone() {
  26011. return new this.constructor().copy(this);
  26012. }
  26013. copy(box) {
  26014. this.min.copy(box.min);
  26015. this.max.copy(box.max);
  26016. return this;
  26017. }
  26018. makeEmpty() {
  26019. this.min.x = this.min.y = +Infinity;
  26020. this.max.x = this.max.y = -Infinity;
  26021. return this;
  26022. }
  26023. isEmpty() {
  26024. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  26025. return this.max.x < this.min.x || this.max.y < this.min.y;
  26026. }
  26027. getCenter(target) {
  26028. if (target === undefined) {
  26029. console.warn('THREE.Box2: .getCenter() target is now required');
  26030. target = new Vector2();
  26031. }
  26032. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  26033. }
  26034. getSize(target) {
  26035. if (target === undefined) {
  26036. console.warn('THREE.Box2: .getSize() target is now required');
  26037. target = new Vector2();
  26038. }
  26039. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  26040. }
  26041. expandByPoint(point) {
  26042. this.min.min(point);
  26043. this.max.max(point);
  26044. return this;
  26045. }
  26046. expandByVector(vector) {
  26047. this.min.sub(vector);
  26048. this.max.add(vector);
  26049. return this;
  26050. }
  26051. expandByScalar(scalar) {
  26052. this.min.addScalar(-scalar);
  26053. this.max.addScalar(scalar);
  26054. return this;
  26055. }
  26056. containsPoint(point) {
  26057. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  26058. }
  26059. containsBox(box) {
  26060. 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;
  26061. }
  26062. getParameter(point, target) {
  26063. // This can potentially have a divide by zero if the box
  26064. // has a size dimension of 0.
  26065. if (target === undefined) {
  26066. console.warn('THREE.Box2: .getParameter() target is now required');
  26067. target = new Vector2();
  26068. }
  26069. 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));
  26070. }
  26071. intersectsBox(box) {
  26072. // using 4 splitting planes to rule out intersections
  26073. 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;
  26074. }
  26075. clampPoint(point, target) {
  26076. if (target === undefined) {
  26077. console.warn('THREE.Box2: .clampPoint() target is now required');
  26078. target = new Vector2();
  26079. }
  26080. return target.copy(point).clamp(this.min, this.max);
  26081. }
  26082. distanceToPoint(point) {
  26083. const clampedPoint = _vector$4.copy(point).clamp(this.min, this.max);
  26084. return clampedPoint.sub(point).length();
  26085. }
  26086. intersect(box) {
  26087. this.min.max(box.min);
  26088. this.max.min(box.max);
  26089. return this;
  26090. }
  26091. union(box) {
  26092. this.min.min(box.min);
  26093. this.max.max(box.max);
  26094. return this;
  26095. }
  26096. translate(offset) {
  26097. this.min.add(offset);
  26098. this.max.add(offset);
  26099. return this;
  26100. }
  26101. equals(box) {
  26102. return box.min.equals(this.min) && box.max.equals(this.max);
  26103. }
  26104. }
  26105. Box2.prototype.isBox2 = true;
  26106. const _startP = /*@__PURE__*/new Vector3();
  26107. const _startEnd = /*@__PURE__*/new Vector3();
  26108. class Line3 {
  26109. constructor(start = new Vector3(), end = new Vector3()) {
  26110. this.start = start;
  26111. this.end = end;
  26112. }
  26113. set(start, end) {
  26114. this.start.copy(start);
  26115. this.end.copy(end);
  26116. return this;
  26117. }
  26118. copy(line) {
  26119. this.start.copy(line.start);
  26120. this.end.copy(line.end);
  26121. return this;
  26122. }
  26123. getCenter(target) {
  26124. if (target === undefined) {
  26125. console.warn('THREE.Line3: .getCenter() target is now required');
  26126. target = new Vector3();
  26127. }
  26128. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  26129. }
  26130. delta(target) {
  26131. if (target === undefined) {
  26132. console.warn('THREE.Line3: .delta() target is now required');
  26133. target = new Vector3();
  26134. }
  26135. return target.subVectors(this.end, this.start);
  26136. }
  26137. distanceSq() {
  26138. return this.start.distanceToSquared(this.end);
  26139. }
  26140. distance() {
  26141. return this.start.distanceTo(this.end);
  26142. }
  26143. at(t, target) {
  26144. if (target === undefined) {
  26145. console.warn('THREE.Line3: .at() target is now required');
  26146. target = new Vector3();
  26147. }
  26148. return this.delta(target).multiplyScalar(t).add(this.start);
  26149. }
  26150. closestPointToPointParameter(point, clampToLine) {
  26151. _startP.subVectors(point, this.start);
  26152. _startEnd.subVectors(this.end, this.start);
  26153. const startEnd2 = _startEnd.dot(_startEnd);
  26154. const startEnd_startP = _startEnd.dot(_startP);
  26155. let t = startEnd_startP / startEnd2;
  26156. if (clampToLine) {
  26157. t = clamp(t, 0, 1);
  26158. }
  26159. return t;
  26160. }
  26161. closestPointToPoint(point, clampToLine, target) {
  26162. const t = this.closestPointToPointParameter(point, clampToLine);
  26163. if (target === undefined) {
  26164. console.warn('THREE.Line3: .closestPointToPoint() target is now required');
  26165. target = new Vector3();
  26166. }
  26167. return this.delta(target).multiplyScalar(t).add(this.start);
  26168. }
  26169. applyMatrix4(matrix) {
  26170. this.start.applyMatrix4(matrix);
  26171. this.end.applyMatrix4(matrix);
  26172. return this;
  26173. }
  26174. equals(line) {
  26175. return line.start.equals(this.start) && line.end.equals(this.end);
  26176. }
  26177. clone() {
  26178. return new this.constructor().copy(this);
  26179. }
  26180. }
  26181. class ImmediateRenderObject extends Object3D {
  26182. constructor(material) {
  26183. super();
  26184. this.material = material;
  26185. this.render = function ()
  26186. /* renderCallback */
  26187. {};
  26188. this.hasPositions = false;
  26189. this.hasNormals = false;
  26190. this.hasColors = false;
  26191. this.hasUvs = false;
  26192. this.positionArray = null;
  26193. this.normalArray = null;
  26194. this.colorArray = null;
  26195. this.uvArray = null;
  26196. this.count = 0;
  26197. }
  26198. }
  26199. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  26200. const _vector$3 = /*@__PURE__*/new Vector3();
  26201. class SpotLightHelper extends Object3D {
  26202. constructor(light, color) {
  26203. super();
  26204. this.light = light;
  26205. this.light.updateMatrixWorld();
  26206. this.matrix = light.matrixWorld;
  26207. this.matrixAutoUpdate = false;
  26208. this.color = color;
  26209. const geometry = new BufferGeometry();
  26210. 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];
  26211. for (let i = 0, j = 1, l = 32; i < l; i++, j++) {
  26212. const p1 = i / l * Math.PI * 2;
  26213. const p2 = j / l * Math.PI * 2;
  26214. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  26215. }
  26216. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  26217. const material = new LineBasicMaterial({
  26218. fog: false,
  26219. toneMapped: false
  26220. });
  26221. this.cone = new LineSegments(geometry, material);
  26222. this.add(this.cone);
  26223. this.update();
  26224. }
  26225. dispose() {
  26226. this.cone.geometry.dispose();
  26227. this.cone.material.dispose();
  26228. }
  26229. update() {
  26230. this.light.updateMatrixWorld();
  26231. const coneLength = this.light.distance ? this.light.distance : 1000;
  26232. const coneWidth = coneLength * Math.tan(this.light.angle);
  26233. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  26234. _vector$3.setFromMatrixPosition(this.light.target.matrixWorld);
  26235. this.cone.lookAt(_vector$3);
  26236. if (this.color !== undefined) {
  26237. this.cone.material.color.set(this.color);
  26238. } else {
  26239. this.cone.material.color.copy(this.light.color);
  26240. }
  26241. }
  26242. }
  26243. const _vector$2 = /*@__PURE__*/new Vector3();
  26244. const _boneMatrix = /*@__PURE__*/new Matrix4();
  26245. const _matrixWorldInv = /*@__PURE__*/new Matrix4();
  26246. class SkeletonHelper extends LineSegments {
  26247. constructor(object) {
  26248. const bones = getBoneList(object);
  26249. const geometry = new BufferGeometry();
  26250. const vertices = [];
  26251. const colors = [];
  26252. const color1 = new Color(0, 0, 1);
  26253. const color2 = new Color(0, 1, 0);
  26254. for (let i = 0; i < bones.length; i++) {
  26255. const bone = bones[i];
  26256. if (bone.parent && bone.parent.isBone) {
  26257. vertices.push(0, 0, 0);
  26258. vertices.push(0, 0, 0);
  26259. colors.push(color1.r, color1.g, color1.b);
  26260. colors.push(color2.r, color2.g, color2.b);
  26261. }
  26262. }
  26263. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26264. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26265. const material = new LineBasicMaterial({
  26266. vertexColors: true,
  26267. depthTest: false,
  26268. depthWrite: false,
  26269. toneMapped: false,
  26270. transparent: true
  26271. });
  26272. super(geometry, material);
  26273. this.type = 'SkeletonHelper';
  26274. this.isSkeletonHelper = true;
  26275. this.root = object;
  26276. this.bones = bones;
  26277. this.matrix = object.matrixWorld;
  26278. this.matrixAutoUpdate = false;
  26279. }
  26280. updateMatrixWorld(force) {
  26281. const bones = this.bones;
  26282. const geometry = this.geometry;
  26283. const position = geometry.getAttribute('position');
  26284. _matrixWorldInv.copy(this.root.matrixWorld).invert();
  26285. for (let i = 0, j = 0; i < bones.length; i++) {
  26286. const bone = bones[i];
  26287. if (bone.parent && bone.parent.isBone) {
  26288. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  26289. _vector$2.setFromMatrixPosition(_boneMatrix);
  26290. position.setXYZ(j, _vector$2.x, _vector$2.y, _vector$2.z);
  26291. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  26292. _vector$2.setFromMatrixPosition(_boneMatrix);
  26293. position.setXYZ(j + 1, _vector$2.x, _vector$2.y, _vector$2.z);
  26294. j += 2;
  26295. }
  26296. }
  26297. geometry.getAttribute('position').needsUpdate = true;
  26298. super.updateMatrixWorld(force);
  26299. }
  26300. }
  26301. function getBoneList(object) {
  26302. const boneList = [];
  26303. if (object && object.isBone) {
  26304. boneList.push(object);
  26305. }
  26306. for (let i = 0; i < object.children.length; i++) {
  26307. boneList.push.apply(boneList, getBoneList(object.children[i]));
  26308. }
  26309. return boneList;
  26310. }
  26311. class PointLightHelper extends Mesh {
  26312. constructor(light, sphereSize, color) {
  26313. const geometry = new SphereGeometry(sphereSize, 4, 2);
  26314. const material = new MeshBasicMaterial({
  26315. wireframe: true,
  26316. fog: false,
  26317. toneMapped: false
  26318. });
  26319. super(geometry, material);
  26320. this.light = light;
  26321. this.light.updateMatrixWorld();
  26322. this.color = color;
  26323. this.type = 'PointLightHelper';
  26324. this.matrix = this.light.matrixWorld;
  26325. this.matrixAutoUpdate = false;
  26326. this.update();
  26327. /*
  26328. // TODO: delete this comment?
  26329. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  26330. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  26331. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  26332. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  26333. const d = light.distance;
  26334. if ( d === 0.0 ) {
  26335. this.lightDistance.visible = false;
  26336. } else {
  26337. this.lightDistance.scale.set( d, d, d );
  26338. }
  26339. this.add( this.lightDistance );
  26340. */
  26341. }
  26342. dispose() {
  26343. this.geometry.dispose();
  26344. this.material.dispose();
  26345. }
  26346. update() {
  26347. if (this.color !== undefined) {
  26348. this.material.color.set(this.color);
  26349. } else {
  26350. this.material.color.copy(this.light.color);
  26351. }
  26352. /*
  26353. const d = this.light.distance;
  26354. if ( d === 0.0 ) {
  26355. this.lightDistance.visible = false;
  26356. } else {
  26357. this.lightDistance.visible = true;
  26358. this.lightDistance.scale.set( d, d, d );
  26359. }
  26360. */
  26361. }
  26362. }
  26363. const _vector$1 = /*@__PURE__*/new Vector3();
  26364. const _color1 = /*@__PURE__*/new Color();
  26365. const _color2 = /*@__PURE__*/new Color();
  26366. class HemisphereLightHelper extends Object3D {
  26367. constructor(light, size, color) {
  26368. super();
  26369. this.light = light;
  26370. this.light.updateMatrixWorld();
  26371. this.matrix = light.matrixWorld;
  26372. this.matrixAutoUpdate = false;
  26373. this.color = color;
  26374. const geometry = new OctahedronGeometry(size);
  26375. geometry.rotateY(Math.PI * 0.5);
  26376. this.material = new MeshBasicMaterial({
  26377. wireframe: true,
  26378. fog: false,
  26379. toneMapped: false
  26380. });
  26381. if (this.color === undefined) this.material.vertexColors = true;
  26382. const position = geometry.getAttribute('position');
  26383. const colors = new Float32Array(position.count * 3);
  26384. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  26385. this.add(new Mesh(geometry, this.material));
  26386. this.update();
  26387. }
  26388. dispose() {
  26389. this.children[0].geometry.dispose();
  26390. this.children[0].material.dispose();
  26391. }
  26392. update() {
  26393. const mesh = this.children[0];
  26394. if (this.color !== undefined) {
  26395. this.material.color.set(this.color);
  26396. } else {
  26397. const colors = mesh.geometry.getAttribute('color');
  26398. _color1.copy(this.light.color);
  26399. _color2.copy(this.light.groundColor);
  26400. for (let i = 0, l = colors.count; i < l; i++) {
  26401. const color = i < l / 2 ? _color1 : _color2;
  26402. colors.setXYZ(i, color.r, color.g, color.b);
  26403. }
  26404. colors.needsUpdate = true;
  26405. }
  26406. mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate());
  26407. }
  26408. }
  26409. class GridHelper extends LineSegments {
  26410. constructor(size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888) {
  26411. color1 = new Color(color1);
  26412. color2 = new Color(color2);
  26413. const center = divisions / 2;
  26414. const step = size / divisions;
  26415. const halfSize = size / 2;
  26416. const vertices = [],
  26417. colors = [];
  26418. for (let i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  26419. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  26420. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  26421. const color = i === center ? color1 : color2;
  26422. color.toArray(colors, j);
  26423. j += 3;
  26424. color.toArray(colors, j);
  26425. j += 3;
  26426. color.toArray(colors, j);
  26427. j += 3;
  26428. color.toArray(colors, j);
  26429. j += 3;
  26430. }
  26431. const geometry = new BufferGeometry();
  26432. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26433. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26434. const material = new LineBasicMaterial({
  26435. vertexColors: true,
  26436. toneMapped: false
  26437. });
  26438. super(geometry, material);
  26439. this.type = 'GridHelper';
  26440. }
  26441. }
  26442. class PolarGridHelper extends LineSegments {
  26443. constructor(radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888) {
  26444. color1 = new Color(color1);
  26445. color2 = new Color(color2);
  26446. const vertices = [];
  26447. const colors = []; // create the radials
  26448. for (let i = 0; i <= radials; i++) {
  26449. const v = i / radials * (Math.PI * 2);
  26450. const x = Math.sin(v) * radius;
  26451. const z = Math.cos(v) * radius;
  26452. vertices.push(0, 0, 0);
  26453. vertices.push(x, 0, z);
  26454. const color = i & 1 ? color1 : color2;
  26455. colors.push(color.r, color.g, color.b);
  26456. colors.push(color.r, color.g, color.b);
  26457. } // create the circles
  26458. for (let i = 0; i <= circles; i++) {
  26459. const color = i & 1 ? color1 : color2;
  26460. const r = radius - radius / circles * i;
  26461. for (let j = 0; j < divisions; j++) {
  26462. // first vertex
  26463. let v = j / divisions * (Math.PI * 2);
  26464. let x = Math.sin(v) * r;
  26465. let z = Math.cos(v) * r;
  26466. vertices.push(x, 0, z);
  26467. colors.push(color.r, color.g, color.b); // second vertex
  26468. v = (j + 1) / divisions * (Math.PI * 2);
  26469. x = Math.sin(v) * r;
  26470. z = Math.cos(v) * r;
  26471. vertices.push(x, 0, z);
  26472. colors.push(color.r, color.g, color.b);
  26473. }
  26474. }
  26475. const geometry = new BufferGeometry();
  26476. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26477. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26478. const material = new LineBasicMaterial({
  26479. vertexColors: true,
  26480. toneMapped: false
  26481. });
  26482. super(geometry, material);
  26483. this.type = 'PolarGridHelper';
  26484. }
  26485. }
  26486. const _v1 = /*@__PURE__*/new Vector3();
  26487. const _v2 = /*@__PURE__*/new Vector3();
  26488. const _v3 = /*@__PURE__*/new Vector3();
  26489. class DirectionalLightHelper extends Object3D {
  26490. constructor(light, size, color) {
  26491. super();
  26492. this.light = light;
  26493. this.light.updateMatrixWorld();
  26494. this.matrix = light.matrixWorld;
  26495. this.matrixAutoUpdate = false;
  26496. this.color = color;
  26497. if (size === undefined) size = 1;
  26498. let geometry = new BufferGeometry();
  26499. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  26500. const material = new LineBasicMaterial({
  26501. fog: false,
  26502. toneMapped: false
  26503. });
  26504. this.lightPlane = new Line(geometry, material);
  26505. this.add(this.lightPlane);
  26506. geometry = new BufferGeometry();
  26507. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  26508. this.targetLine = new Line(geometry, material);
  26509. this.add(this.targetLine);
  26510. this.update();
  26511. }
  26512. dispose() {
  26513. this.lightPlane.geometry.dispose();
  26514. this.lightPlane.material.dispose();
  26515. this.targetLine.geometry.dispose();
  26516. this.targetLine.material.dispose();
  26517. }
  26518. update() {
  26519. _v1.setFromMatrixPosition(this.light.matrixWorld);
  26520. _v2.setFromMatrixPosition(this.light.target.matrixWorld);
  26521. _v3.subVectors(_v2, _v1);
  26522. this.lightPlane.lookAt(_v2);
  26523. if (this.color !== undefined) {
  26524. this.lightPlane.material.color.set(this.color);
  26525. this.targetLine.material.color.set(this.color);
  26526. } else {
  26527. this.lightPlane.material.color.copy(this.light.color);
  26528. this.targetLine.material.color.copy(this.light.color);
  26529. }
  26530. this.targetLine.lookAt(_v2);
  26531. this.targetLine.scale.z = _v3.length();
  26532. }
  26533. }
  26534. const _vector = /*@__PURE__*/new Vector3();
  26535. const _camera = /*@__PURE__*/new Camera();
  26536. /**
  26537. * - shows frustum, line of sight and up of the camera
  26538. * - suitable for fast updates
  26539. * - based on frustum visualization in lightgl.js shadowmap example
  26540. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  26541. */
  26542. class CameraHelper extends LineSegments {
  26543. constructor(camera) {
  26544. const geometry = new BufferGeometry();
  26545. const material = new LineBasicMaterial({
  26546. color: 0xffffff,
  26547. vertexColors: true,
  26548. toneMapped: false
  26549. });
  26550. const vertices = [];
  26551. const colors = [];
  26552. const pointMap = {}; // colors
  26553. const colorFrustum = new Color(0xffaa00);
  26554. const colorCone = new Color(0xff0000);
  26555. const colorUp = new Color(0x00aaff);
  26556. const colorTarget = new Color(0xffffff);
  26557. const colorCross = new Color(0x333333); // near
  26558. addLine('n1', 'n2', colorFrustum);
  26559. addLine('n2', 'n4', colorFrustum);
  26560. addLine('n4', 'n3', colorFrustum);
  26561. addLine('n3', 'n1', colorFrustum); // far
  26562. addLine('f1', 'f2', colorFrustum);
  26563. addLine('f2', 'f4', colorFrustum);
  26564. addLine('f4', 'f3', colorFrustum);
  26565. addLine('f3', 'f1', colorFrustum); // sides
  26566. addLine('n1', 'f1', colorFrustum);
  26567. addLine('n2', 'f2', colorFrustum);
  26568. addLine('n3', 'f3', colorFrustum);
  26569. addLine('n4', 'f4', colorFrustum); // cone
  26570. addLine('p', 'n1', colorCone);
  26571. addLine('p', 'n2', colorCone);
  26572. addLine('p', 'n3', colorCone);
  26573. addLine('p', 'n4', colorCone); // up
  26574. addLine('u1', 'u2', colorUp);
  26575. addLine('u2', 'u3', colorUp);
  26576. addLine('u3', 'u1', colorUp); // target
  26577. addLine('c', 't', colorTarget);
  26578. addLine('p', 'c', colorCross); // cross
  26579. addLine('cn1', 'cn2', colorCross);
  26580. addLine('cn3', 'cn4', colorCross);
  26581. addLine('cf1', 'cf2', colorCross);
  26582. addLine('cf3', 'cf4', colorCross);
  26583. function addLine(a, b, color) {
  26584. addPoint(a, color);
  26585. addPoint(b, color);
  26586. }
  26587. function addPoint(id, color) {
  26588. vertices.push(0, 0, 0);
  26589. colors.push(color.r, color.g, color.b);
  26590. if (pointMap[id] === undefined) {
  26591. pointMap[id] = [];
  26592. }
  26593. pointMap[id].push(vertices.length / 3 - 1);
  26594. }
  26595. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26596. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26597. super(geometry, material);
  26598. this.type = 'CameraHelper';
  26599. this.camera = camera;
  26600. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  26601. this.matrix = camera.matrixWorld;
  26602. this.matrixAutoUpdate = false;
  26603. this.pointMap = pointMap;
  26604. this.update();
  26605. }
  26606. update() {
  26607. const geometry = this.geometry;
  26608. const pointMap = this.pointMap;
  26609. const w = 1,
  26610. h = 1; // we need just camera projection matrix inverse
  26611. // world matrix must be identity
  26612. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  26613. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  26614. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  26615. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  26616. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  26617. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  26618. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  26619. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  26620. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  26621. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  26622. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  26623. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  26624. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  26625. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  26626. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  26627. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  26628. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  26629. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  26630. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  26631. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  26632. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  26633. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  26634. geometry.getAttribute('position').needsUpdate = true;
  26635. }
  26636. dispose() {
  26637. this.geometry.dispose();
  26638. this.material.dispose();
  26639. }
  26640. }
  26641. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  26642. _vector.set(x, y, z).unproject(camera);
  26643. const points = pointMap[point];
  26644. if (points !== undefined) {
  26645. const position = geometry.getAttribute('position');
  26646. for (let i = 0, l = points.length; i < l; i++) {
  26647. position.setXYZ(points[i], _vector.x, _vector.y, _vector.z);
  26648. }
  26649. }
  26650. }
  26651. const _box = /*@__PURE__*/new Box3();
  26652. class BoxHelper extends LineSegments {
  26653. constructor(object, color = 0xffff00) {
  26654. 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]);
  26655. const positions = new Float32Array(8 * 3);
  26656. const geometry = new BufferGeometry();
  26657. geometry.setIndex(new BufferAttribute(indices, 1));
  26658. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  26659. super(geometry, new LineBasicMaterial({
  26660. color: color,
  26661. toneMapped: false
  26662. }));
  26663. this.object = object;
  26664. this.type = 'BoxHelper';
  26665. this.matrixAutoUpdate = false;
  26666. this.update();
  26667. }
  26668. update(object) {
  26669. if (object !== undefined) {
  26670. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  26671. }
  26672. if (this.object !== undefined) {
  26673. _box.setFromObject(this.object);
  26674. }
  26675. if (_box.isEmpty()) return;
  26676. const min = _box.min;
  26677. const max = _box.max;
  26678. /*
  26679. 5____4
  26680. 1/___0/|
  26681. | 6__|_7
  26682. 2/___3/
  26683. 0: max.x, max.y, max.z
  26684. 1: min.x, max.y, max.z
  26685. 2: min.x, min.y, max.z
  26686. 3: max.x, min.y, max.z
  26687. 4: max.x, max.y, min.z
  26688. 5: min.x, max.y, min.z
  26689. 6: min.x, min.y, min.z
  26690. 7: max.x, min.y, min.z
  26691. */
  26692. const position = this.geometry.attributes.position;
  26693. const array = position.array;
  26694. array[0] = max.x;
  26695. array[1] = max.y;
  26696. array[2] = max.z;
  26697. array[3] = min.x;
  26698. array[4] = max.y;
  26699. array[5] = max.z;
  26700. array[6] = min.x;
  26701. array[7] = min.y;
  26702. array[8] = max.z;
  26703. array[9] = max.x;
  26704. array[10] = min.y;
  26705. array[11] = max.z;
  26706. array[12] = max.x;
  26707. array[13] = max.y;
  26708. array[14] = min.z;
  26709. array[15] = min.x;
  26710. array[16] = max.y;
  26711. array[17] = min.z;
  26712. array[18] = min.x;
  26713. array[19] = min.y;
  26714. array[20] = min.z;
  26715. array[21] = max.x;
  26716. array[22] = min.y;
  26717. array[23] = min.z;
  26718. position.needsUpdate = true;
  26719. this.geometry.computeBoundingSphere();
  26720. }
  26721. setFromObject(object) {
  26722. this.object = object;
  26723. this.update();
  26724. return this;
  26725. }
  26726. copy(source) {
  26727. LineSegments.prototype.copy.call(this, source);
  26728. this.object = source.object;
  26729. return this;
  26730. }
  26731. }
  26732. class Box3Helper extends LineSegments {
  26733. constructor(box, color = 0xffff00) {
  26734. 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]);
  26735. 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];
  26736. const geometry = new BufferGeometry();
  26737. geometry.setIndex(new BufferAttribute(indices, 1));
  26738. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  26739. super(geometry, new LineBasicMaterial({
  26740. color: color,
  26741. toneMapped: false
  26742. }));
  26743. this.box = box;
  26744. this.type = 'Box3Helper';
  26745. this.geometry.computeBoundingSphere();
  26746. }
  26747. updateMatrixWorld(force) {
  26748. const box = this.box;
  26749. if (box.isEmpty()) return;
  26750. box.getCenter(this.position);
  26751. box.getSize(this.scale);
  26752. this.scale.multiplyScalar(0.5);
  26753. super.updateMatrixWorld(force);
  26754. }
  26755. }
  26756. class PlaneHelper extends Line {
  26757. constructor(plane, size = 1, hex = 0xffff00) {
  26758. const color = hex;
  26759. 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];
  26760. const geometry = new BufferGeometry();
  26761. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  26762. geometry.computeBoundingSphere();
  26763. super(geometry, new LineBasicMaterial({
  26764. color: color,
  26765. toneMapped: false
  26766. }));
  26767. this.type = 'PlaneHelper';
  26768. this.plane = plane;
  26769. this.size = size;
  26770. const positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  26771. const geometry2 = new BufferGeometry();
  26772. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  26773. geometry2.computeBoundingSphere();
  26774. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  26775. color: color,
  26776. opacity: 0.2,
  26777. transparent: true,
  26778. depthWrite: false,
  26779. toneMapped: false
  26780. })));
  26781. }
  26782. updateMatrixWorld(force) {
  26783. let scale = -this.plane.constant;
  26784. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  26785. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  26786. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  26787. this.lookAt(this.plane.normal);
  26788. super.updateMatrixWorld(force);
  26789. }
  26790. }
  26791. const _axis = /*@__PURE__*/new Vector3();
  26792. let _lineGeometry, _coneGeometry;
  26793. class ArrowHelper extends Object3D {
  26794. // dir is assumed to be normalized
  26795. 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) {
  26796. super();
  26797. this.type = 'ArrowHelper';
  26798. if (_lineGeometry === undefined) {
  26799. _lineGeometry = new BufferGeometry();
  26800. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  26801. _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1);
  26802. _coneGeometry.translate(0, -0.5, 0);
  26803. }
  26804. this.position.copy(origin);
  26805. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  26806. color: color,
  26807. toneMapped: false
  26808. }));
  26809. this.line.matrixAutoUpdate = false;
  26810. this.add(this.line);
  26811. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  26812. color: color,
  26813. toneMapped: false
  26814. }));
  26815. this.cone.matrixAutoUpdate = false;
  26816. this.add(this.cone);
  26817. this.setDirection(dir);
  26818. this.setLength(length, headLength, headWidth);
  26819. }
  26820. setDirection(dir) {
  26821. // dir is assumed to be normalized
  26822. if (dir.y > 0.99999) {
  26823. this.quaternion.set(0, 0, 0, 1);
  26824. } else if (dir.y < -0.99999) {
  26825. this.quaternion.set(1, 0, 0, 0);
  26826. } else {
  26827. _axis.set(dir.z, 0, -dir.x).normalize();
  26828. const radians = Math.acos(dir.y);
  26829. this.quaternion.setFromAxisAngle(_axis, radians);
  26830. }
  26831. }
  26832. setLength(length, headLength = length * 0.2, headWidth = headLength * 0.2) {
  26833. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  26834. this.line.updateMatrix();
  26835. this.cone.scale.set(headWidth, headLength, headWidth);
  26836. this.cone.position.y = length;
  26837. this.cone.updateMatrix();
  26838. }
  26839. setColor(color) {
  26840. this.line.material.color.set(color);
  26841. this.cone.material.color.set(color);
  26842. }
  26843. copy(source) {
  26844. super.copy(source, false);
  26845. this.line.copy(source.line);
  26846. this.cone.copy(source.cone);
  26847. return this;
  26848. }
  26849. }
  26850. class AxesHelper extends LineSegments {
  26851. constructor(size = 1) {
  26852. const vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  26853. const colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  26854. const geometry = new BufferGeometry();
  26855. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26856. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26857. const material = new LineBasicMaterial({
  26858. vertexColors: true,
  26859. toneMapped: false
  26860. });
  26861. super(geometry, material);
  26862. this.type = 'AxesHelper';
  26863. }
  26864. dispose() {
  26865. this.geometry.dispose();
  26866. this.material.dispose();
  26867. }
  26868. }
  26869. const _floatView = new Float32Array(1);
  26870. const _int32View = new Int32Array(_floatView.buffer);
  26871. class DataUtils {
  26872. // Converts float32 to float16 (stored as uint16 value).
  26873. static toHalfFloat(val) {
  26874. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  26875. /* This method is faster than the OpenEXR implementation (very often
  26876. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  26877. * by James Tursa?s half-precision code. */
  26878. _floatView[0] = val;
  26879. const x = _int32View[0];
  26880. let bits = x >> 16 & 0x8000;
  26881. /* Get the sign */
  26882. let m = x >> 12 & 0x07ff;
  26883. /* Keep one extra bit for rounding */
  26884. const e = x >> 23 & 0xff;
  26885. /* Using int is faster here */
  26886. /* If zero, or denormal, or exponent underflows too much for a denormal
  26887. * half, return signed zero. */
  26888. if (e < 103) return bits;
  26889. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  26890. if (e > 142) {
  26891. bits |= 0x7c00;
  26892. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  26893. * not Inf, so make sure we set one mantissa bit too. */
  26894. bits |= (e == 255 ? 0 : 1) && x & 0x007fffff;
  26895. return bits;
  26896. }
  26897. /* If exponent underflows but not too much, return a denormal */
  26898. if (e < 113) {
  26899. m |= 0x0800;
  26900. /* Extra rounding may overflow and set mantissa to 0 and exponent
  26901. * to 1, which is OK. */
  26902. bits |= (m >> 114 - e) + (m >> 113 - e & 1);
  26903. return bits;
  26904. }
  26905. bits |= e - 112 << 10 | m >> 1;
  26906. /* Extra rounding. An overflow will set mantissa to 0 and increment
  26907. * the exponent, which is OK. */
  26908. bits += m & 1;
  26909. return bits;
  26910. }
  26911. }
  26912. const LOD_MIN = 4;
  26913. const LOD_MAX = 8;
  26914. const SIZE_MAX = Math.pow(2, LOD_MAX); // The standard deviations (radians) associated with the extra mips. These are
  26915. // chosen to approximate a Trowbridge-Reitz distribution function times the
  26916. // geometric shadowing function. These sigma values squared must match the
  26917. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  26918. const EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
  26919. 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
  26920. // samples and exit early, but not recompile the shader.
  26921. const MAX_SAMPLES = 20;
  26922. const ENCODINGS = {
  26923. [LinearEncoding]: 0,
  26924. [sRGBEncoding]: 1,
  26925. [RGBEEncoding]: 2,
  26926. [RGBM7Encoding]: 3,
  26927. [RGBM16Encoding]: 4,
  26928. [RGBDEncoding]: 5,
  26929. [GammaEncoding]: 6
  26930. };
  26931. const backgroundMaterial = new MeshBasicMaterial({
  26932. side: BackSide,
  26933. depthWrite: false,
  26934. depthTest: false
  26935. });
  26936. const backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial);
  26937. const _flatCamera = /*@__PURE__*/new OrthographicCamera();
  26938. const {
  26939. _lodPlanes,
  26940. _sizeLods,
  26941. _sigmas
  26942. } = /*@__PURE__*/_createPlanes();
  26943. const _clearColor = /*@__PURE__*/new Color();
  26944. let _oldTarget = null; // Golden Ratio
  26945. const PHI = (1 + Math.sqrt(5)) / 2;
  26946. const INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
  26947. // same axis), used as axis directions evenly spread on a sphere.
  26948. 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)];
  26949. /**
  26950. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  26951. * (PMREM) from a cubeMap environment texture. This allows different levels of
  26952. * blur to be quickly accessed based on material roughness. It is packed into a
  26953. * special CubeUV format that allows us to perform custom interpolation so that
  26954. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  26955. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  26956. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  26957. * higher roughness levels. In this way we maintain resolution to smoothly
  26958. * interpolate diffuse lighting while limiting sampling computation.
  26959. *
  26960. * Paper: Fast, Accurate Image-Based Lighting
  26961. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  26962. */
  26963. function convertLinearToRGBE(color) {
  26964. const maxComponent = Math.max(color.r, color.g, color.b);
  26965. const fExp = Math.min(Math.max(Math.ceil(Math.log2(maxComponent)), -128.0), 127.0);
  26966. color.multiplyScalar(Math.pow(2.0, -fExp));
  26967. const alpha = (fExp + 128.0) / 255.0;
  26968. return alpha;
  26969. }
  26970. class PMREMGenerator {
  26971. constructor(renderer) {
  26972. this._renderer = renderer;
  26973. this._pingPongRenderTarget = null;
  26974. this._blurMaterial = _getBlurShader(MAX_SAMPLES);
  26975. this._equirectShader = null;
  26976. this._cubemapShader = null;
  26977. this._compileMaterial(this._blurMaterial);
  26978. }
  26979. /**
  26980. * Generates a PMREM from a supplied Scene, which can be faster than using an
  26981. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  26982. * in radians to be applied to the scene before PMREM generation. Optional near
  26983. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  26984. * is placed at the origin).
  26985. */
  26986. fromScene(scene, sigma = 0, near = 0.1, far = 100) {
  26987. _oldTarget = this._renderer.getRenderTarget();
  26988. const cubeUVRenderTarget = this._allocateTargets();
  26989. this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  26990. if (sigma > 0) {
  26991. this._blur(cubeUVRenderTarget, 0, 0, sigma);
  26992. }
  26993. this._applyPMREM(cubeUVRenderTarget);
  26994. this._cleanup(cubeUVRenderTarget);
  26995. return cubeUVRenderTarget;
  26996. }
  26997. /**
  26998. * Generates a PMREM from an equirectangular texture, which can be either LDR
  26999. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  27000. * as this matches best with the 256 x 256 cubemap output.
  27001. */
  27002. fromEquirectangular(equirectangular) {
  27003. return this._fromTexture(equirectangular);
  27004. }
  27005. /**
  27006. * Generates a PMREM from an cubemap texture, which can be either LDR
  27007. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  27008. * as this matches best with the 256 x 256 cubemap output.
  27009. */
  27010. fromCubemap(cubemap) {
  27011. return this._fromTexture(cubemap);
  27012. }
  27013. /**
  27014. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  27015. * your texture's network fetch for increased concurrency.
  27016. */
  27017. compileCubemapShader() {
  27018. if (this._cubemapShader === null) {
  27019. this._cubemapShader = _getCubemapShader();
  27020. this._compileMaterial(this._cubemapShader);
  27021. }
  27022. }
  27023. /**
  27024. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  27025. * your texture's network fetch for increased concurrency.
  27026. */
  27027. compileEquirectangularShader() {
  27028. if (this._equirectShader === null) {
  27029. this._equirectShader = _getEquirectShader();
  27030. this._compileMaterial(this._equirectShader);
  27031. }
  27032. }
  27033. /**
  27034. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  27035. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  27036. * one of them will cause any others to also become unusable.
  27037. */
  27038. dispose() {
  27039. this._blurMaterial.dispose();
  27040. if (this._cubemapShader !== null) this._cubemapShader.dispose();
  27041. if (this._equirectShader !== null) this._equirectShader.dispose();
  27042. for (let i = 0; i < _lodPlanes.length; i++) {
  27043. _lodPlanes[i].dispose();
  27044. }
  27045. } // private interface
  27046. _cleanup(outputTarget) {
  27047. this._pingPongRenderTarget.dispose();
  27048. this._renderer.setRenderTarget(_oldTarget);
  27049. outputTarget.scissorTest = false;
  27050. _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
  27051. }
  27052. _fromTexture(texture) {
  27053. _oldTarget = this._renderer.getRenderTarget();
  27054. const cubeUVRenderTarget = this._allocateTargets(texture);
  27055. this._textureToCubeUV(texture, cubeUVRenderTarget);
  27056. this._applyPMREM(cubeUVRenderTarget);
  27057. this._cleanup(cubeUVRenderTarget);
  27058. return cubeUVRenderTarget;
  27059. }
  27060. _allocateTargets(texture) {
  27061. // warning: null texture is valid
  27062. const params = {
  27063. magFilter: NearestFilter,
  27064. minFilter: NearestFilter,
  27065. generateMipmaps: false,
  27066. type: UnsignedByteType,
  27067. format: RGBEFormat,
  27068. encoding: _isLDR(texture) ? texture.encoding : RGBEEncoding,
  27069. depthBuffer: false
  27070. };
  27071. const cubeUVRenderTarget = _createRenderTarget(params);
  27072. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  27073. this._pingPongRenderTarget = _createRenderTarget(params);
  27074. return cubeUVRenderTarget;
  27075. }
  27076. _compileMaterial(material) {
  27077. const tmpMesh = new Mesh(_lodPlanes[0], material);
  27078. this._renderer.compile(tmpMesh, _flatCamera);
  27079. }
  27080. _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  27081. const fov = 90;
  27082. const aspect = 1;
  27083. const cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  27084. const upSign = [1, -1, 1, 1, 1, 1];
  27085. const forwardSign = [1, 1, 1, -1, -1, -1];
  27086. const renderer = this._renderer;
  27087. const originalAutoClear = renderer.autoClear;
  27088. const outputEncoding = renderer.outputEncoding;
  27089. const toneMapping = renderer.toneMapping;
  27090. renderer.getClearColor(_clearColor);
  27091. renderer.toneMapping = NoToneMapping;
  27092. renderer.outputEncoding = LinearEncoding;
  27093. renderer.autoClear = false;
  27094. let useSolidColor = false;
  27095. const background = scene.background;
  27096. if (background) {
  27097. if (background.isColor) {
  27098. backgroundMaterial.color.copy(background).convertSRGBToLinear();
  27099. scene.background = null;
  27100. const alpha = convertLinearToRGBE(backgroundMaterial.color);
  27101. backgroundMaterial.opacity = alpha;
  27102. useSolidColor = true;
  27103. }
  27104. } else {
  27105. backgroundMaterial.color.copy(_clearColor).convertSRGBToLinear();
  27106. const alpha = convertLinearToRGBE(backgroundMaterial.color);
  27107. backgroundMaterial.opacity = alpha;
  27108. useSolidColor = true;
  27109. }
  27110. for (let i = 0; i < 6; i++) {
  27111. const col = i % 3;
  27112. if (col == 0) {
  27113. cubeCamera.up.set(0, upSign[i], 0);
  27114. cubeCamera.lookAt(forwardSign[i], 0, 0);
  27115. } else if (col == 1) {
  27116. cubeCamera.up.set(0, 0, upSign[i]);
  27117. cubeCamera.lookAt(0, forwardSign[i], 0);
  27118. } else {
  27119. cubeCamera.up.set(0, upSign[i], 0);
  27120. cubeCamera.lookAt(0, 0, forwardSign[i]);
  27121. }
  27122. _setViewport(cubeUVRenderTarget, col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX);
  27123. renderer.setRenderTarget(cubeUVRenderTarget);
  27124. if (useSolidColor) {
  27125. renderer.render(backgroundBox, cubeCamera);
  27126. }
  27127. renderer.render(scene, cubeCamera);
  27128. }
  27129. renderer.toneMapping = toneMapping;
  27130. renderer.outputEncoding = outputEncoding;
  27131. renderer.autoClear = originalAutoClear;
  27132. }
  27133. _textureToCubeUV(texture, cubeUVRenderTarget) {
  27134. const renderer = this._renderer;
  27135. if (texture.isCubeTexture) {
  27136. if (this._cubemapShader == null) {
  27137. this._cubemapShader = _getCubemapShader();
  27138. }
  27139. } else {
  27140. if (this._equirectShader == null) {
  27141. this._equirectShader = _getEquirectShader();
  27142. }
  27143. }
  27144. const material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  27145. const mesh = new Mesh(_lodPlanes[0], material);
  27146. const uniforms = material.uniforms;
  27147. uniforms['envMap'].value = texture;
  27148. if (!texture.isCubeTexture) {
  27149. uniforms['texelSize'].value.set(1.0 / texture.image.width, 1.0 / texture.image.height);
  27150. }
  27151. uniforms['inputEncoding'].value = ENCODINGS[texture.encoding];
  27152. uniforms['outputEncoding'].value = ENCODINGS[cubeUVRenderTarget.texture.encoding];
  27153. _setViewport(cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX);
  27154. renderer.setRenderTarget(cubeUVRenderTarget);
  27155. renderer.render(mesh, _flatCamera);
  27156. }
  27157. _applyPMREM(cubeUVRenderTarget) {
  27158. const renderer = this._renderer;
  27159. const autoClear = renderer.autoClear;
  27160. renderer.autoClear = false;
  27161. for (let i = 1; i < TOTAL_LODS; i++) {
  27162. const sigma = Math.sqrt(_sigmas[i] * _sigmas[i] - _sigmas[i - 1] * _sigmas[i - 1]);
  27163. const poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  27164. this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  27165. }
  27166. renderer.autoClear = autoClear;
  27167. }
  27168. /**
  27169. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  27170. * vertically and horizontally, but this breaks down on a cube. Here we apply
  27171. * the blur latitudinally (around the poles), and then longitudinally (towards
  27172. * the poles) to approximate the orthogonally-separable blur. It is least
  27173. * accurate at the poles, but still does a decent job.
  27174. */
  27175. _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  27176. const pingPongRenderTarget = this._pingPongRenderTarget;
  27177. this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  27178. this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  27179. }
  27180. _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  27181. const renderer = this._renderer;
  27182. const blurMaterial = this._blurMaterial;
  27183. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  27184. console.error('blur direction must be either latitudinal or longitudinal!');
  27185. } // Number of standard deviations at which to cut off the discrete approximation.
  27186. const STANDARD_DEVIATIONS = 3;
  27187. const blurMesh = new Mesh(_lodPlanes[lodOut], blurMaterial);
  27188. const blurUniforms = blurMaterial.uniforms;
  27189. const pixels = _sizeLods[lodIn] - 1;
  27190. const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  27191. const sigmaPixels = sigmaRadians / radiansPerPixel;
  27192. const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  27193. if (samples > MAX_SAMPLES) {
  27194. console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
  27195. }
  27196. const weights = [];
  27197. let sum = 0;
  27198. for (let i = 0; i < MAX_SAMPLES; ++i) {
  27199. const x = i / sigmaPixels;
  27200. const weight = Math.exp(-x * x / 2);
  27201. weights.push(weight);
  27202. if (i == 0) {
  27203. sum += weight;
  27204. } else if (i < samples) {
  27205. sum += 2 * weight;
  27206. }
  27207. }
  27208. for (let i = 0; i < weights.length; i++) {
  27209. weights[i] = weights[i] / sum;
  27210. }
  27211. blurUniforms['envMap'].value = targetIn.texture;
  27212. blurUniforms['samples'].value = samples;
  27213. blurUniforms['weights'].value = weights;
  27214. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  27215. if (poleAxis) {
  27216. blurUniforms['poleAxis'].value = poleAxis;
  27217. }
  27218. blurUniforms['dTheta'].value = radiansPerPixel;
  27219. blurUniforms['mipInt'].value = LOD_MAX - lodIn;
  27220. blurUniforms['inputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  27221. blurUniforms['outputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  27222. const outputSize = _sizeLods[lodOut];
  27223. const x = 3 * Math.max(0, SIZE_MAX - 2 * outputSize);
  27224. const y = (lodOut === 0 ? 0 : 2 * SIZE_MAX) + 2 * outputSize * (lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0);
  27225. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  27226. renderer.setRenderTarget(targetOut);
  27227. renderer.render(blurMesh, _flatCamera);
  27228. }
  27229. }
  27230. function _isLDR(texture) {
  27231. if (texture === undefined || texture.type !== UnsignedByteType) return false;
  27232. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  27233. }
  27234. function _createPlanes() {
  27235. const _lodPlanes = [];
  27236. const _sizeLods = [];
  27237. const _sigmas = [];
  27238. let lod = LOD_MAX;
  27239. for (let i = 0; i < TOTAL_LODS; i++) {
  27240. const sizeLod = Math.pow(2, lod);
  27241. _sizeLods.push(sizeLod);
  27242. let sigma = 1.0 / sizeLod;
  27243. if (i > LOD_MAX - LOD_MIN) {
  27244. sigma = EXTRA_LOD_SIGMA[i - LOD_MAX + LOD_MIN - 1];
  27245. } else if (i == 0) {
  27246. sigma = 0;
  27247. }
  27248. _sigmas.push(sigma);
  27249. const texelSize = 1.0 / (sizeLod - 1);
  27250. const min = -texelSize / 2;
  27251. const max = 1 + texelSize / 2;
  27252. const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  27253. const cubeFaces = 6;
  27254. const vertices = 6;
  27255. const positionSize = 3;
  27256. const uvSize = 2;
  27257. const faceIndexSize = 1;
  27258. const position = new Float32Array(positionSize * vertices * cubeFaces);
  27259. const uv = new Float32Array(uvSize * vertices * cubeFaces);
  27260. const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  27261. for (let face = 0; face < cubeFaces; face++) {
  27262. const x = face % 3 * 2 / 3 - 1;
  27263. const y = face > 2 ? 0 : -1;
  27264. 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];
  27265. position.set(coordinates, positionSize * vertices * face);
  27266. uv.set(uv1, uvSize * vertices * face);
  27267. const fill = [face, face, face, face, face, face];
  27268. faceIndex.set(fill, faceIndexSize * vertices * face);
  27269. }
  27270. const planes = new BufferGeometry();
  27271. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  27272. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  27273. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  27274. _lodPlanes.push(planes);
  27275. if (lod > LOD_MIN) {
  27276. lod--;
  27277. }
  27278. }
  27279. return {
  27280. _lodPlanes,
  27281. _sizeLods,
  27282. _sigmas
  27283. };
  27284. }
  27285. function _createRenderTarget(params) {
  27286. const cubeUVRenderTarget = new WebGLRenderTarget(3 * SIZE_MAX, 3 * SIZE_MAX, params);
  27287. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  27288. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  27289. cubeUVRenderTarget.scissorTest = true;
  27290. return cubeUVRenderTarget;
  27291. }
  27292. function _setViewport(target, x, y, width, height) {
  27293. target.viewport.set(x, y, width, height);
  27294. target.scissor.set(x, y, width, height);
  27295. }
  27296. function _getBlurShader(maxSamples) {
  27297. const weights = new Float32Array(maxSamples);
  27298. const poleAxis = new Vector3(0, 1, 0);
  27299. const shaderMaterial = new RawShaderMaterial({
  27300. name: 'SphericalGaussianBlur',
  27301. defines: {
  27302. 'n': maxSamples
  27303. },
  27304. uniforms: {
  27305. 'envMap': {
  27306. value: null
  27307. },
  27308. 'samples': {
  27309. value: 1
  27310. },
  27311. 'weights': {
  27312. value: weights
  27313. },
  27314. 'latitudinal': {
  27315. value: false
  27316. },
  27317. 'dTheta': {
  27318. value: 0
  27319. },
  27320. 'mipInt': {
  27321. value: 0
  27322. },
  27323. 'poleAxis': {
  27324. value: poleAxis
  27325. },
  27326. 'inputEncoding': {
  27327. value: ENCODINGS[LinearEncoding]
  27328. },
  27329. 'outputEncoding': {
  27330. value: ENCODINGS[LinearEncoding]
  27331. }
  27332. },
  27333. vertexShader: _getCommonVertexShader(),
  27334. fragmentShader:
  27335. /* glsl */
  27336. `
  27337. precision mediump float;
  27338. precision mediump int;
  27339. varying vec3 vOutputDirection;
  27340. uniform sampler2D envMap;
  27341. uniform int samples;
  27342. uniform float weights[ n ];
  27343. uniform bool latitudinal;
  27344. uniform float dTheta;
  27345. uniform float mipInt;
  27346. uniform vec3 poleAxis;
  27347. ${_getEncodings()}
  27348. #define ENVMAP_TYPE_CUBE_UV
  27349. #include <cube_uv_reflection_fragment>
  27350. vec3 getSample( float theta, vec3 axis ) {
  27351. float cosTheta = cos( theta );
  27352. // Rodrigues' axis-angle rotation
  27353. vec3 sampleDirection = vOutputDirection * cosTheta
  27354. + cross( axis, vOutputDirection ) * sin( theta )
  27355. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  27356. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  27357. }
  27358. void main() {
  27359. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  27360. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  27361. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  27362. }
  27363. axis = normalize( axis );
  27364. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  27365. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  27366. for ( int i = 1; i < n; i++ ) {
  27367. if ( i >= samples ) {
  27368. break;
  27369. }
  27370. float theta = dTheta * float( i );
  27371. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  27372. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  27373. }
  27374. gl_FragColor = linearToOutputTexel( gl_FragColor );
  27375. }
  27376. `,
  27377. blending: NoBlending,
  27378. depthTest: false,
  27379. depthWrite: false
  27380. });
  27381. return shaderMaterial;
  27382. }
  27383. function _getEquirectShader() {
  27384. const texelSize = new Vector2(1, 1);
  27385. const shaderMaterial = new RawShaderMaterial({
  27386. name: 'EquirectangularToCubeUV',
  27387. uniforms: {
  27388. 'envMap': {
  27389. value: null
  27390. },
  27391. 'texelSize': {
  27392. value: texelSize
  27393. },
  27394. 'inputEncoding': {
  27395. value: ENCODINGS[LinearEncoding]
  27396. },
  27397. 'outputEncoding': {
  27398. value: ENCODINGS[LinearEncoding]
  27399. }
  27400. },
  27401. vertexShader: _getCommonVertexShader(),
  27402. fragmentShader:
  27403. /* glsl */
  27404. `
  27405. precision mediump float;
  27406. precision mediump int;
  27407. varying vec3 vOutputDirection;
  27408. uniform sampler2D envMap;
  27409. uniform vec2 texelSize;
  27410. ${_getEncodings()}
  27411. #include <common>
  27412. void main() {
  27413. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  27414. vec3 outputDirection = normalize( vOutputDirection );
  27415. vec2 uv = equirectUv( outputDirection );
  27416. vec2 f = fract( uv / texelSize - 0.5 );
  27417. uv -= f * texelSize;
  27418. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27419. uv.x += texelSize.x;
  27420. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27421. uv.y += texelSize.y;
  27422. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27423. uv.x -= texelSize.x;
  27424. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27425. vec3 tm = mix( tl, tr, f.x );
  27426. vec3 bm = mix( bl, br, f.x );
  27427. gl_FragColor.rgb = mix( tm, bm, f.y );
  27428. gl_FragColor = linearToOutputTexel( gl_FragColor );
  27429. }
  27430. `,
  27431. blending: NoBlending,
  27432. depthTest: false,
  27433. depthWrite: false
  27434. });
  27435. return shaderMaterial;
  27436. }
  27437. function _getCubemapShader() {
  27438. const shaderMaterial = new RawShaderMaterial({
  27439. name: 'CubemapToCubeUV',
  27440. uniforms: {
  27441. 'envMap': {
  27442. value: null
  27443. },
  27444. 'inputEncoding': {
  27445. value: ENCODINGS[LinearEncoding]
  27446. },
  27447. 'outputEncoding': {
  27448. value: ENCODINGS[LinearEncoding]
  27449. }
  27450. },
  27451. vertexShader: _getCommonVertexShader(),
  27452. fragmentShader:
  27453. /* glsl */
  27454. `
  27455. precision mediump float;
  27456. precision mediump int;
  27457. varying vec3 vOutputDirection;
  27458. uniform samplerCube envMap;
  27459. ${_getEncodings()}
  27460. void main() {
  27461. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  27462. gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;
  27463. gl_FragColor = linearToOutputTexel( gl_FragColor );
  27464. }
  27465. `,
  27466. blending: NoBlending,
  27467. depthTest: false,
  27468. depthWrite: false
  27469. });
  27470. return shaderMaterial;
  27471. }
  27472. function _getCommonVertexShader() {
  27473. return (
  27474. /* glsl */
  27475. `
  27476. precision mediump float;
  27477. precision mediump int;
  27478. attribute vec3 position;
  27479. attribute vec2 uv;
  27480. attribute float faceIndex;
  27481. varying vec3 vOutputDirection;
  27482. // RH coordinate system; PMREM face-indexing convention
  27483. vec3 getDirection( vec2 uv, float face ) {
  27484. uv = 2.0 * uv - 1.0;
  27485. vec3 direction = vec3( uv, 1.0 );
  27486. if ( face == 0.0 ) {
  27487. direction = direction.zyx; // ( 1, v, u ) pos x
  27488. } else if ( face == 1.0 ) {
  27489. direction = direction.xzy;
  27490. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  27491. } else if ( face == 2.0 ) {
  27492. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  27493. } else if ( face == 3.0 ) {
  27494. direction = direction.zyx;
  27495. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  27496. } else if ( face == 4.0 ) {
  27497. direction = direction.xzy;
  27498. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  27499. } else if ( face == 5.0 ) {
  27500. direction.z *= -1.0; // ( u, v, -1 ) neg z
  27501. }
  27502. return direction;
  27503. }
  27504. void main() {
  27505. vOutputDirection = getDirection( uv, faceIndex );
  27506. gl_Position = vec4( position, 1.0 );
  27507. }
  27508. `
  27509. );
  27510. }
  27511. function _getEncodings() {
  27512. return (
  27513. /* glsl */
  27514. `
  27515. uniform int inputEncoding;
  27516. uniform int outputEncoding;
  27517. #include <encodings_pars_fragment>
  27518. vec4 inputTexelToLinear( vec4 value ) {
  27519. if ( inputEncoding == 0 ) {
  27520. return value;
  27521. } else if ( inputEncoding == 1 ) {
  27522. return sRGBToLinear( value );
  27523. } else if ( inputEncoding == 2 ) {
  27524. return RGBEToLinear( value );
  27525. } else if ( inputEncoding == 3 ) {
  27526. return RGBMToLinear( value, 7.0 );
  27527. } else if ( inputEncoding == 4 ) {
  27528. return RGBMToLinear( value, 16.0 );
  27529. } else if ( inputEncoding == 5 ) {
  27530. return RGBDToLinear( value, 256.0 );
  27531. } else {
  27532. return GammaToLinear( value, 2.2 );
  27533. }
  27534. }
  27535. vec4 linearToOutputTexel( vec4 value ) {
  27536. if ( outputEncoding == 0 ) {
  27537. return value;
  27538. } else if ( outputEncoding == 1 ) {
  27539. return LinearTosRGB( value );
  27540. } else if ( outputEncoding == 2 ) {
  27541. return LinearToRGBE( value );
  27542. } else if ( outputEncoding == 3 ) {
  27543. return LinearToRGBM( value, 7.0 );
  27544. } else if ( outputEncoding == 4 ) {
  27545. return LinearToRGBM( value, 16.0 );
  27546. } else if ( outputEncoding == 5 ) {
  27547. return LinearToRGBD( value, 256.0 );
  27548. } else {
  27549. return LinearToGamma( value, 2.2 );
  27550. }
  27551. }
  27552. vec4 envMapTexelToLinear( vec4 color ) {
  27553. return inputTexelToLinear( color );
  27554. }
  27555. `
  27556. );
  27557. }
  27558. const LineStrip = 0;
  27559. const LinePieces = 1;
  27560. const NoColors = 0;
  27561. const FaceColors = 1;
  27562. const VertexColors = 2;
  27563. function MeshFaceMaterial(materials) {
  27564. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  27565. return materials;
  27566. }
  27567. function MultiMaterial(materials = []) {
  27568. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  27569. materials.isMultiMaterial = true;
  27570. materials.materials = materials;
  27571. materials.clone = function () {
  27572. return materials.slice();
  27573. };
  27574. return materials;
  27575. }
  27576. function PointCloud(geometry, material) {
  27577. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  27578. return new Points(geometry, material);
  27579. }
  27580. function Particle(material) {
  27581. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  27582. return new Sprite(material);
  27583. }
  27584. function ParticleSystem(geometry, material) {
  27585. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  27586. return new Points(geometry, material);
  27587. }
  27588. function PointCloudMaterial(parameters) {
  27589. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  27590. return new PointsMaterial(parameters);
  27591. }
  27592. function ParticleBasicMaterial(parameters) {
  27593. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  27594. return new PointsMaterial(parameters);
  27595. }
  27596. function ParticleSystemMaterial(parameters) {
  27597. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  27598. return new PointsMaterial(parameters);
  27599. }
  27600. function Vertex(x, y, z) {
  27601. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  27602. return new Vector3(x, y, z);
  27603. } //
  27604. function DynamicBufferAttribute(array, itemSize) {
  27605. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.');
  27606. return new BufferAttribute(array, itemSize).setUsage(DynamicDrawUsage);
  27607. }
  27608. function Int8Attribute(array, itemSize) {
  27609. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  27610. return new Int8BufferAttribute(array, itemSize);
  27611. }
  27612. function Uint8Attribute(array, itemSize) {
  27613. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  27614. return new Uint8BufferAttribute(array, itemSize);
  27615. }
  27616. function Uint8ClampedAttribute(array, itemSize) {
  27617. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  27618. return new Uint8ClampedBufferAttribute(array, itemSize);
  27619. }
  27620. function Int16Attribute(array, itemSize) {
  27621. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  27622. return new Int16BufferAttribute(array, itemSize);
  27623. }
  27624. function Uint16Attribute(array, itemSize) {
  27625. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  27626. return new Uint16BufferAttribute(array, itemSize);
  27627. }
  27628. function Int32Attribute(array, itemSize) {
  27629. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  27630. return new Int32BufferAttribute(array, itemSize);
  27631. }
  27632. function Uint32Attribute(array, itemSize) {
  27633. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  27634. return new Uint32BufferAttribute(array, itemSize);
  27635. }
  27636. function Float32Attribute(array, itemSize) {
  27637. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  27638. return new Float32BufferAttribute(array, itemSize);
  27639. }
  27640. function Float64Attribute(array, itemSize) {
  27641. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  27642. return new Float64BufferAttribute(array, itemSize);
  27643. } //
  27644. Curve.create = function (construct, getPoint) {
  27645. console.log('THREE.Curve.create() has been deprecated');
  27646. construct.prototype = Object.create(Curve.prototype);
  27647. construct.prototype.constructor = construct;
  27648. construct.prototype.getPoint = getPoint;
  27649. return construct;
  27650. }; //
  27651. Path.prototype.fromPoints = function (points) {
  27652. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  27653. return this.setFromPoints(points);
  27654. }; //
  27655. function AxisHelper(size) {
  27656. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  27657. return new AxesHelper(size);
  27658. }
  27659. function BoundingBoxHelper(object, color) {
  27660. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  27661. return new BoxHelper(object, color);
  27662. }
  27663. function EdgesHelper(object, hex) {
  27664. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  27665. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  27666. color: hex !== undefined ? hex : 0xffffff
  27667. }));
  27668. }
  27669. GridHelper.prototype.setColors = function () {
  27670. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  27671. };
  27672. SkeletonHelper.prototype.update = function () {
  27673. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  27674. };
  27675. function WireframeHelper(object, hex) {
  27676. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  27677. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  27678. color: hex !== undefined ? hex : 0xffffff
  27679. }));
  27680. } //
  27681. Loader.prototype.extractUrlBase = function (url) {
  27682. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  27683. return LoaderUtils.extractUrlBase(url);
  27684. };
  27685. Loader.Handlers = {
  27686. add: function ()
  27687. /* regex, loader */
  27688. {
  27689. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  27690. },
  27691. get: function ()
  27692. /* file */
  27693. {
  27694. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  27695. }
  27696. };
  27697. function XHRLoader(manager) {
  27698. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  27699. return new FileLoader(manager);
  27700. }
  27701. function BinaryTextureLoader(manager) {
  27702. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  27703. return new DataTextureLoader(manager);
  27704. } //
  27705. Box2.prototype.center = function (optionalTarget) {
  27706. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  27707. return this.getCenter(optionalTarget);
  27708. };
  27709. Box2.prototype.empty = function () {
  27710. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  27711. return this.isEmpty();
  27712. };
  27713. Box2.prototype.isIntersectionBox = function (box) {
  27714. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  27715. return this.intersectsBox(box);
  27716. };
  27717. Box2.prototype.size = function (optionalTarget) {
  27718. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  27719. return this.getSize(optionalTarget);
  27720. }; //
  27721. Box3.prototype.center = function (optionalTarget) {
  27722. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  27723. return this.getCenter(optionalTarget);
  27724. };
  27725. Box3.prototype.empty = function () {
  27726. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  27727. return this.isEmpty();
  27728. };
  27729. Box3.prototype.isIntersectionBox = function (box) {
  27730. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  27731. return this.intersectsBox(box);
  27732. };
  27733. Box3.prototype.isIntersectionSphere = function (sphere) {
  27734. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  27735. return this.intersectsSphere(sphere);
  27736. };
  27737. Box3.prototype.size = function (optionalTarget) {
  27738. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  27739. return this.getSize(optionalTarget);
  27740. }; //
  27741. Sphere.prototype.empty = function () {
  27742. console.warn('THREE.Sphere: .empty() has been renamed to .isEmpty().');
  27743. return this.isEmpty();
  27744. }; //
  27745. Frustum.prototype.setFromMatrix = function (m) {
  27746. console.warn('THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().');
  27747. return this.setFromProjectionMatrix(m);
  27748. }; //
  27749. Line3.prototype.center = function (optionalTarget) {
  27750. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  27751. return this.getCenter(optionalTarget);
  27752. }; //
  27753. Matrix3.prototype.flattenToArrayOffset = function (array, offset) {
  27754. console.warn('THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  27755. return this.toArray(array, offset);
  27756. };
  27757. Matrix3.prototype.multiplyVector3 = function (vector) {
  27758. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  27759. return vector.applyMatrix3(this);
  27760. };
  27761. Matrix3.prototype.multiplyVector3Array = function ()
  27762. /* a */
  27763. {
  27764. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  27765. };
  27766. Matrix3.prototype.applyToBufferAttribute = function (attribute) {
  27767. console.warn('THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.');
  27768. return attribute.applyMatrix3(this);
  27769. };
  27770. Matrix3.prototype.applyToVector3Array = function ()
  27771. /* array, offset, length */
  27772. {
  27773. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  27774. };
  27775. Matrix3.prototype.getInverse = function (matrix) {
  27776. console.warn('THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  27777. return this.copy(matrix).invert();
  27778. }; //
  27779. Matrix4.prototype.extractPosition = function (m) {
  27780. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  27781. return this.copyPosition(m);
  27782. };
  27783. Matrix4.prototype.flattenToArrayOffset = function (array, offset) {
  27784. console.warn('THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  27785. return this.toArray(array, offset);
  27786. };
  27787. Matrix4.prototype.getPosition = function () {
  27788. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  27789. return new Vector3().setFromMatrixColumn(this, 3);
  27790. };
  27791. Matrix4.prototype.setRotationFromQuaternion = function (q) {
  27792. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  27793. return this.makeRotationFromQuaternion(q);
  27794. };
  27795. Matrix4.prototype.multiplyToArray = function () {
  27796. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  27797. };
  27798. Matrix4.prototype.multiplyVector3 = function (vector) {
  27799. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  27800. return vector.applyMatrix4(this);
  27801. };
  27802. Matrix4.prototype.multiplyVector4 = function (vector) {
  27803. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  27804. return vector.applyMatrix4(this);
  27805. };
  27806. Matrix4.prototype.multiplyVector3Array = function ()
  27807. /* a */
  27808. {
  27809. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  27810. };
  27811. Matrix4.prototype.rotateAxis = function (v) {
  27812. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  27813. v.transformDirection(this);
  27814. };
  27815. Matrix4.prototype.crossVector = function (vector) {
  27816. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  27817. return vector.applyMatrix4(this);
  27818. };
  27819. Matrix4.prototype.translate = function () {
  27820. console.error('THREE.Matrix4: .translate() has been removed.');
  27821. };
  27822. Matrix4.prototype.rotateX = function () {
  27823. console.error('THREE.Matrix4: .rotateX() has been removed.');
  27824. };
  27825. Matrix4.prototype.rotateY = function () {
  27826. console.error('THREE.Matrix4: .rotateY() has been removed.');
  27827. };
  27828. Matrix4.prototype.rotateZ = function () {
  27829. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  27830. };
  27831. Matrix4.prototype.rotateByAxis = function () {
  27832. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  27833. };
  27834. Matrix4.prototype.applyToBufferAttribute = function (attribute) {
  27835. console.warn('THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.');
  27836. return attribute.applyMatrix4(this);
  27837. };
  27838. Matrix4.prototype.applyToVector3Array = function ()
  27839. /* array, offset, length */
  27840. {
  27841. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  27842. };
  27843. Matrix4.prototype.makeFrustum = function (left, right, bottom, top, near, far) {
  27844. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  27845. return this.makePerspective(left, right, top, bottom, near, far);
  27846. };
  27847. Matrix4.prototype.getInverse = function (matrix) {
  27848. console.warn('THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  27849. return this.copy(matrix).invert();
  27850. }; //
  27851. Plane.prototype.isIntersectionLine = function (line) {
  27852. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  27853. return this.intersectsLine(line);
  27854. }; //
  27855. Quaternion.prototype.multiplyVector3 = function (vector) {
  27856. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  27857. return vector.applyQuaternion(this);
  27858. };
  27859. Quaternion.prototype.inverse = function () {
  27860. console.warn('THREE.Quaternion: .inverse() has been renamed to invert().');
  27861. return this.invert();
  27862. }; //
  27863. Ray.prototype.isIntersectionBox = function (box) {
  27864. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  27865. return this.intersectsBox(box);
  27866. };
  27867. Ray.prototype.isIntersectionPlane = function (plane) {
  27868. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  27869. return this.intersectsPlane(plane);
  27870. };
  27871. Ray.prototype.isIntersectionSphere = function (sphere) {
  27872. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  27873. return this.intersectsSphere(sphere);
  27874. }; //
  27875. Triangle.prototype.area = function () {
  27876. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  27877. return this.getArea();
  27878. };
  27879. Triangle.prototype.barycoordFromPoint = function (point, target) {
  27880. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  27881. return this.getBarycoord(point, target);
  27882. };
  27883. Triangle.prototype.midpoint = function (target) {
  27884. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  27885. return this.getMidpoint(target);
  27886. };
  27887. Triangle.prototypenormal = function (target) {
  27888. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  27889. return this.getNormal(target);
  27890. };
  27891. Triangle.prototype.plane = function (target) {
  27892. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  27893. return this.getPlane(target);
  27894. };
  27895. Triangle.barycoordFromPoint = function (point, a, b, c, target) {
  27896. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  27897. return Triangle.getBarycoord(point, a, b, c, target);
  27898. };
  27899. Triangle.normal = function (a, b, c, target) {
  27900. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  27901. return Triangle.getNormal(a, b, c, target);
  27902. }; //
  27903. Shape.prototype.extractAllPoints = function (divisions) {
  27904. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  27905. return this.extractPoints(divisions);
  27906. };
  27907. Shape.prototype.extrude = function (options) {
  27908. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  27909. return new ExtrudeGeometry(this, options);
  27910. };
  27911. Shape.prototype.makeGeometry = function (options) {
  27912. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  27913. return new ShapeGeometry(this, options);
  27914. }; //
  27915. Vector2.prototype.fromAttribute = function (attribute, index, offset) {
  27916. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  27917. return this.fromBufferAttribute(attribute, index, offset);
  27918. };
  27919. Vector2.prototype.distanceToManhattan = function (v) {
  27920. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  27921. return this.manhattanDistanceTo(v);
  27922. };
  27923. Vector2.prototype.lengthManhattan = function () {
  27924. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  27925. return this.manhattanLength();
  27926. }; //
  27927. Vector3.prototype.setEulerFromRotationMatrix = function () {
  27928. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  27929. };
  27930. Vector3.prototype.setEulerFromQuaternion = function () {
  27931. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  27932. };
  27933. Vector3.prototype.getPositionFromMatrix = function (m) {
  27934. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  27935. return this.setFromMatrixPosition(m);
  27936. };
  27937. Vector3.prototype.getScaleFromMatrix = function (m) {
  27938. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  27939. return this.setFromMatrixScale(m);
  27940. };
  27941. Vector3.prototype.getColumnFromMatrix = function (index, matrix) {
  27942. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  27943. return this.setFromMatrixColumn(matrix, index);
  27944. };
  27945. Vector3.prototype.applyProjection = function (m) {
  27946. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  27947. return this.applyMatrix4(m);
  27948. };
  27949. Vector3.prototype.fromAttribute = function (attribute, index, offset) {
  27950. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  27951. return this.fromBufferAttribute(attribute, index, offset);
  27952. };
  27953. Vector3.prototype.distanceToManhattan = function (v) {
  27954. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  27955. return this.manhattanDistanceTo(v);
  27956. };
  27957. Vector3.prototype.lengthManhattan = function () {
  27958. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  27959. return this.manhattanLength();
  27960. }; //
  27961. Vector4.prototype.fromAttribute = function (attribute, index, offset) {
  27962. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  27963. return this.fromBufferAttribute(attribute, index, offset);
  27964. };
  27965. Vector4.prototype.lengthManhattan = function () {
  27966. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  27967. return this.manhattanLength();
  27968. }; //
  27969. Object3D.prototype.getChildByName = function (name) {
  27970. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  27971. return this.getObjectByName(name);
  27972. };
  27973. Object3D.prototype.renderDepth = function () {
  27974. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  27975. };
  27976. Object3D.prototype.translate = function (distance, axis) {
  27977. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  27978. return this.translateOnAxis(axis, distance);
  27979. };
  27980. Object3D.prototype.getWorldRotation = function () {
  27981. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  27982. };
  27983. Object3D.prototype.applyMatrix = function (matrix) {
  27984. console.warn('THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().');
  27985. return this.applyMatrix4(matrix);
  27986. };
  27987. Object.defineProperties(Object3D.prototype, {
  27988. eulerOrder: {
  27989. get: function () {
  27990. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  27991. return this.rotation.order;
  27992. },
  27993. set: function (value) {
  27994. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  27995. this.rotation.order = value;
  27996. }
  27997. },
  27998. useQuaternion: {
  27999. get: function () {
  28000. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28001. },
  28002. set: function () {
  28003. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28004. }
  28005. }
  28006. });
  28007. Mesh.prototype.setDrawMode = function () {
  28008. console.error('THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28009. };
  28010. Object.defineProperties(Mesh.prototype, {
  28011. drawMode: {
  28012. get: function () {
  28013. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.');
  28014. return TrianglesDrawMode;
  28015. },
  28016. set: function () {
  28017. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28018. }
  28019. }
  28020. });
  28021. SkinnedMesh.prototype.initBones = function () {
  28022. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  28023. }; //
  28024. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  28025. console.warn('THREE.PerspectiveCamera.setLens is deprecated. ' + 'Use .setFocalLength and .filmGauge for a photographic setup.');
  28026. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  28027. this.setFocalLength(focalLength);
  28028. }; //
  28029. Object.defineProperties(Light.prototype, {
  28030. onlyShadow: {
  28031. set: function () {
  28032. console.warn('THREE.Light: .onlyShadow has been removed.');
  28033. }
  28034. },
  28035. shadowCameraFov: {
  28036. set: function (value) {
  28037. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  28038. this.shadow.camera.fov = value;
  28039. }
  28040. },
  28041. shadowCameraLeft: {
  28042. set: function (value) {
  28043. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  28044. this.shadow.camera.left = value;
  28045. }
  28046. },
  28047. shadowCameraRight: {
  28048. set: function (value) {
  28049. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  28050. this.shadow.camera.right = value;
  28051. }
  28052. },
  28053. shadowCameraTop: {
  28054. set: function (value) {
  28055. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  28056. this.shadow.camera.top = value;
  28057. }
  28058. },
  28059. shadowCameraBottom: {
  28060. set: function (value) {
  28061. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  28062. this.shadow.camera.bottom = value;
  28063. }
  28064. },
  28065. shadowCameraNear: {
  28066. set: function (value) {
  28067. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  28068. this.shadow.camera.near = value;
  28069. }
  28070. },
  28071. shadowCameraFar: {
  28072. set: function (value) {
  28073. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  28074. this.shadow.camera.far = value;
  28075. }
  28076. },
  28077. shadowCameraVisible: {
  28078. set: function () {
  28079. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  28080. }
  28081. },
  28082. shadowBias: {
  28083. set: function (value) {
  28084. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  28085. this.shadow.bias = value;
  28086. }
  28087. },
  28088. shadowDarkness: {
  28089. set: function () {
  28090. console.warn('THREE.Light: .shadowDarkness has been removed.');
  28091. }
  28092. },
  28093. shadowMapWidth: {
  28094. set: function (value) {
  28095. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  28096. this.shadow.mapSize.width = value;
  28097. }
  28098. },
  28099. shadowMapHeight: {
  28100. set: function (value) {
  28101. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  28102. this.shadow.mapSize.height = value;
  28103. }
  28104. }
  28105. }); //
  28106. Object.defineProperties(BufferAttribute.prototype, {
  28107. length: {
  28108. get: function () {
  28109. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  28110. return this.array.length;
  28111. }
  28112. },
  28113. dynamic: {
  28114. get: function () {
  28115. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28116. return this.usage === DynamicDrawUsage;
  28117. },
  28118. set: function ()
  28119. /* value */
  28120. {
  28121. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28122. this.setUsage(DynamicDrawUsage);
  28123. }
  28124. }
  28125. });
  28126. BufferAttribute.prototype.setDynamic = function (value) {
  28127. console.warn('THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28128. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28129. return this;
  28130. };
  28131. BufferAttribute.prototype.copyIndicesArray = function ()
  28132. /* indices */
  28133. {
  28134. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  28135. }, BufferAttribute.prototype.setArray = function ()
  28136. /* array */
  28137. {
  28138. console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28139. }; //
  28140. BufferGeometry.prototype.addIndex = function (index) {
  28141. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  28142. this.setIndex(index);
  28143. };
  28144. BufferGeometry.prototype.addAttribute = function (name, attribute) {
  28145. console.warn('THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().');
  28146. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  28147. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  28148. return this.setAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  28149. }
  28150. if (name === 'index') {
  28151. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  28152. this.setIndex(attribute);
  28153. return this;
  28154. }
  28155. return this.setAttribute(name, attribute);
  28156. };
  28157. BufferGeometry.prototype.addDrawCall = function (start, count, indexOffset) {
  28158. if (indexOffset !== undefined) {
  28159. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  28160. }
  28161. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  28162. this.addGroup(start, count);
  28163. };
  28164. BufferGeometry.prototype.clearDrawCalls = function () {
  28165. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  28166. this.clearGroups();
  28167. };
  28168. BufferGeometry.prototype.computeOffsets = function () {
  28169. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  28170. };
  28171. BufferGeometry.prototype.removeAttribute = function (name) {
  28172. console.warn('THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().');
  28173. return this.deleteAttribute(name);
  28174. };
  28175. BufferGeometry.prototype.applyMatrix = function (matrix) {
  28176. console.warn('THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().');
  28177. return this.applyMatrix4(matrix);
  28178. };
  28179. Object.defineProperties(BufferGeometry.prototype, {
  28180. drawcalls: {
  28181. get: function () {
  28182. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  28183. return this.groups;
  28184. }
  28185. },
  28186. offsets: {
  28187. get: function () {
  28188. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  28189. return this.groups;
  28190. }
  28191. }
  28192. });
  28193. InterleavedBuffer.prototype.setDynamic = function (value) {
  28194. console.warn('THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28195. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28196. return this;
  28197. };
  28198. InterleavedBuffer.prototype.setArray = function ()
  28199. /* array */
  28200. {
  28201. console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28202. }; //
  28203. ExtrudeGeometry.prototype.getArrays = function () {
  28204. console.error('THREE.ExtrudeGeometry: .getArrays() has been removed.');
  28205. };
  28206. ExtrudeGeometry.prototype.addShapeList = function () {
  28207. console.error('THREE.ExtrudeGeometry: .addShapeList() has been removed.');
  28208. };
  28209. ExtrudeGeometry.prototype.addShape = function () {
  28210. console.error('THREE.ExtrudeGeometry: .addShape() has been removed.');
  28211. }; //
  28212. Scene.prototype.dispose = function () {
  28213. console.error('THREE.Scene: .dispose() has been removed.');
  28214. }; //
  28215. Uniform.prototype.onUpdate = function () {
  28216. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  28217. return this;
  28218. }; //
  28219. Object.defineProperties(Material.prototype, {
  28220. wrapAround: {
  28221. get: function () {
  28222. console.warn('THREE.Material: .wrapAround has been removed.');
  28223. },
  28224. set: function () {
  28225. console.warn('THREE.Material: .wrapAround has been removed.');
  28226. }
  28227. },
  28228. overdraw: {
  28229. get: function () {
  28230. console.warn('THREE.Material: .overdraw has been removed.');
  28231. },
  28232. set: function () {
  28233. console.warn('THREE.Material: .overdraw has been removed.');
  28234. }
  28235. },
  28236. wrapRGB: {
  28237. get: function () {
  28238. console.warn('THREE.Material: .wrapRGB has been removed.');
  28239. return new Color();
  28240. }
  28241. },
  28242. shading: {
  28243. get: function () {
  28244. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28245. },
  28246. set: function (value) {
  28247. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28248. this.flatShading = value === FlatShading;
  28249. }
  28250. },
  28251. stencilMask: {
  28252. get: function () {
  28253. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28254. return this.stencilFuncMask;
  28255. },
  28256. set: function (value) {
  28257. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28258. this.stencilFuncMask = value;
  28259. }
  28260. }
  28261. });
  28262. Object.defineProperties(ShaderMaterial.prototype, {
  28263. derivatives: {
  28264. get: function () {
  28265. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28266. return this.extensions.derivatives;
  28267. },
  28268. set: function (value) {
  28269. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28270. this.extensions.derivatives = value;
  28271. }
  28272. }
  28273. }); //
  28274. WebGLRenderer.prototype.clearTarget = function (renderTarget, color, depth, stencil) {
  28275. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  28276. this.setRenderTarget(renderTarget);
  28277. this.clear(color, depth, stencil);
  28278. };
  28279. WebGLRenderer.prototype.animate = function (callback) {
  28280. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  28281. this.setAnimationLoop(callback);
  28282. };
  28283. WebGLRenderer.prototype.getCurrentRenderTarget = function () {
  28284. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  28285. return this.getRenderTarget();
  28286. };
  28287. WebGLRenderer.prototype.getMaxAnisotropy = function () {
  28288. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  28289. return this.capabilities.getMaxAnisotropy();
  28290. };
  28291. WebGLRenderer.prototype.getPrecision = function () {
  28292. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  28293. return this.capabilities.precision;
  28294. };
  28295. WebGLRenderer.prototype.resetGLState = function () {
  28296. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  28297. return this.state.reset();
  28298. };
  28299. WebGLRenderer.prototype.supportsFloatTextures = function () {
  28300. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  28301. return this.extensions.get('OES_texture_float');
  28302. };
  28303. WebGLRenderer.prototype.supportsHalfFloatTextures = function () {
  28304. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  28305. return this.extensions.get('OES_texture_half_float');
  28306. };
  28307. WebGLRenderer.prototype.supportsStandardDerivatives = function () {
  28308. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  28309. return this.extensions.get('OES_standard_derivatives');
  28310. };
  28311. WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () {
  28312. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  28313. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  28314. };
  28315. WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () {
  28316. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  28317. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  28318. };
  28319. WebGLRenderer.prototype.supportsBlendMinMax = function () {
  28320. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  28321. return this.extensions.get('EXT_blend_minmax');
  28322. };
  28323. WebGLRenderer.prototype.supportsVertexTextures = function () {
  28324. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  28325. return this.capabilities.vertexTextures;
  28326. };
  28327. WebGLRenderer.prototype.supportsInstancedArrays = function () {
  28328. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  28329. return this.extensions.get('ANGLE_instanced_arrays');
  28330. };
  28331. WebGLRenderer.prototype.enableScissorTest = function (boolean) {
  28332. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  28333. this.setScissorTest(boolean);
  28334. };
  28335. WebGLRenderer.prototype.initMaterial = function () {
  28336. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  28337. };
  28338. WebGLRenderer.prototype.addPrePlugin = function () {
  28339. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  28340. };
  28341. WebGLRenderer.prototype.addPostPlugin = function () {
  28342. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  28343. };
  28344. WebGLRenderer.prototype.updateShadowMap = function () {
  28345. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  28346. };
  28347. WebGLRenderer.prototype.setFaceCulling = function () {
  28348. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  28349. };
  28350. WebGLRenderer.prototype.allocTextureUnit = function () {
  28351. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  28352. };
  28353. WebGLRenderer.prototype.setTexture = function () {
  28354. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  28355. };
  28356. WebGLRenderer.prototype.setTexture2D = function () {
  28357. console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
  28358. };
  28359. WebGLRenderer.prototype.setTextureCube = function () {
  28360. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  28361. };
  28362. WebGLRenderer.prototype.getActiveMipMapLevel = function () {
  28363. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  28364. return this.getActiveMipmapLevel();
  28365. };
  28366. Object.defineProperties(WebGLRenderer.prototype, {
  28367. shadowMapEnabled: {
  28368. get: function () {
  28369. return this.shadowMap.enabled;
  28370. },
  28371. set: function (value) {
  28372. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  28373. this.shadowMap.enabled = value;
  28374. }
  28375. },
  28376. shadowMapType: {
  28377. get: function () {
  28378. return this.shadowMap.type;
  28379. },
  28380. set: function (value) {
  28381. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  28382. this.shadowMap.type = value;
  28383. }
  28384. },
  28385. shadowMapCullFace: {
  28386. get: function () {
  28387. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  28388. return undefined;
  28389. },
  28390. set: function ()
  28391. /* value */
  28392. {
  28393. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  28394. }
  28395. },
  28396. context: {
  28397. get: function () {
  28398. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  28399. return this.getContext();
  28400. }
  28401. },
  28402. vr: {
  28403. get: function () {
  28404. console.warn('THREE.WebGLRenderer: .vr has been renamed to .xr');
  28405. return this.xr;
  28406. }
  28407. },
  28408. gammaInput: {
  28409. get: function () {
  28410. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  28411. return false;
  28412. },
  28413. set: function () {
  28414. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  28415. }
  28416. },
  28417. gammaOutput: {
  28418. get: function () {
  28419. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  28420. return false;
  28421. },
  28422. set: function (value) {
  28423. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  28424. this.outputEncoding = value === true ? sRGBEncoding : LinearEncoding;
  28425. }
  28426. },
  28427. toneMappingWhitePoint: {
  28428. get: function () {
  28429. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  28430. return 1.0;
  28431. },
  28432. set: function () {
  28433. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  28434. }
  28435. }
  28436. });
  28437. Object.defineProperties(WebGLShadowMap.prototype, {
  28438. cullFace: {
  28439. get: function () {
  28440. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  28441. return undefined;
  28442. },
  28443. set: function ()
  28444. /* cullFace */
  28445. {
  28446. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  28447. }
  28448. },
  28449. renderReverseSided: {
  28450. get: function () {
  28451. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  28452. return undefined;
  28453. },
  28454. set: function () {
  28455. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  28456. }
  28457. },
  28458. renderSingleSided: {
  28459. get: function () {
  28460. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  28461. return undefined;
  28462. },
  28463. set: function () {
  28464. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  28465. }
  28466. }
  28467. });
  28468. function WebGLRenderTargetCube(width, height, options) {
  28469. console.warn('THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).');
  28470. return new WebGLCubeRenderTarget(width, options);
  28471. } //
  28472. Object.defineProperties(WebGLRenderTarget.prototype, {
  28473. wrapS: {
  28474. get: function () {
  28475. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  28476. return this.texture.wrapS;
  28477. },
  28478. set: function (value) {
  28479. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  28480. this.texture.wrapS = value;
  28481. }
  28482. },
  28483. wrapT: {
  28484. get: function () {
  28485. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  28486. return this.texture.wrapT;
  28487. },
  28488. set: function (value) {
  28489. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  28490. this.texture.wrapT = value;
  28491. }
  28492. },
  28493. magFilter: {
  28494. get: function () {
  28495. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  28496. return this.texture.magFilter;
  28497. },
  28498. set: function (value) {
  28499. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  28500. this.texture.magFilter = value;
  28501. }
  28502. },
  28503. minFilter: {
  28504. get: function () {
  28505. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  28506. return this.texture.minFilter;
  28507. },
  28508. set: function (value) {
  28509. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  28510. this.texture.minFilter = value;
  28511. }
  28512. },
  28513. anisotropy: {
  28514. get: function () {
  28515. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  28516. return this.texture.anisotropy;
  28517. },
  28518. set: function (value) {
  28519. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  28520. this.texture.anisotropy = value;
  28521. }
  28522. },
  28523. offset: {
  28524. get: function () {
  28525. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  28526. return this.texture.offset;
  28527. },
  28528. set: function (value) {
  28529. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  28530. this.texture.offset = value;
  28531. }
  28532. },
  28533. repeat: {
  28534. get: function () {
  28535. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  28536. return this.texture.repeat;
  28537. },
  28538. set: function (value) {
  28539. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  28540. this.texture.repeat = value;
  28541. }
  28542. },
  28543. format: {
  28544. get: function () {
  28545. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  28546. return this.texture.format;
  28547. },
  28548. set: function (value) {
  28549. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  28550. this.texture.format = value;
  28551. }
  28552. },
  28553. type: {
  28554. get: function () {
  28555. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  28556. return this.texture.type;
  28557. },
  28558. set: function (value) {
  28559. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  28560. this.texture.type = value;
  28561. }
  28562. },
  28563. generateMipmaps: {
  28564. get: function () {
  28565. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  28566. return this.texture.generateMipmaps;
  28567. },
  28568. set: function (value) {
  28569. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  28570. this.texture.generateMipmaps = value;
  28571. }
  28572. }
  28573. }); //
  28574. Audio.prototype.load = function (file) {
  28575. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  28576. const scope = this;
  28577. const audioLoader = new AudioLoader();
  28578. audioLoader.load(file, function (buffer) {
  28579. scope.setBuffer(buffer);
  28580. });
  28581. return this;
  28582. };
  28583. AudioAnalyser.prototype.getData = function () {
  28584. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  28585. return this.getFrequencyData();
  28586. }; //
  28587. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  28588. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  28589. return this.update(renderer, scene);
  28590. };
  28591. CubeCamera.prototype.clear = function (renderer, color, depth, stencil) {
  28592. console.warn('THREE.CubeCamera: .clear() is now .renderTarget.clear().');
  28593. return this.renderTarget.clear(renderer, color, depth, stencil);
  28594. };
  28595. ImageUtils.crossOrigin = undefined;
  28596. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  28597. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  28598. const loader = new TextureLoader();
  28599. loader.setCrossOrigin(this.crossOrigin);
  28600. const texture = loader.load(url, onLoad, undefined, onError);
  28601. if (mapping) texture.mapping = mapping;
  28602. return texture;
  28603. };
  28604. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  28605. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  28606. const loader = new CubeTextureLoader();
  28607. loader.setCrossOrigin(this.crossOrigin);
  28608. const texture = loader.load(urls, onLoad, undefined, onError);
  28609. if (mapping) texture.mapping = mapping;
  28610. return texture;
  28611. };
  28612. ImageUtils.loadCompressedTexture = function () {
  28613. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  28614. };
  28615. ImageUtils.loadCompressedTextureCube = function () {
  28616. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  28617. }; //
  28618. function CanvasRenderer() {
  28619. console.error('THREE.CanvasRenderer has been removed');
  28620. } //
  28621. function JSONLoader() {
  28622. console.error('THREE.JSONLoader has been removed.');
  28623. } //
  28624. const SceneUtils = {
  28625. createMultiMaterialObject: function ()
  28626. /* geometry, materials */
  28627. {
  28628. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28629. },
  28630. detach: function ()
  28631. /* child, parent, scene */
  28632. {
  28633. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28634. },
  28635. attach: function ()
  28636. /* child, scene, parent */
  28637. {
  28638. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28639. }
  28640. }; //
  28641. function LensFlare() {
  28642. console.error('THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js');
  28643. }
  28644. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  28645. /* eslint-disable no-undef */
  28646. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  28647. detail: {
  28648. revision: REVISION
  28649. }
  28650. }));
  28651. /* eslint-enable no-undef */
  28652. }
  28653. if (typeof window !== 'undefined') {
  28654. if (window.__THREE__) {
  28655. console.warn('WARNING: Multiple instances of Three.js being imported.');
  28656. } else {
  28657. window.__THREE__ = REVISION;
  28658. }
  28659. }
  28660. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  28661. exports.AddEquation = AddEquation;
  28662. exports.AddOperation = AddOperation;
  28663. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  28664. exports.AdditiveBlending = AdditiveBlending;
  28665. exports.AlphaFormat = AlphaFormat;
  28666. exports.AlwaysDepth = AlwaysDepth;
  28667. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  28668. exports.AmbientLight = AmbientLight;
  28669. exports.AmbientLightProbe = AmbientLightProbe;
  28670. exports.AnimationClip = AnimationClip;
  28671. exports.AnimationLoader = AnimationLoader;
  28672. exports.AnimationMixer = AnimationMixer;
  28673. exports.AnimationObjectGroup = AnimationObjectGroup;
  28674. exports.AnimationUtils = AnimationUtils;
  28675. exports.ArcCurve = ArcCurve;
  28676. exports.ArrayCamera = ArrayCamera;
  28677. exports.ArrowHelper = ArrowHelper;
  28678. exports.Audio = Audio;
  28679. exports.AudioAnalyser = AudioAnalyser;
  28680. exports.AudioContext = AudioContext;
  28681. exports.AudioListener = AudioListener;
  28682. exports.AudioLoader = AudioLoader;
  28683. exports.AxesHelper = AxesHelper;
  28684. exports.AxisHelper = AxisHelper;
  28685. exports.BackSide = BackSide;
  28686. exports.BasicDepthPacking = BasicDepthPacking;
  28687. exports.BasicShadowMap = BasicShadowMap;
  28688. exports.BinaryTextureLoader = BinaryTextureLoader;
  28689. exports.Bone = Bone;
  28690. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  28691. exports.BoundingBoxHelper = BoundingBoxHelper;
  28692. exports.Box2 = Box2;
  28693. exports.Box3 = Box3;
  28694. exports.Box3Helper = Box3Helper;
  28695. exports.BoxBufferGeometry = BoxGeometry;
  28696. exports.BoxGeometry = BoxGeometry;
  28697. exports.BoxHelper = BoxHelper;
  28698. exports.BufferAttribute = BufferAttribute;
  28699. exports.BufferGeometry = BufferGeometry;
  28700. exports.BufferGeometryLoader = BufferGeometryLoader;
  28701. exports.ByteType = ByteType;
  28702. exports.Cache = Cache;
  28703. exports.Camera = Camera;
  28704. exports.CameraHelper = CameraHelper;
  28705. exports.CanvasRenderer = CanvasRenderer;
  28706. exports.CanvasTexture = CanvasTexture;
  28707. exports.CatmullRomCurve3 = CatmullRomCurve3;
  28708. exports.CineonToneMapping = CineonToneMapping;
  28709. exports.CircleBufferGeometry = CircleGeometry;
  28710. exports.CircleGeometry = CircleGeometry;
  28711. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  28712. exports.Clock = Clock;
  28713. exports.Color = Color;
  28714. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  28715. exports.CompressedTexture = CompressedTexture;
  28716. exports.CompressedTextureLoader = CompressedTextureLoader;
  28717. exports.ConeBufferGeometry = ConeGeometry;
  28718. exports.ConeGeometry = ConeGeometry;
  28719. exports.CubeCamera = CubeCamera;
  28720. exports.CubeReflectionMapping = CubeReflectionMapping;
  28721. exports.CubeRefractionMapping = CubeRefractionMapping;
  28722. exports.CubeTexture = CubeTexture;
  28723. exports.CubeTextureLoader = CubeTextureLoader;
  28724. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  28725. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  28726. exports.CubicBezierCurve = CubicBezierCurve;
  28727. exports.CubicBezierCurve3 = CubicBezierCurve3;
  28728. exports.CubicInterpolant = CubicInterpolant;
  28729. exports.CullFaceBack = CullFaceBack;
  28730. exports.CullFaceFront = CullFaceFront;
  28731. exports.CullFaceFrontBack = CullFaceFrontBack;
  28732. exports.CullFaceNone = CullFaceNone;
  28733. exports.Curve = Curve;
  28734. exports.CurvePath = CurvePath;
  28735. exports.CustomBlending = CustomBlending;
  28736. exports.CustomToneMapping = CustomToneMapping;
  28737. exports.CylinderBufferGeometry = CylinderGeometry;
  28738. exports.CylinderGeometry = CylinderGeometry;
  28739. exports.Cylindrical = Cylindrical;
  28740. exports.DataTexture = DataTexture;
  28741. exports.DataTexture2DArray = DataTexture2DArray;
  28742. exports.DataTexture3D = DataTexture3D;
  28743. exports.DataTextureLoader = DataTextureLoader;
  28744. exports.DataUtils = DataUtils;
  28745. exports.DecrementStencilOp = DecrementStencilOp;
  28746. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  28747. exports.DefaultLoadingManager = DefaultLoadingManager;
  28748. exports.DepthFormat = DepthFormat;
  28749. exports.DepthStencilFormat = DepthStencilFormat;
  28750. exports.DepthTexture = DepthTexture;
  28751. exports.DirectionalLight = DirectionalLight;
  28752. exports.DirectionalLightHelper = DirectionalLightHelper;
  28753. exports.DiscreteInterpolant = DiscreteInterpolant;
  28754. exports.DodecahedronBufferGeometry = DodecahedronGeometry;
  28755. exports.DodecahedronGeometry = DodecahedronGeometry;
  28756. exports.DoubleSide = DoubleSide;
  28757. exports.DstAlphaFactor = DstAlphaFactor;
  28758. exports.DstColorFactor = DstColorFactor;
  28759. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  28760. exports.DynamicCopyUsage = DynamicCopyUsage;
  28761. exports.DynamicDrawUsage = DynamicDrawUsage;
  28762. exports.DynamicReadUsage = DynamicReadUsage;
  28763. exports.EdgesGeometry = EdgesGeometry;
  28764. exports.EdgesHelper = EdgesHelper;
  28765. exports.EllipseCurve = EllipseCurve;
  28766. exports.EqualDepth = EqualDepth;
  28767. exports.EqualStencilFunc = EqualStencilFunc;
  28768. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  28769. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  28770. exports.Euler = Euler;
  28771. exports.EventDispatcher = EventDispatcher;
  28772. exports.ExtrudeBufferGeometry = ExtrudeGeometry;
  28773. exports.ExtrudeGeometry = ExtrudeGeometry;
  28774. exports.FaceColors = FaceColors;
  28775. exports.FileLoader = FileLoader;
  28776. exports.FlatShading = FlatShading;
  28777. exports.Float16BufferAttribute = Float16BufferAttribute;
  28778. exports.Float32Attribute = Float32Attribute;
  28779. exports.Float32BufferAttribute = Float32BufferAttribute;
  28780. exports.Float64Attribute = Float64Attribute;
  28781. exports.Float64BufferAttribute = Float64BufferAttribute;
  28782. exports.FloatType = FloatType;
  28783. exports.Fog = Fog;
  28784. exports.FogExp2 = FogExp2;
  28785. exports.Font = Font;
  28786. exports.FontLoader = FontLoader;
  28787. exports.FrontSide = FrontSide;
  28788. exports.Frustum = Frustum;
  28789. exports.GLBufferAttribute = GLBufferAttribute;
  28790. exports.GLSL1 = GLSL1;
  28791. exports.GLSL3 = GLSL3;
  28792. exports.GammaEncoding = GammaEncoding;
  28793. exports.GreaterDepth = GreaterDepth;
  28794. exports.GreaterEqualDepth = GreaterEqualDepth;
  28795. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  28796. exports.GreaterStencilFunc = GreaterStencilFunc;
  28797. exports.GridHelper = GridHelper;
  28798. exports.Group = Group;
  28799. exports.HalfFloatType = HalfFloatType;
  28800. exports.HemisphereLight = HemisphereLight;
  28801. exports.HemisphereLightHelper = HemisphereLightHelper;
  28802. exports.HemisphereLightProbe = HemisphereLightProbe;
  28803. exports.IcosahedronBufferGeometry = IcosahedronGeometry;
  28804. exports.IcosahedronGeometry = IcosahedronGeometry;
  28805. exports.ImageBitmapLoader = ImageBitmapLoader;
  28806. exports.ImageLoader = ImageLoader;
  28807. exports.ImageUtils = ImageUtils;
  28808. exports.ImmediateRenderObject = ImmediateRenderObject;
  28809. exports.IncrementStencilOp = IncrementStencilOp;
  28810. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  28811. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  28812. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  28813. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  28814. exports.InstancedMesh = InstancedMesh;
  28815. exports.Int16Attribute = Int16Attribute;
  28816. exports.Int16BufferAttribute = Int16BufferAttribute;
  28817. exports.Int32Attribute = Int32Attribute;
  28818. exports.Int32BufferAttribute = Int32BufferAttribute;
  28819. exports.Int8Attribute = Int8Attribute;
  28820. exports.Int8BufferAttribute = Int8BufferAttribute;
  28821. exports.IntType = IntType;
  28822. exports.InterleavedBuffer = InterleavedBuffer;
  28823. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  28824. exports.Interpolant = Interpolant;
  28825. exports.InterpolateDiscrete = InterpolateDiscrete;
  28826. exports.InterpolateLinear = InterpolateLinear;
  28827. exports.InterpolateSmooth = InterpolateSmooth;
  28828. exports.InvertStencilOp = InvertStencilOp;
  28829. exports.JSONLoader = JSONLoader;
  28830. exports.KeepStencilOp = KeepStencilOp;
  28831. exports.KeyframeTrack = KeyframeTrack;
  28832. exports.LOD = LOD;
  28833. exports.LatheBufferGeometry = LatheGeometry;
  28834. exports.LatheGeometry = LatheGeometry;
  28835. exports.Layers = Layers;
  28836. exports.LensFlare = LensFlare;
  28837. exports.LessDepth = LessDepth;
  28838. exports.LessEqualDepth = LessEqualDepth;
  28839. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  28840. exports.LessStencilFunc = LessStencilFunc;
  28841. exports.Light = Light;
  28842. exports.LightProbe = LightProbe;
  28843. exports.Line = Line;
  28844. exports.Line3 = Line3;
  28845. exports.LineBasicMaterial = LineBasicMaterial;
  28846. exports.LineCurve = LineCurve;
  28847. exports.LineCurve3 = LineCurve3;
  28848. exports.LineDashedMaterial = LineDashedMaterial;
  28849. exports.LineLoop = LineLoop;
  28850. exports.LinePieces = LinePieces;
  28851. exports.LineSegments = LineSegments;
  28852. exports.LineStrip = LineStrip;
  28853. exports.LinearEncoding = LinearEncoding;
  28854. exports.LinearFilter = LinearFilter;
  28855. exports.LinearInterpolant = LinearInterpolant;
  28856. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  28857. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  28858. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  28859. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  28860. exports.LinearToneMapping = LinearToneMapping;
  28861. exports.Loader = Loader;
  28862. exports.LoaderUtils = LoaderUtils;
  28863. exports.LoadingManager = LoadingManager;
  28864. exports.LogLuvEncoding = LogLuvEncoding;
  28865. exports.LoopOnce = LoopOnce;
  28866. exports.LoopPingPong = LoopPingPong;
  28867. exports.LoopRepeat = LoopRepeat;
  28868. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  28869. exports.LuminanceFormat = LuminanceFormat;
  28870. exports.MOUSE = MOUSE;
  28871. exports.Material = Material;
  28872. exports.MaterialLoader = MaterialLoader;
  28873. exports.Math = MathUtils;
  28874. exports.MathUtils = MathUtils;
  28875. exports.Matrix3 = Matrix3;
  28876. exports.Matrix4 = Matrix4;
  28877. exports.MaxEquation = MaxEquation;
  28878. exports.Mesh = Mesh;
  28879. exports.MeshBasicMaterial = MeshBasicMaterial;
  28880. exports.MeshDepthMaterial = MeshDepthMaterial;
  28881. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  28882. exports.MeshFaceMaterial = MeshFaceMaterial;
  28883. exports.MeshLambertMaterial = MeshLambertMaterial;
  28884. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  28885. exports.MeshNormalMaterial = MeshNormalMaterial;
  28886. exports.MeshPhongMaterial = MeshPhongMaterial;
  28887. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  28888. exports.MeshStandardMaterial = MeshStandardMaterial;
  28889. exports.MeshToonMaterial = MeshToonMaterial;
  28890. exports.MinEquation = MinEquation;
  28891. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  28892. exports.MixOperation = MixOperation;
  28893. exports.MultiMaterial = MultiMaterial;
  28894. exports.MultiplyBlending = MultiplyBlending;
  28895. exports.MultiplyOperation = MultiplyOperation;
  28896. exports.NearestFilter = NearestFilter;
  28897. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  28898. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  28899. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  28900. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  28901. exports.NeverDepth = NeverDepth;
  28902. exports.NeverStencilFunc = NeverStencilFunc;
  28903. exports.NoBlending = NoBlending;
  28904. exports.NoColors = NoColors;
  28905. exports.NoToneMapping = NoToneMapping;
  28906. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  28907. exports.NormalBlending = NormalBlending;
  28908. exports.NotEqualDepth = NotEqualDepth;
  28909. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  28910. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  28911. exports.Object3D = Object3D;
  28912. exports.ObjectLoader = ObjectLoader;
  28913. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  28914. exports.OctahedronBufferGeometry = OctahedronGeometry;
  28915. exports.OctahedronGeometry = OctahedronGeometry;
  28916. exports.OneFactor = OneFactor;
  28917. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  28918. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  28919. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  28920. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  28921. exports.OrthographicCamera = OrthographicCamera;
  28922. exports.PCFShadowMap = PCFShadowMap;
  28923. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  28924. exports.PMREMGenerator = PMREMGenerator;
  28925. exports.ParametricBufferGeometry = ParametricGeometry;
  28926. exports.ParametricGeometry = ParametricGeometry;
  28927. exports.Particle = Particle;
  28928. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  28929. exports.ParticleSystem = ParticleSystem;
  28930. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  28931. exports.Path = Path;
  28932. exports.PerspectiveCamera = PerspectiveCamera;
  28933. exports.Plane = Plane;
  28934. exports.PlaneBufferGeometry = PlaneGeometry;
  28935. exports.PlaneGeometry = PlaneGeometry;
  28936. exports.PlaneHelper = PlaneHelper;
  28937. exports.PointCloud = PointCloud;
  28938. exports.PointCloudMaterial = PointCloudMaterial;
  28939. exports.PointLight = PointLight;
  28940. exports.PointLightHelper = PointLightHelper;
  28941. exports.Points = Points;
  28942. exports.PointsMaterial = PointsMaterial;
  28943. exports.PolarGridHelper = PolarGridHelper;
  28944. exports.PolyhedronBufferGeometry = PolyhedronGeometry;
  28945. exports.PolyhedronGeometry = PolyhedronGeometry;
  28946. exports.PositionalAudio = PositionalAudio;
  28947. exports.PropertyBinding = PropertyBinding;
  28948. exports.PropertyMixer = PropertyMixer;
  28949. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  28950. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  28951. exports.Quaternion = Quaternion;
  28952. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  28953. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  28954. exports.REVISION = REVISION;
  28955. exports.RGBADepthPacking = RGBADepthPacking;
  28956. exports.RGBAFormat = RGBAFormat;
  28957. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  28958. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  28959. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  28960. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  28961. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  28962. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  28963. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  28964. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  28965. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  28966. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  28967. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  28968. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  28969. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  28970. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  28971. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  28972. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  28973. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  28974. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  28975. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  28976. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  28977. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  28978. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  28979. exports.RGBDEncoding = RGBDEncoding;
  28980. exports.RGBEEncoding = RGBEEncoding;
  28981. exports.RGBEFormat = RGBEFormat;
  28982. exports.RGBFormat = RGBFormat;
  28983. exports.RGBIntegerFormat = RGBIntegerFormat;
  28984. exports.RGBM16Encoding = RGBM16Encoding;
  28985. exports.RGBM7Encoding = RGBM7Encoding;
  28986. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  28987. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  28988. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  28989. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  28990. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  28991. exports.RGFormat = RGFormat;
  28992. exports.RGIntegerFormat = RGIntegerFormat;
  28993. exports.RawShaderMaterial = RawShaderMaterial;
  28994. exports.Ray = Ray;
  28995. exports.Raycaster = Raycaster;
  28996. exports.RectAreaLight = RectAreaLight;
  28997. exports.RedFormat = RedFormat;
  28998. exports.RedIntegerFormat = RedIntegerFormat;
  28999. exports.ReinhardToneMapping = ReinhardToneMapping;
  29000. exports.RepeatWrapping = RepeatWrapping;
  29001. exports.ReplaceStencilOp = ReplaceStencilOp;
  29002. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  29003. exports.RingBufferGeometry = RingGeometry;
  29004. exports.RingGeometry = RingGeometry;
  29005. exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
  29006. exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
  29007. exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
  29008. exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
  29009. exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
  29010. exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
  29011. exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
  29012. exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
  29013. exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
  29014. exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
  29015. exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
  29016. exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
  29017. exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
  29018. exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
  29019. exports.Scene = Scene;
  29020. exports.SceneUtils = SceneUtils;
  29021. exports.ShaderChunk = ShaderChunk;
  29022. exports.ShaderLib = ShaderLib;
  29023. exports.ShaderMaterial = ShaderMaterial;
  29024. exports.ShadowMaterial = ShadowMaterial;
  29025. exports.Shape = Shape;
  29026. exports.ShapeBufferGeometry = ShapeGeometry;
  29027. exports.ShapeGeometry = ShapeGeometry;
  29028. exports.ShapePath = ShapePath;
  29029. exports.ShapeUtils = ShapeUtils;
  29030. exports.ShortType = ShortType;
  29031. exports.Skeleton = Skeleton;
  29032. exports.SkeletonHelper = SkeletonHelper;
  29033. exports.SkinnedMesh = SkinnedMesh;
  29034. exports.SmoothShading = SmoothShading;
  29035. exports.Sphere = Sphere;
  29036. exports.SphereBufferGeometry = SphereGeometry;
  29037. exports.SphereGeometry = SphereGeometry;
  29038. exports.Spherical = Spherical;
  29039. exports.SphericalHarmonics3 = SphericalHarmonics3;
  29040. exports.SplineCurve = SplineCurve;
  29041. exports.SpotLight = SpotLight;
  29042. exports.SpotLightHelper = SpotLightHelper;
  29043. exports.Sprite = Sprite;
  29044. exports.SpriteMaterial = SpriteMaterial;
  29045. exports.SrcAlphaFactor = SrcAlphaFactor;
  29046. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  29047. exports.SrcColorFactor = SrcColorFactor;
  29048. exports.StaticCopyUsage = StaticCopyUsage;
  29049. exports.StaticDrawUsage = StaticDrawUsage;
  29050. exports.StaticReadUsage = StaticReadUsage;
  29051. exports.StereoCamera = StereoCamera;
  29052. exports.StreamCopyUsage = StreamCopyUsage;
  29053. exports.StreamDrawUsage = StreamDrawUsage;
  29054. exports.StreamReadUsage = StreamReadUsage;
  29055. exports.StringKeyframeTrack = StringKeyframeTrack;
  29056. exports.SubtractEquation = SubtractEquation;
  29057. exports.SubtractiveBlending = SubtractiveBlending;
  29058. exports.TOUCH = TOUCH;
  29059. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  29060. exports.TetrahedronBufferGeometry = TetrahedronGeometry;
  29061. exports.TetrahedronGeometry = TetrahedronGeometry;
  29062. exports.TextBufferGeometry = TextGeometry;
  29063. exports.TextGeometry = TextGeometry;
  29064. exports.Texture = Texture;
  29065. exports.TextureLoader = TextureLoader;
  29066. exports.TorusBufferGeometry = TorusGeometry;
  29067. exports.TorusGeometry = TorusGeometry;
  29068. exports.TorusKnotBufferGeometry = TorusKnotGeometry;
  29069. exports.TorusKnotGeometry = TorusKnotGeometry;
  29070. exports.Triangle = Triangle;
  29071. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  29072. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  29073. exports.TrianglesDrawMode = TrianglesDrawMode;
  29074. exports.TubeBufferGeometry = TubeGeometry;
  29075. exports.TubeGeometry = TubeGeometry;
  29076. exports.UVMapping = UVMapping;
  29077. exports.Uint16Attribute = Uint16Attribute;
  29078. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  29079. exports.Uint32Attribute = Uint32Attribute;
  29080. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  29081. exports.Uint8Attribute = Uint8Attribute;
  29082. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  29083. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  29084. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  29085. exports.Uniform = Uniform;
  29086. exports.UniformsLib = UniformsLib;
  29087. exports.UniformsUtils = UniformsUtils;
  29088. exports.UnsignedByteType = UnsignedByteType;
  29089. exports.UnsignedInt248Type = UnsignedInt248Type;
  29090. exports.UnsignedIntType = UnsignedIntType;
  29091. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  29092. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  29093. exports.UnsignedShort565Type = UnsignedShort565Type;
  29094. exports.UnsignedShortType = UnsignedShortType;
  29095. exports.VSMShadowMap = VSMShadowMap;
  29096. exports.Vector2 = Vector2;
  29097. exports.Vector3 = Vector3;
  29098. exports.Vector4 = Vector4;
  29099. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  29100. exports.Vertex = Vertex;
  29101. exports.VertexColors = VertexColors;
  29102. exports.VideoTexture = VideoTexture;
  29103. exports.WebGL1Renderer = WebGL1Renderer;
  29104. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  29105. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  29106. exports.WebGLRenderTarget = WebGLRenderTarget;
  29107. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  29108. exports.WebGLRenderer = WebGLRenderer;
  29109. exports.WebGLUtils = WebGLUtils;
  29110. exports.WireframeGeometry = WireframeGeometry;
  29111. exports.WireframeHelper = WireframeHelper;
  29112. exports.WrapAroundEnding = WrapAroundEnding;
  29113. exports.XHRLoader = XHRLoader;
  29114. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  29115. exports.ZeroFactor = ZeroFactor;
  29116. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  29117. exports.ZeroStencilOp = ZeroStencilOp;
  29118. exports.sRGBEncoding = sRGBEncoding;
  29119. Object.defineProperty(exports, '__esModule', { value: true });
  29120. })));