three.js 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488
  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 = '132';
  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. this.isRenderTargetTexture = false;
  993. }
  994. updateMatrix() {
  995. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  996. }
  997. clone() {
  998. return new this.constructor().copy(this);
  999. }
  1000. copy(source) {
  1001. this.name = source.name;
  1002. this.image = source.image;
  1003. this.mipmaps = source.mipmaps.slice(0);
  1004. this.mapping = source.mapping;
  1005. this.wrapS = source.wrapS;
  1006. this.wrapT = source.wrapT;
  1007. this.magFilter = source.magFilter;
  1008. this.minFilter = source.minFilter;
  1009. this.anisotropy = source.anisotropy;
  1010. this.format = source.format;
  1011. this.internalFormat = source.internalFormat;
  1012. this.type = source.type;
  1013. this.offset.copy(source.offset);
  1014. this.repeat.copy(source.repeat);
  1015. this.center.copy(source.center);
  1016. this.rotation = source.rotation;
  1017. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1018. this.matrix.copy(source.matrix);
  1019. this.generateMipmaps = source.generateMipmaps;
  1020. this.premultiplyAlpha = source.premultiplyAlpha;
  1021. this.flipY = source.flipY;
  1022. this.unpackAlignment = source.unpackAlignment;
  1023. this.encoding = source.encoding;
  1024. return this;
  1025. }
  1026. toJSON(meta) {
  1027. const isRootObject = meta === undefined || typeof meta === 'string';
  1028. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  1029. return meta.textures[this.uuid];
  1030. }
  1031. const output = {
  1032. metadata: {
  1033. version: 4.5,
  1034. type: 'Texture',
  1035. generator: 'Texture.toJSON'
  1036. },
  1037. uuid: this.uuid,
  1038. name: this.name,
  1039. mapping: this.mapping,
  1040. repeat: [this.repeat.x, this.repeat.y],
  1041. offset: [this.offset.x, this.offset.y],
  1042. center: [this.center.x, this.center.y],
  1043. rotation: this.rotation,
  1044. wrap: [this.wrapS, this.wrapT],
  1045. format: this.format,
  1046. type: this.type,
  1047. encoding: this.encoding,
  1048. minFilter: this.minFilter,
  1049. magFilter: this.magFilter,
  1050. anisotropy: this.anisotropy,
  1051. flipY: this.flipY,
  1052. premultiplyAlpha: this.premultiplyAlpha,
  1053. unpackAlignment: this.unpackAlignment
  1054. };
  1055. if (this.image !== undefined) {
  1056. // TODO: Move to THREE.Image
  1057. const image = this.image;
  1058. if (image.uuid === undefined) {
  1059. image.uuid = generateUUID(); // UGH
  1060. }
  1061. if (!isRootObject && meta.images[image.uuid] === undefined) {
  1062. let url;
  1063. if (Array.isArray(image)) {
  1064. // process array of images e.g. CubeTexture
  1065. url = [];
  1066. for (let i = 0, l = image.length; i < l; i++) {
  1067. // check cube texture with data textures
  1068. if (image[i].isDataTexture) {
  1069. url.push(serializeImage(image[i].image));
  1070. } else {
  1071. url.push(serializeImage(image[i]));
  1072. }
  1073. }
  1074. } else {
  1075. // process single image
  1076. url = serializeImage(image);
  1077. }
  1078. meta.images[image.uuid] = {
  1079. uuid: image.uuid,
  1080. url: url
  1081. };
  1082. }
  1083. output.image = image.uuid;
  1084. }
  1085. if (!isRootObject) {
  1086. meta.textures[this.uuid] = output;
  1087. }
  1088. return output;
  1089. }
  1090. dispose() {
  1091. this.dispatchEvent({
  1092. type: 'dispose'
  1093. });
  1094. }
  1095. transformUv(uv) {
  1096. if (this.mapping !== UVMapping) return uv;
  1097. uv.applyMatrix3(this.matrix);
  1098. if (uv.x < 0 || uv.x > 1) {
  1099. switch (this.wrapS) {
  1100. case RepeatWrapping:
  1101. uv.x = uv.x - Math.floor(uv.x);
  1102. break;
  1103. case ClampToEdgeWrapping:
  1104. uv.x = uv.x < 0 ? 0 : 1;
  1105. break;
  1106. case MirroredRepeatWrapping:
  1107. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  1108. uv.x = Math.ceil(uv.x) - uv.x;
  1109. } else {
  1110. uv.x = uv.x - Math.floor(uv.x);
  1111. }
  1112. break;
  1113. }
  1114. }
  1115. if (uv.y < 0 || uv.y > 1) {
  1116. switch (this.wrapT) {
  1117. case RepeatWrapping:
  1118. uv.y = uv.y - Math.floor(uv.y);
  1119. break;
  1120. case ClampToEdgeWrapping:
  1121. uv.y = uv.y < 0 ? 0 : 1;
  1122. break;
  1123. case MirroredRepeatWrapping:
  1124. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  1125. uv.y = Math.ceil(uv.y) - uv.y;
  1126. } else {
  1127. uv.y = uv.y - Math.floor(uv.y);
  1128. }
  1129. break;
  1130. }
  1131. }
  1132. if (this.flipY) {
  1133. uv.y = 1 - uv.y;
  1134. }
  1135. return uv;
  1136. }
  1137. set needsUpdate(value) {
  1138. if (value === true) this.version++;
  1139. }
  1140. }
  1141. Texture.DEFAULT_IMAGE = undefined;
  1142. Texture.DEFAULT_MAPPING = UVMapping;
  1143. Texture.prototype.isTexture = true;
  1144. function serializeImage(image) {
  1145. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  1146. // default images
  1147. return ImageUtils.getDataURL(image);
  1148. } else {
  1149. if (image.data) {
  1150. // images of DataTexture
  1151. return {
  1152. data: Array.prototype.slice.call(image.data),
  1153. width: image.width,
  1154. height: image.height,
  1155. type: image.data.constructor.name
  1156. };
  1157. } else {
  1158. console.warn('THREE.Texture: Unable to serialize Texture.');
  1159. return {};
  1160. }
  1161. }
  1162. }
  1163. class Vector4 {
  1164. constructor(x = 0, y = 0, z = 0, w = 1) {
  1165. this.x = x;
  1166. this.y = y;
  1167. this.z = z;
  1168. this.w = w;
  1169. }
  1170. get width() {
  1171. return this.z;
  1172. }
  1173. set width(value) {
  1174. this.z = value;
  1175. }
  1176. get height() {
  1177. return this.w;
  1178. }
  1179. set height(value) {
  1180. this.w = value;
  1181. }
  1182. set(x, y, z, w) {
  1183. this.x = x;
  1184. this.y = y;
  1185. this.z = z;
  1186. this.w = w;
  1187. return this;
  1188. }
  1189. setScalar(scalar) {
  1190. this.x = scalar;
  1191. this.y = scalar;
  1192. this.z = scalar;
  1193. this.w = scalar;
  1194. return this;
  1195. }
  1196. setX(x) {
  1197. this.x = x;
  1198. return this;
  1199. }
  1200. setY(y) {
  1201. this.y = y;
  1202. return this;
  1203. }
  1204. setZ(z) {
  1205. this.z = z;
  1206. return this;
  1207. }
  1208. setW(w) {
  1209. this.w = w;
  1210. return this;
  1211. }
  1212. setComponent(index, value) {
  1213. switch (index) {
  1214. case 0:
  1215. this.x = value;
  1216. break;
  1217. case 1:
  1218. this.y = value;
  1219. break;
  1220. case 2:
  1221. this.z = value;
  1222. break;
  1223. case 3:
  1224. this.w = value;
  1225. break;
  1226. default:
  1227. throw new Error('index is out of range: ' + index);
  1228. }
  1229. return this;
  1230. }
  1231. getComponent(index) {
  1232. switch (index) {
  1233. case 0:
  1234. return this.x;
  1235. case 1:
  1236. return this.y;
  1237. case 2:
  1238. return this.z;
  1239. case 3:
  1240. return this.w;
  1241. default:
  1242. throw new Error('index is out of range: ' + index);
  1243. }
  1244. }
  1245. clone() {
  1246. return new this.constructor(this.x, this.y, this.z, this.w);
  1247. }
  1248. copy(v) {
  1249. this.x = v.x;
  1250. this.y = v.y;
  1251. this.z = v.z;
  1252. this.w = v.w !== undefined ? v.w : 1;
  1253. return this;
  1254. }
  1255. add(v, w) {
  1256. if (w !== undefined) {
  1257. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  1258. return this.addVectors(v, w);
  1259. }
  1260. this.x += v.x;
  1261. this.y += v.y;
  1262. this.z += v.z;
  1263. this.w += v.w;
  1264. return this;
  1265. }
  1266. addScalar(s) {
  1267. this.x += s;
  1268. this.y += s;
  1269. this.z += s;
  1270. this.w += s;
  1271. return this;
  1272. }
  1273. addVectors(a, b) {
  1274. this.x = a.x + b.x;
  1275. this.y = a.y + b.y;
  1276. this.z = a.z + b.z;
  1277. this.w = a.w + b.w;
  1278. return this;
  1279. }
  1280. addScaledVector(v, s) {
  1281. this.x += v.x * s;
  1282. this.y += v.y * s;
  1283. this.z += v.z * s;
  1284. this.w += v.w * s;
  1285. return this;
  1286. }
  1287. sub(v, w) {
  1288. if (w !== undefined) {
  1289. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  1290. return this.subVectors(v, w);
  1291. }
  1292. this.x -= v.x;
  1293. this.y -= v.y;
  1294. this.z -= v.z;
  1295. this.w -= v.w;
  1296. return this;
  1297. }
  1298. subScalar(s) {
  1299. this.x -= s;
  1300. this.y -= s;
  1301. this.z -= s;
  1302. this.w -= s;
  1303. return this;
  1304. }
  1305. subVectors(a, b) {
  1306. this.x = a.x - b.x;
  1307. this.y = a.y - b.y;
  1308. this.z = a.z - b.z;
  1309. this.w = a.w - b.w;
  1310. return this;
  1311. }
  1312. multiply(v) {
  1313. this.x *= v.x;
  1314. this.y *= v.y;
  1315. this.z *= v.z;
  1316. this.w *= v.w;
  1317. return this;
  1318. }
  1319. multiplyScalar(scalar) {
  1320. this.x *= scalar;
  1321. this.y *= scalar;
  1322. this.z *= scalar;
  1323. this.w *= scalar;
  1324. return this;
  1325. }
  1326. applyMatrix4(m) {
  1327. const x = this.x,
  1328. y = this.y,
  1329. z = this.z,
  1330. w = this.w;
  1331. const e = m.elements;
  1332. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1333. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1334. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1335. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1336. return this;
  1337. }
  1338. divideScalar(scalar) {
  1339. return this.multiplyScalar(1 / scalar);
  1340. }
  1341. setAxisAngleFromQuaternion(q) {
  1342. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1343. // q is assumed to be normalized
  1344. this.w = 2 * Math.acos(q.w);
  1345. const s = Math.sqrt(1 - q.w * q.w);
  1346. if (s < 0.0001) {
  1347. this.x = 1;
  1348. this.y = 0;
  1349. this.z = 0;
  1350. } else {
  1351. this.x = q.x / s;
  1352. this.y = q.y / s;
  1353. this.z = q.z / s;
  1354. }
  1355. return this;
  1356. }
  1357. setAxisAngleFromRotationMatrix(m) {
  1358. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1359. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1360. let angle, x, y, z; // variables for result
  1361. const epsilon = 0.01,
  1362. // margin to allow for rounding errors
  1363. epsilon2 = 0.1,
  1364. // margin to distinguish between 0 and 180 degrees
  1365. te = m.elements,
  1366. m11 = te[0],
  1367. m12 = te[4],
  1368. m13 = te[8],
  1369. m21 = te[1],
  1370. m22 = te[5],
  1371. m23 = te[9],
  1372. m31 = te[2],
  1373. m32 = te[6],
  1374. m33 = te[10];
  1375. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  1376. // singularity found
  1377. // first check for identity matrix which must have +1 for all terms
  1378. // in leading diagonal and zero in other terms
  1379. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  1380. // this singularity is identity matrix so angle = 0
  1381. this.set(1, 0, 0, 0);
  1382. return this; // zero angle, arbitrary axis
  1383. } // otherwise this singularity is angle = 180
  1384. angle = Math.PI;
  1385. const xx = (m11 + 1) / 2;
  1386. const yy = (m22 + 1) / 2;
  1387. const zz = (m33 + 1) / 2;
  1388. const xy = (m12 + m21) / 4;
  1389. const xz = (m13 + m31) / 4;
  1390. const yz = (m23 + m32) / 4;
  1391. if (xx > yy && xx > zz) {
  1392. // m11 is the largest diagonal term
  1393. if (xx < epsilon) {
  1394. x = 0;
  1395. y = 0.707106781;
  1396. z = 0.707106781;
  1397. } else {
  1398. x = Math.sqrt(xx);
  1399. y = xy / x;
  1400. z = xz / x;
  1401. }
  1402. } else if (yy > zz) {
  1403. // m22 is the largest diagonal term
  1404. if (yy < epsilon) {
  1405. x = 0.707106781;
  1406. y = 0;
  1407. z = 0.707106781;
  1408. } else {
  1409. y = Math.sqrt(yy);
  1410. x = xy / y;
  1411. z = yz / y;
  1412. }
  1413. } else {
  1414. // m33 is the largest diagonal term so base result on this
  1415. if (zz < epsilon) {
  1416. x = 0.707106781;
  1417. y = 0.707106781;
  1418. z = 0;
  1419. } else {
  1420. z = Math.sqrt(zz);
  1421. x = xz / z;
  1422. y = yz / z;
  1423. }
  1424. }
  1425. this.set(x, y, z, angle);
  1426. return this; // return 180 deg rotation
  1427. } // as we have reached here there are no singularities so we can handle normally
  1428. let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  1429. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1430. // caught by singularity test above, but I've left it in just in case
  1431. this.x = (m32 - m23) / s;
  1432. this.y = (m13 - m31) / s;
  1433. this.z = (m21 - m12) / s;
  1434. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  1435. return this;
  1436. }
  1437. min(v) {
  1438. this.x = Math.min(this.x, v.x);
  1439. this.y = Math.min(this.y, v.y);
  1440. this.z = Math.min(this.z, v.z);
  1441. this.w = Math.min(this.w, v.w);
  1442. return this;
  1443. }
  1444. max(v) {
  1445. this.x = Math.max(this.x, v.x);
  1446. this.y = Math.max(this.y, v.y);
  1447. this.z = Math.max(this.z, v.z);
  1448. this.w = Math.max(this.w, v.w);
  1449. return this;
  1450. }
  1451. clamp(min, max) {
  1452. // assumes min < max, componentwise
  1453. this.x = Math.max(min.x, Math.min(max.x, this.x));
  1454. this.y = Math.max(min.y, Math.min(max.y, this.y));
  1455. this.z = Math.max(min.z, Math.min(max.z, this.z));
  1456. this.w = Math.max(min.w, Math.min(max.w, this.w));
  1457. return this;
  1458. }
  1459. clampScalar(minVal, maxVal) {
  1460. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  1461. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  1462. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  1463. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  1464. return this;
  1465. }
  1466. clampLength(min, max) {
  1467. const length = this.length();
  1468. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  1469. }
  1470. floor() {
  1471. this.x = Math.floor(this.x);
  1472. this.y = Math.floor(this.y);
  1473. this.z = Math.floor(this.z);
  1474. this.w = Math.floor(this.w);
  1475. return this;
  1476. }
  1477. ceil() {
  1478. this.x = Math.ceil(this.x);
  1479. this.y = Math.ceil(this.y);
  1480. this.z = Math.ceil(this.z);
  1481. this.w = Math.ceil(this.w);
  1482. return this;
  1483. }
  1484. round() {
  1485. this.x = Math.round(this.x);
  1486. this.y = Math.round(this.y);
  1487. this.z = Math.round(this.z);
  1488. this.w = Math.round(this.w);
  1489. return this;
  1490. }
  1491. roundToZero() {
  1492. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  1493. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  1494. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  1495. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  1496. return this;
  1497. }
  1498. negate() {
  1499. this.x = -this.x;
  1500. this.y = -this.y;
  1501. this.z = -this.z;
  1502. this.w = -this.w;
  1503. return this;
  1504. }
  1505. dot(v) {
  1506. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1507. }
  1508. lengthSq() {
  1509. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1510. }
  1511. length() {
  1512. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1513. }
  1514. manhattanLength() {
  1515. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  1516. }
  1517. normalize() {
  1518. return this.divideScalar(this.length() || 1);
  1519. }
  1520. setLength(length) {
  1521. return this.normalize().multiplyScalar(length);
  1522. }
  1523. lerp(v, alpha) {
  1524. this.x += (v.x - this.x) * alpha;
  1525. this.y += (v.y - this.y) * alpha;
  1526. this.z += (v.z - this.z) * alpha;
  1527. this.w += (v.w - this.w) * alpha;
  1528. return this;
  1529. }
  1530. lerpVectors(v1, v2, alpha) {
  1531. this.x = v1.x + (v2.x - v1.x) * alpha;
  1532. this.y = v1.y + (v2.y - v1.y) * alpha;
  1533. this.z = v1.z + (v2.z - v1.z) * alpha;
  1534. this.w = v1.w + (v2.w - v1.w) * alpha;
  1535. return this;
  1536. }
  1537. equals(v) {
  1538. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  1539. }
  1540. fromArray(array, offset = 0) {
  1541. this.x = array[offset];
  1542. this.y = array[offset + 1];
  1543. this.z = array[offset + 2];
  1544. this.w = array[offset + 3];
  1545. return this;
  1546. }
  1547. toArray(array = [], offset = 0) {
  1548. array[offset] = this.x;
  1549. array[offset + 1] = this.y;
  1550. array[offset + 2] = this.z;
  1551. array[offset + 3] = this.w;
  1552. return array;
  1553. }
  1554. fromBufferAttribute(attribute, index, offset) {
  1555. if (offset !== undefined) {
  1556. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  1557. }
  1558. this.x = attribute.getX(index);
  1559. this.y = attribute.getY(index);
  1560. this.z = attribute.getZ(index);
  1561. this.w = attribute.getW(index);
  1562. return this;
  1563. }
  1564. random() {
  1565. this.x = Math.random();
  1566. this.y = Math.random();
  1567. this.z = Math.random();
  1568. this.w = Math.random();
  1569. return this;
  1570. }
  1571. }
  1572. Vector4.prototype.isVector4 = true;
  1573. /*
  1574. In options, we can specify:
  1575. * Texture parameters for an auto-generated target texture
  1576. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1577. */
  1578. class WebGLRenderTarget extends EventDispatcher {
  1579. constructor(width, height, options = {}) {
  1580. super();
  1581. this.width = width;
  1582. this.height = height;
  1583. this.depth = 1;
  1584. this.scissor = new Vector4(0, 0, width, height);
  1585. this.scissorTest = false;
  1586. this.viewport = new Vector4(0, 0, width, height);
  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.isRenderTargetTexture = true;
  1589. this.texture.image = {
  1590. width: width,
  1591. height: height,
  1592. depth: 1
  1593. };
  1594. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  1595. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  1596. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  1597. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1598. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  1599. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1600. }
  1601. setTexture(texture) {
  1602. texture.image = {
  1603. width: this.width,
  1604. height: this.height,
  1605. depth: this.depth
  1606. };
  1607. this.texture = texture;
  1608. }
  1609. setSize(width, height, depth = 1) {
  1610. if (this.width !== width || this.height !== height || this.depth !== depth) {
  1611. this.width = width;
  1612. this.height = height;
  1613. this.depth = depth;
  1614. this.texture.image.width = width;
  1615. this.texture.image.height = height;
  1616. this.texture.image.depth = depth;
  1617. this.dispose();
  1618. }
  1619. this.viewport.set(0, 0, width, height);
  1620. this.scissor.set(0, 0, width, height);
  1621. }
  1622. clone() {
  1623. return new this.constructor().copy(this);
  1624. }
  1625. copy(source) {
  1626. this.width = source.width;
  1627. this.height = source.height;
  1628. this.depth = source.depth;
  1629. this.viewport.copy(source.viewport);
  1630. this.texture = source.texture.clone();
  1631. this.texture.image = { ...this.texture.image
  1632. }; // See #20328.
  1633. this.depthBuffer = source.depthBuffer;
  1634. this.stencilBuffer = source.stencilBuffer;
  1635. this.depthTexture = source.depthTexture;
  1636. return this;
  1637. }
  1638. dispose() {
  1639. this.dispatchEvent({
  1640. type: 'dispose'
  1641. });
  1642. }
  1643. }
  1644. WebGLRenderTarget.prototype.isWebGLRenderTarget = true;
  1645. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  1646. constructor(width, height, count) {
  1647. super(width, height);
  1648. const texture = this.texture;
  1649. this.texture = [];
  1650. for (let i = 0; i < count; i++) {
  1651. this.texture[i] = texture.clone();
  1652. }
  1653. }
  1654. setSize(width, height, depth = 1) {
  1655. if (this.width !== width || this.height !== height || this.depth !== depth) {
  1656. this.width = width;
  1657. this.height = height;
  1658. this.depth = depth;
  1659. for (let i = 0, il = this.texture.length; i < il; i++) {
  1660. this.texture[i].image.width = width;
  1661. this.texture[i].image.height = height;
  1662. this.texture[i].image.depth = depth;
  1663. }
  1664. this.dispose();
  1665. }
  1666. this.viewport.set(0, 0, width, height);
  1667. this.scissor.set(0, 0, width, height);
  1668. return this;
  1669. }
  1670. copy(source) {
  1671. this.dispose();
  1672. this.width = source.width;
  1673. this.height = source.height;
  1674. this.depth = source.depth;
  1675. this.viewport.set(0, 0, this.width, this.height);
  1676. this.scissor.set(0, 0, this.width, this.height);
  1677. this.depthBuffer = source.depthBuffer;
  1678. this.stencilBuffer = source.stencilBuffer;
  1679. this.depthTexture = source.depthTexture;
  1680. this.texture.length = 0;
  1681. for (let i = 0, il = source.texture.length; i < il; i++) {
  1682. this.texture[i] = source.texture[i].clone();
  1683. }
  1684. return this;
  1685. }
  1686. }
  1687. WebGLMultipleRenderTargets.prototype.isWebGLMultipleRenderTargets = true;
  1688. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  1689. constructor(width, height, options) {
  1690. super(width, height, options);
  1691. this.samples = 4;
  1692. }
  1693. copy(source) {
  1694. super.copy.call(this, source);
  1695. this.samples = source.samples;
  1696. return this;
  1697. }
  1698. }
  1699. WebGLMultisampleRenderTarget.prototype.isWebGLMultisampleRenderTarget = true;
  1700. class Quaternion {
  1701. constructor(x = 0, y = 0, z = 0, w = 1) {
  1702. this._x = x;
  1703. this._y = y;
  1704. this._z = z;
  1705. this._w = w;
  1706. }
  1707. static slerp(qa, qb, qm, t) {
  1708. console.warn('THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead.');
  1709. return qm.slerpQuaternions(qa, qb, t);
  1710. }
  1711. static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  1712. // fuzz-free, array-based Quaternion SLERP operation
  1713. let x0 = src0[srcOffset0 + 0],
  1714. y0 = src0[srcOffset0 + 1],
  1715. z0 = src0[srcOffset0 + 2],
  1716. w0 = src0[srcOffset0 + 3];
  1717. const x1 = src1[srcOffset1 + 0],
  1718. y1 = src1[srcOffset1 + 1],
  1719. z1 = src1[srcOffset1 + 2],
  1720. w1 = src1[srcOffset1 + 3];
  1721. if (t === 0) {
  1722. dst[dstOffset + 0] = x0;
  1723. dst[dstOffset + 1] = y0;
  1724. dst[dstOffset + 2] = z0;
  1725. dst[dstOffset + 3] = w0;
  1726. return;
  1727. }
  1728. if (t === 1) {
  1729. dst[dstOffset + 0] = x1;
  1730. dst[dstOffset + 1] = y1;
  1731. dst[dstOffset + 2] = z1;
  1732. dst[dstOffset + 3] = w1;
  1733. return;
  1734. }
  1735. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  1736. let s = 1 - t;
  1737. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1738. dir = cos >= 0 ? 1 : -1,
  1739. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  1740. if (sqrSin > Number.EPSILON) {
  1741. const sin = Math.sqrt(sqrSin),
  1742. len = Math.atan2(sin, cos * dir);
  1743. s = Math.sin(s * len) / sin;
  1744. t = Math.sin(t * len) / sin;
  1745. }
  1746. const tDir = t * dir;
  1747. x0 = x0 * s + x1 * tDir;
  1748. y0 = y0 * s + y1 * tDir;
  1749. z0 = z0 * s + z1 * tDir;
  1750. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  1751. if (s === 1 - t) {
  1752. const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  1753. x0 *= f;
  1754. y0 *= f;
  1755. z0 *= f;
  1756. w0 *= f;
  1757. }
  1758. }
  1759. dst[dstOffset] = x0;
  1760. dst[dstOffset + 1] = y0;
  1761. dst[dstOffset + 2] = z0;
  1762. dst[dstOffset + 3] = w0;
  1763. }
  1764. static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
  1765. const x0 = src0[srcOffset0];
  1766. const y0 = src0[srcOffset0 + 1];
  1767. const z0 = src0[srcOffset0 + 2];
  1768. const w0 = src0[srcOffset0 + 3];
  1769. const x1 = src1[srcOffset1];
  1770. const y1 = src1[srcOffset1 + 1];
  1771. const z1 = src1[srcOffset1 + 2];
  1772. const w1 = src1[srcOffset1 + 3];
  1773. dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  1774. dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  1775. dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  1776. dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  1777. return dst;
  1778. }
  1779. get x() {
  1780. return this._x;
  1781. }
  1782. set x(value) {
  1783. this._x = value;
  1784. this._onChangeCallback();
  1785. }
  1786. get y() {
  1787. return this._y;
  1788. }
  1789. set y(value) {
  1790. this._y = value;
  1791. this._onChangeCallback();
  1792. }
  1793. get z() {
  1794. return this._z;
  1795. }
  1796. set z(value) {
  1797. this._z = value;
  1798. this._onChangeCallback();
  1799. }
  1800. get w() {
  1801. return this._w;
  1802. }
  1803. set w(value) {
  1804. this._w = value;
  1805. this._onChangeCallback();
  1806. }
  1807. set(x, y, z, w) {
  1808. this._x = x;
  1809. this._y = y;
  1810. this._z = z;
  1811. this._w = w;
  1812. this._onChangeCallback();
  1813. return this;
  1814. }
  1815. clone() {
  1816. return new this.constructor(this._x, this._y, this._z, this._w);
  1817. }
  1818. copy(quaternion) {
  1819. this._x = quaternion.x;
  1820. this._y = quaternion.y;
  1821. this._z = quaternion.z;
  1822. this._w = quaternion.w;
  1823. this._onChangeCallback();
  1824. return this;
  1825. }
  1826. setFromEuler(euler, update) {
  1827. if (!(euler && euler.isEuler)) {
  1828. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  1829. }
  1830. const x = euler._x,
  1831. y = euler._y,
  1832. z = euler._z,
  1833. order = euler._order; // http://www.mathworks.com/matlabcentral/fileexchange/
  1834. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1835. // content/SpinCalc.m
  1836. const cos = Math.cos;
  1837. const sin = Math.sin;
  1838. const c1 = cos(x / 2);
  1839. const c2 = cos(y / 2);
  1840. const c3 = cos(z / 2);
  1841. const s1 = sin(x / 2);
  1842. const s2 = sin(y / 2);
  1843. const s3 = sin(z / 2);
  1844. switch (order) {
  1845. case 'XYZ':
  1846. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1847. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1848. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1849. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1850. break;
  1851. case 'YXZ':
  1852. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1853. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1854. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1855. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1856. break;
  1857. case 'ZXY':
  1858. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1859. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1860. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1861. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1862. break;
  1863. case 'ZYX':
  1864. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1865. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1866. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1867. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1868. break;
  1869. case 'YZX':
  1870. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1871. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1872. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1873. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1874. break;
  1875. case 'XZY':
  1876. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1877. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1878. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1879. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1880. break;
  1881. default:
  1882. console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
  1883. }
  1884. if (update !== false) this._onChangeCallback();
  1885. return this;
  1886. }
  1887. setFromAxisAngle(axis, angle) {
  1888. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1889. // assumes axis is normalized
  1890. const halfAngle = angle / 2,
  1891. s = Math.sin(halfAngle);
  1892. this._x = axis.x * s;
  1893. this._y = axis.y * s;
  1894. this._z = axis.z * s;
  1895. this._w = Math.cos(halfAngle);
  1896. this._onChangeCallback();
  1897. return this;
  1898. }
  1899. setFromRotationMatrix(m) {
  1900. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1901. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1902. const te = m.elements,
  1903. m11 = te[0],
  1904. m12 = te[4],
  1905. m13 = te[8],
  1906. m21 = te[1],
  1907. m22 = te[5],
  1908. m23 = te[9],
  1909. m31 = te[2],
  1910. m32 = te[6],
  1911. m33 = te[10],
  1912. trace = m11 + m22 + m33;
  1913. if (trace > 0) {
  1914. const s = 0.5 / Math.sqrt(trace + 1.0);
  1915. this._w = 0.25 / s;
  1916. this._x = (m32 - m23) * s;
  1917. this._y = (m13 - m31) * s;
  1918. this._z = (m21 - m12) * s;
  1919. } else if (m11 > m22 && m11 > m33) {
  1920. const s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1921. this._w = (m32 - m23) / s;
  1922. this._x = 0.25 * s;
  1923. this._y = (m12 + m21) / s;
  1924. this._z = (m13 + m31) / s;
  1925. } else if (m22 > m33) {
  1926. const s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1927. this._w = (m13 - m31) / s;
  1928. this._x = (m12 + m21) / s;
  1929. this._y = 0.25 * s;
  1930. this._z = (m23 + m32) / s;
  1931. } else {
  1932. const s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1933. this._w = (m21 - m12) / s;
  1934. this._x = (m13 + m31) / s;
  1935. this._y = (m23 + m32) / s;
  1936. this._z = 0.25 * s;
  1937. }
  1938. this._onChangeCallback();
  1939. return this;
  1940. }
  1941. setFromUnitVectors(vFrom, vTo) {
  1942. // assumes direction vectors vFrom and vTo are normalized
  1943. let r = vFrom.dot(vTo) + 1;
  1944. if (r < Number.EPSILON) {
  1945. // vFrom and vTo point in opposite directions
  1946. r = 0;
  1947. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  1948. this._x = -vFrom.y;
  1949. this._y = vFrom.x;
  1950. this._z = 0;
  1951. this._w = r;
  1952. } else {
  1953. this._x = 0;
  1954. this._y = -vFrom.z;
  1955. this._z = vFrom.y;
  1956. this._w = r;
  1957. }
  1958. } else {
  1959. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  1960. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  1961. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  1962. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  1963. this._w = r;
  1964. }
  1965. return this.normalize();
  1966. }
  1967. angleTo(q) {
  1968. return 2 * Math.acos(Math.abs(clamp(this.dot(q), -1, 1)));
  1969. }
  1970. rotateTowards(q, step) {
  1971. const angle = this.angleTo(q);
  1972. if (angle === 0) return this;
  1973. const t = Math.min(1, step / angle);
  1974. this.slerp(q, t);
  1975. return this;
  1976. }
  1977. identity() {
  1978. return this.set(0, 0, 0, 1);
  1979. }
  1980. invert() {
  1981. // quaternion is assumed to have unit length
  1982. return this.conjugate();
  1983. }
  1984. conjugate() {
  1985. this._x *= -1;
  1986. this._y *= -1;
  1987. this._z *= -1;
  1988. this._onChangeCallback();
  1989. return this;
  1990. }
  1991. dot(v) {
  1992. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1993. }
  1994. lengthSq() {
  1995. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1996. }
  1997. length() {
  1998. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  1999. }
  2000. normalize() {
  2001. let l = this.length();
  2002. if (l === 0) {
  2003. this._x = 0;
  2004. this._y = 0;
  2005. this._z = 0;
  2006. this._w = 1;
  2007. } else {
  2008. l = 1 / l;
  2009. this._x = this._x * l;
  2010. this._y = this._y * l;
  2011. this._z = this._z * l;
  2012. this._w = this._w * l;
  2013. }
  2014. this._onChangeCallback();
  2015. return this;
  2016. }
  2017. multiply(q, p) {
  2018. if (p !== undefined) {
  2019. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  2020. return this.multiplyQuaternions(q, p);
  2021. }
  2022. return this.multiplyQuaternions(this, q);
  2023. }
  2024. premultiply(q) {
  2025. return this.multiplyQuaternions(q, this);
  2026. }
  2027. multiplyQuaternions(a, b) {
  2028. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2029. const qax = a._x,
  2030. qay = a._y,
  2031. qaz = a._z,
  2032. qaw = a._w;
  2033. const qbx = b._x,
  2034. qby = b._y,
  2035. qbz = b._z,
  2036. qbw = b._w;
  2037. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2038. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2039. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2040. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2041. this._onChangeCallback();
  2042. return this;
  2043. }
  2044. slerp(qb, t) {
  2045. if (t === 0) return this;
  2046. if (t === 1) return this.copy(qb);
  2047. const x = this._x,
  2048. y = this._y,
  2049. z = this._z,
  2050. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2051. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2052. if (cosHalfTheta < 0) {
  2053. this._w = -qb._w;
  2054. this._x = -qb._x;
  2055. this._y = -qb._y;
  2056. this._z = -qb._z;
  2057. cosHalfTheta = -cosHalfTheta;
  2058. } else {
  2059. this.copy(qb);
  2060. }
  2061. if (cosHalfTheta >= 1.0) {
  2062. this._w = w;
  2063. this._x = x;
  2064. this._y = y;
  2065. this._z = z;
  2066. return this;
  2067. }
  2068. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2069. if (sqrSinHalfTheta <= Number.EPSILON) {
  2070. const s = 1 - t;
  2071. this._w = s * w + t * this._w;
  2072. this._x = s * x + t * this._x;
  2073. this._y = s * y + t * this._y;
  2074. this._z = s * z + t * this._z;
  2075. this.normalize();
  2076. this._onChangeCallback();
  2077. return this;
  2078. }
  2079. const sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2080. const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2081. const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2082. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2083. this._w = w * ratioA + this._w * ratioB;
  2084. this._x = x * ratioA + this._x * ratioB;
  2085. this._y = y * ratioA + this._y * ratioB;
  2086. this._z = z * ratioA + this._z * ratioB;
  2087. this._onChangeCallback();
  2088. return this;
  2089. }
  2090. slerpQuaternions(qa, qb, t) {
  2091. this.copy(qa).slerp(qb, t);
  2092. }
  2093. equals(quaternion) {
  2094. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2095. }
  2096. fromArray(array, offset = 0) {
  2097. this._x = array[offset];
  2098. this._y = array[offset + 1];
  2099. this._z = array[offset + 2];
  2100. this._w = array[offset + 3];
  2101. this._onChangeCallback();
  2102. return this;
  2103. }
  2104. toArray(array = [], offset = 0) {
  2105. array[offset] = this._x;
  2106. array[offset + 1] = this._y;
  2107. array[offset + 2] = this._z;
  2108. array[offset + 3] = this._w;
  2109. return array;
  2110. }
  2111. fromBufferAttribute(attribute, index) {
  2112. this._x = attribute.getX(index);
  2113. this._y = attribute.getY(index);
  2114. this._z = attribute.getZ(index);
  2115. this._w = attribute.getW(index);
  2116. return this;
  2117. }
  2118. _onChange(callback) {
  2119. this._onChangeCallback = callback;
  2120. return this;
  2121. }
  2122. _onChangeCallback() {}
  2123. }
  2124. Quaternion.prototype.isQuaternion = true;
  2125. class Vector3 {
  2126. constructor(x = 0, y = 0, z = 0) {
  2127. this.x = x;
  2128. this.y = y;
  2129. this.z = z;
  2130. }
  2131. set(x, y, z) {
  2132. if (z === undefined) z = this.z; // sprite.scale.set(x,y)
  2133. this.x = x;
  2134. this.y = y;
  2135. this.z = z;
  2136. return this;
  2137. }
  2138. setScalar(scalar) {
  2139. this.x = scalar;
  2140. this.y = scalar;
  2141. this.z = scalar;
  2142. return this;
  2143. }
  2144. setX(x) {
  2145. this.x = x;
  2146. return this;
  2147. }
  2148. setY(y) {
  2149. this.y = y;
  2150. return this;
  2151. }
  2152. setZ(z) {
  2153. this.z = z;
  2154. return this;
  2155. }
  2156. setComponent(index, value) {
  2157. switch (index) {
  2158. case 0:
  2159. this.x = value;
  2160. break;
  2161. case 1:
  2162. this.y = value;
  2163. break;
  2164. case 2:
  2165. this.z = value;
  2166. break;
  2167. default:
  2168. throw new Error('index is out of range: ' + index);
  2169. }
  2170. return this;
  2171. }
  2172. getComponent(index) {
  2173. switch (index) {
  2174. case 0:
  2175. return this.x;
  2176. case 1:
  2177. return this.y;
  2178. case 2:
  2179. return this.z;
  2180. default:
  2181. throw new Error('index is out of range: ' + index);
  2182. }
  2183. }
  2184. clone() {
  2185. return new this.constructor(this.x, this.y, this.z);
  2186. }
  2187. copy(v) {
  2188. this.x = v.x;
  2189. this.y = v.y;
  2190. this.z = v.z;
  2191. return this;
  2192. }
  2193. add(v, w) {
  2194. if (w !== undefined) {
  2195. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2196. return this.addVectors(v, w);
  2197. }
  2198. this.x += v.x;
  2199. this.y += v.y;
  2200. this.z += v.z;
  2201. return this;
  2202. }
  2203. addScalar(s) {
  2204. this.x += s;
  2205. this.y += s;
  2206. this.z += s;
  2207. return this;
  2208. }
  2209. addVectors(a, b) {
  2210. this.x = a.x + b.x;
  2211. this.y = a.y + b.y;
  2212. this.z = a.z + b.z;
  2213. return this;
  2214. }
  2215. addScaledVector(v, s) {
  2216. this.x += v.x * s;
  2217. this.y += v.y * s;
  2218. this.z += v.z * s;
  2219. return this;
  2220. }
  2221. sub(v, w) {
  2222. if (w !== undefined) {
  2223. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2224. return this.subVectors(v, w);
  2225. }
  2226. this.x -= v.x;
  2227. this.y -= v.y;
  2228. this.z -= v.z;
  2229. return this;
  2230. }
  2231. subScalar(s) {
  2232. this.x -= s;
  2233. this.y -= s;
  2234. this.z -= s;
  2235. return this;
  2236. }
  2237. subVectors(a, b) {
  2238. this.x = a.x - b.x;
  2239. this.y = a.y - b.y;
  2240. this.z = a.z - b.z;
  2241. return this;
  2242. }
  2243. multiply(v, w) {
  2244. if (w !== undefined) {
  2245. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  2246. return this.multiplyVectors(v, w);
  2247. }
  2248. this.x *= v.x;
  2249. this.y *= v.y;
  2250. this.z *= v.z;
  2251. return this;
  2252. }
  2253. multiplyScalar(scalar) {
  2254. this.x *= scalar;
  2255. this.y *= scalar;
  2256. this.z *= scalar;
  2257. return this;
  2258. }
  2259. multiplyVectors(a, b) {
  2260. this.x = a.x * b.x;
  2261. this.y = a.y * b.y;
  2262. this.z = a.z * b.z;
  2263. return this;
  2264. }
  2265. applyEuler(euler) {
  2266. if (!(euler && euler.isEuler)) {
  2267. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2268. }
  2269. return this.applyQuaternion(_quaternion$4.setFromEuler(euler));
  2270. }
  2271. applyAxisAngle(axis, angle) {
  2272. return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle));
  2273. }
  2274. applyMatrix3(m) {
  2275. const x = this.x,
  2276. y = this.y,
  2277. z = this.z;
  2278. const e = m.elements;
  2279. this.x = e[0] * x + e[3] * y + e[6] * z;
  2280. this.y = e[1] * x + e[4] * y + e[7] * z;
  2281. this.z = e[2] * x + e[5] * y + e[8] * z;
  2282. return this;
  2283. }
  2284. applyNormalMatrix(m) {
  2285. return this.applyMatrix3(m).normalize();
  2286. }
  2287. applyMatrix4(m) {
  2288. const x = this.x,
  2289. y = this.y,
  2290. z = this.z;
  2291. const e = m.elements;
  2292. const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2293. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2294. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2295. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2296. return this;
  2297. }
  2298. applyQuaternion(q) {
  2299. const x = this.x,
  2300. y = this.y,
  2301. z = this.z;
  2302. const qx = q.x,
  2303. qy = q.y,
  2304. qz = q.z,
  2305. qw = q.w; // calculate quat * vector
  2306. const ix = qw * x + qy * z - qz * y;
  2307. const iy = qw * y + qz * x - qx * z;
  2308. const iz = qw * z + qx * y - qy * x;
  2309. const iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  2310. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2311. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2312. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2313. return this;
  2314. }
  2315. project(camera) {
  2316. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  2317. }
  2318. unproject(camera) {
  2319. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  2320. }
  2321. transformDirection(m) {
  2322. // input: THREE.Matrix4 affine matrix
  2323. // vector interpreted as a direction
  2324. const x = this.x,
  2325. y = this.y,
  2326. z = this.z;
  2327. const e = m.elements;
  2328. this.x = e[0] * x + e[4] * y + e[8] * z;
  2329. this.y = e[1] * x + e[5] * y + e[9] * z;
  2330. this.z = e[2] * x + e[6] * y + e[10] * z;
  2331. return this.normalize();
  2332. }
  2333. divide(v) {
  2334. this.x /= v.x;
  2335. this.y /= v.y;
  2336. this.z /= v.z;
  2337. return this;
  2338. }
  2339. divideScalar(scalar) {
  2340. return this.multiplyScalar(1 / scalar);
  2341. }
  2342. min(v) {
  2343. this.x = Math.min(this.x, v.x);
  2344. this.y = Math.min(this.y, v.y);
  2345. this.z = Math.min(this.z, v.z);
  2346. return this;
  2347. }
  2348. max(v) {
  2349. this.x = Math.max(this.x, v.x);
  2350. this.y = Math.max(this.y, v.y);
  2351. this.z = Math.max(this.z, v.z);
  2352. return this;
  2353. }
  2354. clamp(min, max) {
  2355. // assumes min < max, componentwise
  2356. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2357. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2358. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2359. return this;
  2360. }
  2361. clampScalar(minVal, maxVal) {
  2362. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2363. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2364. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2365. return this;
  2366. }
  2367. clampLength(min, max) {
  2368. const length = this.length();
  2369. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2370. }
  2371. floor() {
  2372. this.x = Math.floor(this.x);
  2373. this.y = Math.floor(this.y);
  2374. this.z = Math.floor(this.z);
  2375. return this;
  2376. }
  2377. ceil() {
  2378. this.x = Math.ceil(this.x);
  2379. this.y = Math.ceil(this.y);
  2380. this.z = Math.ceil(this.z);
  2381. return this;
  2382. }
  2383. round() {
  2384. this.x = Math.round(this.x);
  2385. this.y = Math.round(this.y);
  2386. this.z = Math.round(this.z);
  2387. return this;
  2388. }
  2389. roundToZero() {
  2390. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2391. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2392. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2393. return this;
  2394. }
  2395. negate() {
  2396. this.x = -this.x;
  2397. this.y = -this.y;
  2398. this.z = -this.z;
  2399. return this;
  2400. }
  2401. dot(v) {
  2402. return this.x * v.x + this.y * v.y + this.z * v.z;
  2403. } // TODO lengthSquared?
  2404. lengthSq() {
  2405. return this.x * this.x + this.y * this.y + this.z * this.z;
  2406. }
  2407. length() {
  2408. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2409. }
  2410. manhattanLength() {
  2411. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  2412. }
  2413. normalize() {
  2414. return this.divideScalar(this.length() || 1);
  2415. }
  2416. setLength(length) {
  2417. return this.normalize().multiplyScalar(length);
  2418. }
  2419. lerp(v, alpha) {
  2420. this.x += (v.x - this.x) * alpha;
  2421. this.y += (v.y - this.y) * alpha;
  2422. this.z += (v.z - this.z) * alpha;
  2423. return this;
  2424. }
  2425. lerpVectors(v1, v2, alpha) {
  2426. this.x = v1.x + (v2.x - v1.x) * alpha;
  2427. this.y = v1.y + (v2.y - v1.y) * alpha;
  2428. this.z = v1.z + (v2.z - v1.z) * alpha;
  2429. return this;
  2430. }
  2431. cross(v, w) {
  2432. if (w !== undefined) {
  2433. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  2434. return this.crossVectors(v, w);
  2435. }
  2436. return this.crossVectors(this, v);
  2437. }
  2438. crossVectors(a, b) {
  2439. const ax = a.x,
  2440. ay = a.y,
  2441. az = a.z;
  2442. const bx = b.x,
  2443. by = b.y,
  2444. bz = b.z;
  2445. this.x = ay * bz - az * by;
  2446. this.y = az * bx - ax * bz;
  2447. this.z = ax * by - ay * bx;
  2448. return this;
  2449. }
  2450. projectOnVector(v) {
  2451. const denominator = v.lengthSq();
  2452. if (denominator === 0) return this.set(0, 0, 0);
  2453. const scalar = v.dot(this) / denominator;
  2454. return this.copy(v).multiplyScalar(scalar);
  2455. }
  2456. projectOnPlane(planeNormal) {
  2457. _vector$c.copy(this).projectOnVector(planeNormal);
  2458. return this.sub(_vector$c);
  2459. }
  2460. reflect(normal) {
  2461. // reflect incident vector off plane orthogonal to normal
  2462. // normal is assumed to have unit length
  2463. return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal)));
  2464. }
  2465. angleTo(v) {
  2466. const denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  2467. if (denominator === 0) return Math.PI / 2;
  2468. const theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  2469. return Math.acos(clamp(theta, -1, 1));
  2470. }
  2471. distanceTo(v) {
  2472. return Math.sqrt(this.distanceToSquared(v));
  2473. }
  2474. distanceToSquared(v) {
  2475. const dx = this.x - v.x,
  2476. dy = this.y - v.y,
  2477. dz = this.z - v.z;
  2478. return dx * dx + dy * dy + dz * dz;
  2479. }
  2480. manhattanDistanceTo(v) {
  2481. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  2482. }
  2483. setFromSpherical(s) {
  2484. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  2485. }
  2486. setFromSphericalCoords(radius, phi, theta) {
  2487. const sinPhiRadius = Math.sin(phi) * radius;
  2488. this.x = sinPhiRadius * Math.sin(theta);
  2489. this.y = Math.cos(phi) * radius;
  2490. this.z = sinPhiRadius * Math.cos(theta);
  2491. return this;
  2492. }
  2493. setFromCylindrical(c) {
  2494. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  2495. }
  2496. setFromCylindricalCoords(radius, theta, y) {
  2497. this.x = radius * Math.sin(theta);
  2498. this.y = y;
  2499. this.z = radius * Math.cos(theta);
  2500. return this;
  2501. }
  2502. setFromMatrixPosition(m) {
  2503. const e = m.elements;
  2504. this.x = e[12];
  2505. this.y = e[13];
  2506. this.z = e[14];
  2507. return this;
  2508. }
  2509. setFromMatrixScale(m) {
  2510. const sx = this.setFromMatrixColumn(m, 0).length();
  2511. const sy = this.setFromMatrixColumn(m, 1).length();
  2512. const sz = this.setFromMatrixColumn(m, 2).length();
  2513. this.x = sx;
  2514. this.y = sy;
  2515. this.z = sz;
  2516. return this;
  2517. }
  2518. setFromMatrixColumn(m, index) {
  2519. return this.fromArray(m.elements, index * 4);
  2520. }
  2521. setFromMatrix3Column(m, index) {
  2522. return this.fromArray(m.elements, index * 3);
  2523. }
  2524. equals(v) {
  2525. return v.x === this.x && v.y === this.y && v.z === this.z;
  2526. }
  2527. fromArray(array, offset = 0) {
  2528. this.x = array[offset];
  2529. this.y = array[offset + 1];
  2530. this.z = array[offset + 2];
  2531. return this;
  2532. }
  2533. toArray(array = [], offset = 0) {
  2534. array[offset] = this.x;
  2535. array[offset + 1] = this.y;
  2536. array[offset + 2] = this.z;
  2537. return array;
  2538. }
  2539. fromBufferAttribute(attribute, index, offset) {
  2540. if (offset !== undefined) {
  2541. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  2542. }
  2543. this.x = attribute.getX(index);
  2544. this.y = attribute.getY(index);
  2545. this.z = attribute.getZ(index);
  2546. return this;
  2547. }
  2548. random() {
  2549. this.x = Math.random();
  2550. this.y = Math.random();
  2551. this.z = Math.random();
  2552. return this;
  2553. }
  2554. }
  2555. Vector3.prototype.isVector3 = true;
  2556. const _vector$c = /*@__PURE__*/new Vector3();
  2557. const _quaternion$4 = /*@__PURE__*/new Quaternion();
  2558. class Box3 {
  2559. constructor(min = new Vector3(+Infinity, +Infinity, +Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity)) {
  2560. this.min = min;
  2561. this.max = max;
  2562. }
  2563. set(min, max) {
  2564. this.min.copy(min);
  2565. this.max.copy(max);
  2566. return this;
  2567. }
  2568. setFromArray(array) {
  2569. let minX = +Infinity;
  2570. let minY = +Infinity;
  2571. let minZ = +Infinity;
  2572. let maxX = -Infinity;
  2573. let maxY = -Infinity;
  2574. let maxZ = -Infinity;
  2575. for (let i = 0, l = array.length; i < l; i += 3) {
  2576. const x = array[i];
  2577. const y = array[i + 1];
  2578. const z = array[i + 2];
  2579. if (x < minX) minX = x;
  2580. if (y < minY) minY = y;
  2581. if (z < minZ) minZ = z;
  2582. if (x > maxX) maxX = x;
  2583. if (y > maxY) maxY = y;
  2584. if (z > maxZ) maxZ = z;
  2585. }
  2586. this.min.set(minX, minY, minZ);
  2587. this.max.set(maxX, maxY, maxZ);
  2588. return this;
  2589. }
  2590. setFromBufferAttribute(attribute) {
  2591. let minX = +Infinity;
  2592. let minY = +Infinity;
  2593. let minZ = +Infinity;
  2594. let maxX = -Infinity;
  2595. let maxY = -Infinity;
  2596. let maxZ = -Infinity;
  2597. for (let i = 0, l = attribute.count; i < l; i++) {
  2598. const x = attribute.getX(i);
  2599. const y = attribute.getY(i);
  2600. const z = attribute.getZ(i);
  2601. if (x < minX) minX = x;
  2602. if (y < minY) minY = y;
  2603. if (z < minZ) minZ = z;
  2604. if (x > maxX) maxX = x;
  2605. if (y > maxY) maxY = y;
  2606. if (z > maxZ) maxZ = z;
  2607. }
  2608. this.min.set(minX, minY, minZ);
  2609. this.max.set(maxX, maxY, maxZ);
  2610. return this;
  2611. }
  2612. setFromPoints(points) {
  2613. this.makeEmpty();
  2614. for (let i = 0, il = points.length; i < il; i++) {
  2615. this.expandByPoint(points[i]);
  2616. }
  2617. return this;
  2618. }
  2619. setFromCenterAndSize(center, size) {
  2620. const halfSize = _vector$b.copy(size).multiplyScalar(0.5);
  2621. this.min.copy(center).sub(halfSize);
  2622. this.max.copy(center).add(halfSize);
  2623. return this;
  2624. }
  2625. setFromObject(object) {
  2626. this.makeEmpty();
  2627. return this.expandByObject(object);
  2628. }
  2629. clone() {
  2630. return new this.constructor().copy(this);
  2631. }
  2632. copy(box) {
  2633. this.min.copy(box.min);
  2634. this.max.copy(box.max);
  2635. return this;
  2636. }
  2637. makeEmpty() {
  2638. this.min.x = this.min.y = this.min.z = +Infinity;
  2639. this.max.x = this.max.y = this.max.z = -Infinity;
  2640. return this;
  2641. }
  2642. isEmpty() {
  2643. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2644. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  2645. }
  2646. getCenter(target) {
  2647. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  2648. }
  2649. getSize(target) {
  2650. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  2651. }
  2652. expandByPoint(point) {
  2653. this.min.min(point);
  2654. this.max.max(point);
  2655. return this;
  2656. }
  2657. expandByVector(vector) {
  2658. this.min.sub(vector);
  2659. this.max.add(vector);
  2660. return this;
  2661. }
  2662. expandByScalar(scalar) {
  2663. this.min.addScalar(-scalar);
  2664. this.max.addScalar(scalar);
  2665. return this;
  2666. }
  2667. expandByObject(object) {
  2668. // Computes the world-axis-aligned bounding box of an object (including its children),
  2669. // accounting for both the object's, and children's, world transforms
  2670. object.updateWorldMatrix(false, false);
  2671. const geometry = object.geometry;
  2672. if (geometry !== undefined) {
  2673. if (geometry.boundingBox === null) {
  2674. geometry.computeBoundingBox();
  2675. }
  2676. _box$3.copy(geometry.boundingBox);
  2677. _box$3.applyMatrix4(object.matrixWorld);
  2678. this.union(_box$3);
  2679. }
  2680. const children = object.children;
  2681. for (let i = 0, l = children.length; i < l; i++) {
  2682. this.expandByObject(children[i]);
  2683. }
  2684. return this;
  2685. }
  2686. containsPoint(point) {
  2687. 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;
  2688. }
  2689. containsBox(box) {
  2690. 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;
  2691. }
  2692. getParameter(point, target) {
  2693. // This can potentially have a divide by zero if the box
  2694. // has a size dimension of 0.
  2695. 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));
  2696. }
  2697. intersectsBox(box) {
  2698. // using 6 splitting planes to rule out intersections.
  2699. 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;
  2700. }
  2701. intersectsSphere(sphere) {
  2702. // Find the point on the AABB closest to the sphere center.
  2703. this.clampPoint(sphere.center, _vector$b); // If that point is inside the sphere, the AABB and sphere intersect.
  2704. return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  2705. }
  2706. intersectsPlane(plane) {
  2707. // We compute the minimum and maximum dot product values. If those values
  2708. // are on the same side (back or front) of the plane, then there is no intersection.
  2709. let min, max;
  2710. if (plane.normal.x > 0) {
  2711. min = plane.normal.x * this.min.x;
  2712. max = plane.normal.x * this.max.x;
  2713. } else {
  2714. min = plane.normal.x * this.max.x;
  2715. max = plane.normal.x * this.min.x;
  2716. }
  2717. if (plane.normal.y > 0) {
  2718. min += plane.normal.y * this.min.y;
  2719. max += plane.normal.y * this.max.y;
  2720. } else {
  2721. min += plane.normal.y * this.max.y;
  2722. max += plane.normal.y * this.min.y;
  2723. }
  2724. if (plane.normal.z > 0) {
  2725. min += plane.normal.z * this.min.z;
  2726. max += plane.normal.z * this.max.z;
  2727. } else {
  2728. min += plane.normal.z * this.max.z;
  2729. max += plane.normal.z * this.min.z;
  2730. }
  2731. return min <= -plane.constant && max >= -plane.constant;
  2732. }
  2733. intersectsTriangle(triangle) {
  2734. if (this.isEmpty()) {
  2735. return false;
  2736. } // compute box center and extents
  2737. this.getCenter(_center);
  2738. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  2739. _v0$2.subVectors(triangle.a, _center);
  2740. _v1$7.subVectors(triangle.b, _center);
  2741. _v2$3.subVectors(triangle.c, _center); // compute edge vectors for triangle
  2742. _f0.subVectors(_v1$7, _v0$2);
  2743. _f1.subVectors(_v2$3, _v1$7);
  2744. _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
  2745. // 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
  2746. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2747. 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];
  2748. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  2749. return false;
  2750. } // test 3 face normals from the aabb
  2751. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  2752. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  2753. return false;
  2754. } // finally testing the face normal of the triangle
  2755. // use already existing triangle edge vectors here
  2756. _triangleNormal.crossVectors(_f0, _f1);
  2757. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  2758. return satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents);
  2759. }
  2760. clampPoint(point, target) {
  2761. return target.copy(point).clamp(this.min, this.max);
  2762. }
  2763. distanceToPoint(point) {
  2764. const clampedPoint = _vector$b.copy(point).clamp(this.min, this.max);
  2765. return clampedPoint.sub(point).length();
  2766. }
  2767. getBoundingSphere(target) {
  2768. this.getCenter(target.center);
  2769. target.radius = this.getSize(_vector$b).length() * 0.5;
  2770. return target;
  2771. }
  2772. intersect(box) {
  2773. this.min.max(box.min);
  2774. 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.
  2775. if (this.isEmpty()) this.makeEmpty();
  2776. return this;
  2777. }
  2778. union(box) {
  2779. this.min.min(box.min);
  2780. this.max.max(box.max);
  2781. return this;
  2782. }
  2783. applyMatrix4(matrix) {
  2784. // transform of empty box is an empty box.
  2785. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2786. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  2787. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  2788. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  2789. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  2790. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  2791. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  2792. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  2793. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  2794. this.setFromPoints(_points);
  2795. return this;
  2796. }
  2797. translate(offset) {
  2798. this.min.add(offset);
  2799. this.max.add(offset);
  2800. return this;
  2801. }
  2802. equals(box) {
  2803. return box.min.equals(this.min) && box.max.equals(this.max);
  2804. }
  2805. }
  2806. Box3.prototype.isBox3 = true;
  2807. 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()];
  2808. const _vector$b = /*@__PURE__*/new Vector3();
  2809. const _box$3 = /*@__PURE__*/new Box3(); // triangle centered vertices
  2810. const _v0$2 = /*@__PURE__*/new Vector3();
  2811. const _v1$7 = /*@__PURE__*/new Vector3();
  2812. const _v2$3 = /*@__PURE__*/new Vector3(); // triangle edge vectors
  2813. const _f0 = /*@__PURE__*/new Vector3();
  2814. const _f1 = /*@__PURE__*/new Vector3();
  2815. const _f2 = /*@__PURE__*/new Vector3();
  2816. const _center = /*@__PURE__*/new Vector3();
  2817. const _extents = /*@__PURE__*/new Vector3();
  2818. const _triangleNormal = /*@__PURE__*/new Vector3();
  2819. const _testAxis = /*@__PURE__*/new Vector3();
  2820. function satForAxes(axes, v0, v1, v2, extents) {
  2821. for (let i = 0, j = axes.length - 3; i <= j; i += 3) {
  2822. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  2823. 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
  2824. const p0 = v0.dot(_testAxis);
  2825. const p1 = v1.dot(_testAxis);
  2826. const p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  2827. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  2828. // points of the projected triangle are outside the projected half-length of the aabb
  2829. // the axis is seperating and we can exit
  2830. return false;
  2831. }
  2832. }
  2833. return true;
  2834. }
  2835. const _box$2 = /*@__PURE__*/new Box3();
  2836. const _v1$6 = /*@__PURE__*/new Vector3();
  2837. const _toFarthestPoint = /*@__PURE__*/new Vector3();
  2838. const _toPoint = /*@__PURE__*/new Vector3();
  2839. class Sphere {
  2840. constructor(center = new Vector3(), radius = -1) {
  2841. this.center = center;
  2842. this.radius = radius;
  2843. }
  2844. set(center, radius) {
  2845. this.center.copy(center);
  2846. this.radius = radius;
  2847. return this;
  2848. }
  2849. setFromPoints(points, optionalCenter) {
  2850. const center = this.center;
  2851. if (optionalCenter !== undefined) {
  2852. center.copy(optionalCenter);
  2853. } else {
  2854. _box$2.setFromPoints(points).getCenter(center);
  2855. }
  2856. let maxRadiusSq = 0;
  2857. for (let i = 0, il = points.length; i < il; i++) {
  2858. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  2859. }
  2860. this.radius = Math.sqrt(maxRadiusSq);
  2861. return this;
  2862. }
  2863. copy(sphere) {
  2864. this.center.copy(sphere.center);
  2865. this.radius = sphere.radius;
  2866. return this;
  2867. }
  2868. isEmpty() {
  2869. return this.radius < 0;
  2870. }
  2871. makeEmpty() {
  2872. this.center.set(0, 0, 0);
  2873. this.radius = -1;
  2874. return this;
  2875. }
  2876. containsPoint(point) {
  2877. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  2878. }
  2879. distanceToPoint(point) {
  2880. return point.distanceTo(this.center) - this.radius;
  2881. }
  2882. intersectsSphere(sphere) {
  2883. const radiusSum = this.radius + sphere.radius;
  2884. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  2885. }
  2886. intersectsBox(box) {
  2887. return box.intersectsSphere(this);
  2888. }
  2889. intersectsPlane(plane) {
  2890. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  2891. }
  2892. clampPoint(point, target) {
  2893. const deltaLengthSq = this.center.distanceToSquared(point);
  2894. target.copy(point);
  2895. if (deltaLengthSq > this.radius * this.radius) {
  2896. target.sub(this.center).normalize();
  2897. target.multiplyScalar(this.radius).add(this.center);
  2898. }
  2899. return target;
  2900. }
  2901. getBoundingBox(target) {
  2902. if (this.isEmpty()) {
  2903. // Empty sphere produces empty bounding box
  2904. target.makeEmpty();
  2905. return target;
  2906. }
  2907. target.set(this.center, this.center);
  2908. target.expandByScalar(this.radius);
  2909. return target;
  2910. }
  2911. applyMatrix4(matrix) {
  2912. this.center.applyMatrix4(matrix);
  2913. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2914. return this;
  2915. }
  2916. translate(offset) {
  2917. this.center.add(offset);
  2918. return this;
  2919. }
  2920. expandByPoint(point) {
  2921. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  2922. _toPoint.subVectors(point, this.center);
  2923. const lengthSq = _toPoint.lengthSq();
  2924. if (lengthSq > this.radius * this.radius) {
  2925. const length = Math.sqrt(lengthSq);
  2926. const missingRadiusHalf = (length - this.radius) * 0.5; // Nudge this sphere towards the target point. Add half the missing distance to radius,
  2927. // and the other half to position. This gives a tighter enclosure, instead of if
  2928. // the whole missing distance were just added to radius.
  2929. this.center.add(_toPoint.multiplyScalar(missingRadiusHalf / length));
  2930. this.radius += missingRadiusHalf;
  2931. }
  2932. return this;
  2933. }
  2934. union(sphere) {
  2935. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  2936. // To enclose another sphere into this sphere, we only need to enclose two points:
  2937. // 1) Enclose the farthest point on the other sphere into this sphere.
  2938. // 2) Enclose the opposite point of the farthest point into this sphere.
  2939. _toFarthestPoint.subVectors(sphere.center, this.center).normalize().multiplyScalar(sphere.radius);
  2940. this.expandByPoint(_v1$6.copy(sphere.center).add(_toFarthestPoint));
  2941. this.expandByPoint(_v1$6.copy(sphere.center).sub(_toFarthestPoint));
  2942. return this;
  2943. }
  2944. equals(sphere) {
  2945. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  2946. }
  2947. clone() {
  2948. return new this.constructor().copy(this);
  2949. }
  2950. }
  2951. const _vector$a = /*@__PURE__*/new Vector3();
  2952. const _segCenter = /*@__PURE__*/new Vector3();
  2953. const _segDir = /*@__PURE__*/new Vector3();
  2954. const _diff = /*@__PURE__*/new Vector3();
  2955. const _edge1 = /*@__PURE__*/new Vector3();
  2956. const _edge2 = /*@__PURE__*/new Vector3();
  2957. const _normal$1 = /*@__PURE__*/new Vector3();
  2958. class Ray {
  2959. constructor(origin = new Vector3(), direction = new Vector3(0, 0, -1)) {
  2960. this.origin = origin;
  2961. this.direction = direction;
  2962. }
  2963. set(origin, direction) {
  2964. this.origin.copy(origin);
  2965. this.direction.copy(direction);
  2966. return this;
  2967. }
  2968. copy(ray) {
  2969. this.origin.copy(ray.origin);
  2970. this.direction.copy(ray.direction);
  2971. return this;
  2972. }
  2973. at(t, target) {
  2974. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  2975. }
  2976. lookAt(v) {
  2977. this.direction.copy(v).sub(this.origin).normalize();
  2978. return this;
  2979. }
  2980. recast(t) {
  2981. this.origin.copy(this.at(t, _vector$a));
  2982. return this;
  2983. }
  2984. closestPointToPoint(point, target) {
  2985. target.subVectors(point, this.origin);
  2986. const directionDistance = target.dot(this.direction);
  2987. if (directionDistance < 0) {
  2988. return target.copy(this.origin);
  2989. }
  2990. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  2991. }
  2992. distanceToPoint(point) {
  2993. return Math.sqrt(this.distanceSqToPoint(point));
  2994. }
  2995. distanceSqToPoint(point) {
  2996. const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  2997. if (directionDistance < 0) {
  2998. return this.origin.distanceToSquared(point);
  2999. }
  3000. _vector$a.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3001. return _vector$a.distanceToSquared(point);
  3002. }
  3003. distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  3004. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3005. // It returns the min distance between the ray and the segment
  3006. // defined by v0 and v1
  3007. // It can also set two optional targets :
  3008. // - The closest point on the ray
  3009. // - The closest point on the segment
  3010. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  3011. _segDir.copy(v1).sub(v0).normalize();
  3012. _diff.copy(this.origin).sub(_segCenter);
  3013. const segExtent = v0.distanceTo(v1) * 0.5;
  3014. const a01 = -this.direction.dot(_segDir);
  3015. const b0 = _diff.dot(this.direction);
  3016. const b1 = -_diff.dot(_segDir);
  3017. const c = _diff.lengthSq();
  3018. const det = Math.abs(1 - a01 * a01);
  3019. let s0, s1, sqrDist, extDet;
  3020. if (det > 0) {
  3021. // The ray and segment are not parallel.
  3022. s0 = a01 * b1 - b0;
  3023. s1 = a01 * b0 - b1;
  3024. extDet = segExtent * det;
  3025. if (s0 >= 0) {
  3026. if (s1 >= -extDet) {
  3027. if (s1 <= extDet) {
  3028. // region 0
  3029. // Minimum at interior points of ray and segment.
  3030. const invDet = 1 / det;
  3031. s0 *= invDet;
  3032. s1 *= invDet;
  3033. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  3034. } else {
  3035. // region 1
  3036. s1 = segExtent;
  3037. s0 = Math.max(0, -(a01 * s1 + b0));
  3038. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3039. }
  3040. } else {
  3041. // region 5
  3042. s1 = -segExtent;
  3043. s0 = Math.max(0, -(a01 * s1 + b0));
  3044. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3045. }
  3046. } else {
  3047. if (s1 <= -extDet) {
  3048. // region 4
  3049. s0 = Math.max(0, -(-a01 * segExtent + b0));
  3050. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3051. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3052. } else if (s1 <= extDet) {
  3053. // region 3
  3054. s0 = 0;
  3055. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  3056. sqrDist = s1 * (s1 + 2 * b1) + c;
  3057. } else {
  3058. // region 2
  3059. s0 = Math.max(0, -(a01 * segExtent + b0));
  3060. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3061. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3062. }
  3063. }
  3064. } else {
  3065. // Ray and segment are parallel.
  3066. s1 = a01 > 0 ? -segExtent : segExtent;
  3067. s0 = Math.max(0, -(a01 * s1 + b0));
  3068. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3069. }
  3070. if (optionalPointOnRay) {
  3071. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  3072. }
  3073. if (optionalPointOnSegment) {
  3074. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  3075. }
  3076. return sqrDist;
  3077. }
  3078. intersectSphere(sphere, target) {
  3079. _vector$a.subVectors(sphere.center, this.origin);
  3080. const tca = _vector$a.dot(this.direction);
  3081. const d2 = _vector$a.dot(_vector$a) - tca * tca;
  3082. const radius2 = sphere.radius * sphere.radius;
  3083. if (d2 > radius2) return null;
  3084. const thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  3085. const t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  3086. const t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  3087. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  3088. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3089. // in order to always return an intersect point that is in front of the ray.
  3090. 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
  3091. return this.at(t0, target);
  3092. }
  3093. intersectsSphere(sphere) {
  3094. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  3095. }
  3096. distanceToPlane(plane) {
  3097. const denominator = plane.normal.dot(this.direction);
  3098. if (denominator === 0) {
  3099. // line is coplanar, return origin
  3100. if (plane.distanceToPoint(this.origin) === 0) {
  3101. return 0;
  3102. } // Null is preferable to undefined since undefined means.... it is undefined
  3103. return null;
  3104. }
  3105. const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  3106. return t >= 0 ? t : null;
  3107. }
  3108. intersectPlane(plane, target) {
  3109. const t = this.distanceToPlane(plane);
  3110. if (t === null) {
  3111. return null;
  3112. }
  3113. return this.at(t, target);
  3114. }
  3115. intersectsPlane(plane) {
  3116. // check if the ray lies on the plane first
  3117. const distToPoint = plane.distanceToPoint(this.origin);
  3118. if (distToPoint === 0) {
  3119. return true;
  3120. }
  3121. const denominator = plane.normal.dot(this.direction);
  3122. if (denominator * distToPoint < 0) {
  3123. return true;
  3124. } // ray origin is behind the plane (and is pointing behind it)
  3125. return false;
  3126. }
  3127. intersectBox(box, target) {
  3128. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3129. const invdirx = 1 / this.direction.x,
  3130. invdiry = 1 / this.direction.y,
  3131. invdirz = 1 / this.direction.z;
  3132. const origin = this.origin;
  3133. if (invdirx >= 0) {
  3134. tmin = (box.min.x - origin.x) * invdirx;
  3135. tmax = (box.max.x - origin.x) * invdirx;
  3136. } else {
  3137. tmin = (box.max.x - origin.x) * invdirx;
  3138. tmax = (box.min.x - origin.x) * invdirx;
  3139. }
  3140. if (invdiry >= 0) {
  3141. tymin = (box.min.y - origin.y) * invdiry;
  3142. tymax = (box.max.y - origin.y) * invdiry;
  3143. } else {
  3144. tymin = (box.max.y - origin.y) * invdiry;
  3145. tymax = (box.min.y - origin.y) * invdiry;
  3146. }
  3147. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  3148. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3149. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  3150. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  3151. if (invdirz >= 0) {
  3152. tzmin = (box.min.z - origin.z) * invdirz;
  3153. tzmax = (box.max.z - origin.z) * invdirz;
  3154. } else {
  3155. tzmin = (box.max.z - origin.z) * invdirz;
  3156. tzmax = (box.min.z - origin.z) * invdirz;
  3157. }
  3158. if (tmin > tzmax || tzmin > tmax) return null;
  3159. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  3160. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  3161. if (tmax < 0) return null;
  3162. return this.at(tmin >= 0 ? tmin : tmax, target);
  3163. }
  3164. intersectsBox(box) {
  3165. return this.intersectBox(box, _vector$a) !== null;
  3166. }
  3167. intersectTriangle(a, b, c, backfaceCulling, target) {
  3168. // Compute the offset origin, edges, and normal.
  3169. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3170. _edge1.subVectors(b, a);
  3171. _edge2.subVectors(c, a);
  3172. _normal$1.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3173. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3174. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3175. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3176. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3177. let DdN = this.direction.dot(_normal$1);
  3178. let sign;
  3179. if (DdN > 0) {
  3180. if (backfaceCulling) return null;
  3181. sign = 1;
  3182. } else if (DdN < 0) {
  3183. sign = -1;
  3184. DdN = -DdN;
  3185. } else {
  3186. return null;
  3187. }
  3188. _diff.subVectors(this.origin, a);
  3189. const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  3190. if (DdQxE2 < 0) {
  3191. return null;
  3192. }
  3193. const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  3194. if (DdE1xQ < 0) {
  3195. return null;
  3196. } // b1+b2 > 1, no intersection
  3197. if (DdQxE2 + DdE1xQ > DdN) {
  3198. return null;
  3199. } // Line intersects triangle, check if ray does.
  3200. const QdN = -sign * _diff.dot(_normal$1); // t < 0, no intersection
  3201. if (QdN < 0) {
  3202. return null;
  3203. } // Ray intersects triangle.
  3204. return this.at(QdN / DdN, target);
  3205. }
  3206. applyMatrix4(matrix4) {
  3207. this.origin.applyMatrix4(matrix4);
  3208. this.direction.transformDirection(matrix4);
  3209. return this;
  3210. }
  3211. equals(ray) {
  3212. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  3213. }
  3214. clone() {
  3215. return new this.constructor().copy(this);
  3216. }
  3217. }
  3218. class Matrix4 {
  3219. constructor() {
  3220. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  3221. if (arguments.length > 0) {
  3222. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  3223. }
  3224. }
  3225. set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  3226. const te = this.elements;
  3227. te[0] = n11;
  3228. te[4] = n12;
  3229. te[8] = n13;
  3230. te[12] = n14;
  3231. te[1] = n21;
  3232. te[5] = n22;
  3233. te[9] = n23;
  3234. te[13] = n24;
  3235. te[2] = n31;
  3236. te[6] = n32;
  3237. te[10] = n33;
  3238. te[14] = n34;
  3239. te[3] = n41;
  3240. te[7] = n42;
  3241. te[11] = n43;
  3242. te[15] = n44;
  3243. return this;
  3244. }
  3245. identity() {
  3246. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3247. return this;
  3248. }
  3249. clone() {
  3250. return new Matrix4().fromArray(this.elements);
  3251. }
  3252. copy(m) {
  3253. const te = this.elements;
  3254. const me = m.elements;
  3255. te[0] = me[0];
  3256. te[1] = me[1];
  3257. te[2] = me[2];
  3258. te[3] = me[3];
  3259. te[4] = me[4];
  3260. te[5] = me[5];
  3261. te[6] = me[6];
  3262. te[7] = me[7];
  3263. te[8] = me[8];
  3264. te[9] = me[9];
  3265. te[10] = me[10];
  3266. te[11] = me[11];
  3267. te[12] = me[12];
  3268. te[13] = me[13];
  3269. te[14] = me[14];
  3270. te[15] = me[15];
  3271. return this;
  3272. }
  3273. copyPosition(m) {
  3274. const te = this.elements,
  3275. me = m.elements;
  3276. te[12] = me[12];
  3277. te[13] = me[13];
  3278. te[14] = me[14];
  3279. return this;
  3280. }
  3281. setFromMatrix3(m) {
  3282. const me = m.elements;
  3283. 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);
  3284. return this;
  3285. }
  3286. extractBasis(xAxis, yAxis, zAxis) {
  3287. xAxis.setFromMatrixColumn(this, 0);
  3288. yAxis.setFromMatrixColumn(this, 1);
  3289. zAxis.setFromMatrixColumn(this, 2);
  3290. return this;
  3291. }
  3292. makeBasis(xAxis, yAxis, zAxis) {
  3293. 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);
  3294. return this;
  3295. }
  3296. extractRotation(m) {
  3297. // this method does not support reflection matrices
  3298. const te = this.elements;
  3299. const me = m.elements;
  3300. const scaleX = 1 / _v1$5.setFromMatrixColumn(m, 0).length();
  3301. const scaleY = 1 / _v1$5.setFromMatrixColumn(m, 1).length();
  3302. const scaleZ = 1 / _v1$5.setFromMatrixColumn(m, 2).length();
  3303. te[0] = me[0] * scaleX;
  3304. te[1] = me[1] * scaleX;
  3305. te[2] = me[2] * scaleX;
  3306. te[3] = 0;
  3307. te[4] = me[4] * scaleY;
  3308. te[5] = me[5] * scaleY;
  3309. te[6] = me[6] * scaleY;
  3310. te[7] = 0;
  3311. te[8] = me[8] * scaleZ;
  3312. te[9] = me[9] * scaleZ;
  3313. te[10] = me[10] * scaleZ;
  3314. te[11] = 0;
  3315. te[12] = 0;
  3316. te[13] = 0;
  3317. te[14] = 0;
  3318. te[15] = 1;
  3319. return this;
  3320. }
  3321. makeRotationFromEuler(euler) {
  3322. if (!(euler && euler.isEuler)) {
  3323. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  3324. }
  3325. const te = this.elements;
  3326. const x = euler.x,
  3327. y = euler.y,
  3328. z = euler.z;
  3329. const a = Math.cos(x),
  3330. b = Math.sin(x);
  3331. const c = Math.cos(y),
  3332. d = Math.sin(y);
  3333. const e = Math.cos(z),
  3334. f = Math.sin(z);
  3335. if (euler.order === 'XYZ') {
  3336. const ae = a * e,
  3337. af = a * f,
  3338. be = b * e,
  3339. bf = b * f;
  3340. te[0] = c * e;
  3341. te[4] = -c * f;
  3342. te[8] = d;
  3343. te[1] = af + be * d;
  3344. te[5] = ae - bf * d;
  3345. te[9] = -b * c;
  3346. te[2] = bf - ae * d;
  3347. te[6] = be + af * d;
  3348. te[10] = a * c;
  3349. } else if (euler.order === 'YXZ') {
  3350. const ce = c * e,
  3351. cf = c * f,
  3352. de = d * e,
  3353. df = d * f;
  3354. te[0] = ce + df * b;
  3355. te[4] = de * b - cf;
  3356. te[8] = a * d;
  3357. te[1] = a * f;
  3358. te[5] = a * e;
  3359. te[9] = -b;
  3360. te[2] = cf * b - de;
  3361. te[6] = df + ce * b;
  3362. te[10] = a * c;
  3363. } else if (euler.order === 'ZXY') {
  3364. const ce = c * e,
  3365. cf = c * f,
  3366. de = d * e,
  3367. df = d * f;
  3368. te[0] = ce - df * b;
  3369. te[4] = -a * f;
  3370. te[8] = de + cf * b;
  3371. te[1] = cf + de * b;
  3372. te[5] = a * e;
  3373. te[9] = df - ce * b;
  3374. te[2] = -a * d;
  3375. te[6] = b;
  3376. te[10] = a * c;
  3377. } else if (euler.order === 'ZYX') {
  3378. const ae = a * e,
  3379. af = a * f,
  3380. be = b * e,
  3381. bf = b * f;
  3382. te[0] = c * e;
  3383. te[4] = be * d - af;
  3384. te[8] = ae * d + bf;
  3385. te[1] = c * f;
  3386. te[5] = bf * d + ae;
  3387. te[9] = af * d - be;
  3388. te[2] = -d;
  3389. te[6] = b * c;
  3390. te[10] = a * c;
  3391. } else if (euler.order === 'YZX') {
  3392. const ac = a * c,
  3393. ad = a * d,
  3394. bc = b * c,
  3395. bd = b * d;
  3396. te[0] = c * e;
  3397. te[4] = bd - ac * f;
  3398. te[8] = bc * f + ad;
  3399. te[1] = f;
  3400. te[5] = a * e;
  3401. te[9] = -b * e;
  3402. te[2] = -d * e;
  3403. te[6] = ad * f + bc;
  3404. te[10] = ac - bd * f;
  3405. } else if (euler.order === 'XZY') {
  3406. const ac = a * c,
  3407. ad = a * d,
  3408. bc = b * c,
  3409. bd = b * d;
  3410. te[0] = c * e;
  3411. te[4] = -f;
  3412. te[8] = d * e;
  3413. te[1] = ac * f + bd;
  3414. te[5] = a * e;
  3415. te[9] = ad * f - bc;
  3416. te[2] = bc * f - ad;
  3417. te[6] = b * e;
  3418. te[10] = bd * f + ac;
  3419. } // bottom row
  3420. te[3] = 0;
  3421. te[7] = 0;
  3422. te[11] = 0; // last column
  3423. te[12] = 0;
  3424. te[13] = 0;
  3425. te[14] = 0;
  3426. te[15] = 1;
  3427. return this;
  3428. }
  3429. makeRotationFromQuaternion(q) {
  3430. return this.compose(_zero, q, _one);
  3431. }
  3432. lookAt(eye, target, up) {
  3433. const te = this.elements;
  3434. _z.subVectors(eye, target);
  3435. if (_z.lengthSq() === 0) {
  3436. // eye and target are in the same position
  3437. _z.z = 1;
  3438. }
  3439. _z.normalize();
  3440. _x.crossVectors(up, _z);
  3441. if (_x.lengthSq() === 0) {
  3442. // up and z are parallel
  3443. if (Math.abs(up.z) === 1) {
  3444. _z.x += 0.0001;
  3445. } else {
  3446. _z.z += 0.0001;
  3447. }
  3448. _z.normalize();
  3449. _x.crossVectors(up, _z);
  3450. }
  3451. _x.normalize();
  3452. _y.crossVectors(_z, _x);
  3453. te[0] = _x.x;
  3454. te[4] = _y.x;
  3455. te[8] = _z.x;
  3456. te[1] = _x.y;
  3457. te[5] = _y.y;
  3458. te[9] = _z.y;
  3459. te[2] = _x.z;
  3460. te[6] = _y.z;
  3461. te[10] = _z.z;
  3462. return this;
  3463. }
  3464. multiply(m, n) {
  3465. if (n !== undefined) {
  3466. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  3467. return this.multiplyMatrices(m, n);
  3468. }
  3469. return this.multiplyMatrices(this, m);
  3470. }
  3471. premultiply(m) {
  3472. return this.multiplyMatrices(m, this);
  3473. }
  3474. multiplyMatrices(a, b) {
  3475. const ae = a.elements;
  3476. const be = b.elements;
  3477. const te = this.elements;
  3478. const a11 = ae[0],
  3479. a12 = ae[4],
  3480. a13 = ae[8],
  3481. a14 = ae[12];
  3482. const a21 = ae[1],
  3483. a22 = ae[5],
  3484. a23 = ae[9],
  3485. a24 = ae[13];
  3486. const a31 = ae[2],
  3487. a32 = ae[6],
  3488. a33 = ae[10],
  3489. a34 = ae[14];
  3490. const a41 = ae[3],
  3491. a42 = ae[7],
  3492. a43 = ae[11],
  3493. a44 = ae[15];
  3494. const b11 = be[0],
  3495. b12 = be[4],
  3496. b13 = be[8],
  3497. b14 = be[12];
  3498. const b21 = be[1],
  3499. b22 = be[5],
  3500. b23 = be[9],
  3501. b24 = be[13];
  3502. const b31 = be[2],
  3503. b32 = be[6],
  3504. b33 = be[10],
  3505. b34 = be[14];
  3506. const b41 = be[3],
  3507. b42 = be[7],
  3508. b43 = be[11],
  3509. b44 = be[15];
  3510. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3511. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3512. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3513. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3514. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3515. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3516. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3517. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3518. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3519. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3520. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3521. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3522. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3523. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3524. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3525. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3526. return this;
  3527. }
  3528. multiplyScalar(s) {
  3529. const te = this.elements;
  3530. te[0] *= s;
  3531. te[4] *= s;
  3532. te[8] *= s;
  3533. te[12] *= s;
  3534. te[1] *= s;
  3535. te[5] *= s;
  3536. te[9] *= s;
  3537. te[13] *= s;
  3538. te[2] *= s;
  3539. te[6] *= s;
  3540. te[10] *= s;
  3541. te[14] *= s;
  3542. te[3] *= s;
  3543. te[7] *= s;
  3544. te[11] *= s;
  3545. te[15] *= s;
  3546. return this;
  3547. }
  3548. determinant() {
  3549. const te = this.elements;
  3550. const n11 = te[0],
  3551. n12 = te[4],
  3552. n13 = te[8],
  3553. n14 = te[12];
  3554. const n21 = te[1],
  3555. n22 = te[5],
  3556. n23 = te[9],
  3557. n24 = te[13];
  3558. const n31 = te[2],
  3559. n32 = te[6],
  3560. n33 = te[10],
  3561. n34 = te[14];
  3562. const n41 = te[3],
  3563. n42 = te[7],
  3564. n43 = te[11],
  3565. n44 = te[15]; //TODO: make this more efficient
  3566. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3567. 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);
  3568. }
  3569. transpose() {
  3570. const te = this.elements;
  3571. let tmp;
  3572. tmp = te[1];
  3573. te[1] = te[4];
  3574. te[4] = tmp;
  3575. tmp = te[2];
  3576. te[2] = te[8];
  3577. te[8] = tmp;
  3578. tmp = te[6];
  3579. te[6] = te[9];
  3580. te[9] = tmp;
  3581. tmp = te[3];
  3582. te[3] = te[12];
  3583. te[12] = tmp;
  3584. tmp = te[7];
  3585. te[7] = te[13];
  3586. te[13] = tmp;
  3587. tmp = te[11];
  3588. te[11] = te[14];
  3589. te[14] = tmp;
  3590. return this;
  3591. }
  3592. setPosition(x, y, z) {
  3593. const te = this.elements;
  3594. if (x.isVector3) {
  3595. te[12] = x.x;
  3596. te[13] = x.y;
  3597. te[14] = x.z;
  3598. } else {
  3599. te[12] = x;
  3600. te[13] = y;
  3601. te[14] = z;
  3602. }
  3603. return this;
  3604. }
  3605. invert() {
  3606. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3607. const te = this.elements,
  3608. n11 = te[0],
  3609. n21 = te[1],
  3610. n31 = te[2],
  3611. n41 = te[3],
  3612. n12 = te[4],
  3613. n22 = te[5],
  3614. n32 = te[6],
  3615. n42 = te[7],
  3616. n13 = te[8],
  3617. n23 = te[9],
  3618. n33 = te[10],
  3619. n43 = te[11],
  3620. n14 = te[12],
  3621. n24 = te[13],
  3622. n34 = te[14],
  3623. n44 = te[15],
  3624. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3625. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3626. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3627. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3628. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3629. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  3630. const detInv = 1 / det;
  3631. te[0] = t11 * detInv;
  3632. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  3633. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  3634. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  3635. te[4] = t12 * detInv;
  3636. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  3637. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  3638. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  3639. te[8] = t13 * detInv;
  3640. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  3641. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  3642. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  3643. te[12] = t14 * detInv;
  3644. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  3645. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  3646. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  3647. return this;
  3648. }
  3649. scale(v) {
  3650. const te = this.elements;
  3651. const x = v.x,
  3652. y = v.y,
  3653. z = v.z;
  3654. te[0] *= x;
  3655. te[4] *= y;
  3656. te[8] *= z;
  3657. te[1] *= x;
  3658. te[5] *= y;
  3659. te[9] *= z;
  3660. te[2] *= x;
  3661. te[6] *= y;
  3662. te[10] *= z;
  3663. te[3] *= x;
  3664. te[7] *= y;
  3665. te[11] *= z;
  3666. return this;
  3667. }
  3668. getMaxScaleOnAxis() {
  3669. const te = this.elements;
  3670. const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  3671. const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  3672. const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  3673. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  3674. }
  3675. makeTranslation(x, y, z) {
  3676. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  3677. return this;
  3678. }
  3679. makeRotationX(theta) {
  3680. const c = Math.cos(theta),
  3681. s = Math.sin(theta);
  3682. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  3683. return this;
  3684. }
  3685. makeRotationY(theta) {
  3686. const c = Math.cos(theta),
  3687. s = Math.sin(theta);
  3688. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  3689. return this;
  3690. }
  3691. makeRotationZ(theta) {
  3692. const c = Math.cos(theta),
  3693. s = Math.sin(theta);
  3694. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3695. return this;
  3696. }
  3697. makeRotationAxis(axis, angle) {
  3698. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3699. const c = Math.cos(angle);
  3700. const s = Math.sin(angle);
  3701. const t = 1 - c;
  3702. const x = axis.x,
  3703. y = axis.y,
  3704. z = axis.z;
  3705. const tx = t * x,
  3706. ty = t * y;
  3707. 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);
  3708. return this;
  3709. }
  3710. makeScale(x, y, z) {
  3711. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  3712. return this;
  3713. }
  3714. makeShear(xy, xz, yx, yz, zx, zy) {
  3715. this.set(1, yx, zx, 0, xy, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1);
  3716. return this;
  3717. }
  3718. compose(position, quaternion, scale) {
  3719. const te = this.elements;
  3720. const x = quaternion._x,
  3721. y = quaternion._y,
  3722. z = quaternion._z,
  3723. w = quaternion._w;
  3724. const x2 = x + x,
  3725. y2 = y + y,
  3726. z2 = z + z;
  3727. const xx = x * x2,
  3728. xy = x * y2,
  3729. xz = x * z2;
  3730. const yy = y * y2,
  3731. yz = y * z2,
  3732. zz = z * z2;
  3733. const wx = w * x2,
  3734. wy = w * y2,
  3735. wz = w * z2;
  3736. const sx = scale.x,
  3737. sy = scale.y,
  3738. sz = scale.z;
  3739. te[0] = (1 - (yy + zz)) * sx;
  3740. te[1] = (xy + wz) * sx;
  3741. te[2] = (xz - wy) * sx;
  3742. te[3] = 0;
  3743. te[4] = (xy - wz) * sy;
  3744. te[5] = (1 - (xx + zz)) * sy;
  3745. te[6] = (yz + wx) * sy;
  3746. te[7] = 0;
  3747. te[8] = (xz + wy) * sz;
  3748. te[9] = (yz - wx) * sz;
  3749. te[10] = (1 - (xx + yy)) * sz;
  3750. te[11] = 0;
  3751. te[12] = position.x;
  3752. te[13] = position.y;
  3753. te[14] = position.z;
  3754. te[15] = 1;
  3755. return this;
  3756. }
  3757. decompose(position, quaternion, scale) {
  3758. const te = this.elements;
  3759. let sx = _v1$5.set(te[0], te[1], te[2]).length();
  3760. const sy = _v1$5.set(te[4], te[5], te[6]).length();
  3761. const sz = _v1$5.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  3762. const det = this.determinant();
  3763. if (det < 0) sx = -sx;
  3764. position.x = te[12];
  3765. position.y = te[13];
  3766. position.z = te[14]; // scale the rotation part
  3767. _m1$2.copy(this);
  3768. const invSX = 1 / sx;
  3769. const invSY = 1 / sy;
  3770. const invSZ = 1 / sz;
  3771. _m1$2.elements[0] *= invSX;
  3772. _m1$2.elements[1] *= invSX;
  3773. _m1$2.elements[2] *= invSX;
  3774. _m1$2.elements[4] *= invSY;
  3775. _m1$2.elements[5] *= invSY;
  3776. _m1$2.elements[6] *= invSY;
  3777. _m1$2.elements[8] *= invSZ;
  3778. _m1$2.elements[9] *= invSZ;
  3779. _m1$2.elements[10] *= invSZ;
  3780. quaternion.setFromRotationMatrix(_m1$2);
  3781. scale.x = sx;
  3782. scale.y = sy;
  3783. scale.z = sz;
  3784. return this;
  3785. }
  3786. makePerspective(left, right, top, bottom, near, far) {
  3787. if (far === undefined) {
  3788. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  3789. }
  3790. const te = this.elements;
  3791. const x = 2 * near / (right - left);
  3792. const y = 2 * near / (top - bottom);
  3793. const a = (right + left) / (right - left);
  3794. const b = (top + bottom) / (top - bottom);
  3795. const c = -(far + near) / (far - near);
  3796. const d = -2 * far * near / (far - near);
  3797. te[0] = x;
  3798. te[4] = 0;
  3799. te[8] = a;
  3800. te[12] = 0;
  3801. te[1] = 0;
  3802. te[5] = y;
  3803. te[9] = b;
  3804. te[13] = 0;
  3805. te[2] = 0;
  3806. te[6] = 0;
  3807. te[10] = c;
  3808. te[14] = d;
  3809. te[3] = 0;
  3810. te[7] = 0;
  3811. te[11] = -1;
  3812. te[15] = 0;
  3813. return this;
  3814. }
  3815. makeOrthographic(left, right, top, bottom, near, far) {
  3816. const te = this.elements;
  3817. const w = 1.0 / (right - left);
  3818. const h = 1.0 / (top - bottom);
  3819. const p = 1.0 / (far - near);
  3820. const x = (right + left) * w;
  3821. const y = (top + bottom) * h;
  3822. const z = (far + near) * p;
  3823. te[0] = 2 * w;
  3824. te[4] = 0;
  3825. te[8] = 0;
  3826. te[12] = -x;
  3827. te[1] = 0;
  3828. te[5] = 2 * h;
  3829. te[9] = 0;
  3830. te[13] = -y;
  3831. te[2] = 0;
  3832. te[6] = 0;
  3833. te[10] = -2 * p;
  3834. te[14] = -z;
  3835. te[3] = 0;
  3836. te[7] = 0;
  3837. te[11] = 0;
  3838. te[15] = 1;
  3839. return this;
  3840. }
  3841. equals(matrix) {
  3842. const te = this.elements;
  3843. const me = matrix.elements;
  3844. for (let i = 0; i < 16; i++) {
  3845. if (te[i] !== me[i]) return false;
  3846. }
  3847. return true;
  3848. }
  3849. fromArray(array, offset = 0) {
  3850. for (let i = 0; i < 16; i++) {
  3851. this.elements[i] = array[i + offset];
  3852. }
  3853. return this;
  3854. }
  3855. toArray(array = [], offset = 0) {
  3856. const te = this.elements;
  3857. array[offset] = te[0];
  3858. array[offset + 1] = te[1];
  3859. array[offset + 2] = te[2];
  3860. array[offset + 3] = te[3];
  3861. array[offset + 4] = te[4];
  3862. array[offset + 5] = te[5];
  3863. array[offset + 6] = te[6];
  3864. array[offset + 7] = te[7];
  3865. array[offset + 8] = te[8];
  3866. array[offset + 9] = te[9];
  3867. array[offset + 10] = te[10];
  3868. array[offset + 11] = te[11];
  3869. array[offset + 12] = te[12];
  3870. array[offset + 13] = te[13];
  3871. array[offset + 14] = te[14];
  3872. array[offset + 15] = te[15];
  3873. return array;
  3874. }
  3875. }
  3876. Matrix4.prototype.isMatrix4 = true;
  3877. const _v1$5 = /*@__PURE__*/new Vector3();
  3878. const _m1$2 = /*@__PURE__*/new Matrix4();
  3879. const _zero = /*@__PURE__*/new Vector3(0, 0, 0);
  3880. const _one = /*@__PURE__*/new Vector3(1, 1, 1);
  3881. const _x = /*@__PURE__*/new Vector3();
  3882. const _y = /*@__PURE__*/new Vector3();
  3883. const _z = /*@__PURE__*/new Vector3();
  3884. const _matrix$1 = /*@__PURE__*/new Matrix4();
  3885. const _quaternion$3 = /*@__PURE__*/new Quaternion();
  3886. class Euler {
  3887. constructor(x = 0, y = 0, z = 0, order = Euler.DefaultOrder) {
  3888. this._x = x;
  3889. this._y = y;
  3890. this._z = z;
  3891. this._order = order;
  3892. }
  3893. get x() {
  3894. return this._x;
  3895. }
  3896. set x(value) {
  3897. this._x = value;
  3898. this._onChangeCallback();
  3899. }
  3900. get y() {
  3901. return this._y;
  3902. }
  3903. set y(value) {
  3904. this._y = value;
  3905. this._onChangeCallback();
  3906. }
  3907. get z() {
  3908. return this._z;
  3909. }
  3910. set z(value) {
  3911. this._z = value;
  3912. this._onChangeCallback();
  3913. }
  3914. get order() {
  3915. return this._order;
  3916. }
  3917. set order(value) {
  3918. this._order = value;
  3919. this._onChangeCallback();
  3920. }
  3921. set(x, y, z, order = this._order) {
  3922. this._x = x;
  3923. this._y = y;
  3924. this._z = z;
  3925. this._order = order;
  3926. this._onChangeCallback();
  3927. return this;
  3928. }
  3929. clone() {
  3930. return new this.constructor(this._x, this._y, this._z, this._order);
  3931. }
  3932. copy(euler) {
  3933. this._x = euler._x;
  3934. this._y = euler._y;
  3935. this._z = euler._z;
  3936. this._order = euler._order;
  3937. this._onChangeCallback();
  3938. return this;
  3939. }
  3940. setFromRotationMatrix(m, order = this._order, update = true) {
  3941. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3942. const te = m.elements;
  3943. const m11 = te[0],
  3944. m12 = te[4],
  3945. m13 = te[8];
  3946. const m21 = te[1],
  3947. m22 = te[5],
  3948. m23 = te[9];
  3949. const m31 = te[2],
  3950. m32 = te[6],
  3951. m33 = te[10];
  3952. switch (order) {
  3953. case 'XYZ':
  3954. this._y = Math.asin(clamp(m13, -1, 1));
  3955. if (Math.abs(m13) < 0.9999999) {
  3956. this._x = Math.atan2(-m23, m33);
  3957. this._z = Math.atan2(-m12, m11);
  3958. } else {
  3959. this._x = Math.atan2(m32, m22);
  3960. this._z = 0;
  3961. }
  3962. break;
  3963. case 'YXZ':
  3964. this._x = Math.asin(-clamp(m23, -1, 1));
  3965. if (Math.abs(m23) < 0.9999999) {
  3966. this._y = Math.atan2(m13, m33);
  3967. this._z = Math.atan2(m21, m22);
  3968. } else {
  3969. this._y = Math.atan2(-m31, m11);
  3970. this._z = 0;
  3971. }
  3972. break;
  3973. case 'ZXY':
  3974. this._x = Math.asin(clamp(m32, -1, 1));
  3975. if (Math.abs(m32) < 0.9999999) {
  3976. this._y = Math.atan2(-m31, m33);
  3977. this._z = Math.atan2(-m12, m22);
  3978. } else {
  3979. this._y = 0;
  3980. this._z = Math.atan2(m21, m11);
  3981. }
  3982. break;
  3983. case 'ZYX':
  3984. this._y = Math.asin(-clamp(m31, -1, 1));
  3985. if (Math.abs(m31) < 0.9999999) {
  3986. this._x = Math.atan2(m32, m33);
  3987. this._z = Math.atan2(m21, m11);
  3988. } else {
  3989. this._x = 0;
  3990. this._z = Math.atan2(-m12, m22);
  3991. }
  3992. break;
  3993. case 'YZX':
  3994. this._z = Math.asin(clamp(m21, -1, 1));
  3995. if (Math.abs(m21) < 0.9999999) {
  3996. this._x = Math.atan2(-m23, m22);
  3997. this._y = Math.atan2(-m31, m11);
  3998. } else {
  3999. this._x = 0;
  4000. this._y = Math.atan2(m13, m33);
  4001. }
  4002. break;
  4003. case 'XZY':
  4004. this._z = Math.asin(-clamp(m12, -1, 1));
  4005. if (Math.abs(m12) < 0.9999999) {
  4006. this._x = Math.atan2(m32, m22);
  4007. this._y = Math.atan2(m13, m11);
  4008. } else {
  4009. this._x = Math.atan2(-m23, m33);
  4010. this._y = 0;
  4011. }
  4012. break;
  4013. default:
  4014. console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
  4015. }
  4016. this._order = order;
  4017. if (update === true) this._onChangeCallback();
  4018. return this;
  4019. }
  4020. setFromQuaternion(q, order, update) {
  4021. _matrix$1.makeRotationFromQuaternion(q);
  4022. return this.setFromRotationMatrix(_matrix$1, order, update);
  4023. }
  4024. setFromVector3(v, order = this._order) {
  4025. return this.set(v.x, v.y, v.z, order);
  4026. }
  4027. reorder(newOrder) {
  4028. // WARNING: this discards revolution information -bhouston
  4029. _quaternion$3.setFromEuler(this);
  4030. return this.setFromQuaternion(_quaternion$3, newOrder);
  4031. }
  4032. equals(euler) {
  4033. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4034. }
  4035. fromArray(array) {
  4036. this._x = array[0];
  4037. this._y = array[1];
  4038. this._z = array[2];
  4039. if (array[3] !== undefined) this._order = array[3];
  4040. this._onChangeCallback();
  4041. return this;
  4042. }
  4043. toArray(array = [], offset = 0) {
  4044. array[offset] = this._x;
  4045. array[offset + 1] = this._y;
  4046. array[offset + 2] = this._z;
  4047. array[offset + 3] = this._order;
  4048. return array;
  4049. }
  4050. toVector3(optionalResult) {
  4051. if (optionalResult) {
  4052. return optionalResult.set(this._x, this._y, this._z);
  4053. } else {
  4054. return new Vector3(this._x, this._y, this._z);
  4055. }
  4056. }
  4057. _onChange(callback) {
  4058. this._onChangeCallback = callback;
  4059. return this;
  4060. }
  4061. _onChangeCallback() {}
  4062. }
  4063. Euler.prototype.isEuler = true;
  4064. Euler.DefaultOrder = 'XYZ';
  4065. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4066. class Layers {
  4067. constructor() {
  4068. this.mask = 1 | 0;
  4069. }
  4070. set(channel) {
  4071. this.mask = 1 << channel | 0;
  4072. }
  4073. enable(channel) {
  4074. this.mask |= 1 << channel | 0;
  4075. }
  4076. enableAll() {
  4077. this.mask = 0xffffffff | 0;
  4078. }
  4079. toggle(channel) {
  4080. this.mask ^= 1 << channel | 0;
  4081. }
  4082. disable(channel) {
  4083. this.mask &= ~(1 << channel | 0);
  4084. }
  4085. disableAll() {
  4086. this.mask = 0;
  4087. }
  4088. test(layers) {
  4089. return (this.mask & layers.mask) !== 0;
  4090. }
  4091. }
  4092. let _object3DId = 0;
  4093. const _v1$4 = /*@__PURE__*/new Vector3();
  4094. const _q1 = /*@__PURE__*/new Quaternion();
  4095. const _m1$1 = /*@__PURE__*/new Matrix4();
  4096. const _target = /*@__PURE__*/new Vector3();
  4097. const _position$3 = /*@__PURE__*/new Vector3();
  4098. const _scale$2 = /*@__PURE__*/new Vector3();
  4099. const _quaternion$2 = /*@__PURE__*/new Quaternion();
  4100. const _xAxis = /*@__PURE__*/new Vector3(1, 0, 0);
  4101. const _yAxis = /*@__PURE__*/new Vector3(0, 1, 0);
  4102. const _zAxis = /*@__PURE__*/new Vector3(0, 0, 1);
  4103. const _addedEvent = {
  4104. type: 'added'
  4105. };
  4106. const _removedEvent = {
  4107. type: 'removed'
  4108. };
  4109. class Object3D extends EventDispatcher {
  4110. constructor() {
  4111. super();
  4112. Object.defineProperty(this, 'id', {
  4113. value: _object3DId++
  4114. });
  4115. this.uuid = generateUUID();
  4116. this.name = '';
  4117. this.type = 'Object3D';
  4118. this.parent = null;
  4119. this.children = [];
  4120. this.up = Object3D.DefaultUp.clone();
  4121. const position = new Vector3();
  4122. const rotation = new Euler();
  4123. const quaternion = new Quaternion();
  4124. const scale = new Vector3(1, 1, 1);
  4125. function onRotationChange() {
  4126. quaternion.setFromEuler(rotation, false);
  4127. }
  4128. function onQuaternionChange() {
  4129. rotation.setFromQuaternion(quaternion, undefined, false);
  4130. }
  4131. rotation._onChange(onRotationChange);
  4132. quaternion._onChange(onQuaternionChange);
  4133. Object.defineProperties(this, {
  4134. position: {
  4135. configurable: true,
  4136. enumerable: true,
  4137. value: position
  4138. },
  4139. rotation: {
  4140. configurable: true,
  4141. enumerable: true,
  4142. value: rotation
  4143. },
  4144. quaternion: {
  4145. configurable: true,
  4146. enumerable: true,
  4147. value: quaternion
  4148. },
  4149. scale: {
  4150. configurable: true,
  4151. enumerable: true,
  4152. value: scale
  4153. },
  4154. modelViewMatrix: {
  4155. value: new Matrix4()
  4156. },
  4157. normalMatrix: {
  4158. value: new Matrix3()
  4159. }
  4160. });
  4161. this.matrix = new Matrix4();
  4162. this.matrixWorld = new Matrix4();
  4163. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4164. this.matrixWorldNeedsUpdate = false;
  4165. this.layers = new Layers();
  4166. this.visible = true;
  4167. this.castShadow = false;
  4168. this.receiveShadow = false;
  4169. this.frustumCulled = true;
  4170. this.renderOrder = 0;
  4171. this.animations = [];
  4172. this.userData = {};
  4173. }
  4174. onBeforeRender() {}
  4175. onAfterRender() {}
  4176. applyMatrix4(matrix) {
  4177. if (this.matrixAutoUpdate) this.updateMatrix();
  4178. this.matrix.premultiply(matrix);
  4179. this.matrix.decompose(this.position, this.quaternion, this.scale);
  4180. }
  4181. applyQuaternion(q) {
  4182. this.quaternion.premultiply(q);
  4183. return this;
  4184. }
  4185. setRotationFromAxisAngle(axis, angle) {
  4186. // assumes axis is normalized
  4187. this.quaternion.setFromAxisAngle(axis, angle);
  4188. }
  4189. setRotationFromEuler(euler) {
  4190. this.quaternion.setFromEuler(euler, true);
  4191. }
  4192. setRotationFromMatrix(m) {
  4193. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4194. this.quaternion.setFromRotationMatrix(m);
  4195. }
  4196. setRotationFromQuaternion(q) {
  4197. // assumes q is normalized
  4198. this.quaternion.copy(q);
  4199. }
  4200. rotateOnAxis(axis, angle) {
  4201. // rotate object on axis in object space
  4202. // axis is assumed to be normalized
  4203. _q1.setFromAxisAngle(axis, angle);
  4204. this.quaternion.multiply(_q1);
  4205. return this;
  4206. }
  4207. rotateOnWorldAxis(axis, angle) {
  4208. // rotate object on axis in world space
  4209. // axis is assumed to be normalized
  4210. // method assumes no rotated parent
  4211. _q1.setFromAxisAngle(axis, angle);
  4212. this.quaternion.premultiply(_q1);
  4213. return this;
  4214. }
  4215. rotateX(angle) {
  4216. return this.rotateOnAxis(_xAxis, angle);
  4217. }
  4218. rotateY(angle) {
  4219. return this.rotateOnAxis(_yAxis, angle);
  4220. }
  4221. rotateZ(angle) {
  4222. return this.rotateOnAxis(_zAxis, angle);
  4223. }
  4224. translateOnAxis(axis, distance) {
  4225. // translate object by distance along axis in object space
  4226. // axis is assumed to be normalized
  4227. _v1$4.copy(axis).applyQuaternion(this.quaternion);
  4228. this.position.add(_v1$4.multiplyScalar(distance));
  4229. return this;
  4230. }
  4231. translateX(distance) {
  4232. return this.translateOnAxis(_xAxis, distance);
  4233. }
  4234. translateY(distance) {
  4235. return this.translateOnAxis(_yAxis, distance);
  4236. }
  4237. translateZ(distance) {
  4238. return this.translateOnAxis(_zAxis, distance);
  4239. }
  4240. localToWorld(vector) {
  4241. return vector.applyMatrix4(this.matrixWorld);
  4242. }
  4243. worldToLocal(vector) {
  4244. return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
  4245. }
  4246. lookAt(x, y, z) {
  4247. // This method does not support objects having non-uniformly-scaled parent(s)
  4248. if (x.isVector3) {
  4249. _target.copy(x);
  4250. } else {
  4251. _target.set(x, y, z);
  4252. }
  4253. const parent = this.parent;
  4254. this.updateWorldMatrix(true, false);
  4255. _position$3.setFromMatrixPosition(this.matrixWorld);
  4256. if (this.isCamera || this.isLight) {
  4257. _m1$1.lookAt(_position$3, _target, this.up);
  4258. } else {
  4259. _m1$1.lookAt(_target, _position$3, this.up);
  4260. }
  4261. this.quaternion.setFromRotationMatrix(_m1$1);
  4262. if (parent) {
  4263. _m1$1.extractRotation(parent.matrixWorld);
  4264. _q1.setFromRotationMatrix(_m1$1);
  4265. this.quaternion.premultiply(_q1.invert());
  4266. }
  4267. }
  4268. add(object) {
  4269. if (arguments.length > 1) {
  4270. for (let i = 0; i < arguments.length; i++) {
  4271. this.add(arguments[i]);
  4272. }
  4273. return this;
  4274. }
  4275. if (object === this) {
  4276. console.error('THREE.Object3D.add: object can\'t be added as a child of itself.', object);
  4277. return this;
  4278. }
  4279. if (object && object.isObject3D) {
  4280. if (object.parent !== null) {
  4281. object.parent.remove(object);
  4282. }
  4283. object.parent = this;
  4284. this.children.push(object);
  4285. object.dispatchEvent(_addedEvent);
  4286. } else {
  4287. console.error('THREE.Object3D.add: object not an instance of THREE.Object3D.', object);
  4288. }
  4289. return this;
  4290. }
  4291. remove(object) {
  4292. if (arguments.length > 1) {
  4293. for (let i = 0; i < arguments.length; i++) {
  4294. this.remove(arguments[i]);
  4295. }
  4296. return this;
  4297. }
  4298. const index = this.children.indexOf(object);
  4299. if (index !== -1) {
  4300. object.parent = null;
  4301. this.children.splice(index, 1);
  4302. object.dispatchEvent(_removedEvent);
  4303. }
  4304. return this;
  4305. }
  4306. removeFromParent() {
  4307. const parent = this.parent;
  4308. if (parent !== null) {
  4309. parent.remove(this);
  4310. }
  4311. return this;
  4312. }
  4313. clear() {
  4314. for (let i = 0; i < this.children.length; i++) {
  4315. const object = this.children[i];
  4316. object.parent = null;
  4317. object.dispatchEvent(_removedEvent);
  4318. }
  4319. this.children.length = 0;
  4320. return this;
  4321. }
  4322. attach(object) {
  4323. // adds object as a child of this, while maintaining the object's world transform
  4324. this.updateWorldMatrix(true, false);
  4325. _m1$1.copy(this.matrixWorld).invert();
  4326. if (object.parent !== null) {
  4327. object.parent.updateWorldMatrix(true, false);
  4328. _m1$1.multiply(object.parent.matrixWorld);
  4329. }
  4330. object.applyMatrix4(_m1$1);
  4331. this.add(object);
  4332. object.updateWorldMatrix(false, true);
  4333. return this;
  4334. }
  4335. getObjectById(id) {
  4336. return this.getObjectByProperty('id', id);
  4337. }
  4338. getObjectByName(name) {
  4339. return this.getObjectByProperty('name', name);
  4340. }
  4341. getObjectByProperty(name, value) {
  4342. if (this[name] === value) return this;
  4343. for (let i = 0, l = this.children.length; i < l; i++) {
  4344. const child = this.children[i];
  4345. const object = child.getObjectByProperty(name, value);
  4346. if (object !== undefined) {
  4347. return object;
  4348. }
  4349. }
  4350. return undefined;
  4351. }
  4352. getWorldPosition(target) {
  4353. this.updateWorldMatrix(true, false);
  4354. return target.setFromMatrixPosition(this.matrixWorld);
  4355. }
  4356. getWorldQuaternion(target) {
  4357. this.updateWorldMatrix(true, false);
  4358. this.matrixWorld.decompose(_position$3, target, _scale$2);
  4359. return target;
  4360. }
  4361. getWorldScale(target) {
  4362. this.updateWorldMatrix(true, false);
  4363. this.matrixWorld.decompose(_position$3, _quaternion$2, target);
  4364. return target;
  4365. }
  4366. getWorldDirection(target) {
  4367. this.updateWorldMatrix(true, false);
  4368. const e = this.matrixWorld.elements;
  4369. return target.set(e[8], e[9], e[10]).normalize();
  4370. }
  4371. raycast() {}
  4372. traverse(callback) {
  4373. callback(this);
  4374. const children = this.children;
  4375. for (let i = 0, l = children.length; i < l; i++) {
  4376. children[i].traverse(callback);
  4377. }
  4378. }
  4379. traverseVisible(callback) {
  4380. if (this.visible === false) return;
  4381. callback(this);
  4382. const children = this.children;
  4383. for (let i = 0, l = children.length; i < l; i++) {
  4384. children[i].traverseVisible(callback);
  4385. }
  4386. }
  4387. traverseAncestors(callback) {
  4388. const parent = this.parent;
  4389. if (parent !== null) {
  4390. callback(parent);
  4391. parent.traverseAncestors(callback);
  4392. }
  4393. }
  4394. updateMatrix() {
  4395. this.matrix.compose(this.position, this.quaternion, this.scale);
  4396. this.matrixWorldNeedsUpdate = true;
  4397. }
  4398. updateMatrixWorld(force) {
  4399. if (this.matrixAutoUpdate) this.updateMatrix();
  4400. if (this.matrixWorldNeedsUpdate || force) {
  4401. if (this.parent === null) {
  4402. this.matrixWorld.copy(this.matrix);
  4403. } else {
  4404. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4405. }
  4406. this.matrixWorldNeedsUpdate = false;
  4407. force = true;
  4408. } // update children
  4409. const children = this.children;
  4410. for (let i = 0, l = children.length; i < l; i++) {
  4411. children[i].updateMatrixWorld(force);
  4412. }
  4413. }
  4414. updateWorldMatrix(updateParents, updateChildren) {
  4415. const parent = this.parent;
  4416. if (updateParents === true && parent !== null) {
  4417. parent.updateWorldMatrix(true, false);
  4418. }
  4419. if (this.matrixAutoUpdate) this.updateMatrix();
  4420. if (this.parent === null) {
  4421. this.matrixWorld.copy(this.matrix);
  4422. } else {
  4423. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4424. } // update children
  4425. if (updateChildren === true) {
  4426. const children = this.children;
  4427. for (let i = 0, l = children.length; i < l; i++) {
  4428. children[i].updateWorldMatrix(false, true);
  4429. }
  4430. }
  4431. }
  4432. toJSON(meta) {
  4433. // meta is a string when called from JSON.stringify
  4434. const isRootObject = meta === undefined || typeof meta === 'string';
  4435. const output = {}; // meta is a hash used to collect geometries, materials.
  4436. // not providing it implies that this is the root object
  4437. // being serialized.
  4438. if (isRootObject) {
  4439. // initialize meta obj
  4440. meta = {
  4441. geometries: {},
  4442. materials: {},
  4443. textures: {},
  4444. images: {},
  4445. shapes: {},
  4446. skeletons: {},
  4447. animations: {}
  4448. };
  4449. output.metadata = {
  4450. version: 4.5,
  4451. type: 'Object',
  4452. generator: 'Object3D.toJSON'
  4453. };
  4454. } // standard Object3D serialization
  4455. const object = {};
  4456. object.uuid = this.uuid;
  4457. object.type = this.type;
  4458. if (this.name !== '') object.name = this.name;
  4459. if (this.castShadow === true) object.castShadow = true;
  4460. if (this.receiveShadow === true) object.receiveShadow = true;
  4461. if (this.visible === false) object.visible = false;
  4462. if (this.frustumCulled === false) object.frustumCulled = false;
  4463. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  4464. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  4465. object.layers = this.layers.mask;
  4466. object.matrix = this.matrix.toArray();
  4467. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  4468. if (this.isInstancedMesh) {
  4469. object.type = 'InstancedMesh';
  4470. object.count = this.count;
  4471. object.instanceMatrix = this.instanceMatrix.toJSON();
  4472. if (this.instanceColor !== null) object.instanceColor = this.instanceColor.toJSON();
  4473. } //
  4474. function serialize(library, element) {
  4475. if (library[element.uuid] === undefined) {
  4476. library[element.uuid] = element.toJSON(meta);
  4477. }
  4478. return element.uuid;
  4479. }
  4480. if (this.isScene) {
  4481. if (this.background) {
  4482. if (this.background.isColor) {
  4483. object.background = this.background.toJSON();
  4484. } else if (this.background.isTexture) {
  4485. object.background = this.background.toJSON(meta).uuid;
  4486. }
  4487. }
  4488. if (this.environment && this.environment.isTexture) {
  4489. object.environment = this.environment.toJSON(meta).uuid;
  4490. }
  4491. } else if (this.isMesh || this.isLine || this.isPoints) {
  4492. object.geometry = serialize(meta.geometries, this.geometry);
  4493. const parameters = this.geometry.parameters;
  4494. if (parameters !== undefined && parameters.shapes !== undefined) {
  4495. const shapes = parameters.shapes;
  4496. if (Array.isArray(shapes)) {
  4497. for (let i = 0, l = shapes.length; i < l; i++) {
  4498. const shape = shapes[i];
  4499. serialize(meta.shapes, shape);
  4500. }
  4501. } else {
  4502. serialize(meta.shapes, shapes);
  4503. }
  4504. }
  4505. }
  4506. if (this.isSkinnedMesh) {
  4507. object.bindMode = this.bindMode;
  4508. object.bindMatrix = this.bindMatrix.toArray();
  4509. if (this.skeleton !== undefined) {
  4510. serialize(meta.skeletons, this.skeleton);
  4511. object.skeleton = this.skeleton.uuid;
  4512. }
  4513. }
  4514. if (this.material !== undefined) {
  4515. if (Array.isArray(this.material)) {
  4516. const uuids = [];
  4517. for (let i = 0, l = this.material.length; i < l; i++) {
  4518. uuids.push(serialize(meta.materials, this.material[i]));
  4519. }
  4520. object.material = uuids;
  4521. } else {
  4522. object.material = serialize(meta.materials, this.material);
  4523. }
  4524. } //
  4525. if (this.children.length > 0) {
  4526. object.children = [];
  4527. for (let i = 0; i < this.children.length; i++) {
  4528. object.children.push(this.children[i].toJSON(meta).object);
  4529. }
  4530. } //
  4531. if (this.animations.length > 0) {
  4532. object.animations = [];
  4533. for (let i = 0; i < this.animations.length; i++) {
  4534. const animation = this.animations[i];
  4535. object.animations.push(serialize(meta.animations, animation));
  4536. }
  4537. }
  4538. if (isRootObject) {
  4539. const geometries = extractFromCache(meta.geometries);
  4540. const materials = extractFromCache(meta.materials);
  4541. const textures = extractFromCache(meta.textures);
  4542. const images = extractFromCache(meta.images);
  4543. const shapes = extractFromCache(meta.shapes);
  4544. const skeletons = extractFromCache(meta.skeletons);
  4545. const animations = extractFromCache(meta.animations);
  4546. if (geometries.length > 0) output.geometries = geometries;
  4547. if (materials.length > 0) output.materials = materials;
  4548. if (textures.length > 0) output.textures = textures;
  4549. if (images.length > 0) output.images = images;
  4550. if (shapes.length > 0) output.shapes = shapes;
  4551. if (skeletons.length > 0) output.skeletons = skeletons;
  4552. if (animations.length > 0) output.animations = animations;
  4553. }
  4554. output.object = object;
  4555. return output; // extract data from the cache hash
  4556. // remove metadata on each item
  4557. // and return as array
  4558. function extractFromCache(cache) {
  4559. const values = [];
  4560. for (const key in cache) {
  4561. const data = cache[key];
  4562. delete data.metadata;
  4563. values.push(data);
  4564. }
  4565. return values;
  4566. }
  4567. }
  4568. clone(recursive) {
  4569. return new this.constructor().copy(this, recursive);
  4570. }
  4571. copy(source, recursive = true) {
  4572. this.name = source.name;
  4573. this.up.copy(source.up);
  4574. this.position.copy(source.position);
  4575. this.rotation.order = source.rotation.order;
  4576. this.quaternion.copy(source.quaternion);
  4577. this.scale.copy(source.scale);
  4578. this.matrix.copy(source.matrix);
  4579. this.matrixWorld.copy(source.matrixWorld);
  4580. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4581. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4582. this.layers.mask = source.layers.mask;
  4583. this.visible = source.visible;
  4584. this.castShadow = source.castShadow;
  4585. this.receiveShadow = source.receiveShadow;
  4586. this.frustumCulled = source.frustumCulled;
  4587. this.renderOrder = source.renderOrder;
  4588. this.userData = JSON.parse(JSON.stringify(source.userData));
  4589. if (recursive === true) {
  4590. for (let i = 0; i < source.children.length; i++) {
  4591. const child = source.children[i];
  4592. this.add(child.clone());
  4593. }
  4594. }
  4595. return this;
  4596. }
  4597. }
  4598. Object3D.DefaultUp = new Vector3(0, 1, 0);
  4599. Object3D.DefaultMatrixAutoUpdate = true;
  4600. Object3D.prototype.isObject3D = true;
  4601. const _v0$1 = /*@__PURE__*/new Vector3();
  4602. const _v1$3 = /*@__PURE__*/new Vector3();
  4603. const _v2$2 = /*@__PURE__*/new Vector3();
  4604. const _v3$1 = /*@__PURE__*/new Vector3();
  4605. const _vab = /*@__PURE__*/new Vector3();
  4606. const _vac = /*@__PURE__*/new Vector3();
  4607. const _vbc = /*@__PURE__*/new Vector3();
  4608. const _vap = /*@__PURE__*/new Vector3();
  4609. const _vbp = /*@__PURE__*/new Vector3();
  4610. const _vcp = /*@__PURE__*/new Vector3();
  4611. class Triangle {
  4612. constructor(a = new Vector3(), b = new Vector3(), c = new Vector3()) {
  4613. this.a = a;
  4614. this.b = b;
  4615. this.c = c;
  4616. }
  4617. static getNormal(a, b, c, target) {
  4618. target.subVectors(c, b);
  4619. _v0$1.subVectors(a, b);
  4620. target.cross(_v0$1);
  4621. const targetLengthSq = target.lengthSq();
  4622. if (targetLengthSq > 0) {
  4623. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  4624. }
  4625. return target.set(0, 0, 0);
  4626. } // static/instance method to calculate barycentric coordinates
  4627. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4628. static getBarycoord(point, a, b, c, target) {
  4629. _v0$1.subVectors(c, a);
  4630. _v1$3.subVectors(b, a);
  4631. _v2$2.subVectors(point, a);
  4632. const dot00 = _v0$1.dot(_v0$1);
  4633. const dot01 = _v0$1.dot(_v1$3);
  4634. const dot02 = _v0$1.dot(_v2$2);
  4635. const dot11 = _v1$3.dot(_v1$3);
  4636. const dot12 = _v1$3.dot(_v2$2);
  4637. const denom = dot00 * dot11 - dot01 * dot01; // collinear or singular triangle
  4638. if (denom === 0) {
  4639. // arbitrary location outside of triangle?
  4640. // not sure if this is the best idea, maybe should be returning undefined
  4641. return target.set(-2, -1, -1);
  4642. }
  4643. const invDenom = 1 / denom;
  4644. const u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  4645. const v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  4646. return target.set(1 - u - v, v, u);
  4647. }
  4648. static containsPoint(point, a, b, c) {
  4649. this.getBarycoord(point, a, b, c, _v3$1);
  4650. return _v3$1.x >= 0 && _v3$1.y >= 0 && _v3$1.x + _v3$1.y <= 1;
  4651. }
  4652. static getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
  4653. this.getBarycoord(point, p1, p2, p3, _v3$1);
  4654. target.set(0, 0);
  4655. target.addScaledVector(uv1, _v3$1.x);
  4656. target.addScaledVector(uv2, _v3$1.y);
  4657. target.addScaledVector(uv3, _v3$1.z);
  4658. return target;
  4659. }
  4660. static isFrontFacing(a, b, c, direction) {
  4661. _v0$1.subVectors(c, b);
  4662. _v1$3.subVectors(a, b); // strictly front facing
  4663. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  4664. }
  4665. set(a, b, c) {
  4666. this.a.copy(a);
  4667. this.b.copy(b);
  4668. this.c.copy(c);
  4669. return this;
  4670. }
  4671. setFromPointsAndIndices(points, i0, i1, i2) {
  4672. this.a.copy(points[i0]);
  4673. this.b.copy(points[i1]);
  4674. this.c.copy(points[i2]);
  4675. return this;
  4676. }
  4677. clone() {
  4678. return new this.constructor().copy(this);
  4679. }
  4680. copy(triangle) {
  4681. this.a.copy(triangle.a);
  4682. this.b.copy(triangle.b);
  4683. this.c.copy(triangle.c);
  4684. return this;
  4685. }
  4686. getArea() {
  4687. _v0$1.subVectors(this.c, this.b);
  4688. _v1$3.subVectors(this.a, this.b);
  4689. return _v0$1.cross(_v1$3).length() * 0.5;
  4690. }
  4691. getMidpoint(target) {
  4692. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  4693. }
  4694. getNormal(target) {
  4695. return Triangle.getNormal(this.a, this.b, this.c, target);
  4696. }
  4697. getPlane(target) {
  4698. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  4699. }
  4700. getBarycoord(point, target) {
  4701. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  4702. }
  4703. getUV(point, uv1, uv2, uv3, target) {
  4704. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  4705. }
  4706. containsPoint(point) {
  4707. return Triangle.containsPoint(point, this.a, this.b, this.c);
  4708. }
  4709. isFrontFacing(direction) {
  4710. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  4711. }
  4712. intersectsBox(box) {
  4713. return box.intersectsTriangle(this);
  4714. }
  4715. closestPointToPoint(p, target) {
  4716. const a = this.a,
  4717. b = this.b,
  4718. c = this.c;
  4719. let v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4720. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4721. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4722. // basically, we're distinguishing which of the voronoi regions of the triangle
  4723. // the point lies in with the minimum amount of redundant computation.
  4724. _vab.subVectors(b, a);
  4725. _vac.subVectors(c, a);
  4726. _vap.subVectors(p, a);
  4727. const d1 = _vab.dot(_vap);
  4728. const d2 = _vac.dot(_vap);
  4729. if (d1 <= 0 && d2 <= 0) {
  4730. // vertex region of A; barycentric coords (1, 0, 0)
  4731. return target.copy(a);
  4732. }
  4733. _vbp.subVectors(p, b);
  4734. const d3 = _vab.dot(_vbp);
  4735. const d4 = _vac.dot(_vbp);
  4736. if (d3 >= 0 && d4 <= d3) {
  4737. // vertex region of B; barycentric coords (0, 1, 0)
  4738. return target.copy(b);
  4739. }
  4740. const vc = d1 * d4 - d3 * d2;
  4741. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  4742. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  4743. return target.copy(a).addScaledVector(_vab, v);
  4744. }
  4745. _vcp.subVectors(p, c);
  4746. const d5 = _vab.dot(_vcp);
  4747. const d6 = _vac.dot(_vcp);
  4748. if (d6 >= 0 && d5 <= d6) {
  4749. // vertex region of C; barycentric coords (0, 0, 1)
  4750. return target.copy(c);
  4751. }
  4752. const vb = d5 * d2 - d1 * d6;
  4753. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  4754. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  4755. return target.copy(a).addScaledVector(_vac, w);
  4756. }
  4757. const va = d3 * d6 - d5 * d4;
  4758. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  4759. _vbc.subVectors(c, b);
  4760. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  4761. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  4762. } // face region
  4763. const denom = 1 / (va + vb + vc); // u = va * denom
  4764. v = vb * denom;
  4765. w = vc * denom;
  4766. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  4767. }
  4768. equals(triangle) {
  4769. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  4770. }
  4771. }
  4772. let materialId = 0;
  4773. class Material extends EventDispatcher {
  4774. constructor() {
  4775. super();
  4776. Object.defineProperty(this, 'id', {
  4777. value: materialId++
  4778. });
  4779. this.uuid = generateUUID();
  4780. this.name = '';
  4781. this.type = 'Material';
  4782. this.fog = true;
  4783. this.blending = NormalBlending;
  4784. this.side = FrontSide;
  4785. this.vertexColors = false;
  4786. this.opacity = 1;
  4787. this.format = RGBAFormat;
  4788. this.transparent = false;
  4789. this.blendSrc = SrcAlphaFactor;
  4790. this.blendDst = OneMinusSrcAlphaFactor;
  4791. this.blendEquation = AddEquation;
  4792. this.blendSrcAlpha = null;
  4793. this.blendDstAlpha = null;
  4794. this.blendEquationAlpha = null;
  4795. this.depthFunc = LessEqualDepth;
  4796. this.depthTest = true;
  4797. this.depthWrite = true;
  4798. this.stencilWriteMask = 0xff;
  4799. this.stencilFunc = AlwaysStencilFunc;
  4800. this.stencilRef = 0;
  4801. this.stencilFuncMask = 0xff;
  4802. this.stencilFail = KeepStencilOp;
  4803. this.stencilZFail = KeepStencilOp;
  4804. this.stencilZPass = KeepStencilOp;
  4805. this.stencilWrite = false;
  4806. this.clippingPlanes = null;
  4807. this.clipIntersection = false;
  4808. this.clipShadows = false;
  4809. this.shadowSide = null;
  4810. this.colorWrite = true;
  4811. this.precision = null; // override the renderer's default precision for this material
  4812. this.polygonOffset = false;
  4813. this.polygonOffsetFactor = 0;
  4814. this.polygonOffsetUnits = 0;
  4815. this.dithering = false;
  4816. this.alphaToCoverage = false;
  4817. this.premultipliedAlpha = false;
  4818. this.visible = true;
  4819. this.toneMapped = true;
  4820. this.userData = {};
  4821. this.version = 0;
  4822. this._alphaTest = 0;
  4823. }
  4824. get alphaTest() {
  4825. return this._alphaTest;
  4826. }
  4827. set alphaTest(value) {
  4828. if (this._alphaTest > 0 !== value > 0) {
  4829. this.version++;
  4830. }
  4831. this._alphaTest = value;
  4832. }
  4833. onBuild() {}
  4834. onBeforeCompile() {}
  4835. customProgramCacheKey() {
  4836. return this.onBeforeCompile.toString();
  4837. }
  4838. setValues(values) {
  4839. if (values === undefined) return;
  4840. for (const key in values) {
  4841. const newValue = values[key];
  4842. if (newValue === undefined) {
  4843. console.warn('THREE.Material: \'' + key + '\' parameter is undefined.');
  4844. continue;
  4845. } // for backward compatability if shading is set in the constructor
  4846. if (key === 'shading') {
  4847. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  4848. this.flatShading = newValue === FlatShading ? true : false;
  4849. continue;
  4850. }
  4851. const currentValue = this[key];
  4852. if (currentValue === undefined) {
  4853. console.warn('THREE.' + this.type + ': \'' + key + '\' is not a property of this material.');
  4854. continue;
  4855. }
  4856. if (currentValue && currentValue.isColor) {
  4857. currentValue.set(newValue);
  4858. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  4859. currentValue.copy(newValue);
  4860. } else {
  4861. this[key] = newValue;
  4862. }
  4863. }
  4864. }
  4865. toJSON(meta) {
  4866. const isRoot = meta === undefined || typeof meta === 'string';
  4867. if (isRoot) {
  4868. meta = {
  4869. textures: {},
  4870. images: {}
  4871. };
  4872. }
  4873. const data = {
  4874. metadata: {
  4875. version: 4.5,
  4876. type: 'Material',
  4877. generator: 'Material.toJSON'
  4878. }
  4879. }; // standard Material serialization
  4880. data.uuid = this.uuid;
  4881. data.type = this.type;
  4882. if (this.name !== '') data.name = this.name;
  4883. if (this.color && this.color.isColor) data.color = this.color.getHex();
  4884. if (this.roughness !== undefined) data.roughness = this.roughness;
  4885. if (this.metalness !== undefined) data.metalness = this.metalness;
  4886. if (this.sheenTint && this.sheenTint.isColor) data.sheenTint = this.sheenTint.getHex();
  4887. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  4888. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  4889. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  4890. if (this.specularIntensity !== undefined) data.specularIntensity = this.specularIntensity;
  4891. if (this.specularTint && this.specularTint.isColor) data.specularTint = this.specularTint.getHex();
  4892. if (this.shininess !== undefined) data.shininess = this.shininess;
  4893. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  4894. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  4895. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  4896. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  4897. }
  4898. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  4899. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  4900. }
  4901. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  4902. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  4903. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  4904. }
  4905. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  4906. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  4907. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  4908. if (this.lightMap && this.lightMap.isTexture) {
  4909. data.lightMap = this.lightMap.toJSON(meta).uuid;
  4910. data.lightMapIntensity = this.lightMapIntensity;
  4911. }
  4912. if (this.aoMap && this.aoMap.isTexture) {
  4913. data.aoMap = this.aoMap.toJSON(meta).uuid;
  4914. data.aoMapIntensity = this.aoMapIntensity;
  4915. }
  4916. if (this.bumpMap && this.bumpMap.isTexture) {
  4917. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  4918. data.bumpScale = this.bumpScale;
  4919. }
  4920. if (this.normalMap && this.normalMap.isTexture) {
  4921. data.normalMap = this.normalMap.toJSON(meta).uuid;
  4922. data.normalMapType = this.normalMapType;
  4923. data.normalScale = this.normalScale.toArray();
  4924. }
  4925. if (this.displacementMap && this.displacementMap.isTexture) {
  4926. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  4927. data.displacementScale = this.displacementScale;
  4928. data.displacementBias = this.displacementBias;
  4929. }
  4930. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  4931. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  4932. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  4933. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  4934. if (this.specularIntensityMap && this.specularIntensityMap.isTexture) data.specularIntensityMap = this.specularIntensityMap.toJSON(meta).uuid;
  4935. if (this.specularTintMap && this.specularTintMap.isTexture) data.specularTintMap = this.specularTintMap.toJSON(meta).uuid;
  4936. if (this.envMap && this.envMap.isTexture) {
  4937. data.envMap = this.envMap.toJSON(meta).uuid;
  4938. if (this.combine !== undefined) data.combine = this.combine;
  4939. }
  4940. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  4941. if (this.reflectivity !== undefined) data.reflectivity = this.reflectivity;
  4942. if (this.refractionRatio !== undefined) data.refractionRatio = this.refractionRatio;
  4943. if (this.gradientMap && this.gradientMap.isTexture) {
  4944. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  4945. }
  4946. if (this.transmission !== undefined) data.transmission = this.transmission;
  4947. if (this.transmissionMap && this.transmissionMap.isTexture) data.transmissionMap = this.transmissionMap.toJSON(meta).uuid;
  4948. if (this.thickness !== undefined) data.thickness = this.thickness;
  4949. if (this.thicknessMap && this.thicknessMap.isTexture) data.thicknessMap = this.thicknessMap.toJSON(meta).uuid;
  4950. if (this.attenuationDistance !== undefined) data.attenuationDistance = this.attenuationDistance;
  4951. if (this.attenuationTint !== undefined) data.attenuationTint = this.attenuationTint.getHex();
  4952. if (this.size !== undefined) data.size = this.size;
  4953. if (this.shadowSide !== null) data.shadowSide = this.shadowSide;
  4954. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  4955. if (this.blending !== NormalBlending) data.blending = this.blending;
  4956. if (this.side !== FrontSide) data.side = this.side;
  4957. if (this.vertexColors) data.vertexColors = true;
  4958. if (this.opacity < 1) data.opacity = this.opacity;
  4959. if (this.format !== RGBAFormat) data.format = this.format;
  4960. if (this.transparent === true) data.transparent = this.transparent;
  4961. data.depthFunc = this.depthFunc;
  4962. data.depthTest = this.depthTest;
  4963. data.depthWrite = this.depthWrite;
  4964. data.colorWrite = this.colorWrite;
  4965. data.stencilWrite = this.stencilWrite;
  4966. data.stencilWriteMask = this.stencilWriteMask;
  4967. data.stencilFunc = this.stencilFunc;
  4968. data.stencilRef = this.stencilRef;
  4969. data.stencilFuncMask = this.stencilFuncMask;
  4970. data.stencilFail = this.stencilFail;
  4971. data.stencilZFail = this.stencilZFail;
  4972. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  4973. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  4974. if (this.polygonOffset === true) data.polygonOffset = true;
  4975. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  4976. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  4977. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  4978. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  4979. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  4980. if (this.scale !== undefined) data.scale = this.scale;
  4981. if (this.dithering === true) data.dithering = true;
  4982. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  4983. if (this.alphaToCoverage === true) data.alphaToCoverage = this.alphaToCoverage;
  4984. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  4985. if (this.wireframe === true) data.wireframe = this.wireframe;
  4986. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  4987. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  4988. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  4989. if (this.flatShading === true) data.flatShading = this.flatShading;
  4990. if (this.visible === false) data.visible = false;
  4991. if (this.toneMapped === false) data.toneMapped = false;
  4992. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  4993. function extractFromCache(cache) {
  4994. const values = [];
  4995. for (const key in cache) {
  4996. const data = cache[key];
  4997. delete data.metadata;
  4998. values.push(data);
  4999. }
  5000. return values;
  5001. }
  5002. if (isRoot) {
  5003. const textures = extractFromCache(meta.textures);
  5004. const images = extractFromCache(meta.images);
  5005. if (textures.length > 0) data.textures = textures;
  5006. if (images.length > 0) data.images = images;
  5007. }
  5008. return data;
  5009. }
  5010. clone() {
  5011. return new this.constructor().copy(this);
  5012. }
  5013. copy(source) {
  5014. this.name = source.name;
  5015. this.fog = source.fog;
  5016. this.blending = source.blending;
  5017. this.side = source.side;
  5018. this.vertexColors = source.vertexColors;
  5019. this.opacity = source.opacity;
  5020. this.format = source.format;
  5021. this.transparent = source.transparent;
  5022. this.blendSrc = source.blendSrc;
  5023. this.blendDst = source.blendDst;
  5024. this.blendEquation = source.blendEquation;
  5025. this.blendSrcAlpha = source.blendSrcAlpha;
  5026. this.blendDstAlpha = source.blendDstAlpha;
  5027. this.blendEquationAlpha = source.blendEquationAlpha;
  5028. this.depthFunc = source.depthFunc;
  5029. this.depthTest = source.depthTest;
  5030. this.depthWrite = source.depthWrite;
  5031. this.stencilWriteMask = source.stencilWriteMask;
  5032. this.stencilFunc = source.stencilFunc;
  5033. this.stencilRef = source.stencilRef;
  5034. this.stencilFuncMask = source.stencilFuncMask;
  5035. this.stencilFail = source.stencilFail;
  5036. this.stencilZFail = source.stencilZFail;
  5037. this.stencilZPass = source.stencilZPass;
  5038. this.stencilWrite = source.stencilWrite;
  5039. const srcPlanes = source.clippingPlanes;
  5040. let dstPlanes = null;
  5041. if (srcPlanes !== null) {
  5042. const n = srcPlanes.length;
  5043. dstPlanes = new Array(n);
  5044. for (let i = 0; i !== n; ++i) {
  5045. dstPlanes[i] = srcPlanes[i].clone();
  5046. }
  5047. }
  5048. this.clippingPlanes = dstPlanes;
  5049. this.clipIntersection = source.clipIntersection;
  5050. this.clipShadows = source.clipShadows;
  5051. this.shadowSide = source.shadowSide;
  5052. this.colorWrite = source.colorWrite;
  5053. this.precision = source.precision;
  5054. this.polygonOffset = source.polygonOffset;
  5055. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5056. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5057. this.dithering = source.dithering;
  5058. this.alphaTest = source.alphaTest;
  5059. this.alphaToCoverage = source.alphaToCoverage;
  5060. this.premultipliedAlpha = source.premultipliedAlpha;
  5061. this.visible = source.visible;
  5062. this.toneMapped = source.toneMapped;
  5063. this.userData = JSON.parse(JSON.stringify(source.userData));
  5064. return this;
  5065. }
  5066. dispose() {
  5067. this.dispatchEvent({
  5068. type: 'dispose'
  5069. });
  5070. }
  5071. set needsUpdate(value) {
  5072. if (value === true) this.version++;
  5073. }
  5074. }
  5075. Material.prototype.isMaterial = true;
  5076. const _colorKeywords = {
  5077. 'aliceblue': 0xF0F8FF,
  5078. 'antiquewhite': 0xFAEBD7,
  5079. 'aqua': 0x00FFFF,
  5080. 'aquamarine': 0x7FFFD4,
  5081. 'azure': 0xF0FFFF,
  5082. 'beige': 0xF5F5DC,
  5083. 'bisque': 0xFFE4C4,
  5084. 'black': 0x000000,
  5085. 'blanchedalmond': 0xFFEBCD,
  5086. 'blue': 0x0000FF,
  5087. 'blueviolet': 0x8A2BE2,
  5088. 'brown': 0xA52A2A,
  5089. 'burlywood': 0xDEB887,
  5090. 'cadetblue': 0x5F9EA0,
  5091. 'chartreuse': 0x7FFF00,
  5092. 'chocolate': 0xD2691E,
  5093. 'coral': 0xFF7F50,
  5094. 'cornflowerblue': 0x6495ED,
  5095. 'cornsilk': 0xFFF8DC,
  5096. 'crimson': 0xDC143C,
  5097. 'cyan': 0x00FFFF,
  5098. 'darkblue': 0x00008B,
  5099. 'darkcyan': 0x008B8B,
  5100. 'darkgoldenrod': 0xB8860B,
  5101. 'darkgray': 0xA9A9A9,
  5102. 'darkgreen': 0x006400,
  5103. 'darkgrey': 0xA9A9A9,
  5104. 'darkkhaki': 0xBDB76B,
  5105. 'darkmagenta': 0x8B008B,
  5106. 'darkolivegreen': 0x556B2F,
  5107. 'darkorange': 0xFF8C00,
  5108. 'darkorchid': 0x9932CC,
  5109. 'darkred': 0x8B0000,
  5110. 'darksalmon': 0xE9967A,
  5111. 'darkseagreen': 0x8FBC8F,
  5112. 'darkslateblue': 0x483D8B,
  5113. 'darkslategray': 0x2F4F4F,
  5114. 'darkslategrey': 0x2F4F4F,
  5115. 'darkturquoise': 0x00CED1,
  5116. 'darkviolet': 0x9400D3,
  5117. 'deeppink': 0xFF1493,
  5118. 'deepskyblue': 0x00BFFF,
  5119. 'dimgray': 0x696969,
  5120. 'dimgrey': 0x696969,
  5121. 'dodgerblue': 0x1E90FF,
  5122. 'firebrick': 0xB22222,
  5123. 'floralwhite': 0xFFFAF0,
  5124. 'forestgreen': 0x228B22,
  5125. 'fuchsia': 0xFF00FF,
  5126. 'gainsboro': 0xDCDCDC,
  5127. 'ghostwhite': 0xF8F8FF,
  5128. 'gold': 0xFFD700,
  5129. 'goldenrod': 0xDAA520,
  5130. 'gray': 0x808080,
  5131. 'green': 0x008000,
  5132. 'greenyellow': 0xADFF2F,
  5133. 'grey': 0x808080,
  5134. 'honeydew': 0xF0FFF0,
  5135. 'hotpink': 0xFF69B4,
  5136. 'indianred': 0xCD5C5C,
  5137. 'indigo': 0x4B0082,
  5138. 'ivory': 0xFFFFF0,
  5139. 'khaki': 0xF0E68C,
  5140. 'lavender': 0xE6E6FA,
  5141. 'lavenderblush': 0xFFF0F5,
  5142. 'lawngreen': 0x7CFC00,
  5143. 'lemonchiffon': 0xFFFACD,
  5144. 'lightblue': 0xADD8E6,
  5145. 'lightcoral': 0xF08080,
  5146. 'lightcyan': 0xE0FFFF,
  5147. 'lightgoldenrodyellow': 0xFAFAD2,
  5148. 'lightgray': 0xD3D3D3,
  5149. 'lightgreen': 0x90EE90,
  5150. 'lightgrey': 0xD3D3D3,
  5151. 'lightpink': 0xFFB6C1,
  5152. 'lightsalmon': 0xFFA07A,
  5153. 'lightseagreen': 0x20B2AA,
  5154. 'lightskyblue': 0x87CEFA,
  5155. 'lightslategray': 0x778899,
  5156. 'lightslategrey': 0x778899,
  5157. 'lightsteelblue': 0xB0C4DE,
  5158. 'lightyellow': 0xFFFFE0,
  5159. 'lime': 0x00FF00,
  5160. 'limegreen': 0x32CD32,
  5161. 'linen': 0xFAF0E6,
  5162. 'magenta': 0xFF00FF,
  5163. 'maroon': 0x800000,
  5164. 'mediumaquamarine': 0x66CDAA,
  5165. 'mediumblue': 0x0000CD,
  5166. 'mediumorchid': 0xBA55D3,
  5167. 'mediumpurple': 0x9370DB,
  5168. 'mediumseagreen': 0x3CB371,
  5169. 'mediumslateblue': 0x7B68EE,
  5170. 'mediumspringgreen': 0x00FA9A,
  5171. 'mediumturquoise': 0x48D1CC,
  5172. 'mediumvioletred': 0xC71585,
  5173. 'midnightblue': 0x191970,
  5174. 'mintcream': 0xF5FFFA,
  5175. 'mistyrose': 0xFFE4E1,
  5176. 'moccasin': 0xFFE4B5,
  5177. 'navajowhite': 0xFFDEAD,
  5178. 'navy': 0x000080,
  5179. 'oldlace': 0xFDF5E6,
  5180. 'olive': 0x808000,
  5181. 'olivedrab': 0x6B8E23,
  5182. 'orange': 0xFFA500,
  5183. 'orangered': 0xFF4500,
  5184. 'orchid': 0xDA70D6,
  5185. 'palegoldenrod': 0xEEE8AA,
  5186. 'palegreen': 0x98FB98,
  5187. 'paleturquoise': 0xAFEEEE,
  5188. 'palevioletred': 0xDB7093,
  5189. 'papayawhip': 0xFFEFD5,
  5190. 'peachpuff': 0xFFDAB9,
  5191. 'peru': 0xCD853F,
  5192. 'pink': 0xFFC0CB,
  5193. 'plum': 0xDDA0DD,
  5194. 'powderblue': 0xB0E0E6,
  5195. 'purple': 0x800080,
  5196. 'rebeccapurple': 0x663399,
  5197. 'red': 0xFF0000,
  5198. 'rosybrown': 0xBC8F8F,
  5199. 'royalblue': 0x4169E1,
  5200. 'saddlebrown': 0x8B4513,
  5201. 'salmon': 0xFA8072,
  5202. 'sandybrown': 0xF4A460,
  5203. 'seagreen': 0x2E8B57,
  5204. 'seashell': 0xFFF5EE,
  5205. 'sienna': 0xA0522D,
  5206. 'silver': 0xC0C0C0,
  5207. 'skyblue': 0x87CEEB,
  5208. 'slateblue': 0x6A5ACD,
  5209. 'slategray': 0x708090,
  5210. 'slategrey': 0x708090,
  5211. 'snow': 0xFFFAFA,
  5212. 'springgreen': 0x00FF7F,
  5213. 'steelblue': 0x4682B4,
  5214. 'tan': 0xD2B48C,
  5215. 'teal': 0x008080,
  5216. 'thistle': 0xD8BFD8,
  5217. 'tomato': 0xFF6347,
  5218. 'turquoise': 0x40E0D0,
  5219. 'violet': 0xEE82EE,
  5220. 'wheat': 0xF5DEB3,
  5221. 'white': 0xFFFFFF,
  5222. 'whitesmoke': 0xF5F5F5,
  5223. 'yellow': 0xFFFF00,
  5224. 'yellowgreen': 0x9ACD32
  5225. };
  5226. const _hslA = {
  5227. h: 0,
  5228. s: 0,
  5229. l: 0
  5230. };
  5231. const _hslB = {
  5232. h: 0,
  5233. s: 0,
  5234. l: 0
  5235. };
  5236. function hue2rgb(p, q, t) {
  5237. if (t < 0) t += 1;
  5238. if (t > 1) t -= 1;
  5239. if (t < 1 / 6) return p + (q - p) * 6 * t;
  5240. if (t < 1 / 2) return q;
  5241. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  5242. return p;
  5243. }
  5244. function SRGBToLinear(c) {
  5245. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  5246. }
  5247. function LinearToSRGB(c) {
  5248. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  5249. }
  5250. class Color {
  5251. constructor(r, g, b) {
  5252. if (g === undefined && b === undefined) {
  5253. // r is THREE.Color, hex or string
  5254. return this.set(r);
  5255. }
  5256. return this.setRGB(r, g, b);
  5257. }
  5258. set(value) {
  5259. if (value && value.isColor) {
  5260. this.copy(value);
  5261. } else if (typeof value === 'number') {
  5262. this.setHex(value);
  5263. } else if (typeof value === 'string') {
  5264. this.setStyle(value);
  5265. }
  5266. return this;
  5267. }
  5268. setScalar(scalar) {
  5269. this.r = scalar;
  5270. this.g = scalar;
  5271. this.b = scalar;
  5272. return this;
  5273. }
  5274. setHex(hex) {
  5275. hex = Math.floor(hex);
  5276. this.r = (hex >> 16 & 255) / 255;
  5277. this.g = (hex >> 8 & 255) / 255;
  5278. this.b = (hex & 255) / 255;
  5279. return this;
  5280. }
  5281. setRGB(r, g, b) {
  5282. this.r = r;
  5283. this.g = g;
  5284. this.b = b;
  5285. return this;
  5286. }
  5287. setHSL(h, s, l) {
  5288. // h,s,l ranges are in 0.0 - 1.0
  5289. h = euclideanModulo(h, 1);
  5290. s = clamp(s, 0, 1);
  5291. l = clamp(l, 0, 1);
  5292. if (s === 0) {
  5293. this.r = this.g = this.b = l;
  5294. } else {
  5295. const p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  5296. const q = 2 * l - p;
  5297. this.r = hue2rgb(q, p, h + 1 / 3);
  5298. this.g = hue2rgb(q, p, h);
  5299. this.b = hue2rgb(q, p, h - 1 / 3);
  5300. }
  5301. return this;
  5302. }
  5303. setStyle(style) {
  5304. function handleAlpha(string) {
  5305. if (string === undefined) return;
  5306. if (parseFloat(string) < 1) {
  5307. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  5308. }
  5309. }
  5310. let m;
  5311. if (m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style)) {
  5312. // rgb / hsl
  5313. let color;
  5314. const name = m[1];
  5315. const components = m[2];
  5316. switch (name) {
  5317. case 'rgb':
  5318. case 'rgba':
  5319. if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5320. // rgb(255,0,0) rgba(255,0,0,0.5)
  5321. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  5322. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  5323. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  5324. handleAlpha(color[4]);
  5325. return this;
  5326. }
  5327. if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5328. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5329. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  5330. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  5331. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  5332. handleAlpha(color[4]);
  5333. return this;
  5334. }
  5335. break;
  5336. case 'hsl':
  5337. case 'hsla':
  5338. if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5339. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5340. const h = parseFloat(color[1]) / 360;
  5341. const s = parseInt(color[2], 10) / 100;
  5342. const l = parseInt(color[3], 10) / 100;
  5343. handleAlpha(color[4]);
  5344. return this.setHSL(h, s, l);
  5345. }
  5346. break;
  5347. }
  5348. } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) {
  5349. // hex color
  5350. const hex = m[1];
  5351. const size = hex.length;
  5352. if (size === 3) {
  5353. // #ff0
  5354. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  5355. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  5356. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  5357. return this;
  5358. } else if (size === 6) {
  5359. // #ff0000
  5360. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  5361. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  5362. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  5363. return this;
  5364. }
  5365. }
  5366. if (style && style.length > 0) {
  5367. return this.setColorName(style);
  5368. }
  5369. return this;
  5370. }
  5371. setColorName(style) {
  5372. // color keywords
  5373. const hex = _colorKeywords[style.toLowerCase()];
  5374. if (hex !== undefined) {
  5375. // red
  5376. this.setHex(hex);
  5377. } else {
  5378. // unknown color
  5379. console.warn('THREE.Color: Unknown color ' + style);
  5380. }
  5381. return this;
  5382. }
  5383. clone() {
  5384. return new this.constructor(this.r, this.g, this.b);
  5385. }
  5386. copy(color) {
  5387. this.r = color.r;
  5388. this.g = color.g;
  5389. this.b = color.b;
  5390. return this;
  5391. }
  5392. copyGammaToLinear(color, gammaFactor = 2.0) {
  5393. this.r = Math.pow(color.r, gammaFactor);
  5394. this.g = Math.pow(color.g, gammaFactor);
  5395. this.b = Math.pow(color.b, gammaFactor);
  5396. return this;
  5397. }
  5398. copyLinearToGamma(color, gammaFactor = 2.0) {
  5399. const safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  5400. this.r = Math.pow(color.r, safeInverse);
  5401. this.g = Math.pow(color.g, safeInverse);
  5402. this.b = Math.pow(color.b, safeInverse);
  5403. return this;
  5404. }
  5405. convertGammaToLinear(gammaFactor) {
  5406. this.copyGammaToLinear(this, gammaFactor);
  5407. return this;
  5408. }
  5409. convertLinearToGamma(gammaFactor) {
  5410. this.copyLinearToGamma(this, gammaFactor);
  5411. return this;
  5412. }
  5413. copySRGBToLinear(color) {
  5414. this.r = SRGBToLinear(color.r);
  5415. this.g = SRGBToLinear(color.g);
  5416. this.b = SRGBToLinear(color.b);
  5417. return this;
  5418. }
  5419. copyLinearToSRGB(color) {
  5420. this.r = LinearToSRGB(color.r);
  5421. this.g = LinearToSRGB(color.g);
  5422. this.b = LinearToSRGB(color.b);
  5423. return this;
  5424. }
  5425. convertSRGBToLinear() {
  5426. this.copySRGBToLinear(this);
  5427. return this;
  5428. }
  5429. convertLinearToSRGB() {
  5430. this.copyLinearToSRGB(this);
  5431. return this;
  5432. }
  5433. getHex() {
  5434. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  5435. }
  5436. getHexString() {
  5437. return ('000000' + this.getHex().toString(16)).slice(-6);
  5438. }
  5439. getHSL(target) {
  5440. // h,s,l ranges are in 0.0 - 1.0
  5441. const r = this.r,
  5442. g = this.g,
  5443. b = this.b;
  5444. const max = Math.max(r, g, b);
  5445. const min = Math.min(r, g, b);
  5446. let hue, saturation;
  5447. const lightness = (min + max) / 2.0;
  5448. if (min === max) {
  5449. hue = 0;
  5450. saturation = 0;
  5451. } else {
  5452. const delta = max - min;
  5453. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  5454. switch (max) {
  5455. case r:
  5456. hue = (g - b) / delta + (g < b ? 6 : 0);
  5457. break;
  5458. case g:
  5459. hue = (b - r) / delta + 2;
  5460. break;
  5461. case b:
  5462. hue = (r - g) / delta + 4;
  5463. break;
  5464. }
  5465. hue /= 6;
  5466. }
  5467. target.h = hue;
  5468. target.s = saturation;
  5469. target.l = lightness;
  5470. return target;
  5471. }
  5472. getStyle() {
  5473. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  5474. }
  5475. offsetHSL(h, s, l) {
  5476. this.getHSL(_hslA);
  5477. _hslA.h += h;
  5478. _hslA.s += s;
  5479. _hslA.l += l;
  5480. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  5481. return this;
  5482. }
  5483. add(color) {
  5484. this.r += color.r;
  5485. this.g += color.g;
  5486. this.b += color.b;
  5487. return this;
  5488. }
  5489. addColors(color1, color2) {
  5490. this.r = color1.r + color2.r;
  5491. this.g = color1.g + color2.g;
  5492. this.b = color1.b + color2.b;
  5493. return this;
  5494. }
  5495. addScalar(s) {
  5496. this.r += s;
  5497. this.g += s;
  5498. this.b += s;
  5499. return this;
  5500. }
  5501. sub(color) {
  5502. this.r = Math.max(0, this.r - color.r);
  5503. this.g = Math.max(0, this.g - color.g);
  5504. this.b = Math.max(0, this.b - color.b);
  5505. return this;
  5506. }
  5507. multiply(color) {
  5508. this.r *= color.r;
  5509. this.g *= color.g;
  5510. this.b *= color.b;
  5511. return this;
  5512. }
  5513. multiplyScalar(s) {
  5514. this.r *= s;
  5515. this.g *= s;
  5516. this.b *= s;
  5517. return this;
  5518. }
  5519. lerp(color, alpha) {
  5520. this.r += (color.r - this.r) * alpha;
  5521. this.g += (color.g - this.g) * alpha;
  5522. this.b += (color.b - this.b) * alpha;
  5523. return this;
  5524. }
  5525. lerpColors(color1, color2, alpha) {
  5526. this.r = color1.r + (color2.r - color1.r) * alpha;
  5527. this.g = color1.g + (color2.g - color1.g) * alpha;
  5528. this.b = color1.b + (color2.b - color1.b) * alpha;
  5529. return this;
  5530. }
  5531. lerpHSL(color, alpha) {
  5532. this.getHSL(_hslA);
  5533. color.getHSL(_hslB);
  5534. const h = lerp(_hslA.h, _hslB.h, alpha);
  5535. const s = lerp(_hslA.s, _hslB.s, alpha);
  5536. const l = lerp(_hslA.l, _hslB.l, alpha);
  5537. this.setHSL(h, s, l);
  5538. return this;
  5539. }
  5540. equals(c) {
  5541. return c.r === this.r && c.g === this.g && c.b === this.b;
  5542. }
  5543. fromArray(array, offset = 0) {
  5544. this.r = array[offset];
  5545. this.g = array[offset + 1];
  5546. this.b = array[offset + 2];
  5547. return this;
  5548. }
  5549. toArray(array = [], offset = 0) {
  5550. array[offset] = this.r;
  5551. array[offset + 1] = this.g;
  5552. array[offset + 2] = this.b;
  5553. return array;
  5554. }
  5555. fromBufferAttribute(attribute, index) {
  5556. this.r = attribute.getX(index);
  5557. this.g = attribute.getY(index);
  5558. this.b = attribute.getZ(index);
  5559. if (attribute.normalized === true) {
  5560. // assuming Uint8Array
  5561. this.r /= 255;
  5562. this.g /= 255;
  5563. this.b /= 255;
  5564. }
  5565. return this;
  5566. }
  5567. toJSON() {
  5568. return this.getHex();
  5569. }
  5570. }
  5571. Color.NAMES = _colorKeywords;
  5572. Color.prototype.isColor = true;
  5573. Color.prototype.r = 1;
  5574. Color.prototype.g = 1;
  5575. Color.prototype.b = 1;
  5576. /**
  5577. * parameters = {
  5578. * color: <hex>,
  5579. * opacity: <float>,
  5580. * map: new THREE.Texture( <Image> ),
  5581. *
  5582. * lightMap: new THREE.Texture( <Image> ),
  5583. * lightMapIntensity: <float>
  5584. *
  5585. * aoMap: new THREE.Texture( <Image> ),
  5586. * aoMapIntensity: <float>
  5587. *
  5588. * specularMap: new THREE.Texture( <Image> ),
  5589. *
  5590. * alphaMap: new THREE.Texture( <Image> ),
  5591. *
  5592. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  5593. * combine: THREE.Multiply,
  5594. * reflectivity: <float>,
  5595. * refractionRatio: <float>,
  5596. *
  5597. * depthTest: <bool>,
  5598. * depthWrite: <bool>,
  5599. *
  5600. * wireframe: <boolean>,
  5601. * wireframeLinewidth: <float>,
  5602. * }
  5603. */
  5604. class MeshBasicMaterial extends Material {
  5605. constructor(parameters) {
  5606. super();
  5607. this.type = 'MeshBasicMaterial';
  5608. this.color = new Color(0xffffff); // emissive
  5609. this.map = null;
  5610. this.lightMap = null;
  5611. this.lightMapIntensity = 1.0;
  5612. this.aoMap = null;
  5613. this.aoMapIntensity = 1.0;
  5614. this.specularMap = null;
  5615. this.alphaMap = null;
  5616. this.envMap = null;
  5617. this.combine = MultiplyOperation;
  5618. this.reflectivity = 1;
  5619. this.refractionRatio = 0.98;
  5620. this.wireframe = false;
  5621. this.wireframeLinewidth = 1;
  5622. this.wireframeLinecap = 'round';
  5623. this.wireframeLinejoin = 'round';
  5624. this.setValues(parameters);
  5625. }
  5626. copy(source) {
  5627. super.copy(source);
  5628. this.color.copy(source.color);
  5629. this.map = source.map;
  5630. this.lightMap = source.lightMap;
  5631. this.lightMapIntensity = source.lightMapIntensity;
  5632. this.aoMap = source.aoMap;
  5633. this.aoMapIntensity = source.aoMapIntensity;
  5634. this.specularMap = source.specularMap;
  5635. this.alphaMap = source.alphaMap;
  5636. this.envMap = source.envMap;
  5637. this.combine = source.combine;
  5638. this.reflectivity = source.reflectivity;
  5639. this.refractionRatio = source.refractionRatio;
  5640. this.wireframe = source.wireframe;
  5641. this.wireframeLinewidth = source.wireframeLinewidth;
  5642. this.wireframeLinecap = source.wireframeLinecap;
  5643. this.wireframeLinejoin = source.wireframeLinejoin;
  5644. return this;
  5645. }
  5646. }
  5647. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  5648. const _vector$9 = /*@__PURE__*/new Vector3();
  5649. const _vector2$1 = /*@__PURE__*/new Vector2();
  5650. class BufferAttribute {
  5651. constructor(array, itemSize, normalized) {
  5652. if (Array.isArray(array)) {
  5653. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  5654. }
  5655. this.name = '';
  5656. this.array = array;
  5657. this.itemSize = itemSize;
  5658. this.count = array !== undefined ? array.length / itemSize : 0;
  5659. this.normalized = normalized === true;
  5660. this.usage = StaticDrawUsage;
  5661. this.updateRange = {
  5662. offset: 0,
  5663. count: -1
  5664. };
  5665. this.version = 0;
  5666. }
  5667. onUploadCallback() {}
  5668. set needsUpdate(value) {
  5669. if (value === true) this.version++;
  5670. }
  5671. setUsage(value) {
  5672. this.usage = value;
  5673. return this;
  5674. }
  5675. copy(source) {
  5676. this.name = source.name;
  5677. this.array = new source.array.constructor(source.array);
  5678. this.itemSize = source.itemSize;
  5679. this.count = source.count;
  5680. this.normalized = source.normalized;
  5681. this.usage = source.usage;
  5682. return this;
  5683. }
  5684. copyAt(index1, attribute, index2) {
  5685. index1 *= this.itemSize;
  5686. index2 *= attribute.itemSize;
  5687. for (let i = 0, l = this.itemSize; i < l; i++) {
  5688. this.array[index1 + i] = attribute.array[index2 + i];
  5689. }
  5690. return this;
  5691. }
  5692. copyArray(array) {
  5693. this.array.set(array);
  5694. return this;
  5695. }
  5696. copyColorsArray(colors) {
  5697. const array = this.array;
  5698. let offset = 0;
  5699. for (let i = 0, l = colors.length; i < l; i++) {
  5700. let color = colors[i];
  5701. if (color === undefined) {
  5702. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  5703. color = new Color();
  5704. }
  5705. array[offset++] = color.r;
  5706. array[offset++] = color.g;
  5707. array[offset++] = color.b;
  5708. }
  5709. return this;
  5710. }
  5711. copyVector2sArray(vectors) {
  5712. const array = this.array;
  5713. let offset = 0;
  5714. for (let i = 0, l = vectors.length; i < l; i++) {
  5715. let vector = vectors[i];
  5716. if (vector === undefined) {
  5717. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  5718. vector = new Vector2();
  5719. }
  5720. array[offset++] = vector.x;
  5721. array[offset++] = vector.y;
  5722. }
  5723. return this;
  5724. }
  5725. copyVector3sArray(vectors) {
  5726. const array = this.array;
  5727. let offset = 0;
  5728. for (let i = 0, l = vectors.length; i < l; i++) {
  5729. let vector = vectors[i];
  5730. if (vector === undefined) {
  5731. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  5732. vector = new Vector3();
  5733. }
  5734. array[offset++] = vector.x;
  5735. array[offset++] = vector.y;
  5736. array[offset++] = vector.z;
  5737. }
  5738. return this;
  5739. }
  5740. copyVector4sArray(vectors) {
  5741. const array = this.array;
  5742. let offset = 0;
  5743. for (let i = 0, l = vectors.length; i < l; i++) {
  5744. let vector = vectors[i];
  5745. if (vector === undefined) {
  5746. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  5747. vector = new Vector4();
  5748. }
  5749. array[offset++] = vector.x;
  5750. array[offset++] = vector.y;
  5751. array[offset++] = vector.z;
  5752. array[offset++] = vector.w;
  5753. }
  5754. return this;
  5755. }
  5756. applyMatrix3(m) {
  5757. if (this.itemSize === 2) {
  5758. for (let i = 0, l = this.count; i < l; i++) {
  5759. _vector2$1.fromBufferAttribute(this, i);
  5760. _vector2$1.applyMatrix3(m);
  5761. this.setXY(i, _vector2$1.x, _vector2$1.y);
  5762. }
  5763. } else if (this.itemSize === 3) {
  5764. for (let i = 0, l = this.count; i < l; i++) {
  5765. _vector$9.fromBufferAttribute(this, i);
  5766. _vector$9.applyMatrix3(m);
  5767. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5768. }
  5769. }
  5770. return this;
  5771. }
  5772. applyMatrix4(m) {
  5773. for (let i = 0, l = this.count; i < l; i++) {
  5774. _vector$9.x = this.getX(i);
  5775. _vector$9.y = this.getY(i);
  5776. _vector$9.z = this.getZ(i);
  5777. _vector$9.applyMatrix4(m);
  5778. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5779. }
  5780. return this;
  5781. }
  5782. applyNormalMatrix(m) {
  5783. for (let i = 0, l = this.count; i < l; i++) {
  5784. _vector$9.x = this.getX(i);
  5785. _vector$9.y = this.getY(i);
  5786. _vector$9.z = this.getZ(i);
  5787. _vector$9.applyNormalMatrix(m);
  5788. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5789. }
  5790. return this;
  5791. }
  5792. transformDirection(m) {
  5793. for (let i = 0, l = this.count; i < l; i++) {
  5794. _vector$9.x = this.getX(i);
  5795. _vector$9.y = this.getY(i);
  5796. _vector$9.z = this.getZ(i);
  5797. _vector$9.transformDirection(m);
  5798. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5799. }
  5800. return this;
  5801. }
  5802. set(value, offset = 0) {
  5803. this.array.set(value, offset);
  5804. return this;
  5805. }
  5806. getX(index) {
  5807. return this.array[index * this.itemSize];
  5808. }
  5809. setX(index, x) {
  5810. this.array[index * this.itemSize] = x;
  5811. return this;
  5812. }
  5813. getY(index) {
  5814. return this.array[index * this.itemSize + 1];
  5815. }
  5816. setY(index, y) {
  5817. this.array[index * this.itemSize + 1] = y;
  5818. return this;
  5819. }
  5820. getZ(index) {
  5821. return this.array[index * this.itemSize + 2];
  5822. }
  5823. setZ(index, z) {
  5824. this.array[index * this.itemSize + 2] = z;
  5825. return this;
  5826. }
  5827. getW(index) {
  5828. return this.array[index * this.itemSize + 3];
  5829. }
  5830. setW(index, w) {
  5831. this.array[index * this.itemSize + 3] = w;
  5832. return this;
  5833. }
  5834. setXY(index, x, y) {
  5835. index *= this.itemSize;
  5836. this.array[index + 0] = x;
  5837. this.array[index + 1] = y;
  5838. return this;
  5839. }
  5840. setXYZ(index, x, y, z) {
  5841. index *= this.itemSize;
  5842. this.array[index + 0] = x;
  5843. this.array[index + 1] = y;
  5844. this.array[index + 2] = z;
  5845. return this;
  5846. }
  5847. setXYZW(index, x, y, z, w) {
  5848. index *= this.itemSize;
  5849. this.array[index + 0] = x;
  5850. this.array[index + 1] = y;
  5851. this.array[index + 2] = z;
  5852. this.array[index + 3] = w;
  5853. return this;
  5854. }
  5855. onUpload(callback) {
  5856. this.onUploadCallback = callback;
  5857. return this;
  5858. }
  5859. clone() {
  5860. return new this.constructor(this.array, this.itemSize).copy(this);
  5861. }
  5862. toJSON() {
  5863. const data = {
  5864. itemSize: this.itemSize,
  5865. type: this.array.constructor.name,
  5866. array: Array.prototype.slice.call(this.array),
  5867. normalized: this.normalized
  5868. };
  5869. if (this.name !== '') data.name = this.name;
  5870. if (this.usage !== StaticDrawUsage) data.usage = this.usage;
  5871. if (this.updateRange.offset !== 0 || this.updateRange.count !== -1) data.updateRange = this.updateRange;
  5872. return data;
  5873. }
  5874. }
  5875. BufferAttribute.prototype.isBufferAttribute = true; //
  5876. class Int8BufferAttribute extends BufferAttribute {
  5877. constructor(array, itemSize, normalized) {
  5878. super(new Int8Array(array), itemSize, normalized);
  5879. }
  5880. }
  5881. class Uint8BufferAttribute extends BufferAttribute {
  5882. constructor(array, itemSize, normalized) {
  5883. super(new Uint8Array(array), itemSize, normalized);
  5884. }
  5885. }
  5886. class Uint8ClampedBufferAttribute extends BufferAttribute {
  5887. constructor(array, itemSize, normalized) {
  5888. super(new Uint8ClampedArray(array), itemSize, normalized);
  5889. }
  5890. }
  5891. class Int16BufferAttribute extends BufferAttribute {
  5892. constructor(array, itemSize, normalized) {
  5893. super(new Int16Array(array), itemSize, normalized);
  5894. }
  5895. }
  5896. class Uint16BufferAttribute extends BufferAttribute {
  5897. constructor(array, itemSize, normalized) {
  5898. super(new Uint16Array(array), itemSize, normalized);
  5899. }
  5900. }
  5901. class Int32BufferAttribute extends BufferAttribute {
  5902. constructor(array, itemSize, normalized) {
  5903. super(new Int32Array(array), itemSize, normalized);
  5904. }
  5905. }
  5906. class Uint32BufferAttribute extends BufferAttribute {
  5907. constructor(array, itemSize, normalized) {
  5908. super(new Uint32Array(array), itemSize, normalized);
  5909. }
  5910. }
  5911. class Float16BufferAttribute extends BufferAttribute {
  5912. constructor(array, itemSize, normalized) {
  5913. super(new Uint16Array(array), itemSize, normalized);
  5914. }
  5915. }
  5916. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  5917. class Float32BufferAttribute extends BufferAttribute {
  5918. constructor(array, itemSize, normalized) {
  5919. super(new Float32Array(array), itemSize, normalized);
  5920. }
  5921. }
  5922. class Float64BufferAttribute extends BufferAttribute {
  5923. constructor(array, itemSize, normalized) {
  5924. super(new Float64Array(array), itemSize, normalized);
  5925. }
  5926. } //
  5927. function arrayMax(array) {
  5928. if (array.length === 0) return -Infinity;
  5929. let max = array[0];
  5930. for (let i = 1, l = array.length; i < l; ++i) {
  5931. if (array[i] > max) max = array[i];
  5932. }
  5933. return max;
  5934. }
  5935. const TYPED_ARRAYS = {
  5936. Int8Array: Int8Array,
  5937. Uint8Array: Uint8Array,
  5938. Uint8ClampedArray: Uint8ClampedArray,
  5939. Int16Array: Int16Array,
  5940. Uint16Array: Uint16Array,
  5941. Int32Array: Int32Array,
  5942. Uint32Array: Uint32Array,
  5943. Float32Array: Float32Array,
  5944. Float64Array: Float64Array
  5945. };
  5946. function getTypedArray(type, buffer) {
  5947. return new TYPED_ARRAYS[type](buffer);
  5948. }
  5949. let _id = 0;
  5950. const _m1 = /*@__PURE__*/new Matrix4();
  5951. const _obj = /*@__PURE__*/new Object3D();
  5952. const _offset = /*@__PURE__*/new Vector3();
  5953. const _box$1 = /*@__PURE__*/new Box3();
  5954. const _boxMorphTargets = /*@__PURE__*/new Box3();
  5955. const _vector$8 = /*@__PURE__*/new Vector3();
  5956. class BufferGeometry extends EventDispatcher {
  5957. constructor() {
  5958. super();
  5959. Object.defineProperty(this, 'id', {
  5960. value: _id++
  5961. });
  5962. this.uuid = generateUUID();
  5963. this.name = '';
  5964. this.type = 'BufferGeometry';
  5965. this.index = null;
  5966. this.attributes = {};
  5967. this.morphAttributes = {};
  5968. this.morphTargetsRelative = false;
  5969. this.groups = [];
  5970. this.boundingBox = null;
  5971. this.boundingSphere = null;
  5972. this.drawRange = {
  5973. start: 0,
  5974. count: Infinity
  5975. };
  5976. this.userData = {};
  5977. }
  5978. getIndex() {
  5979. return this.index;
  5980. }
  5981. setIndex(index) {
  5982. if (Array.isArray(index)) {
  5983. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  5984. } else {
  5985. this.index = index;
  5986. }
  5987. return this;
  5988. }
  5989. getAttribute(name) {
  5990. return this.attributes[name];
  5991. }
  5992. setAttribute(name, attribute) {
  5993. this.attributes[name] = attribute;
  5994. return this;
  5995. }
  5996. deleteAttribute(name) {
  5997. delete this.attributes[name];
  5998. return this;
  5999. }
  6000. hasAttribute(name) {
  6001. return this.attributes[name] !== undefined;
  6002. }
  6003. addGroup(start, count, materialIndex = 0) {
  6004. this.groups.push({
  6005. start: start,
  6006. count: count,
  6007. materialIndex: materialIndex
  6008. });
  6009. }
  6010. clearGroups() {
  6011. this.groups = [];
  6012. }
  6013. setDrawRange(start, count) {
  6014. this.drawRange.start = start;
  6015. this.drawRange.count = count;
  6016. }
  6017. applyMatrix4(matrix) {
  6018. const position = this.attributes.position;
  6019. if (position !== undefined) {
  6020. position.applyMatrix4(matrix);
  6021. position.needsUpdate = true;
  6022. }
  6023. const normal = this.attributes.normal;
  6024. if (normal !== undefined) {
  6025. const normalMatrix = new Matrix3().getNormalMatrix(matrix);
  6026. normal.applyNormalMatrix(normalMatrix);
  6027. normal.needsUpdate = true;
  6028. }
  6029. const tangent = this.attributes.tangent;
  6030. if (tangent !== undefined) {
  6031. tangent.transformDirection(matrix);
  6032. tangent.needsUpdate = true;
  6033. }
  6034. if (this.boundingBox !== null) {
  6035. this.computeBoundingBox();
  6036. }
  6037. if (this.boundingSphere !== null) {
  6038. this.computeBoundingSphere();
  6039. }
  6040. return this;
  6041. }
  6042. applyQuaternion(q) {
  6043. _m1.makeRotationFromQuaternion(q);
  6044. this.applyMatrix4(_m1);
  6045. return this;
  6046. }
  6047. rotateX(angle) {
  6048. // rotate geometry around world x-axis
  6049. _m1.makeRotationX(angle);
  6050. this.applyMatrix4(_m1);
  6051. return this;
  6052. }
  6053. rotateY(angle) {
  6054. // rotate geometry around world y-axis
  6055. _m1.makeRotationY(angle);
  6056. this.applyMatrix4(_m1);
  6057. return this;
  6058. }
  6059. rotateZ(angle) {
  6060. // rotate geometry around world z-axis
  6061. _m1.makeRotationZ(angle);
  6062. this.applyMatrix4(_m1);
  6063. return this;
  6064. }
  6065. translate(x, y, z) {
  6066. // translate geometry
  6067. _m1.makeTranslation(x, y, z);
  6068. this.applyMatrix4(_m1);
  6069. return this;
  6070. }
  6071. scale(x, y, z) {
  6072. // scale geometry
  6073. _m1.makeScale(x, y, z);
  6074. this.applyMatrix4(_m1);
  6075. return this;
  6076. }
  6077. lookAt(vector) {
  6078. _obj.lookAt(vector);
  6079. _obj.updateMatrix();
  6080. this.applyMatrix4(_obj.matrix);
  6081. return this;
  6082. }
  6083. center() {
  6084. this.computeBoundingBox();
  6085. this.boundingBox.getCenter(_offset).negate();
  6086. this.translate(_offset.x, _offset.y, _offset.z);
  6087. return this;
  6088. }
  6089. setFromPoints(points) {
  6090. const position = [];
  6091. for (let i = 0, l = points.length; i < l; i++) {
  6092. const point = points[i];
  6093. position.push(point.x, point.y, point.z || 0);
  6094. }
  6095. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  6096. return this;
  6097. }
  6098. computeBoundingBox() {
  6099. if (this.boundingBox === null) {
  6100. this.boundingBox = new Box3();
  6101. }
  6102. const position = this.attributes.position;
  6103. const morphAttributesPosition = this.morphAttributes.position;
  6104. if (position && position.isGLBufferAttribute) {
  6105. console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
  6106. this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
  6107. return;
  6108. }
  6109. if (position !== undefined) {
  6110. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  6111. if (morphAttributesPosition) {
  6112. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6113. const morphAttribute = morphAttributesPosition[i];
  6114. _box$1.setFromBufferAttribute(morphAttribute);
  6115. if (this.morphTargetsRelative) {
  6116. _vector$8.addVectors(this.boundingBox.min, _box$1.min);
  6117. this.boundingBox.expandByPoint(_vector$8);
  6118. _vector$8.addVectors(this.boundingBox.max, _box$1.max);
  6119. this.boundingBox.expandByPoint(_vector$8);
  6120. } else {
  6121. this.boundingBox.expandByPoint(_box$1.min);
  6122. this.boundingBox.expandByPoint(_box$1.max);
  6123. }
  6124. }
  6125. }
  6126. } else {
  6127. this.boundingBox.makeEmpty();
  6128. }
  6129. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  6130. console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  6131. }
  6132. }
  6133. computeBoundingSphere() {
  6134. if (this.boundingSphere === null) {
  6135. this.boundingSphere = new Sphere();
  6136. }
  6137. const position = this.attributes.position;
  6138. const morphAttributesPosition = this.morphAttributes.position;
  6139. if (position && position.isGLBufferAttribute) {
  6140. console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
  6141. this.boundingSphere.set(new Vector3(), Infinity);
  6142. return;
  6143. }
  6144. if (position) {
  6145. // first, find the center of the bounding sphere
  6146. const center = this.boundingSphere.center;
  6147. _box$1.setFromBufferAttribute(position); // process morph attributes if present
  6148. if (morphAttributesPosition) {
  6149. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6150. const morphAttribute = morphAttributesPosition[i];
  6151. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  6152. if (this.morphTargetsRelative) {
  6153. _vector$8.addVectors(_box$1.min, _boxMorphTargets.min);
  6154. _box$1.expandByPoint(_vector$8);
  6155. _vector$8.addVectors(_box$1.max, _boxMorphTargets.max);
  6156. _box$1.expandByPoint(_vector$8);
  6157. } else {
  6158. _box$1.expandByPoint(_boxMorphTargets.min);
  6159. _box$1.expandByPoint(_boxMorphTargets.max);
  6160. }
  6161. }
  6162. }
  6163. _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  6164. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6165. let maxRadiusSq = 0;
  6166. for (let i = 0, il = position.count; i < il; i++) {
  6167. _vector$8.fromBufferAttribute(position, i);
  6168. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6169. } // process morph attributes if present
  6170. if (morphAttributesPosition) {
  6171. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6172. const morphAttribute = morphAttributesPosition[i];
  6173. const morphTargetsRelative = this.morphTargetsRelative;
  6174. for (let j = 0, jl = morphAttribute.count; j < jl; j++) {
  6175. _vector$8.fromBufferAttribute(morphAttribute, j);
  6176. if (morphTargetsRelative) {
  6177. _offset.fromBufferAttribute(position, j);
  6178. _vector$8.add(_offset);
  6179. }
  6180. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6181. }
  6182. }
  6183. }
  6184. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  6185. if (isNaN(this.boundingSphere.radius)) {
  6186. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  6187. }
  6188. }
  6189. }
  6190. computeTangents() {
  6191. const index = this.index;
  6192. const attributes = this.attributes; // based on http://www.terathon.com/code/tangent.html
  6193. // (per vertex tangents)
  6194. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  6195. console.error('THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)');
  6196. return;
  6197. }
  6198. const indices = index.array;
  6199. const positions = attributes.position.array;
  6200. const normals = attributes.normal.array;
  6201. const uvs = attributes.uv.array;
  6202. const nVertices = positions.length / 3;
  6203. if (attributes.tangent === undefined) {
  6204. this.setAttribute('tangent', new BufferAttribute(new Float32Array(4 * nVertices), 4));
  6205. }
  6206. const tangents = attributes.tangent.array;
  6207. const tan1 = [],
  6208. tan2 = [];
  6209. for (let i = 0; i < nVertices; i++) {
  6210. tan1[i] = new Vector3();
  6211. tan2[i] = new Vector3();
  6212. }
  6213. const vA = new Vector3(),
  6214. vB = new Vector3(),
  6215. vC = new Vector3(),
  6216. uvA = new Vector2(),
  6217. uvB = new Vector2(),
  6218. uvC = new Vector2(),
  6219. sdir = new Vector3(),
  6220. tdir = new Vector3();
  6221. function handleTriangle(a, b, c) {
  6222. vA.fromArray(positions, a * 3);
  6223. vB.fromArray(positions, b * 3);
  6224. vC.fromArray(positions, c * 3);
  6225. uvA.fromArray(uvs, a * 2);
  6226. uvB.fromArray(uvs, b * 2);
  6227. uvC.fromArray(uvs, c * 2);
  6228. vB.sub(vA);
  6229. vC.sub(vA);
  6230. uvB.sub(uvA);
  6231. uvC.sub(uvA);
  6232. const r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y); // silently ignore degenerate uv triangles having coincident or colinear vertices
  6233. if (!isFinite(r)) return;
  6234. sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
  6235. tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
  6236. tan1[a].add(sdir);
  6237. tan1[b].add(sdir);
  6238. tan1[c].add(sdir);
  6239. tan2[a].add(tdir);
  6240. tan2[b].add(tdir);
  6241. tan2[c].add(tdir);
  6242. }
  6243. let groups = this.groups;
  6244. if (groups.length === 0) {
  6245. groups = [{
  6246. start: 0,
  6247. count: indices.length
  6248. }];
  6249. }
  6250. for (let i = 0, il = groups.length; i < il; ++i) {
  6251. const group = groups[i];
  6252. const start = group.start;
  6253. const count = group.count;
  6254. for (let j = start, jl = start + count; j < jl; j += 3) {
  6255. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  6256. }
  6257. }
  6258. const tmp = new Vector3(),
  6259. tmp2 = new Vector3();
  6260. const n = new Vector3(),
  6261. n2 = new Vector3();
  6262. function handleVertex(v) {
  6263. n.fromArray(normals, v * 3);
  6264. n2.copy(n);
  6265. const t = tan1[v]; // Gram-Schmidt orthogonalize
  6266. tmp.copy(t);
  6267. tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
  6268. tmp2.crossVectors(n2, t);
  6269. const test = tmp2.dot(tan2[v]);
  6270. const w = test < 0.0 ? -1.0 : 1.0;
  6271. tangents[v * 4] = tmp.x;
  6272. tangents[v * 4 + 1] = tmp.y;
  6273. tangents[v * 4 + 2] = tmp.z;
  6274. tangents[v * 4 + 3] = w;
  6275. }
  6276. for (let i = 0, il = groups.length; i < il; ++i) {
  6277. const group = groups[i];
  6278. const start = group.start;
  6279. const count = group.count;
  6280. for (let j = start, jl = start + count; j < jl; j += 3) {
  6281. handleVertex(indices[j + 0]);
  6282. handleVertex(indices[j + 1]);
  6283. handleVertex(indices[j + 2]);
  6284. }
  6285. }
  6286. }
  6287. computeVertexNormals() {
  6288. const index = this.index;
  6289. const positionAttribute = this.getAttribute('position');
  6290. if (positionAttribute !== undefined) {
  6291. let normalAttribute = this.getAttribute('normal');
  6292. if (normalAttribute === undefined) {
  6293. normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
  6294. this.setAttribute('normal', normalAttribute);
  6295. } else {
  6296. // reset existing normals to zero
  6297. for (let i = 0, il = normalAttribute.count; i < il; i++) {
  6298. normalAttribute.setXYZ(i, 0, 0, 0);
  6299. }
  6300. }
  6301. const pA = new Vector3(),
  6302. pB = new Vector3(),
  6303. pC = new Vector3();
  6304. const nA = new Vector3(),
  6305. nB = new Vector3(),
  6306. nC = new Vector3();
  6307. const cb = new Vector3(),
  6308. ab = new Vector3(); // indexed elements
  6309. if (index) {
  6310. for (let i = 0, il = index.count; i < il; i += 3) {
  6311. const vA = index.getX(i + 0);
  6312. const vB = index.getX(i + 1);
  6313. const vC = index.getX(i + 2);
  6314. pA.fromBufferAttribute(positionAttribute, vA);
  6315. pB.fromBufferAttribute(positionAttribute, vB);
  6316. pC.fromBufferAttribute(positionAttribute, vC);
  6317. cb.subVectors(pC, pB);
  6318. ab.subVectors(pA, pB);
  6319. cb.cross(ab);
  6320. nA.fromBufferAttribute(normalAttribute, vA);
  6321. nB.fromBufferAttribute(normalAttribute, vB);
  6322. nC.fromBufferAttribute(normalAttribute, vC);
  6323. nA.add(cb);
  6324. nB.add(cb);
  6325. nC.add(cb);
  6326. normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
  6327. normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
  6328. normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
  6329. }
  6330. } else {
  6331. // non-indexed elements (unconnected triangle soup)
  6332. for (let i = 0, il = positionAttribute.count; i < il; i += 3) {
  6333. pA.fromBufferAttribute(positionAttribute, i + 0);
  6334. pB.fromBufferAttribute(positionAttribute, i + 1);
  6335. pC.fromBufferAttribute(positionAttribute, i + 2);
  6336. cb.subVectors(pC, pB);
  6337. ab.subVectors(pA, pB);
  6338. cb.cross(ab);
  6339. normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z);
  6340. normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z);
  6341. normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z);
  6342. }
  6343. }
  6344. this.normalizeNormals();
  6345. normalAttribute.needsUpdate = true;
  6346. }
  6347. }
  6348. merge(geometry, offset) {
  6349. if (!(geometry && geometry.isBufferGeometry)) {
  6350. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  6351. return;
  6352. }
  6353. if (offset === undefined) {
  6354. offset = 0;
  6355. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  6356. }
  6357. const attributes = this.attributes;
  6358. for (const key in attributes) {
  6359. if (geometry.attributes[key] === undefined) continue;
  6360. const attribute1 = attributes[key];
  6361. const attributeArray1 = attribute1.array;
  6362. const attribute2 = geometry.attributes[key];
  6363. const attributeArray2 = attribute2.array;
  6364. const attributeOffset = attribute2.itemSize * offset;
  6365. const length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  6366. for (let i = 0, j = attributeOffset; i < length; i++, j++) {
  6367. attributeArray1[j] = attributeArray2[i];
  6368. }
  6369. }
  6370. return this;
  6371. }
  6372. normalizeNormals() {
  6373. const normals = this.attributes.normal;
  6374. for (let i = 0, il = normals.count; i < il; i++) {
  6375. _vector$8.fromBufferAttribute(normals, i);
  6376. _vector$8.normalize();
  6377. normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z);
  6378. }
  6379. }
  6380. toNonIndexed() {
  6381. function convertBufferAttribute(attribute, indices) {
  6382. const array = attribute.array;
  6383. const itemSize = attribute.itemSize;
  6384. const normalized = attribute.normalized;
  6385. const array2 = new array.constructor(indices.length * itemSize);
  6386. let index = 0,
  6387. index2 = 0;
  6388. for (let i = 0, l = indices.length; i < l; i++) {
  6389. if (attribute.isInterleavedBufferAttribute) {
  6390. index = indices[i] * attribute.data.stride + attribute.offset;
  6391. } else {
  6392. index = indices[i] * itemSize;
  6393. }
  6394. for (let j = 0; j < itemSize; j++) {
  6395. array2[index2++] = array[index++];
  6396. }
  6397. }
  6398. return new BufferAttribute(array2, itemSize, normalized);
  6399. } //
  6400. if (this.index === null) {
  6401. console.warn('THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.');
  6402. return this;
  6403. }
  6404. const geometry2 = new BufferGeometry();
  6405. const indices = this.index.array;
  6406. const attributes = this.attributes; // attributes
  6407. for (const name in attributes) {
  6408. const attribute = attributes[name];
  6409. const newAttribute = convertBufferAttribute(attribute, indices);
  6410. geometry2.setAttribute(name, newAttribute);
  6411. } // morph attributes
  6412. const morphAttributes = this.morphAttributes;
  6413. for (const name in morphAttributes) {
  6414. const morphArray = [];
  6415. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6416. for (let i = 0, il = morphAttribute.length; i < il; i++) {
  6417. const attribute = morphAttribute[i];
  6418. const newAttribute = convertBufferAttribute(attribute, indices);
  6419. morphArray.push(newAttribute);
  6420. }
  6421. geometry2.morphAttributes[name] = morphArray;
  6422. }
  6423. geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
  6424. const groups = this.groups;
  6425. for (let i = 0, l = groups.length; i < l; i++) {
  6426. const group = groups[i];
  6427. geometry2.addGroup(group.start, group.count, group.materialIndex);
  6428. }
  6429. return geometry2;
  6430. }
  6431. toJSON() {
  6432. const data = {
  6433. metadata: {
  6434. version: 4.5,
  6435. type: 'BufferGeometry',
  6436. generator: 'BufferGeometry.toJSON'
  6437. }
  6438. }; // standard BufferGeometry serialization
  6439. data.uuid = this.uuid;
  6440. data.type = this.type;
  6441. if (this.name !== '') data.name = this.name;
  6442. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  6443. if (this.parameters !== undefined) {
  6444. const parameters = this.parameters;
  6445. for (const key in parameters) {
  6446. if (parameters[key] !== undefined) data[key] = parameters[key];
  6447. }
  6448. return data;
  6449. } // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6450. data.data = {
  6451. attributes: {}
  6452. };
  6453. const index = this.index;
  6454. if (index !== null) {
  6455. data.data.index = {
  6456. type: index.array.constructor.name,
  6457. array: Array.prototype.slice.call(index.array)
  6458. };
  6459. }
  6460. const attributes = this.attributes;
  6461. for (const key in attributes) {
  6462. const attribute = attributes[key];
  6463. data.data.attributes[key] = attribute.toJSON(data.data);
  6464. }
  6465. const morphAttributes = {};
  6466. let hasMorphAttributes = false;
  6467. for (const key in this.morphAttributes) {
  6468. const attributeArray = this.morphAttributes[key];
  6469. const array = [];
  6470. for (let i = 0, il = attributeArray.length; i < il; i++) {
  6471. const attribute = attributeArray[i];
  6472. array.push(attribute.toJSON(data.data));
  6473. }
  6474. if (array.length > 0) {
  6475. morphAttributes[key] = array;
  6476. hasMorphAttributes = true;
  6477. }
  6478. }
  6479. if (hasMorphAttributes) {
  6480. data.data.morphAttributes = morphAttributes;
  6481. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6482. }
  6483. const groups = this.groups;
  6484. if (groups.length > 0) {
  6485. data.data.groups = JSON.parse(JSON.stringify(groups));
  6486. }
  6487. const boundingSphere = this.boundingSphere;
  6488. if (boundingSphere !== null) {
  6489. data.data.boundingSphere = {
  6490. center: boundingSphere.center.toArray(),
  6491. radius: boundingSphere.radius
  6492. };
  6493. }
  6494. return data;
  6495. }
  6496. clone() {
  6497. /*
  6498. // Handle primitives
  6499. const parameters = this.parameters;
  6500. if ( parameters !== undefined ) {
  6501. const values = [];
  6502. for ( const key in parameters ) {
  6503. values.push( parameters[ key ] );
  6504. }
  6505. const geometry = Object.create( this.constructor.prototype );
  6506. this.constructor.apply( geometry, values );
  6507. return geometry;
  6508. }
  6509. return new this.constructor().copy( this );
  6510. */
  6511. return new BufferGeometry().copy(this);
  6512. }
  6513. copy(source) {
  6514. // reset
  6515. this.index = null;
  6516. this.attributes = {};
  6517. this.morphAttributes = {};
  6518. this.groups = [];
  6519. this.boundingBox = null;
  6520. this.boundingSphere = null; // used for storing cloned, shared data
  6521. const data = {}; // name
  6522. this.name = source.name; // index
  6523. const index = source.index;
  6524. if (index !== null) {
  6525. this.setIndex(index.clone(data));
  6526. } // attributes
  6527. const attributes = source.attributes;
  6528. for (const name in attributes) {
  6529. const attribute = attributes[name];
  6530. this.setAttribute(name, attribute.clone(data));
  6531. } // morph attributes
  6532. const morphAttributes = source.morphAttributes;
  6533. for (const name in morphAttributes) {
  6534. const array = [];
  6535. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6536. for (let i = 0, l = morphAttribute.length; i < l; i++) {
  6537. array.push(morphAttribute[i].clone(data));
  6538. }
  6539. this.morphAttributes[name] = array;
  6540. }
  6541. this.morphTargetsRelative = source.morphTargetsRelative; // groups
  6542. const groups = source.groups;
  6543. for (let i = 0, l = groups.length; i < l; i++) {
  6544. const group = groups[i];
  6545. this.addGroup(group.start, group.count, group.materialIndex);
  6546. } // bounding box
  6547. const boundingBox = source.boundingBox;
  6548. if (boundingBox !== null) {
  6549. this.boundingBox = boundingBox.clone();
  6550. } // bounding sphere
  6551. const boundingSphere = source.boundingSphere;
  6552. if (boundingSphere !== null) {
  6553. this.boundingSphere = boundingSphere.clone();
  6554. } // draw range
  6555. this.drawRange.start = source.drawRange.start;
  6556. this.drawRange.count = source.drawRange.count; // user data
  6557. this.userData = source.userData;
  6558. return this;
  6559. }
  6560. dispose() {
  6561. this.dispatchEvent({
  6562. type: 'dispose'
  6563. });
  6564. }
  6565. }
  6566. BufferGeometry.prototype.isBufferGeometry = true;
  6567. const _inverseMatrix$2 = /*@__PURE__*/new Matrix4();
  6568. const _ray$2 = /*@__PURE__*/new Ray();
  6569. const _sphere$3 = /*@__PURE__*/new Sphere();
  6570. const _vA$1 = /*@__PURE__*/new Vector3();
  6571. const _vB$1 = /*@__PURE__*/new Vector3();
  6572. const _vC$1 = /*@__PURE__*/new Vector3();
  6573. const _tempA = /*@__PURE__*/new Vector3();
  6574. const _tempB = /*@__PURE__*/new Vector3();
  6575. const _tempC = /*@__PURE__*/new Vector3();
  6576. const _morphA = /*@__PURE__*/new Vector3();
  6577. const _morphB = /*@__PURE__*/new Vector3();
  6578. const _morphC = /*@__PURE__*/new Vector3();
  6579. const _uvA$1 = /*@__PURE__*/new Vector2();
  6580. const _uvB$1 = /*@__PURE__*/new Vector2();
  6581. const _uvC$1 = /*@__PURE__*/new Vector2();
  6582. const _intersectionPoint = /*@__PURE__*/new Vector3();
  6583. const _intersectionPointWorld = /*@__PURE__*/new Vector3();
  6584. class Mesh extends Object3D {
  6585. constructor(geometry = new BufferGeometry(), material = new MeshBasicMaterial()) {
  6586. super();
  6587. this.type = 'Mesh';
  6588. this.geometry = geometry;
  6589. this.material = material;
  6590. this.updateMorphTargets();
  6591. }
  6592. copy(source) {
  6593. super.copy(source);
  6594. if (source.morphTargetInfluences !== undefined) {
  6595. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6596. }
  6597. if (source.morphTargetDictionary !== undefined) {
  6598. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  6599. }
  6600. this.material = source.material;
  6601. this.geometry = source.geometry;
  6602. return this;
  6603. }
  6604. updateMorphTargets() {
  6605. const geometry = this.geometry;
  6606. if (geometry.isBufferGeometry) {
  6607. const morphAttributes = geometry.morphAttributes;
  6608. const keys = Object.keys(morphAttributes);
  6609. if (keys.length > 0) {
  6610. const morphAttribute = morphAttributes[keys[0]];
  6611. if (morphAttribute !== undefined) {
  6612. this.morphTargetInfluences = [];
  6613. this.morphTargetDictionary = {};
  6614. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  6615. const name = morphAttribute[m].name || String(m);
  6616. this.morphTargetInfluences.push(0);
  6617. this.morphTargetDictionary[name] = m;
  6618. }
  6619. }
  6620. }
  6621. } else {
  6622. const morphTargets = geometry.morphTargets;
  6623. if (morphTargets !== undefined && morphTargets.length > 0) {
  6624. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6625. }
  6626. }
  6627. }
  6628. raycast(raycaster, intersects) {
  6629. const geometry = this.geometry;
  6630. const material = this.material;
  6631. const matrixWorld = this.matrixWorld;
  6632. if (material === undefined) return; // Checking boundingSphere distance to ray
  6633. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  6634. _sphere$3.copy(geometry.boundingSphere);
  6635. _sphere$3.applyMatrix4(matrixWorld);
  6636. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  6637. _inverseMatrix$2.copy(matrixWorld).invert();
  6638. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2); // Check boundingBox before continuing
  6639. if (geometry.boundingBox !== null) {
  6640. if (_ray$2.intersectsBox(geometry.boundingBox) === false) return;
  6641. }
  6642. let intersection;
  6643. if (geometry.isBufferGeometry) {
  6644. const index = geometry.index;
  6645. const position = geometry.attributes.position;
  6646. const morphPosition = geometry.morphAttributes.position;
  6647. const morphTargetsRelative = geometry.morphTargetsRelative;
  6648. const uv = geometry.attributes.uv;
  6649. const uv2 = geometry.attributes.uv2;
  6650. const groups = geometry.groups;
  6651. const drawRange = geometry.drawRange;
  6652. if (index !== null) {
  6653. // indexed buffer geometry
  6654. if (Array.isArray(material)) {
  6655. for (let i = 0, il = groups.length; i < il; i++) {
  6656. const group = groups[i];
  6657. const groupMaterial = material[group.materialIndex];
  6658. const start = Math.max(group.start, drawRange.start);
  6659. const end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  6660. for (let j = start, jl = end; j < jl; j += 3) {
  6661. const a = index.getX(j);
  6662. const b = index.getX(j + 1);
  6663. const c = index.getX(j + 2);
  6664. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6665. if (intersection) {
  6666. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  6667. intersection.face.materialIndex = group.materialIndex;
  6668. intersects.push(intersection);
  6669. }
  6670. }
  6671. }
  6672. } else {
  6673. const start = Math.max(0, drawRange.start);
  6674. const end = Math.min(index.count, drawRange.start + drawRange.count);
  6675. for (let i = start, il = end; i < il; i += 3) {
  6676. const a = index.getX(i);
  6677. const b = index.getX(i + 1);
  6678. const c = index.getX(i + 2);
  6679. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6680. if (intersection) {
  6681. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  6682. intersects.push(intersection);
  6683. }
  6684. }
  6685. }
  6686. } else if (position !== undefined) {
  6687. // non-indexed buffer geometry
  6688. if (Array.isArray(material)) {
  6689. for (let i = 0, il = groups.length; i < il; i++) {
  6690. const group = groups[i];
  6691. const groupMaterial = material[group.materialIndex];
  6692. const start = Math.max(group.start, drawRange.start);
  6693. const end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  6694. for (let j = start, jl = end; j < jl; j += 3) {
  6695. const a = j;
  6696. const b = j + 1;
  6697. const c = j + 2;
  6698. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6699. if (intersection) {
  6700. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  6701. intersection.face.materialIndex = group.materialIndex;
  6702. intersects.push(intersection);
  6703. }
  6704. }
  6705. }
  6706. } else {
  6707. const start = Math.max(0, drawRange.start);
  6708. const end = Math.min(position.count, drawRange.start + drawRange.count);
  6709. for (let i = start, il = end; i < il; i += 3) {
  6710. const a = i;
  6711. const b = i + 1;
  6712. const c = i + 2;
  6713. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6714. if (intersection) {
  6715. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  6716. intersects.push(intersection);
  6717. }
  6718. }
  6719. }
  6720. }
  6721. } else if (geometry.isGeometry) {
  6722. console.error('THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6723. }
  6724. }
  6725. }
  6726. Mesh.prototype.isMesh = true;
  6727. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  6728. let intersect;
  6729. if (material.side === BackSide) {
  6730. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  6731. } else {
  6732. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  6733. }
  6734. if (intersect === null) return null;
  6735. _intersectionPointWorld.copy(point);
  6736. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  6737. const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  6738. if (distance < raycaster.near || distance > raycaster.far) return null;
  6739. return {
  6740. distance: distance,
  6741. point: _intersectionPointWorld.clone(),
  6742. object: object
  6743. };
  6744. }
  6745. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  6746. _vA$1.fromBufferAttribute(position, a);
  6747. _vB$1.fromBufferAttribute(position, b);
  6748. _vC$1.fromBufferAttribute(position, c);
  6749. const morphInfluences = object.morphTargetInfluences;
  6750. if (morphPosition && morphInfluences) {
  6751. _morphA.set(0, 0, 0);
  6752. _morphB.set(0, 0, 0);
  6753. _morphC.set(0, 0, 0);
  6754. for (let i = 0, il = morphPosition.length; i < il; i++) {
  6755. const influence = morphInfluences[i];
  6756. const morphAttribute = morphPosition[i];
  6757. if (influence === 0) continue;
  6758. _tempA.fromBufferAttribute(morphAttribute, a);
  6759. _tempB.fromBufferAttribute(morphAttribute, b);
  6760. _tempC.fromBufferAttribute(morphAttribute, c);
  6761. if (morphTargetsRelative) {
  6762. _morphA.addScaledVector(_tempA, influence);
  6763. _morphB.addScaledVector(_tempB, influence);
  6764. _morphC.addScaledVector(_tempC, influence);
  6765. } else {
  6766. _morphA.addScaledVector(_tempA.sub(_vA$1), influence);
  6767. _morphB.addScaledVector(_tempB.sub(_vB$1), influence);
  6768. _morphC.addScaledVector(_tempC.sub(_vC$1), influence);
  6769. }
  6770. }
  6771. _vA$1.add(_morphA);
  6772. _vB$1.add(_morphB);
  6773. _vC$1.add(_morphC);
  6774. }
  6775. if (object.isSkinnedMesh) {
  6776. object.boneTransform(a, _vA$1);
  6777. object.boneTransform(b, _vB$1);
  6778. object.boneTransform(c, _vC$1);
  6779. }
  6780. const intersection = checkIntersection(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint);
  6781. if (intersection) {
  6782. if (uv) {
  6783. _uvA$1.fromBufferAttribute(uv, a);
  6784. _uvB$1.fromBufferAttribute(uv, b);
  6785. _uvC$1.fromBufferAttribute(uv, c);
  6786. intersection.uv = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6787. }
  6788. if (uv2) {
  6789. _uvA$1.fromBufferAttribute(uv2, a);
  6790. _uvB$1.fromBufferAttribute(uv2, b);
  6791. _uvC$1.fromBufferAttribute(uv2, c);
  6792. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6793. }
  6794. const face = {
  6795. a: a,
  6796. b: b,
  6797. c: c,
  6798. normal: new Vector3(),
  6799. materialIndex: 0
  6800. };
  6801. Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal);
  6802. intersection.face = face;
  6803. }
  6804. return intersection;
  6805. }
  6806. class BoxGeometry extends BufferGeometry {
  6807. constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
  6808. super();
  6809. this.type = 'BoxGeometry';
  6810. this.parameters = {
  6811. width: width,
  6812. height: height,
  6813. depth: depth,
  6814. widthSegments: widthSegments,
  6815. heightSegments: heightSegments,
  6816. depthSegments: depthSegments
  6817. };
  6818. const scope = this; // segments
  6819. widthSegments = Math.floor(widthSegments);
  6820. heightSegments = Math.floor(heightSegments);
  6821. depthSegments = Math.floor(depthSegments); // buffers
  6822. const indices = [];
  6823. const vertices = [];
  6824. const normals = [];
  6825. const uvs = []; // helper variables
  6826. let numberOfVertices = 0;
  6827. let groupStart = 0; // build each side of the box geometry
  6828. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  6829. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  6830. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  6831. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  6832. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  6833. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  6834. // build geometry
  6835. this.setIndex(indices);
  6836. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  6837. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  6838. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  6839. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  6840. const segmentWidth = width / gridX;
  6841. const segmentHeight = height / gridY;
  6842. const widthHalf = width / 2;
  6843. const heightHalf = height / 2;
  6844. const depthHalf = depth / 2;
  6845. const gridX1 = gridX + 1;
  6846. const gridY1 = gridY + 1;
  6847. let vertexCounter = 0;
  6848. let groupCount = 0;
  6849. const vector = new Vector3(); // generate vertices, normals and uvs
  6850. for (let iy = 0; iy < gridY1; iy++) {
  6851. const y = iy * segmentHeight - heightHalf;
  6852. for (let ix = 0; ix < gridX1; ix++) {
  6853. const x = ix * segmentWidth - widthHalf; // set values to correct vector component
  6854. vector[u] = x * udir;
  6855. vector[v] = y * vdir;
  6856. vector[w] = depthHalf; // now apply vector to vertex buffer
  6857. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  6858. vector[u] = 0;
  6859. vector[v] = 0;
  6860. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  6861. normals.push(vector.x, vector.y, vector.z); // uvs
  6862. uvs.push(ix / gridX);
  6863. uvs.push(1 - iy / gridY); // counters
  6864. vertexCounter += 1;
  6865. }
  6866. } // indices
  6867. // 1. you need three indices to draw a single face
  6868. // 2. a single segment consists of two faces
  6869. // 3. so we need to generate six (2*3) indices per segment
  6870. for (let iy = 0; iy < gridY; iy++) {
  6871. for (let ix = 0; ix < gridX; ix++) {
  6872. const a = numberOfVertices + ix + gridX1 * iy;
  6873. const b = numberOfVertices + ix + gridX1 * (iy + 1);
  6874. const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  6875. const d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  6876. indices.push(a, b, d);
  6877. indices.push(b, c, d); // increase counter
  6878. groupCount += 6;
  6879. }
  6880. } // add a group to the geometry. this will ensure multi material support
  6881. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  6882. groupStart += groupCount; // update total number of vertices
  6883. numberOfVertices += vertexCounter;
  6884. }
  6885. }
  6886. static fromJSON(data) {
  6887. return new BoxGeometry(data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  6888. }
  6889. }
  6890. /**
  6891. * Uniform Utilities
  6892. */
  6893. function cloneUniforms(src) {
  6894. const dst = {};
  6895. for (const u in src) {
  6896. dst[u] = {};
  6897. for (const p in src[u]) {
  6898. const property = src[u][p];
  6899. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion)) {
  6900. dst[u][p] = property.clone();
  6901. } else if (Array.isArray(property)) {
  6902. dst[u][p] = property.slice();
  6903. } else {
  6904. dst[u][p] = property;
  6905. }
  6906. }
  6907. }
  6908. return dst;
  6909. }
  6910. function mergeUniforms(uniforms) {
  6911. const merged = {};
  6912. for (let u = 0; u < uniforms.length; u++) {
  6913. const tmp = cloneUniforms(uniforms[u]);
  6914. for (const p in tmp) {
  6915. merged[p] = tmp[p];
  6916. }
  6917. }
  6918. return merged;
  6919. } // Legacy
  6920. const UniformsUtils = {
  6921. clone: cloneUniforms,
  6922. merge: mergeUniforms
  6923. };
  6924. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  6925. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  6926. /**
  6927. * parameters = {
  6928. * defines: { "label" : "value" },
  6929. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  6930. *
  6931. * fragmentShader: <string>,
  6932. * vertexShader: <string>,
  6933. *
  6934. * wireframe: <boolean>,
  6935. * wireframeLinewidth: <float>,
  6936. *
  6937. * lights: <bool>
  6938. * }
  6939. */
  6940. class ShaderMaterial extends Material {
  6941. constructor(parameters) {
  6942. super();
  6943. this.type = 'ShaderMaterial';
  6944. this.defines = {};
  6945. this.uniforms = {};
  6946. this.vertexShader = default_vertex;
  6947. this.fragmentShader = default_fragment;
  6948. this.linewidth = 1;
  6949. this.wireframe = false;
  6950. this.wireframeLinewidth = 1;
  6951. this.fog = false; // set to use scene fog
  6952. this.lights = false; // set to use scene lights
  6953. this.clipping = false; // set to use user-defined clipping planes
  6954. this.extensions = {
  6955. derivatives: false,
  6956. // set to use derivatives
  6957. fragDepth: false,
  6958. // set to use fragment depth values
  6959. drawBuffers: false,
  6960. // set to use draw buffers
  6961. shaderTextureLOD: false // set to use shader texture LOD
  6962. }; // When rendered geometry doesn't include these attributes but the material does,
  6963. // use these default values in WebGL. This avoids errors when buffer data is missing.
  6964. this.defaultAttributeValues = {
  6965. 'color': [1, 1, 1],
  6966. 'uv': [0, 0],
  6967. 'uv2': [0, 0]
  6968. };
  6969. this.index0AttributeName = undefined;
  6970. this.uniformsNeedUpdate = false;
  6971. this.glslVersion = null;
  6972. if (parameters !== undefined) {
  6973. if (parameters.attributes !== undefined) {
  6974. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  6975. }
  6976. this.setValues(parameters);
  6977. }
  6978. }
  6979. copy(source) {
  6980. super.copy(source);
  6981. this.fragmentShader = source.fragmentShader;
  6982. this.vertexShader = source.vertexShader;
  6983. this.uniforms = cloneUniforms(source.uniforms);
  6984. this.defines = Object.assign({}, source.defines);
  6985. this.wireframe = source.wireframe;
  6986. this.wireframeLinewidth = source.wireframeLinewidth;
  6987. this.lights = source.lights;
  6988. this.clipping = source.clipping;
  6989. this.extensions = Object.assign({}, source.extensions);
  6990. this.glslVersion = source.glslVersion;
  6991. return this;
  6992. }
  6993. toJSON(meta) {
  6994. const data = super.toJSON(meta);
  6995. data.glslVersion = this.glslVersion;
  6996. data.uniforms = {};
  6997. for (const name in this.uniforms) {
  6998. const uniform = this.uniforms[name];
  6999. const value = uniform.value;
  7000. if (value && value.isTexture) {
  7001. data.uniforms[name] = {
  7002. type: 't',
  7003. value: value.toJSON(meta).uuid
  7004. };
  7005. } else if (value && value.isColor) {
  7006. data.uniforms[name] = {
  7007. type: 'c',
  7008. value: value.getHex()
  7009. };
  7010. } else if (value && value.isVector2) {
  7011. data.uniforms[name] = {
  7012. type: 'v2',
  7013. value: value.toArray()
  7014. };
  7015. } else if (value && value.isVector3) {
  7016. data.uniforms[name] = {
  7017. type: 'v3',
  7018. value: value.toArray()
  7019. };
  7020. } else if (value && value.isVector4) {
  7021. data.uniforms[name] = {
  7022. type: 'v4',
  7023. value: value.toArray()
  7024. };
  7025. } else if (value && value.isMatrix3) {
  7026. data.uniforms[name] = {
  7027. type: 'm3',
  7028. value: value.toArray()
  7029. };
  7030. } else if (value && value.isMatrix4) {
  7031. data.uniforms[name] = {
  7032. type: 'm4',
  7033. value: value.toArray()
  7034. };
  7035. } else {
  7036. data.uniforms[name] = {
  7037. value: value
  7038. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7039. }
  7040. }
  7041. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  7042. data.vertexShader = this.vertexShader;
  7043. data.fragmentShader = this.fragmentShader;
  7044. const extensions = {};
  7045. for (const key in this.extensions) {
  7046. if (this.extensions[key] === true) extensions[key] = true;
  7047. }
  7048. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  7049. return data;
  7050. }
  7051. }
  7052. ShaderMaterial.prototype.isShaderMaterial = true;
  7053. class Camera extends Object3D {
  7054. constructor() {
  7055. super();
  7056. this.type = 'Camera';
  7057. this.matrixWorldInverse = new Matrix4();
  7058. this.projectionMatrix = new Matrix4();
  7059. this.projectionMatrixInverse = new Matrix4();
  7060. }
  7061. copy(source, recursive) {
  7062. super.copy(source, recursive);
  7063. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  7064. this.projectionMatrix.copy(source.projectionMatrix);
  7065. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  7066. return this;
  7067. }
  7068. getWorldDirection(target) {
  7069. this.updateWorldMatrix(true, false);
  7070. const e = this.matrixWorld.elements;
  7071. return target.set(-e[8], -e[9], -e[10]).normalize();
  7072. }
  7073. updateMatrixWorld(force) {
  7074. super.updateMatrixWorld(force);
  7075. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7076. }
  7077. updateWorldMatrix(updateParents, updateChildren) {
  7078. super.updateWorldMatrix(updateParents, updateChildren);
  7079. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7080. }
  7081. clone() {
  7082. return new this.constructor().copy(this);
  7083. }
  7084. }
  7085. Camera.prototype.isCamera = true;
  7086. class PerspectiveCamera extends Camera {
  7087. constructor(fov = 50, aspect = 1, near = 0.1, far = 2000) {
  7088. super();
  7089. this.type = 'PerspectiveCamera';
  7090. this.fov = fov;
  7091. this.zoom = 1;
  7092. this.near = near;
  7093. this.far = far;
  7094. this.focus = 10;
  7095. this.aspect = aspect;
  7096. this.view = null;
  7097. this.filmGauge = 35; // width of the film (default in millimeters)
  7098. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7099. this.updateProjectionMatrix();
  7100. }
  7101. copy(source, recursive) {
  7102. super.copy(source, recursive);
  7103. this.fov = source.fov;
  7104. this.zoom = source.zoom;
  7105. this.near = source.near;
  7106. this.far = source.far;
  7107. this.focus = source.focus;
  7108. this.aspect = source.aspect;
  7109. this.view = source.view === null ? null : Object.assign({}, source.view);
  7110. this.filmGauge = source.filmGauge;
  7111. this.filmOffset = source.filmOffset;
  7112. return this;
  7113. }
  7114. /**
  7115. * Sets the FOV by focal length in respect to the current .filmGauge.
  7116. *
  7117. * The default film gauge is 35, so that the focal length can be specified for
  7118. * a 35mm (full frame) camera.
  7119. *
  7120. * Values for focal length and film gauge must have the same unit.
  7121. */
  7122. setFocalLength(focalLength) {
  7123. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7124. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7125. this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope);
  7126. this.updateProjectionMatrix();
  7127. }
  7128. /**
  7129. * Calculates the focal length from the current .fov and .filmGauge.
  7130. */
  7131. getFocalLength() {
  7132. const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov);
  7133. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7134. }
  7135. getEffectiveFOV() {
  7136. return RAD2DEG * 2 * Math.atan(Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom);
  7137. }
  7138. getFilmWidth() {
  7139. // film not completely covered in portrait format (aspect < 1)
  7140. return this.filmGauge * Math.min(this.aspect, 1);
  7141. }
  7142. getFilmHeight() {
  7143. // film not completely covered in landscape format (aspect > 1)
  7144. return this.filmGauge / Math.max(this.aspect, 1);
  7145. }
  7146. /**
  7147. * Sets an offset in a larger frustum. This is useful for multi-window or
  7148. * multi-monitor/multi-machine setups.
  7149. *
  7150. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7151. * the monitors are in grid like this
  7152. *
  7153. * +---+---+---+
  7154. * | A | B | C |
  7155. * +---+---+---+
  7156. * | D | E | F |
  7157. * +---+---+---+
  7158. *
  7159. * then for each monitor you would call it like this
  7160. *
  7161. * const w = 1920;
  7162. * const h = 1080;
  7163. * const fullWidth = w * 3;
  7164. * const fullHeight = h * 2;
  7165. *
  7166. * --A--
  7167. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7168. * --B--
  7169. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7170. * --C--
  7171. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7172. * --D--
  7173. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7174. * --E--
  7175. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7176. * --F--
  7177. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7178. *
  7179. * Note there is no reason monitors have to be the same size or in a grid.
  7180. */
  7181. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  7182. this.aspect = fullWidth / fullHeight;
  7183. if (this.view === null) {
  7184. this.view = {
  7185. enabled: true,
  7186. fullWidth: 1,
  7187. fullHeight: 1,
  7188. offsetX: 0,
  7189. offsetY: 0,
  7190. width: 1,
  7191. height: 1
  7192. };
  7193. }
  7194. this.view.enabled = true;
  7195. this.view.fullWidth = fullWidth;
  7196. this.view.fullHeight = fullHeight;
  7197. this.view.offsetX = x;
  7198. this.view.offsetY = y;
  7199. this.view.width = width;
  7200. this.view.height = height;
  7201. this.updateProjectionMatrix();
  7202. }
  7203. clearViewOffset() {
  7204. if (this.view !== null) {
  7205. this.view.enabled = false;
  7206. }
  7207. this.updateProjectionMatrix();
  7208. }
  7209. updateProjectionMatrix() {
  7210. const near = this.near;
  7211. let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom;
  7212. let height = 2 * top;
  7213. let width = this.aspect * height;
  7214. let left = -0.5 * width;
  7215. const view = this.view;
  7216. if (this.view !== null && this.view.enabled) {
  7217. const fullWidth = view.fullWidth,
  7218. fullHeight = view.fullHeight;
  7219. left += view.offsetX * width / fullWidth;
  7220. top -= view.offsetY * height / fullHeight;
  7221. width *= view.width / fullWidth;
  7222. height *= view.height / fullHeight;
  7223. }
  7224. const skew = this.filmOffset;
  7225. if (skew !== 0) left += near * skew / this.getFilmWidth();
  7226. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  7227. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  7228. }
  7229. toJSON(meta) {
  7230. const data = super.toJSON(meta);
  7231. data.object.fov = this.fov;
  7232. data.object.zoom = this.zoom;
  7233. data.object.near = this.near;
  7234. data.object.far = this.far;
  7235. data.object.focus = this.focus;
  7236. data.object.aspect = this.aspect;
  7237. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  7238. data.object.filmGauge = this.filmGauge;
  7239. data.object.filmOffset = this.filmOffset;
  7240. return data;
  7241. }
  7242. }
  7243. PerspectiveCamera.prototype.isPerspectiveCamera = true;
  7244. const fov = 90,
  7245. aspect = 1;
  7246. class CubeCamera extends Object3D {
  7247. constructor(near, far, renderTarget) {
  7248. super();
  7249. this.type = 'CubeCamera';
  7250. if (renderTarget.isWebGLCubeRenderTarget !== true) {
  7251. console.error('THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.');
  7252. return;
  7253. }
  7254. this.renderTarget = renderTarget;
  7255. const cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  7256. cameraPX.layers = this.layers;
  7257. cameraPX.up.set(0, -1, 0);
  7258. cameraPX.lookAt(new Vector3(1, 0, 0));
  7259. this.add(cameraPX);
  7260. const cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  7261. cameraNX.layers = this.layers;
  7262. cameraNX.up.set(0, -1, 0);
  7263. cameraNX.lookAt(new Vector3(-1, 0, 0));
  7264. this.add(cameraNX);
  7265. const cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  7266. cameraPY.layers = this.layers;
  7267. cameraPY.up.set(0, 0, 1);
  7268. cameraPY.lookAt(new Vector3(0, 1, 0));
  7269. this.add(cameraPY);
  7270. const cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  7271. cameraNY.layers = this.layers;
  7272. cameraNY.up.set(0, 0, -1);
  7273. cameraNY.lookAt(new Vector3(0, -1, 0));
  7274. this.add(cameraNY);
  7275. const cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  7276. cameraPZ.layers = this.layers;
  7277. cameraPZ.up.set(0, -1, 0);
  7278. cameraPZ.lookAt(new Vector3(0, 0, 1));
  7279. this.add(cameraPZ);
  7280. const cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  7281. cameraNZ.layers = this.layers;
  7282. cameraNZ.up.set(0, -1, 0);
  7283. cameraNZ.lookAt(new Vector3(0, 0, -1));
  7284. this.add(cameraNZ);
  7285. }
  7286. update(renderer, scene) {
  7287. if (this.parent === null) this.updateMatrixWorld();
  7288. const renderTarget = this.renderTarget;
  7289. const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children;
  7290. const currentXrEnabled = renderer.xr.enabled;
  7291. const currentRenderTarget = renderer.getRenderTarget();
  7292. renderer.xr.enabled = false;
  7293. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7294. renderTarget.texture.generateMipmaps = false;
  7295. renderer.setRenderTarget(renderTarget, 0);
  7296. renderer.render(scene, cameraPX);
  7297. renderer.setRenderTarget(renderTarget, 1);
  7298. renderer.render(scene, cameraNX);
  7299. renderer.setRenderTarget(renderTarget, 2);
  7300. renderer.render(scene, cameraPY);
  7301. renderer.setRenderTarget(renderTarget, 3);
  7302. renderer.render(scene, cameraNY);
  7303. renderer.setRenderTarget(renderTarget, 4);
  7304. renderer.render(scene, cameraPZ);
  7305. renderTarget.texture.generateMipmaps = generateMipmaps;
  7306. renderer.setRenderTarget(renderTarget, 5);
  7307. renderer.render(scene, cameraNZ);
  7308. renderer.setRenderTarget(currentRenderTarget);
  7309. renderer.xr.enabled = currentXrEnabled;
  7310. }
  7311. }
  7312. class CubeTexture extends Texture {
  7313. constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  7314. images = images !== undefined ? images : [];
  7315. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7316. format = format !== undefined ? format : RGBFormat;
  7317. super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  7318. this.flipY = false;
  7319. }
  7320. get images() {
  7321. return this.image;
  7322. }
  7323. set images(value) {
  7324. this.image = value;
  7325. }
  7326. }
  7327. CubeTexture.prototype.isCubeTexture = true;
  7328. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7329. constructor(size, options, dummy) {
  7330. if (Number.isInteger(options)) {
  7331. console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');
  7332. options = dummy;
  7333. }
  7334. super(size, size, options);
  7335. options = options || {}; // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7336. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7337. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7338. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7339. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7340. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7341. this.texture = new CubeTexture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  7342. this.texture.isRenderTargetTexture = true;
  7343. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7344. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7345. this.texture._needsFlipEnvMap = false;
  7346. }
  7347. fromEquirectangularTexture(renderer, texture) {
  7348. this.texture.type = texture.type;
  7349. this.texture.format = RGBAFormat; // see #18859
  7350. this.texture.encoding = texture.encoding;
  7351. this.texture.generateMipmaps = texture.generateMipmaps;
  7352. this.texture.minFilter = texture.minFilter;
  7353. this.texture.magFilter = texture.magFilter;
  7354. const shader = {
  7355. uniforms: {
  7356. tEquirect: {
  7357. value: null
  7358. }
  7359. },
  7360. vertexShader:
  7361. /* glsl */
  7362. `
  7363. varying vec3 vWorldDirection;
  7364. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7365. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7366. }
  7367. void main() {
  7368. vWorldDirection = transformDirection( position, modelMatrix );
  7369. #include <begin_vertex>
  7370. #include <project_vertex>
  7371. }
  7372. `,
  7373. fragmentShader:
  7374. /* glsl */
  7375. `
  7376. uniform sampler2D tEquirect;
  7377. varying vec3 vWorldDirection;
  7378. #include <common>
  7379. void main() {
  7380. vec3 direction = normalize( vWorldDirection );
  7381. vec2 sampleUV = equirectUv( direction );
  7382. gl_FragColor = texture2D( tEquirect, sampleUV );
  7383. }
  7384. `
  7385. };
  7386. const geometry = new BoxGeometry(5, 5, 5);
  7387. const material = new ShaderMaterial({
  7388. name: 'CubemapFromEquirect',
  7389. uniforms: cloneUniforms(shader.uniforms),
  7390. vertexShader: shader.vertexShader,
  7391. fragmentShader: shader.fragmentShader,
  7392. side: BackSide,
  7393. blending: NoBlending
  7394. });
  7395. material.uniforms.tEquirect.value = texture;
  7396. const mesh = new Mesh(geometry, material);
  7397. const currentMinFilter = texture.minFilter; // Avoid blurred poles
  7398. if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
  7399. const camera = new CubeCamera(1, 10, this);
  7400. camera.update(renderer, mesh);
  7401. texture.minFilter = currentMinFilter;
  7402. mesh.geometry.dispose();
  7403. mesh.material.dispose();
  7404. return this;
  7405. }
  7406. clear(renderer, color, depth, stencil) {
  7407. const currentRenderTarget = renderer.getRenderTarget();
  7408. for (let i = 0; i < 6; i++) {
  7409. renderer.setRenderTarget(this, i);
  7410. renderer.clear(color, depth, stencil);
  7411. }
  7412. renderer.setRenderTarget(currentRenderTarget);
  7413. }
  7414. }
  7415. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  7416. const _vector1 = /*@__PURE__*/new Vector3();
  7417. const _vector2 = /*@__PURE__*/new Vector3();
  7418. const _normalMatrix = /*@__PURE__*/new Matrix3();
  7419. class Plane {
  7420. constructor(normal = new Vector3(1, 0, 0), constant = 0) {
  7421. // normal is assumed to be normalized
  7422. this.normal = normal;
  7423. this.constant = constant;
  7424. }
  7425. set(normal, constant) {
  7426. this.normal.copy(normal);
  7427. this.constant = constant;
  7428. return this;
  7429. }
  7430. setComponents(x, y, z, w) {
  7431. this.normal.set(x, y, z);
  7432. this.constant = w;
  7433. return this;
  7434. }
  7435. setFromNormalAndCoplanarPoint(normal, point) {
  7436. this.normal.copy(normal);
  7437. this.constant = -point.dot(this.normal);
  7438. return this;
  7439. }
  7440. setFromCoplanarPoints(a, b, c) {
  7441. const normal = _vector1.subVectors(c, b).cross(_vector2.subVectors(a, b)).normalize(); // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7442. this.setFromNormalAndCoplanarPoint(normal, a);
  7443. return this;
  7444. }
  7445. copy(plane) {
  7446. this.normal.copy(plane.normal);
  7447. this.constant = plane.constant;
  7448. return this;
  7449. }
  7450. normalize() {
  7451. // Note: will lead to a divide by zero if the plane is invalid.
  7452. const inverseNormalLength = 1.0 / this.normal.length();
  7453. this.normal.multiplyScalar(inverseNormalLength);
  7454. this.constant *= inverseNormalLength;
  7455. return this;
  7456. }
  7457. negate() {
  7458. this.constant *= -1;
  7459. this.normal.negate();
  7460. return this;
  7461. }
  7462. distanceToPoint(point) {
  7463. return this.normal.dot(point) + this.constant;
  7464. }
  7465. distanceToSphere(sphere) {
  7466. return this.distanceToPoint(sphere.center) - sphere.radius;
  7467. }
  7468. projectPoint(point, target) {
  7469. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  7470. }
  7471. intersectLine(line, target) {
  7472. const direction = line.delta(_vector1);
  7473. const denominator = this.normal.dot(direction);
  7474. if (denominator === 0) {
  7475. // line is coplanar, return origin
  7476. if (this.distanceToPoint(line.start) === 0) {
  7477. return target.copy(line.start);
  7478. } // Unsure if this is the correct method to handle this case.
  7479. return null;
  7480. }
  7481. const t = -(line.start.dot(this.normal) + this.constant) / denominator;
  7482. if (t < 0 || t > 1) {
  7483. return null;
  7484. }
  7485. return target.copy(direction).multiplyScalar(t).add(line.start);
  7486. }
  7487. intersectsLine(line) {
  7488. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7489. const startSign = this.distanceToPoint(line.start);
  7490. const endSign = this.distanceToPoint(line.end);
  7491. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  7492. }
  7493. intersectsBox(box) {
  7494. return box.intersectsPlane(this);
  7495. }
  7496. intersectsSphere(sphere) {
  7497. return sphere.intersectsPlane(this);
  7498. }
  7499. coplanarPoint(target) {
  7500. return target.copy(this.normal).multiplyScalar(-this.constant);
  7501. }
  7502. applyMatrix4(matrix, optionalNormalMatrix) {
  7503. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  7504. const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  7505. const normal = this.normal.applyMatrix3(normalMatrix).normalize();
  7506. this.constant = -referencePoint.dot(normal);
  7507. return this;
  7508. }
  7509. translate(offset) {
  7510. this.constant -= offset.dot(this.normal);
  7511. return this;
  7512. }
  7513. equals(plane) {
  7514. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  7515. }
  7516. clone() {
  7517. return new this.constructor().copy(this);
  7518. }
  7519. }
  7520. Plane.prototype.isPlane = true;
  7521. const _sphere$2 = /*@__PURE__*/new Sphere();
  7522. const _vector$7 = /*@__PURE__*/new Vector3();
  7523. class Frustum {
  7524. constructor(p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane()) {
  7525. this.planes = [p0, p1, p2, p3, p4, p5];
  7526. }
  7527. set(p0, p1, p2, p3, p4, p5) {
  7528. const planes = this.planes;
  7529. planes[0].copy(p0);
  7530. planes[1].copy(p1);
  7531. planes[2].copy(p2);
  7532. planes[3].copy(p3);
  7533. planes[4].copy(p4);
  7534. planes[5].copy(p5);
  7535. return this;
  7536. }
  7537. copy(frustum) {
  7538. const planes = this.planes;
  7539. for (let i = 0; i < 6; i++) {
  7540. planes[i].copy(frustum.planes[i]);
  7541. }
  7542. return this;
  7543. }
  7544. setFromProjectionMatrix(m) {
  7545. const planes = this.planes;
  7546. const me = m.elements;
  7547. const me0 = me[0],
  7548. me1 = me[1],
  7549. me2 = me[2],
  7550. me3 = me[3];
  7551. const me4 = me[4],
  7552. me5 = me[5],
  7553. me6 = me[6],
  7554. me7 = me[7];
  7555. const me8 = me[8],
  7556. me9 = me[9],
  7557. me10 = me[10],
  7558. me11 = me[11];
  7559. const me12 = me[12],
  7560. me13 = me[13],
  7561. me14 = me[14],
  7562. me15 = me[15];
  7563. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  7564. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  7565. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  7566. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  7567. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  7568. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  7569. return this;
  7570. }
  7571. intersectsObject(object) {
  7572. const geometry = object.geometry;
  7573. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  7574. _sphere$2.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  7575. return this.intersectsSphere(_sphere$2);
  7576. }
  7577. intersectsSprite(sprite) {
  7578. _sphere$2.center.set(0, 0, 0);
  7579. _sphere$2.radius = 0.7071067811865476;
  7580. _sphere$2.applyMatrix4(sprite.matrixWorld);
  7581. return this.intersectsSphere(_sphere$2);
  7582. }
  7583. intersectsSphere(sphere) {
  7584. const planes = this.planes;
  7585. const center = sphere.center;
  7586. const negRadius = -sphere.radius;
  7587. for (let i = 0; i < 6; i++) {
  7588. const distance = planes[i].distanceToPoint(center);
  7589. if (distance < negRadius) {
  7590. return false;
  7591. }
  7592. }
  7593. return true;
  7594. }
  7595. intersectsBox(box) {
  7596. const planes = this.planes;
  7597. for (let i = 0; i < 6; i++) {
  7598. const plane = planes[i]; // corner at max distance
  7599. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7600. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7601. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7602. if (plane.distanceToPoint(_vector$7) < 0) {
  7603. return false;
  7604. }
  7605. }
  7606. return true;
  7607. }
  7608. containsPoint(point) {
  7609. const planes = this.planes;
  7610. for (let i = 0; i < 6; i++) {
  7611. if (planes[i].distanceToPoint(point) < 0) {
  7612. return false;
  7613. }
  7614. }
  7615. return true;
  7616. }
  7617. clone() {
  7618. return new this.constructor().copy(this);
  7619. }
  7620. }
  7621. function WebGLAnimation() {
  7622. let context = null;
  7623. let isAnimating = false;
  7624. let animationLoop = null;
  7625. let requestId = null;
  7626. function onAnimationFrame(time, frame) {
  7627. animationLoop(time, frame);
  7628. requestId = context.requestAnimationFrame(onAnimationFrame);
  7629. }
  7630. return {
  7631. start: function () {
  7632. if (isAnimating === true) return;
  7633. if (animationLoop === null) return;
  7634. requestId = context.requestAnimationFrame(onAnimationFrame);
  7635. isAnimating = true;
  7636. },
  7637. stop: function () {
  7638. context.cancelAnimationFrame(requestId);
  7639. isAnimating = false;
  7640. },
  7641. setAnimationLoop: function (callback) {
  7642. animationLoop = callback;
  7643. },
  7644. setContext: function (value) {
  7645. context = value;
  7646. }
  7647. };
  7648. }
  7649. function WebGLAttributes(gl, capabilities) {
  7650. const isWebGL2 = capabilities.isWebGL2;
  7651. const buffers = new WeakMap();
  7652. function createBuffer(attribute, bufferType) {
  7653. const array = attribute.array;
  7654. const usage = attribute.usage;
  7655. const buffer = gl.createBuffer();
  7656. gl.bindBuffer(bufferType, buffer);
  7657. gl.bufferData(bufferType, array, usage);
  7658. attribute.onUploadCallback();
  7659. let type = gl.FLOAT;
  7660. if (array instanceof Float32Array) {
  7661. type = gl.FLOAT;
  7662. } else if (array instanceof Float64Array) {
  7663. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  7664. } else if (array instanceof Uint16Array) {
  7665. if (attribute.isFloat16BufferAttribute) {
  7666. if (isWebGL2) {
  7667. type = gl.HALF_FLOAT;
  7668. } else {
  7669. console.warn('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
  7670. }
  7671. } else {
  7672. type = gl.UNSIGNED_SHORT;
  7673. }
  7674. } else if (array instanceof Int16Array) {
  7675. type = gl.SHORT;
  7676. } else if (array instanceof Uint32Array) {
  7677. type = gl.UNSIGNED_INT;
  7678. } else if (array instanceof Int32Array) {
  7679. type = gl.INT;
  7680. } else if (array instanceof Int8Array) {
  7681. type = gl.BYTE;
  7682. } else if (array instanceof Uint8Array) {
  7683. type = gl.UNSIGNED_BYTE;
  7684. } else if (array instanceof Uint8ClampedArray) {
  7685. type = gl.UNSIGNED_BYTE;
  7686. }
  7687. return {
  7688. buffer: buffer,
  7689. type: type,
  7690. bytesPerElement: array.BYTES_PER_ELEMENT,
  7691. version: attribute.version
  7692. };
  7693. }
  7694. function updateBuffer(buffer, attribute, bufferType) {
  7695. const array = attribute.array;
  7696. const updateRange = attribute.updateRange;
  7697. gl.bindBuffer(bufferType, buffer);
  7698. if (updateRange.count === -1) {
  7699. // Not using update ranges
  7700. gl.bufferSubData(bufferType, 0, array);
  7701. } else {
  7702. if (isWebGL2) {
  7703. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  7704. } else {
  7705. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  7706. }
  7707. updateRange.count = -1; // reset range
  7708. }
  7709. } //
  7710. function get(attribute) {
  7711. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7712. return buffers.get(attribute);
  7713. }
  7714. function remove(attribute) {
  7715. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7716. const data = buffers.get(attribute);
  7717. if (data) {
  7718. gl.deleteBuffer(data.buffer);
  7719. buffers.delete(attribute);
  7720. }
  7721. }
  7722. function update(attribute, bufferType) {
  7723. if (attribute.isGLBufferAttribute) {
  7724. const cached = buffers.get(attribute);
  7725. if (!cached || cached.version < attribute.version) {
  7726. buffers.set(attribute, {
  7727. buffer: attribute.buffer,
  7728. type: attribute.type,
  7729. bytesPerElement: attribute.elementSize,
  7730. version: attribute.version
  7731. });
  7732. }
  7733. return;
  7734. }
  7735. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7736. const data = buffers.get(attribute);
  7737. if (data === undefined) {
  7738. buffers.set(attribute, createBuffer(attribute, bufferType));
  7739. } else if (data.version < attribute.version) {
  7740. updateBuffer(data.buffer, attribute, bufferType);
  7741. data.version = attribute.version;
  7742. }
  7743. }
  7744. return {
  7745. get: get,
  7746. remove: remove,
  7747. update: update
  7748. };
  7749. }
  7750. class PlaneGeometry extends BufferGeometry {
  7751. constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) {
  7752. super();
  7753. this.type = 'PlaneGeometry';
  7754. this.parameters = {
  7755. width: width,
  7756. height: height,
  7757. widthSegments: widthSegments,
  7758. heightSegments: heightSegments
  7759. };
  7760. const width_half = width / 2;
  7761. const height_half = height / 2;
  7762. const gridX = Math.floor(widthSegments);
  7763. const gridY = Math.floor(heightSegments);
  7764. const gridX1 = gridX + 1;
  7765. const gridY1 = gridY + 1;
  7766. const segment_width = width / gridX;
  7767. const segment_height = height / gridY; //
  7768. const indices = [];
  7769. const vertices = [];
  7770. const normals = [];
  7771. const uvs = [];
  7772. for (let iy = 0; iy < gridY1; iy++) {
  7773. const y = iy * segment_height - height_half;
  7774. for (let ix = 0; ix < gridX1; ix++) {
  7775. const x = ix * segment_width - width_half;
  7776. vertices.push(x, -y, 0);
  7777. normals.push(0, 0, 1);
  7778. uvs.push(ix / gridX);
  7779. uvs.push(1 - iy / gridY);
  7780. }
  7781. }
  7782. for (let iy = 0; iy < gridY; iy++) {
  7783. for (let ix = 0; ix < gridX; ix++) {
  7784. const a = ix + gridX1 * iy;
  7785. const b = ix + gridX1 * (iy + 1);
  7786. const c = ix + 1 + gridX1 * (iy + 1);
  7787. const d = ix + 1 + gridX1 * iy;
  7788. indices.push(a, b, d);
  7789. indices.push(b, c, d);
  7790. }
  7791. }
  7792. this.setIndex(indices);
  7793. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  7794. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  7795. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  7796. }
  7797. static fromJSON(data) {
  7798. return new PlaneGeometry(data.width, data.height, data.widthSegments, data.heightSegments);
  7799. }
  7800. }
  7801. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7802. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7803. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  7804. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  7805. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif";
  7806. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7807. var begin_vertex = "vec3 transformed = vec3( position );";
  7808. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7809. var bsdfs = "vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( 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 dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in 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 dotVH = saturate( dot( geometry.viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float NoH ) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float NoV, float NoL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( NoL + NoV - NoL * NoV ) ) );\n}\nvec3 BRDF_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";
  7810. 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";
  7811. 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";
  7812. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7813. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7814. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7815. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7816. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7817. 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";
  7818. 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";
  7819. var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}";
  7820. 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";
  7821. 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";
  7822. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7823. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7824. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7825. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7826. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7827. 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}";
  7828. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  7829. 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";
  7830. 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";
  7831. 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";
  7832. 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";
  7833. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  7834. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  7835. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
  7836. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
  7837. 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}";
  7838. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tlightMapIrradiance *= PI;\n\t#endif\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  7839. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7840. 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\tgetPointLightInfo( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotLightInfo( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalLightInfo( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( - dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\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";
  7841. 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\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#else\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in 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\treturn irradiance;\n\t}\n#endif";
  7842. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getIBLIrradiance( const in GeometricContext geometry ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 reflectVec;\n\t\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\t\treflectVec = reflect( - viewDir, normal );\n\t\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\t#else\n\t\t\t\treflectVec = refract( - viewDir, normal, refractionRatio );\n\t\t\t#endif\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n#endif";
  7843. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7844. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)";
  7845. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7846. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight, 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_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)";
  7847. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularTintFactor = specularTint;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARTINTMAP\n\t\t\tspecularTintFactor *= specularTintMapTexelToLinear( texture2D( specularTintMap, vUv ) ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularTintFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( ior - 1.0 ) / ( ior + 1.0 ) ) * specularTintFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenTint = sheenTint;\n#endif";
  7848. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenTint;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\tvec3 FssEss = specularColor * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += irradiance * BRDF_Sheen( material.roughness, directLight.direction, geometry, material.sheenTint );\n\t#else\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  7849. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\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";
  7850. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
  7851. 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";
  7852. 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";
  7853. 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";
  7854. 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";
  7855. 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";
  7856. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  7857. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7858. 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";
  7859. 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";
  7860. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7861. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7862. 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";
  7863. 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";
  7864. 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";
  7865. 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;";
  7866. 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";
  7867. var normal_pars_fragment = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif";
  7868. var normal_pars_vertex = "#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif";
  7869. var normal_vertex = "#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif";
  7870. 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";
  7871. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7872. 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";
  7873. 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";
  7874. var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  7875. 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}";
  7876. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7877. 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;";
  7878. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7879. 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";
  7880. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7881. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7882. 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";
  7883. 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";
  7884. 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";
  7885. 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}";
  7886. 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";
  7887. 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";
  7888. 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";
  7889. 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";
  7890. 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";
  7891. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7892. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7893. 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; }";
  7894. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tfloat transmissionAlpha = 1.0;\n\tfloat transmissionFactor = transmission;\n\tfloat thicknessFactor = thickness;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\ttransmissionFactor *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tthicknessFactor *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, roughnessFactor, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, ior, thicknessFactor,\n\t\tattenuationTint, attenuationDistance );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, transmissionFactor );\n\ttransmissionAlpha = transmission.a;\n#endif";
  7895. var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationTint;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( vec3 n, vec3 v, float thickness, float ior, mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( float roughness, float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( vec2 fragCoord, float roughness, float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( vec3 radiance, float transmissionDistance, vec3 attenuationColor, float attenuationDistance ) {\n\t\tif ( attenuationDistance == 0.0 ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( vec3 n, vec3 v, float roughness, vec3 diffuseColor, vec3 specularColor, float specularF90,\n\t\tvec3 position, mat4 modelMatrix, mat4 viewMatrix, mat4 projMatrix, float ior, float thickness,\n\t\tvec3 attenuationColor, float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif";
  7896. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7897. 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";
  7898. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7899. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7900. 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";
  7901. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7902. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION )\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
  7903. 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}";
  7904. 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}";
  7905. 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}";
  7906. 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}";
  7907. 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 <alphatest_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
  7908. 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}";
  7909. 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 <alphatest_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  7910. 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}";
  7911. 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}";
  7912. 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}";
  7913. 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\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7914. 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}";
  7915. 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 <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7916. 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#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  7917. 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 <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7918. 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}";
  7919. var meshmatcap_frag = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7920. var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  7921. var meshnormal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}";
  7922. var meshnormal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  7923. 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 <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7924. var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7925. var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularTint;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARTINTMAP\n\t\tuniform sampler2D specularTintMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenTint;\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - clearcoat * Fcc ) + clearcoatSpecular * clearcoat;\n\t#endif\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7926. var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}";
  7927. 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 <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7928. var meshtoon_vert = "#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7929. 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 <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7930. 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}";
  7931. 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}";
  7932. 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}";
  7933. 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 <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  7934. 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}";
  7935. const ShaderChunk = {
  7936. alphamap_fragment: alphamap_fragment,
  7937. alphamap_pars_fragment: alphamap_pars_fragment,
  7938. alphatest_fragment: alphatest_fragment,
  7939. alphatest_pars_fragment: alphatest_pars_fragment,
  7940. aomap_fragment: aomap_fragment,
  7941. aomap_pars_fragment: aomap_pars_fragment,
  7942. begin_vertex: begin_vertex,
  7943. beginnormal_vertex: beginnormal_vertex,
  7944. bsdfs: bsdfs,
  7945. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7946. clipping_planes_fragment: clipping_planes_fragment,
  7947. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7948. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7949. clipping_planes_vertex: clipping_planes_vertex,
  7950. color_fragment: color_fragment,
  7951. color_pars_fragment: color_pars_fragment,
  7952. color_pars_vertex: color_pars_vertex,
  7953. color_vertex: color_vertex,
  7954. common: common,
  7955. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7956. defaultnormal_vertex: defaultnormal_vertex,
  7957. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7958. displacementmap_vertex: displacementmap_vertex,
  7959. emissivemap_fragment: emissivemap_fragment,
  7960. emissivemap_pars_fragment: emissivemap_pars_fragment,
  7961. encodings_fragment: encodings_fragment,
  7962. encodings_pars_fragment: encodings_pars_fragment,
  7963. envmap_fragment: envmap_fragment,
  7964. envmap_common_pars_fragment: envmap_common_pars_fragment,
  7965. envmap_pars_fragment: envmap_pars_fragment,
  7966. envmap_pars_vertex: envmap_pars_vertex,
  7967. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  7968. envmap_vertex: envmap_vertex,
  7969. fog_vertex: fog_vertex,
  7970. fog_pars_vertex: fog_pars_vertex,
  7971. fog_fragment: fog_fragment,
  7972. fog_pars_fragment: fog_pars_fragment,
  7973. gradientmap_pars_fragment: gradientmap_pars_fragment,
  7974. lightmap_fragment: lightmap_fragment,
  7975. lightmap_pars_fragment: lightmap_pars_fragment,
  7976. lights_lambert_vertex: lights_lambert_vertex,
  7977. lights_pars_begin: lights_pars_begin,
  7978. lights_toon_fragment: lights_toon_fragment,
  7979. lights_toon_pars_fragment: lights_toon_pars_fragment,
  7980. lights_phong_fragment: lights_phong_fragment,
  7981. lights_phong_pars_fragment: lights_phong_pars_fragment,
  7982. lights_physical_fragment: lights_physical_fragment,
  7983. lights_physical_pars_fragment: lights_physical_pars_fragment,
  7984. lights_fragment_begin: lights_fragment_begin,
  7985. lights_fragment_maps: lights_fragment_maps,
  7986. lights_fragment_end: lights_fragment_end,
  7987. logdepthbuf_fragment: logdepthbuf_fragment,
  7988. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  7989. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  7990. logdepthbuf_vertex: logdepthbuf_vertex,
  7991. map_fragment: map_fragment,
  7992. map_pars_fragment: map_pars_fragment,
  7993. map_particle_fragment: map_particle_fragment,
  7994. map_particle_pars_fragment: map_particle_pars_fragment,
  7995. metalnessmap_fragment: metalnessmap_fragment,
  7996. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  7997. morphnormal_vertex: morphnormal_vertex,
  7998. morphtarget_pars_vertex: morphtarget_pars_vertex,
  7999. morphtarget_vertex: morphtarget_vertex,
  8000. normal_fragment_begin: normal_fragment_begin,
  8001. normal_fragment_maps: normal_fragment_maps,
  8002. normal_pars_fragment: normal_pars_fragment,
  8003. normal_pars_vertex: normal_pars_vertex,
  8004. normal_vertex: normal_vertex,
  8005. normalmap_pars_fragment: normalmap_pars_fragment,
  8006. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8007. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8008. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8009. output_fragment: output_fragment,
  8010. packing: packing,
  8011. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8012. project_vertex: project_vertex,
  8013. dithering_fragment: dithering_fragment,
  8014. dithering_pars_fragment: dithering_pars_fragment,
  8015. roughnessmap_fragment: roughnessmap_fragment,
  8016. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8017. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8018. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8019. shadowmap_vertex: shadowmap_vertex,
  8020. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8021. skinbase_vertex: skinbase_vertex,
  8022. skinning_pars_vertex: skinning_pars_vertex,
  8023. skinning_vertex: skinning_vertex,
  8024. skinnormal_vertex: skinnormal_vertex,
  8025. specularmap_fragment: specularmap_fragment,
  8026. specularmap_pars_fragment: specularmap_pars_fragment,
  8027. tonemapping_fragment: tonemapping_fragment,
  8028. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8029. transmission_fragment: transmission_fragment,
  8030. transmission_pars_fragment: transmission_pars_fragment,
  8031. uv_pars_fragment: uv_pars_fragment,
  8032. uv_pars_vertex: uv_pars_vertex,
  8033. uv_vertex: uv_vertex,
  8034. uv2_pars_fragment: uv2_pars_fragment,
  8035. uv2_pars_vertex: uv2_pars_vertex,
  8036. uv2_vertex: uv2_vertex,
  8037. worldpos_vertex: worldpos_vertex,
  8038. background_frag: background_frag,
  8039. background_vert: background_vert,
  8040. cube_frag: cube_frag,
  8041. cube_vert: cube_vert,
  8042. depth_frag: depth_frag,
  8043. depth_vert: depth_vert,
  8044. distanceRGBA_frag: distanceRGBA_frag,
  8045. distanceRGBA_vert: distanceRGBA_vert,
  8046. equirect_frag: equirect_frag,
  8047. equirect_vert: equirect_vert,
  8048. linedashed_frag: linedashed_frag,
  8049. linedashed_vert: linedashed_vert,
  8050. meshbasic_frag: meshbasic_frag,
  8051. meshbasic_vert: meshbasic_vert,
  8052. meshlambert_frag: meshlambert_frag,
  8053. meshlambert_vert: meshlambert_vert,
  8054. meshmatcap_frag: meshmatcap_frag,
  8055. meshmatcap_vert: meshmatcap_vert,
  8056. meshnormal_frag: meshnormal_frag,
  8057. meshnormal_vert: meshnormal_vert,
  8058. meshphong_frag: meshphong_frag,
  8059. meshphong_vert: meshphong_vert,
  8060. meshphysical_frag: meshphysical_frag,
  8061. meshphysical_vert: meshphysical_vert,
  8062. meshtoon_frag: meshtoon_frag,
  8063. meshtoon_vert: meshtoon_vert,
  8064. points_frag: points_frag,
  8065. points_vert: points_vert,
  8066. shadow_frag: shadow_frag,
  8067. shadow_vert: shadow_vert,
  8068. sprite_frag: sprite_frag,
  8069. sprite_vert: sprite_vert
  8070. };
  8071. /**
  8072. * Uniforms library for shared webgl shaders
  8073. */
  8074. const UniformsLib = {
  8075. common: {
  8076. diffuse: {
  8077. value: new Color(0xffffff)
  8078. },
  8079. opacity: {
  8080. value: 1.0
  8081. },
  8082. map: {
  8083. value: null
  8084. },
  8085. uvTransform: {
  8086. value: new Matrix3()
  8087. },
  8088. uv2Transform: {
  8089. value: new Matrix3()
  8090. },
  8091. alphaMap: {
  8092. value: null
  8093. },
  8094. alphaTest: {
  8095. value: 0
  8096. }
  8097. },
  8098. specularmap: {
  8099. specularMap: {
  8100. value: null
  8101. }
  8102. },
  8103. envmap: {
  8104. envMap: {
  8105. value: null
  8106. },
  8107. flipEnvMap: {
  8108. value: -1
  8109. },
  8110. reflectivity: {
  8111. value: 1.0
  8112. },
  8113. // basic, lambert, phong
  8114. ior: {
  8115. value: 1.5
  8116. },
  8117. // standard, physical
  8118. refractionRatio: {
  8119. value: 0.98
  8120. },
  8121. maxMipLevel: {
  8122. value: 0
  8123. }
  8124. },
  8125. aomap: {
  8126. aoMap: {
  8127. value: null
  8128. },
  8129. aoMapIntensity: {
  8130. value: 1
  8131. }
  8132. },
  8133. lightmap: {
  8134. lightMap: {
  8135. value: null
  8136. },
  8137. lightMapIntensity: {
  8138. value: 1
  8139. }
  8140. },
  8141. emissivemap: {
  8142. emissiveMap: {
  8143. value: null
  8144. }
  8145. },
  8146. bumpmap: {
  8147. bumpMap: {
  8148. value: null
  8149. },
  8150. bumpScale: {
  8151. value: 1
  8152. }
  8153. },
  8154. normalmap: {
  8155. normalMap: {
  8156. value: null
  8157. },
  8158. normalScale: {
  8159. value: new Vector2(1, 1)
  8160. }
  8161. },
  8162. displacementmap: {
  8163. displacementMap: {
  8164. value: null
  8165. },
  8166. displacementScale: {
  8167. value: 1
  8168. },
  8169. displacementBias: {
  8170. value: 0
  8171. }
  8172. },
  8173. roughnessmap: {
  8174. roughnessMap: {
  8175. value: null
  8176. }
  8177. },
  8178. metalnessmap: {
  8179. metalnessMap: {
  8180. value: null
  8181. }
  8182. },
  8183. gradientmap: {
  8184. gradientMap: {
  8185. value: null
  8186. }
  8187. },
  8188. fog: {
  8189. fogDensity: {
  8190. value: 0.00025
  8191. },
  8192. fogNear: {
  8193. value: 1
  8194. },
  8195. fogFar: {
  8196. value: 2000
  8197. },
  8198. fogColor: {
  8199. value: new Color(0xffffff)
  8200. }
  8201. },
  8202. lights: {
  8203. ambientLightColor: {
  8204. value: []
  8205. },
  8206. lightProbe: {
  8207. value: []
  8208. },
  8209. directionalLights: {
  8210. value: [],
  8211. properties: {
  8212. direction: {},
  8213. color: {}
  8214. }
  8215. },
  8216. directionalLightShadows: {
  8217. value: [],
  8218. properties: {
  8219. shadowBias: {},
  8220. shadowNormalBias: {},
  8221. shadowRadius: {},
  8222. shadowMapSize: {}
  8223. }
  8224. },
  8225. directionalShadowMap: {
  8226. value: []
  8227. },
  8228. directionalShadowMatrix: {
  8229. value: []
  8230. },
  8231. spotLights: {
  8232. value: [],
  8233. properties: {
  8234. color: {},
  8235. position: {},
  8236. direction: {},
  8237. distance: {},
  8238. coneCos: {},
  8239. penumbraCos: {},
  8240. decay: {}
  8241. }
  8242. },
  8243. spotLightShadows: {
  8244. value: [],
  8245. properties: {
  8246. shadowBias: {},
  8247. shadowNormalBias: {},
  8248. shadowRadius: {},
  8249. shadowMapSize: {}
  8250. }
  8251. },
  8252. spotShadowMap: {
  8253. value: []
  8254. },
  8255. spotShadowMatrix: {
  8256. value: []
  8257. },
  8258. pointLights: {
  8259. value: [],
  8260. properties: {
  8261. color: {},
  8262. position: {},
  8263. decay: {},
  8264. distance: {}
  8265. }
  8266. },
  8267. pointLightShadows: {
  8268. value: [],
  8269. properties: {
  8270. shadowBias: {},
  8271. shadowNormalBias: {},
  8272. shadowRadius: {},
  8273. shadowMapSize: {},
  8274. shadowCameraNear: {},
  8275. shadowCameraFar: {}
  8276. }
  8277. },
  8278. pointShadowMap: {
  8279. value: []
  8280. },
  8281. pointShadowMatrix: {
  8282. value: []
  8283. },
  8284. hemisphereLights: {
  8285. value: [],
  8286. properties: {
  8287. direction: {},
  8288. skyColor: {},
  8289. groundColor: {}
  8290. }
  8291. },
  8292. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8293. rectAreaLights: {
  8294. value: [],
  8295. properties: {
  8296. color: {},
  8297. position: {},
  8298. width: {},
  8299. height: {}
  8300. }
  8301. },
  8302. ltc_1: {
  8303. value: null
  8304. },
  8305. ltc_2: {
  8306. value: null
  8307. }
  8308. },
  8309. points: {
  8310. diffuse: {
  8311. value: new Color(0xffffff)
  8312. },
  8313. opacity: {
  8314. value: 1.0
  8315. },
  8316. size: {
  8317. value: 1.0
  8318. },
  8319. scale: {
  8320. value: 1.0
  8321. },
  8322. map: {
  8323. value: null
  8324. },
  8325. alphaMap: {
  8326. value: null
  8327. },
  8328. alphaTest: {
  8329. value: 0
  8330. },
  8331. uvTransform: {
  8332. value: new Matrix3()
  8333. }
  8334. },
  8335. sprite: {
  8336. diffuse: {
  8337. value: new Color(0xffffff)
  8338. },
  8339. opacity: {
  8340. value: 1.0
  8341. },
  8342. center: {
  8343. value: new Vector2(0.5, 0.5)
  8344. },
  8345. rotation: {
  8346. value: 0.0
  8347. },
  8348. map: {
  8349. value: null
  8350. },
  8351. alphaMap: {
  8352. value: null
  8353. },
  8354. alphaTest: {
  8355. value: 0
  8356. },
  8357. uvTransform: {
  8358. value: new Matrix3()
  8359. }
  8360. }
  8361. };
  8362. const ShaderLib = {
  8363. basic: {
  8364. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  8365. vertexShader: ShaderChunk.meshbasic_vert,
  8366. fragmentShader: ShaderChunk.meshbasic_frag
  8367. },
  8368. lambert: {
  8369. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  8370. emissive: {
  8371. value: new Color(0x000000)
  8372. }
  8373. }]),
  8374. vertexShader: ShaderChunk.meshlambert_vert,
  8375. fragmentShader: ShaderChunk.meshlambert_frag
  8376. },
  8377. phong: {
  8378. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  8379. emissive: {
  8380. value: new Color(0x000000)
  8381. },
  8382. specular: {
  8383. value: new Color(0x111111)
  8384. },
  8385. shininess: {
  8386. value: 30
  8387. }
  8388. }]),
  8389. vertexShader: ShaderChunk.meshphong_vert,
  8390. fragmentShader: ShaderChunk.meshphong_frag
  8391. },
  8392. standard: {
  8393. 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, {
  8394. emissive: {
  8395. value: new Color(0x000000)
  8396. },
  8397. roughness: {
  8398. value: 1.0
  8399. },
  8400. metalness: {
  8401. value: 0.0
  8402. },
  8403. envMapIntensity: {
  8404. value: 1
  8405. } // temporary
  8406. }]),
  8407. vertexShader: ShaderChunk.meshphysical_vert,
  8408. fragmentShader: ShaderChunk.meshphysical_frag
  8409. },
  8410. toon: {
  8411. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  8412. emissive: {
  8413. value: new Color(0x000000)
  8414. }
  8415. }]),
  8416. vertexShader: ShaderChunk.meshtoon_vert,
  8417. fragmentShader: ShaderChunk.meshtoon_frag
  8418. },
  8419. matcap: {
  8420. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  8421. matcap: {
  8422. value: null
  8423. }
  8424. }]),
  8425. vertexShader: ShaderChunk.meshmatcap_vert,
  8426. fragmentShader: ShaderChunk.meshmatcap_frag
  8427. },
  8428. points: {
  8429. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  8430. vertexShader: ShaderChunk.points_vert,
  8431. fragmentShader: ShaderChunk.points_frag
  8432. },
  8433. dashed: {
  8434. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  8435. scale: {
  8436. value: 1
  8437. },
  8438. dashSize: {
  8439. value: 1
  8440. },
  8441. totalSize: {
  8442. value: 2
  8443. }
  8444. }]),
  8445. vertexShader: ShaderChunk.linedashed_vert,
  8446. fragmentShader: ShaderChunk.linedashed_frag
  8447. },
  8448. depth: {
  8449. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  8450. vertexShader: ShaderChunk.depth_vert,
  8451. fragmentShader: ShaderChunk.depth_frag
  8452. },
  8453. normal: {
  8454. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  8455. opacity: {
  8456. value: 1.0
  8457. }
  8458. }]),
  8459. vertexShader: ShaderChunk.meshnormal_vert,
  8460. fragmentShader: ShaderChunk.meshnormal_frag
  8461. },
  8462. sprite: {
  8463. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  8464. vertexShader: ShaderChunk.sprite_vert,
  8465. fragmentShader: ShaderChunk.sprite_frag
  8466. },
  8467. background: {
  8468. uniforms: {
  8469. uvTransform: {
  8470. value: new Matrix3()
  8471. },
  8472. t2D: {
  8473. value: null
  8474. }
  8475. },
  8476. vertexShader: ShaderChunk.background_vert,
  8477. fragmentShader: ShaderChunk.background_frag
  8478. },
  8479. /* -------------------------------------------------------------------------
  8480. // Cube map shader
  8481. ------------------------------------------------------------------------- */
  8482. cube: {
  8483. uniforms: mergeUniforms([UniformsLib.envmap, {
  8484. opacity: {
  8485. value: 1.0
  8486. }
  8487. }]),
  8488. vertexShader: ShaderChunk.cube_vert,
  8489. fragmentShader: ShaderChunk.cube_frag
  8490. },
  8491. equirect: {
  8492. uniforms: {
  8493. tEquirect: {
  8494. value: null
  8495. }
  8496. },
  8497. vertexShader: ShaderChunk.equirect_vert,
  8498. fragmentShader: ShaderChunk.equirect_frag
  8499. },
  8500. distanceRGBA: {
  8501. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  8502. referencePosition: {
  8503. value: new Vector3()
  8504. },
  8505. nearDistance: {
  8506. value: 1
  8507. },
  8508. farDistance: {
  8509. value: 1000
  8510. }
  8511. }]),
  8512. vertexShader: ShaderChunk.distanceRGBA_vert,
  8513. fragmentShader: ShaderChunk.distanceRGBA_frag
  8514. },
  8515. shadow: {
  8516. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  8517. color: {
  8518. value: new Color(0x00000)
  8519. },
  8520. opacity: {
  8521. value: 1.0
  8522. }
  8523. }]),
  8524. vertexShader: ShaderChunk.shadow_vert,
  8525. fragmentShader: ShaderChunk.shadow_frag
  8526. }
  8527. };
  8528. ShaderLib.physical = {
  8529. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  8530. clearcoat: {
  8531. value: 0
  8532. },
  8533. clearcoatMap: {
  8534. value: null
  8535. },
  8536. clearcoatRoughness: {
  8537. value: 0
  8538. },
  8539. clearcoatRoughnessMap: {
  8540. value: null
  8541. },
  8542. clearcoatNormalScale: {
  8543. value: new Vector2(1, 1)
  8544. },
  8545. clearcoatNormalMap: {
  8546. value: null
  8547. },
  8548. sheenTint: {
  8549. value: new Color(0x000000)
  8550. },
  8551. transmission: {
  8552. value: 0
  8553. },
  8554. transmissionMap: {
  8555. value: null
  8556. },
  8557. transmissionSamplerSize: {
  8558. value: new Vector2()
  8559. },
  8560. transmissionSamplerMap: {
  8561. value: null
  8562. },
  8563. thickness: {
  8564. value: 0
  8565. },
  8566. thicknessMap: {
  8567. value: null
  8568. },
  8569. attenuationDistance: {
  8570. value: 0
  8571. },
  8572. attenuationTint: {
  8573. value: new Color(0x000000)
  8574. },
  8575. specularIntensity: {
  8576. value: 0
  8577. },
  8578. specularIntensityMap: {
  8579. value: null
  8580. },
  8581. specularTint: {
  8582. value: new Color(1, 1, 1)
  8583. },
  8584. specularTintMap: {
  8585. value: null
  8586. }
  8587. }]),
  8588. vertexShader: ShaderChunk.meshphysical_vert,
  8589. fragmentShader: ShaderChunk.meshphysical_frag
  8590. };
  8591. function WebGLBackground(renderer, cubemaps, state, objects, premultipliedAlpha) {
  8592. const clearColor = new Color(0x000000);
  8593. let clearAlpha = 0;
  8594. let planeMesh;
  8595. let boxMesh;
  8596. let currentBackground = null;
  8597. let currentBackgroundVersion = 0;
  8598. let currentTonemapping = null;
  8599. function render(renderList, scene) {
  8600. let forceClear = false;
  8601. let background = scene.isScene === true ? scene.background : null;
  8602. if (background && background.isTexture) {
  8603. background = cubemaps.get(background);
  8604. } // Ignore background in AR
  8605. // TODO: Reconsider this.
  8606. const xr = renderer.xr;
  8607. const session = xr.getSession && xr.getSession();
  8608. if (session && session.environmentBlendMode === 'additive') {
  8609. background = null;
  8610. }
  8611. if (background === null) {
  8612. setClear(clearColor, clearAlpha);
  8613. } else if (background && background.isColor) {
  8614. setClear(background, 1);
  8615. forceClear = true;
  8616. }
  8617. if (renderer.autoClear || forceClear) {
  8618. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  8619. }
  8620. if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) {
  8621. if (boxMesh === undefined) {
  8622. boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({
  8623. name: 'BackgroundCubeMaterial',
  8624. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  8625. vertexShader: ShaderLib.cube.vertexShader,
  8626. fragmentShader: ShaderLib.cube.fragmentShader,
  8627. side: BackSide,
  8628. depthTest: false,
  8629. depthWrite: false,
  8630. fog: false
  8631. }));
  8632. boxMesh.geometry.deleteAttribute('normal');
  8633. boxMesh.geometry.deleteAttribute('uv');
  8634. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  8635. this.matrixWorld.copyPosition(camera.matrixWorld);
  8636. }; // enable code injection for non-built-in material
  8637. Object.defineProperty(boxMesh.material, 'envMap', {
  8638. get: function () {
  8639. return this.uniforms.envMap.value;
  8640. }
  8641. });
  8642. objects.update(boxMesh);
  8643. }
  8644. boxMesh.material.uniforms.envMap.value = background;
  8645. boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background.isRenderTargetTexture === false ? -1 : 1;
  8646. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8647. boxMesh.material.needsUpdate = true;
  8648. currentBackground = background;
  8649. currentBackgroundVersion = background.version;
  8650. currentTonemapping = renderer.toneMapping;
  8651. } // push to the pre-sorted opaque render list
  8652. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  8653. } else if (background && background.isTexture) {
  8654. if (planeMesh === undefined) {
  8655. planeMesh = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({
  8656. name: 'BackgroundMaterial',
  8657. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  8658. vertexShader: ShaderLib.background.vertexShader,
  8659. fragmentShader: ShaderLib.background.fragmentShader,
  8660. side: FrontSide,
  8661. depthTest: false,
  8662. depthWrite: false,
  8663. fog: false
  8664. }));
  8665. planeMesh.geometry.deleteAttribute('normal'); // enable code injection for non-built-in material
  8666. Object.defineProperty(planeMesh.material, 'map', {
  8667. get: function () {
  8668. return this.uniforms.t2D.value;
  8669. }
  8670. });
  8671. objects.update(planeMesh);
  8672. }
  8673. planeMesh.material.uniforms.t2D.value = background;
  8674. if (background.matrixAutoUpdate === true) {
  8675. background.updateMatrix();
  8676. }
  8677. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  8678. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8679. planeMesh.material.needsUpdate = true;
  8680. currentBackground = background;
  8681. currentBackgroundVersion = background.version;
  8682. currentTonemapping = renderer.toneMapping;
  8683. } // push to the pre-sorted opaque render list
  8684. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  8685. }
  8686. }
  8687. function setClear(color, alpha) {
  8688. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  8689. }
  8690. return {
  8691. getClearColor: function () {
  8692. return clearColor;
  8693. },
  8694. setClearColor: function (color, alpha = 1) {
  8695. clearColor.set(color);
  8696. clearAlpha = alpha;
  8697. setClear(clearColor, clearAlpha);
  8698. },
  8699. getClearAlpha: function () {
  8700. return clearAlpha;
  8701. },
  8702. setClearAlpha: function (alpha) {
  8703. clearAlpha = alpha;
  8704. setClear(clearColor, clearAlpha);
  8705. },
  8706. render: render
  8707. };
  8708. }
  8709. function WebGLBindingStates(gl, extensions, attributes, capabilities) {
  8710. const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  8711. const extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
  8712. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8713. const bindingStates = {};
  8714. const defaultState = createBindingState(null);
  8715. let currentState = defaultState;
  8716. function setup(object, material, program, geometry, index) {
  8717. let updateBuffers = false;
  8718. if (vaoAvailable) {
  8719. const state = getBindingState(geometry, program, material);
  8720. if (currentState !== state) {
  8721. currentState = state;
  8722. bindVertexArrayObject(currentState.object);
  8723. }
  8724. updateBuffers = needsUpdate(geometry, index);
  8725. if (updateBuffers) saveCache(geometry, index);
  8726. } else {
  8727. const wireframe = material.wireframe === true;
  8728. if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
  8729. currentState.geometry = geometry.id;
  8730. currentState.program = program.id;
  8731. currentState.wireframe = wireframe;
  8732. updateBuffers = true;
  8733. }
  8734. }
  8735. if (object.isInstancedMesh === true) {
  8736. updateBuffers = true;
  8737. }
  8738. if (index !== null) {
  8739. attributes.update(index, gl.ELEMENT_ARRAY_BUFFER);
  8740. }
  8741. if (updateBuffers) {
  8742. setupVertexAttributes(object, material, program, geometry);
  8743. if (index !== null) {
  8744. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index).buffer);
  8745. }
  8746. }
  8747. }
  8748. function createVertexArrayObject() {
  8749. if (capabilities.isWebGL2) return gl.createVertexArray();
  8750. return extension.createVertexArrayOES();
  8751. }
  8752. function bindVertexArrayObject(vao) {
  8753. if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
  8754. return extension.bindVertexArrayOES(vao);
  8755. }
  8756. function deleteVertexArrayObject(vao) {
  8757. if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
  8758. return extension.deleteVertexArrayOES(vao);
  8759. }
  8760. function getBindingState(geometry, program, material) {
  8761. const wireframe = material.wireframe === true;
  8762. let programMap = bindingStates[geometry.id];
  8763. if (programMap === undefined) {
  8764. programMap = {};
  8765. bindingStates[geometry.id] = programMap;
  8766. }
  8767. let stateMap = programMap[program.id];
  8768. if (stateMap === undefined) {
  8769. stateMap = {};
  8770. programMap[program.id] = stateMap;
  8771. }
  8772. let state = stateMap[wireframe];
  8773. if (state === undefined) {
  8774. state = createBindingState(createVertexArrayObject());
  8775. stateMap[wireframe] = state;
  8776. }
  8777. return state;
  8778. }
  8779. function createBindingState(vao) {
  8780. const newAttributes = [];
  8781. const enabledAttributes = [];
  8782. const attributeDivisors = [];
  8783. for (let i = 0; i < maxVertexAttributes; i++) {
  8784. newAttributes[i] = 0;
  8785. enabledAttributes[i] = 0;
  8786. attributeDivisors[i] = 0;
  8787. }
  8788. return {
  8789. // for backward compatibility on non-VAO support browser
  8790. geometry: null,
  8791. program: null,
  8792. wireframe: false,
  8793. newAttributes: newAttributes,
  8794. enabledAttributes: enabledAttributes,
  8795. attributeDivisors: attributeDivisors,
  8796. object: vao,
  8797. attributes: {},
  8798. index: null
  8799. };
  8800. }
  8801. function needsUpdate(geometry, index) {
  8802. const cachedAttributes = currentState.attributes;
  8803. const geometryAttributes = geometry.attributes;
  8804. let attributesNum = 0;
  8805. for (const key in geometryAttributes) {
  8806. const cachedAttribute = cachedAttributes[key];
  8807. const geometryAttribute = geometryAttributes[key];
  8808. if (cachedAttribute === undefined) return true;
  8809. if (cachedAttribute.attribute !== geometryAttribute) return true;
  8810. if (cachedAttribute.data !== geometryAttribute.data) return true;
  8811. attributesNum++;
  8812. }
  8813. if (currentState.attributesNum !== attributesNum) return true;
  8814. if (currentState.index !== index) return true;
  8815. return false;
  8816. }
  8817. function saveCache(geometry, index) {
  8818. const cache = {};
  8819. const attributes = geometry.attributes;
  8820. let attributesNum = 0;
  8821. for (const key in attributes) {
  8822. const attribute = attributes[key];
  8823. const data = {};
  8824. data.attribute = attribute;
  8825. if (attribute.data) {
  8826. data.data = attribute.data;
  8827. }
  8828. cache[key] = data;
  8829. attributesNum++;
  8830. }
  8831. currentState.attributes = cache;
  8832. currentState.attributesNum = attributesNum;
  8833. currentState.index = index;
  8834. }
  8835. function initAttributes() {
  8836. const newAttributes = currentState.newAttributes;
  8837. for (let i = 0, il = newAttributes.length; i < il; i++) {
  8838. newAttributes[i] = 0;
  8839. }
  8840. }
  8841. function enableAttribute(attribute) {
  8842. enableAttributeAndDivisor(attribute, 0);
  8843. }
  8844. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  8845. const newAttributes = currentState.newAttributes;
  8846. const enabledAttributes = currentState.enabledAttributes;
  8847. const attributeDivisors = currentState.attributeDivisors;
  8848. newAttributes[attribute] = 1;
  8849. if (enabledAttributes[attribute] === 0) {
  8850. gl.enableVertexAttribArray(attribute);
  8851. enabledAttributes[attribute] = 1;
  8852. }
  8853. if (attributeDivisors[attribute] !== meshPerAttribute) {
  8854. const extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  8855. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  8856. attributeDivisors[attribute] = meshPerAttribute;
  8857. }
  8858. }
  8859. function disableUnusedAttributes() {
  8860. const newAttributes = currentState.newAttributes;
  8861. const enabledAttributes = currentState.enabledAttributes;
  8862. for (let i = 0, il = enabledAttributes.length; i < il; i++) {
  8863. if (enabledAttributes[i] !== newAttributes[i]) {
  8864. gl.disableVertexAttribArray(i);
  8865. enabledAttributes[i] = 0;
  8866. }
  8867. }
  8868. }
  8869. function vertexAttribPointer(index, size, type, normalized, stride, offset) {
  8870. if (capabilities.isWebGL2 === true && (type === gl.INT || type === gl.UNSIGNED_INT)) {
  8871. gl.vertexAttribIPointer(index, size, type, stride, offset);
  8872. } else {
  8873. gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
  8874. }
  8875. }
  8876. function setupVertexAttributes(object, material, program, geometry) {
  8877. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  8878. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  8879. }
  8880. initAttributes();
  8881. const geometryAttributes = geometry.attributes;
  8882. const programAttributes = program.getAttributes();
  8883. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8884. for (const name in programAttributes) {
  8885. const programAttribute = programAttributes[name];
  8886. if (programAttribute.location >= 0) {
  8887. let geometryAttribute = geometryAttributes[name];
  8888. if (geometryAttribute === undefined) {
  8889. if (name === 'instanceMatrix' && object.instanceMatrix) geometryAttribute = object.instanceMatrix;
  8890. if (name === 'instanceColor' && object.instanceColor) geometryAttribute = object.instanceColor;
  8891. }
  8892. if (geometryAttribute !== undefined) {
  8893. const normalized = geometryAttribute.normalized;
  8894. const size = geometryAttribute.itemSize;
  8895. const attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  8896. if (attribute === undefined) continue;
  8897. const buffer = attribute.buffer;
  8898. const type = attribute.type;
  8899. const bytesPerElement = attribute.bytesPerElement;
  8900. if (geometryAttribute.isInterleavedBufferAttribute) {
  8901. const data = geometryAttribute.data;
  8902. const stride = data.stride;
  8903. const offset = geometryAttribute.offset;
  8904. if (data && data.isInstancedInterleavedBuffer) {
  8905. for (let i = 0; i < programAttribute.locationSize; i++) {
  8906. enableAttributeAndDivisor(programAttribute.location + i, data.meshPerAttribute);
  8907. }
  8908. if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
  8909. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8910. }
  8911. } else {
  8912. for (let i = 0; i < programAttribute.locationSize; i++) {
  8913. enableAttribute(programAttribute.location + i);
  8914. }
  8915. }
  8916. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8917. for (let i = 0; i < programAttribute.locationSize; i++) {
  8918. vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, stride * bytesPerElement, (offset + size / programAttribute.locationSize * i) * bytesPerElement);
  8919. }
  8920. } else {
  8921. if (geometryAttribute.isInstancedBufferAttribute) {
  8922. for (let i = 0; i < programAttribute.locationSize; i++) {
  8923. enableAttributeAndDivisor(programAttribute.location + i, geometryAttribute.meshPerAttribute);
  8924. }
  8925. if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
  8926. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8927. }
  8928. } else {
  8929. for (let i = 0; i < programAttribute.locationSize; i++) {
  8930. enableAttribute(programAttribute.location + i);
  8931. }
  8932. }
  8933. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8934. for (let i = 0; i < programAttribute.locationSize; i++) {
  8935. vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, size * bytesPerElement, size / programAttribute.locationSize * i * bytesPerElement);
  8936. }
  8937. }
  8938. } else if (materialDefaultAttributeValues !== undefined) {
  8939. const value = materialDefaultAttributeValues[name];
  8940. if (value !== undefined) {
  8941. switch (value.length) {
  8942. case 2:
  8943. gl.vertexAttrib2fv(programAttribute.location, value);
  8944. break;
  8945. case 3:
  8946. gl.vertexAttrib3fv(programAttribute.location, value);
  8947. break;
  8948. case 4:
  8949. gl.vertexAttrib4fv(programAttribute.location, value);
  8950. break;
  8951. default:
  8952. gl.vertexAttrib1fv(programAttribute.location, value);
  8953. }
  8954. }
  8955. }
  8956. }
  8957. }
  8958. disableUnusedAttributes();
  8959. }
  8960. function dispose() {
  8961. reset();
  8962. for (const geometryId in bindingStates) {
  8963. const programMap = bindingStates[geometryId];
  8964. for (const programId in programMap) {
  8965. const stateMap = programMap[programId];
  8966. for (const wireframe in stateMap) {
  8967. deleteVertexArrayObject(stateMap[wireframe].object);
  8968. delete stateMap[wireframe];
  8969. }
  8970. delete programMap[programId];
  8971. }
  8972. delete bindingStates[geometryId];
  8973. }
  8974. }
  8975. function releaseStatesOfGeometry(geometry) {
  8976. if (bindingStates[geometry.id] === undefined) return;
  8977. const programMap = bindingStates[geometry.id];
  8978. for (const programId in programMap) {
  8979. const stateMap = programMap[programId];
  8980. for (const wireframe in stateMap) {
  8981. deleteVertexArrayObject(stateMap[wireframe].object);
  8982. delete stateMap[wireframe];
  8983. }
  8984. delete programMap[programId];
  8985. }
  8986. delete bindingStates[geometry.id];
  8987. }
  8988. function releaseStatesOfProgram(program) {
  8989. for (const geometryId in bindingStates) {
  8990. const programMap = bindingStates[geometryId];
  8991. if (programMap[program.id] === undefined) continue;
  8992. const stateMap = programMap[program.id];
  8993. for (const wireframe in stateMap) {
  8994. deleteVertexArrayObject(stateMap[wireframe].object);
  8995. delete stateMap[wireframe];
  8996. }
  8997. delete programMap[program.id];
  8998. }
  8999. }
  9000. function reset() {
  9001. resetDefaultState();
  9002. if (currentState === defaultState) return;
  9003. currentState = defaultState;
  9004. bindVertexArrayObject(currentState.object);
  9005. } // for backward-compatilibity
  9006. function resetDefaultState() {
  9007. defaultState.geometry = null;
  9008. defaultState.program = null;
  9009. defaultState.wireframe = false;
  9010. }
  9011. return {
  9012. setup: setup,
  9013. reset: reset,
  9014. resetDefaultState: resetDefaultState,
  9015. dispose: dispose,
  9016. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9017. releaseStatesOfProgram: releaseStatesOfProgram,
  9018. initAttributes: initAttributes,
  9019. enableAttribute: enableAttribute,
  9020. disableUnusedAttributes: disableUnusedAttributes
  9021. };
  9022. }
  9023. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  9024. const isWebGL2 = capabilities.isWebGL2;
  9025. let mode;
  9026. function setMode(value) {
  9027. mode = value;
  9028. }
  9029. function render(start, count) {
  9030. gl.drawArrays(mode, start, count);
  9031. info.update(count, mode, 1);
  9032. }
  9033. function renderInstances(start, count, primcount) {
  9034. if (primcount === 0) return;
  9035. let extension, methodName;
  9036. if (isWebGL2) {
  9037. extension = gl;
  9038. methodName = 'drawArraysInstanced';
  9039. } else {
  9040. extension = extensions.get('ANGLE_instanced_arrays');
  9041. methodName = 'drawArraysInstancedANGLE';
  9042. if (extension === null) {
  9043. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9044. return;
  9045. }
  9046. }
  9047. extension[methodName](mode, start, count, primcount);
  9048. info.update(count, mode, primcount);
  9049. } //
  9050. this.setMode = setMode;
  9051. this.render = render;
  9052. this.renderInstances = renderInstances;
  9053. }
  9054. function WebGLCapabilities(gl, extensions, parameters) {
  9055. let maxAnisotropy;
  9056. function getMaxAnisotropy() {
  9057. if (maxAnisotropy !== undefined) return maxAnisotropy;
  9058. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  9059. const extension = extensions.get('EXT_texture_filter_anisotropic');
  9060. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  9061. } else {
  9062. maxAnisotropy = 0;
  9063. }
  9064. return maxAnisotropy;
  9065. }
  9066. function getMaxPrecision(precision) {
  9067. if (precision === 'highp') {
  9068. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) {
  9069. return 'highp';
  9070. }
  9071. precision = 'mediump';
  9072. }
  9073. if (precision === 'mediump') {
  9074. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) {
  9075. return 'mediump';
  9076. }
  9077. }
  9078. return 'lowp';
  9079. }
  9080. /* eslint-disable no-undef */
  9081. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  9082. /* eslint-enable no-undef */
  9083. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9084. const maxPrecision = getMaxPrecision(precision);
  9085. if (maxPrecision !== precision) {
  9086. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  9087. precision = maxPrecision;
  9088. }
  9089. const drawBuffers = isWebGL2 || extensions.has('WEBGL_draw_buffers');
  9090. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9091. const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
  9092. const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9093. const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
  9094. const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9095. const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  9096. const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
  9097. const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS);
  9098. const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9099. const vertexTextures = maxVertexTextures > 0;
  9100. const floatFragmentTextures = isWebGL2 || extensions.has('OES_texture_float');
  9101. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9102. const maxSamples = isWebGL2 ? gl.getParameter(gl.MAX_SAMPLES) : 0;
  9103. return {
  9104. isWebGL2: isWebGL2,
  9105. drawBuffers: drawBuffers,
  9106. getMaxAnisotropy: getMaxAnisotropy,
  9107. getMaxPrecision: getMaxPrecision,
  9108. precision: precision,
  9109. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9110. maxTextures: maxTextures,
  9111. maxVertexTextures: maxVertexTextures,
  9112. maxTextureSize: maxTextureSize,
  9113. maxCubemapSize: maxCubemapSize,
  9114. maxAttributes: maxAttributes,
  9115. maxVertexUniforms: maxVertexUniforms,
  9116. maxVaryings: maxVaryings,
  9117. maxFragmentUniforms: maxFragmentUniforms,
  9118. vertexTextures: vertexTextures,
  9119. floatFragmentTextures: floatFragmentTextures,
  9120. floatVertexTextures: floatVertexTextures,
  9121. maxSamples: maxSamples
  9122. };
  9123. }
  9124. function WebGLClipping(properties) {
  9125. const scope = this;
  9126. let globalState = null,
  9127. numGlobalPlanes = 0,
  9128. localClippingEnabled = false,
  9129. renderingShadows = false;
  9130. const plane = new Plane(),
  9131. viewNormalMatrix = new Matrix3(),
  9132. uniform = {
  9133. value: null,
  9134. needsUpdate: false
  9135. };
  9136. this.uniform = uniform;
  9137. this.numPlanes = 0;
  9138. this.numIntersection = 0;
  9139. this.init = function (planes, enableLocalClipping, camera) {
  9140. const enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  9141. // run another frame in order to reset the state:
  9142. numGlobalPlanes !== 0 || localClippingEnabled;
  9143. localClippingEnabled = enableLocalClipping;
  9144. globalState = projectPlanes(planes, camera, 0);
  9145. numGlobalPlanes = planes.length;
  9146. return enabled;
  9147. };
  9148. this.beginShadows = function () {
  9149. renderingShadows = true;
  9150. projectPlanes(null);
  9151. };
  9152. this.endShadows = function () {
  9153. renderingShadows = false;
  9154. resetGlobalState();
  9155. };
  9156. this.setState = function (material, camera, useCache) {
  9157. const planes = material.clippingPlanes,
  9158. clipIntersection = material.clipIntersection,
  9159. clipShadows = material.clipShadows;
  9160. const materialProperties = properties.get(material);
  9161. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  9162. // there's no local clipping
  9163. if (renderingShadows) {
  9164. // there's no global clipping
  9165. projectPlanes(null);
  9166. } else {
  9167. resetGlobalState();
  9168. }
  9169. } else {
  9170. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9171. lGlobal = nGlobal * 4;
  9172. let dstArray = materialProperties.clippingState || null;
  9173. uniform.value = dstArray; // ensure unique state
  9174. dstArray = projectPlanes(planes, camera, lGlobal, useCache);
  9175. for (let i = 0; i !== lGlobal; ++i) {
  9176. dstArray[i] = globalState[i];
  9177. }
  9178. materialProperties.clippingState = dstArray;
  9179. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9180. this.numPlanes += nGlobal;
  9181. }
  9182. };
  9183. function resetGlobalState() {
  9184. if (uniform.value !== globalState) {
  9185. uniform.value = globalState;
  9186. uniform.needsUpdate = numGlobalPlanes > 0;
  9187. }
  9188. scope.numPlanes = numGlobalPlanes;
  9189. scope.numIntersection = 0;
  9190. }
  9191. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  9192. const nPlanes = planes !== null ? planes.length : 0;
  9193. let dstArray = null;
  9194. if (nPlanes !== 0) {
  9195. dstArray = uniform.value;
  9196. if (skipTransform !== true || dstArray === null) {
  9197. const flatSize = dstOffset + nPlanes * 4,
  9198. viewMatrix = camera.matrixWorldInverse;
  9199. viewNormalMatrix.getNormalMatrix(viewMatrix);
  9200. if (dstArray === null || dstArray.length < flatSize) {
  9201. dstArray = new Float32Array(flatSize);
  9202. }
  9203. for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  9204. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  9205. plane.normal.toArray(dstArray, i4);
  9206. dstArray[i4 + 3] = plane.constant;
  9207. }
  9208. }
  9209. uniform.value = dstArray;
  9210. uniform.needsUpdate = true;
  9211. }
  9212. scope.numPlanes = nPlanes;
  9213. scope.numIntersection = 0;
  9214. return dstArray;
  9215. }
  9216. }
  9217. function WebGLCubeMaps(renderer) {
  9218. let cubemaps = new WeakMap();
  9219. function mapTextureMapping(texture, mapping) {
  9220. if (mapping === EquirectangularReflectionMapping) {
  9221. texture.mapping = CubeReflectionMapping;
  9222. } else if (mapping === EquirectangularRefractionMapping) {
  9223. texture.mapping = CubeRefractionMapping;
  9224. }
  9225. return texture;
  9226. }
  9227. function get(texture) {
  9228. if (texture && texture.isTexture && texture.isRenderTargetTexture === false) {
  9229. const mapping = texture.mapping;
  9230. if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
  9231. if (cubemaps.has(texture)) {
  9232. const cubemap = cubemaps.get(texture).texture;
  9233. return mapTextureMapping(cubemap, texture.mapping);
  9234. } else {
  9235. const image = texture.image;
  9236. if (image && image.height > 0) {
  9237. const currentRenderTarget = renderer.getRenderTarget();
  9238. const renderTarget = new WebGLCubeRenderTarget(image.height / 2);
  9239. renderTarget.fromEquirectangularTexture(renderer, texture);
  9240. cubemaps.set(texture, renderTarget);
  9241. renderer.setRenderTarget(currentRenderTarget);
  9242. texture.addEventListener('dispose', onTextureDispose);
  9243. return mapTextureMapping(renderTarget.texture, texture.mapping);
  9244. } else {
  9245. // image not yet ready. try the conversion next frame
  9246. return null;
  9247. }
  9248. }
  9249. }
  9250. }
  9251. return texture;
  9252. }
  9253. function onTextureDispose(event) {
  9254. const texture = event.target;
  9255. texture.removeEventListener('dispose', onTextureDispose);
  9256. const cubemap = cubemaps.get(texture);
  9257. if (cubemap !== undefined) {
  9258. cubemaps.delete(texture);
  9259. cubemap.dispose();
  9260. }
  9261. }
  9262. function dispose() {
  9263. cubemaps = new WeakMap();
  9264. }
  9265. return {
  9266. get: get,
  9267. dispose: dispose
  9268. };
  9269. }
  9270. class OrthographicCamera extends Camera {
  9271. constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) {
  9272. super();
  9273. this.type = 'OrthographicCamera';
  9274. this.zoom = 1;
  9275. this.view = null;
  9276. this.left = left;
  9277. this.right = right;
  9278. this.top = top;
  9279. this.bottom = bottom;
  9280. this.near = near;
  9281. this.far = far;
  9282. this.updateProjectionMatrix();
  9283. }
  9284. copy(source, recursive) {
  9285. super.copy(source, recursive);
  9286. this.left = source.left;
  9287. this.right = source.right;
  9288. this.top = source.top;
  9289. this.bottom = source.bottom;
  9290. this.near = source.near;
  9291. this.far = source.far;
  9292. this.zoom = source.zoom;
  9293. this.view = source.view === null ? null : Object.assign({}, source.view);
  9294. return this;
  9295. }
  9296. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  9297. if (this.view === null) {
  9298. this.view = {
  9299. enabled: true,
  9300. fullWidth: 1,
  9301. fullHeight: 1,
  9302. offsetX: 0,
  9303. offsetY: 0,
  9304. width: 1,
  9305. height: 1
  9306. };
  9307. }
  9308. this.view.enabled = true;
  9309. this.view.fullWidth = fullWidth;
  9310. this.view.fullHeight = fullHeight;
  9311. this.view.offsetX = x;
  9312. this.view.offsetY = y;
  9313. this.view.width = width;
  9314. this.view.height = height;
  9315. this.updateProjectionMatrix();
  9316. }
  9317. clearViewOffset() {
  9318. if (this.view !== null) {
  9319. this.view.enabled = false;
  9320. }
  9321. this.updateProjectionMatrix();
  9322. }
  9323. updateProjectionMatrix() {
  9324. const dx = (this.right - this.left) / (2 * this.zoom);
  9325. const dy = (this.top - this.bottom) / (2 * this.zoom);
  9326. const cx = (this.right + this.left) / 2;
  9327. const cy = (this.top + this.bottom) / 2;
  9328. let left = cx - dx;
  9329. let right = cx + dx;
  9330. let top = cy + dy;
  9331. let bottom = cy - dy;
  9332. if (this.view !== null && this.view.enabled) {
  9333. const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  9334. const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  9335. left += scaleW * this.view.offsetX;
  9336. right = left + scaleW * this.view.width;
  9337. top -= scaleH * this.view.offsetY;
  9338. bottom = top - scaleH * this.view.height;
  9339. }
  9340. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  9341. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  9342. }
  9343. toJSON(meta) {
  9344. const data = super.toJSON(meta);
  9345. data.object.zoom = this.zoom;
  9346. data.object.left = this.left;
  9347. data.object.right = this.right;
  9348. data.object.top = this.top;
  9349. data.object.bottom = this.bottom;
  9350. data.object.near = this.near;
  9351. data.object.far = this.far;
  9352. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  9353. return data;
  9354. }
  9355. }
  9356. OrthographicCamera.prototype.isOrthographicCamera = true;
  9357. class RawShaderMaterial extends ShaderMaterial {
  9358. constructor(parameters) {
  9359. super(parameters);
  9360. this.type = 'RawShaderMaterial';
  9361. }
  9362. }
  9363. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  9364. const LOD_MIN = 4;
  9365. const LOD_MAX = 8;
  9366. const SIZE_MAX = Math.pow(2, LOD_MAX); // The standard deviations (radians) associated with the extra mips. These are
  9367. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9368. // geometric shadowing function. These sigma values squared must match the
  9369. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9370. const EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
  9371. 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
  9372. // samples and exit early, but not recompile the shader.
  9373. const MAX_SAMPLES = 20;
  9374. const ENCODINGS = {
  9375. [LinearEncoding]: 0,
  9376. [sRGBEncoding]: 1,
  9377. [RGBEEncoding]: 2,
  9378. [RGBM7Encoding]: 3,
  9379. [RGBM16Encoding]: 4,
  9380. [RGBDEncoding]: 5,
  9381. [GammaEncoding]: 6
  9382. };
  9383. const _flatCamera = /*@__PURE__*/new OrthographicCamera();
  9384. const {
  9385. _lodPlanes,
  9386. _sizeLods,
  9387. _sigmas
  9388. } = /*@__PURE__*/_createPlanes();
  9389. const _clearColor = /*@__PURE__*/new Color();
  9390. let _oldTarget = null; // Golden Ratio
  9391. const PHI = (1 + Math.sqrt(5)) / 2;
  9392. const INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
  9393. // same axis), used as axis directions evenly spread on a sphere.
  9394. 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)];
  9395. /**
  9396. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9397. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9398. * blur to be quickly accessed based on material roughness. It is packed into a
  9399. * special CubeUV format that allows us to perform custom interpolation so that
  9400. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9401. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9402. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9403. * higher roughness levels. In this way we maintain resolution to smoothly
  9404. * interpolate diffuse lighting while limiting sampling computation.
  9405. *
  9406. * Paper: Fast, Accurate Image-Based Lighting
  9407. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9408. */
  9409. class PMREMGenerator {
  9410. constructor(renderer) {
  9411. this._renderer = renderer;
  9412. this._pingPongRenderTarget = null;
  9413. this._blurMaterial = _getBlurShader(MAX_SAMPLES);
  9414. this._equirectShader = null;
  9415. this._cubemapShader = null;
  9416. this._compileMaterial(this._blurMaterial);
  9417. }
  9418. /**
  9419. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9420. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9421. * in radians to be applied to the scene before PMREM generation. Optional near
  9422. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9423. * is placed at the origin).
  9424. */
  9425. fromScene(scene, sigma = 0, near = 0.1, far = 100) {
  9426. _oldTarget = this._renderer.getRenderTarget();
  9427. const cubeUVRenderTarget = this._allocateTargets();
  9428. this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  9429. if (sigma > 0) {
  9430. this._blur(cubeUVRenderTarget, 0, 0, sigma);
  9431. }
  9432. this._applyPMREM(cubeUVRenderTarget);
  9433. this._cleanup(cubeUVRenderTarget);
  9434. return cubeUVRenderTarget;
  9435. }
  9436. /**
  9437. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9438. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  9439. * as this matches best with the 256 x 256 cubemap output.
  9440. */
  9441. fromEquirectangular(equirectangular) {
  9442. return this._fromTexture(equirectangular);
  9443. }
  9444. /**
  9445. * Generates a PMREM from an cubemap texture, which can be either LDR
  9446. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  9447. * as this matches best with the 256 x 256 cubemap output.
  9448. */
  9449. fromCubemap(cubemap) {
  9450. return this._fromTexture(cubemap);
  9451. }
  9452. /**
  9453. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9454. * your texture's network fetch for increased concurrency.
  9455. */
  9456. compileCubemapShader() {
  9457. if (this._cubemapShader === null) {
  9458. this._cubemapShader = _getCubemapShader();
  9459. this._compileMaterial(this._cubemapShader);
  9460. }
  9461. }
  9462. /**
  9463. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9464. * your texture's network fetch for increased concurrency.
  9465. */
  9466. compileEquirectangularShader() {
  9467. if (this._equirectShader === null) {
  9468. this._equirectShader = _getEquirectShader();
  9469. this._compileMaterial(this._equirectShader);
  9470. }
  9471. }
  9472. /**
  9473. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9474. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9475. * one of them will cause any others to also become unusable.
  9476. */
  9477. dispose() {
  9478. this._blurMaterial.dispose();
  9479. if (this._cubemapShader !== null) this._cubemapShader.dispose();
  9480. if (this._equirectShader !== null) this._equirectShader.dispose();
  9481. for (let i = 0; i < _lodPlanes.length; i++) {
  9482. _lodPlanes[i].dispose();
  9483. }
  9484. } // private interface
  9485. _cleanup(outputTarget) {
  9486. this._pingPongRenderTarget.dispose();
  9487. this._renderer.setRenderTarget(_oldTarget);
  9488. outputTarget.scissorTest = false;
  9489. _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
  9490. }
  9491. _fromTexture(texture) {
  9492. _oldTarget = this._renderer.getRenderTarget();
  9493. const cubeUVRenderTarget = this._allocateTargets(texture);
  9494. this._textureToCubeUV(texture, cubeUVRenderTarget);
  9495. this._applyPMREM(cubeUVRenderTarget);
  9496. this._cleanup(cubeUVRenderTarget);
  9497. return cubeUVRenderTarget;
  9498. }
  9499. _allocateTargets(texture) {
  9500. // warning: null texture is valid
  9501. const params = {
  9502. magFilter: NearestFilter,
  9503. minFilter: NearestFilter,
  9504. generateMipmaps: false,
  9505. type: UnsignedByteType,
  9506. format: RGBEFormat,
  9507. encoding: _isLDR(texture) ? texture.encoding : RGBEEncoding,
  9508. depthBuffer: false
  9509. };
  9510. const cubeUVRenderTarget = _createRenderTarget(params);
  9511. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  9512. this._pingPongRenderTarget = _createRenderTarget(params);
  9513. return cubeUVRenderTarget;
  9514. }
  9515. _compileMaterial(material) {
  9516. const tmpMesh = new Mesh(_lodPlanes[0], material);
  9517. this._renderer.compile(tmpMesh, _flatCamera);
  9518. }
  9519. _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  9520. const fov = 90;
  9521. const aspect = 1;
  9522. const cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  9523. const upSign = [1, -1, 1, 1, 1, 1];
  9524. const forwardSign = [1, 1, 1, -1, -1, -1];
  9525. const renderer = this._renderer;
  9526. const originalAutoClear = renderer.autoClear;
  9527. const outputEncoding = renderer.outputEncoding;
  9528. const toneMapping = renderer.toneMapping;
  9529. renderer.getClearColor(_clearColor);
  9530. renderer.toneMapping = NoToneMapping;
  9531. renderer.outputEncoding = LinearEncoding;
  9532. renderer.autoClear = false;
  9533. const backgroundMaterial = new MeshBasicMaterial({
  9534. name: 'PMREM.Background',
  9535. side: BackSide,
  9536. depthWrite: false,
  9537. depthTest: false
  9538. });
  9539. const backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial);
  9540. let useSolidColor = false;
  9541. const background = scene.background;
  9542. if (background) {
  9543. if (background.isColor) {
  9544. backgroundMaterial.color.copy(background);
  9545. scene.background = null;
  9546. useSolidColor = true;
  9547. }
  9548. } else {
  9549. backgroundMaterial.color.copy(_clearColor);
  9550. useSolidColor = true;
  9551. }
  9552. for (let i = 0; i < 6; i++) {
  9553. const col = i % 3;
  9554. if (col == 0) {
  9555. cubeCamera.up.set(0, upSign[i], 0);
  9556. cubeCamera.lookAt(forwardSign[i], 0, 0);
  9557. } else if (col == 1) {
  9558. cubeCamera.up.set(0, 0, upSign[i]);
  9559. cubeCamera.lookAt(0, forwardSign[i], 0);
  9560. } else {
  9561. cubeCamera.up.set(0, upSign[i], 0);
  9562. cubeCamera.lookAt(0, 0, forwardSign[i]);
  9563. }
  9564. _setViewport(cubeUVRenderTarget, col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX);
  9565. renderer.setRenderTarget(cubeUVRenderTarget);
  9566. if (useSolidColor) {
  9567. renderer.render(backgroundBox, cubeCamera);
  9568. }
  9569. renderer.render(scene, cubeCamera);
  9570. }
  9571. backgroundBox.geometry.dispose();
  9572. backgroundBox.material.dispose();
  9573. renderer.toneMapping = toneMapping;
  9574. renderer.outputEncoding = outputEncoding;
  9575. renderer.autoClear = originalAutoClear;
  9576. scene.background = background;
  9577. }
  9578. _textureToCubeUV(texture, cubeUVRenderTarget) {
  9579. const renderer = this._renderer;
  9580. if (texture.isCubeTexture) {
  9581. if (this._cubemapShader == null) {
  9582. this._cubemapShader = _getCubemapShader();
  9583. }
  9584. } else {
  9585. if (this._equirectShader == null) {
  9586. this._equirectShader = _getEquirectShader();
  9587. }
  9588. }
  9589. const material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  9590. const mesh = new Mesh(_lodPlanes[0], material);
  9591. const uniforms = material.uniforms;
  9592. uniforms['envMap'].value = texture;
  9593. if (!texture.isCubeTexture) {
  9594. uniforms['texelSize'].value.set(1.0 / texture.image.width, 1.0 / texture.image.height);
  9595. }
  9596. uniforms['inputEncoding'].value = ENCODINGS[texture.encoding];
  9597. uniforms['outputEncoding'].value = ENCODINGS[cubeUVRenderTarget.texture.encoding];
  9598. _setViewport(cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX);
  9599. renderer.setRenderTarget(cubeUVRenderTarget);
  9600. renderer.render(mesh, _flatCamera);
  9601. }
  9602. _applyPMREM(cubeUVRenderTarget) {
  9603. const renderer = this._renderer;
  9604. const autoClear = renderer.autoClear;
  9605. renderer.autoClear = false;
  9606. for (let i = 1; i < TOTAL_LODS; i++) {
  9607. const sigma = Math.sqrt(_sigmas[i] * _sigmas[i] - _sigmas[i - 1] * _sigmas[i - 1]);
  9608. const poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  9609. this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  9610. }
  9611. renderer.autoClear = autoClear;
  9612. }
  9613. /**
  9614. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9615. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9616. * the blur latitudinally (around the poles), and then longitudinally (towards
  9617. * the poles) to approximate the orthogonally-separable blur. It is least
  9618. * accurate at the poles, but still does a decent job.
  9619. */
  9620. _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  9621. const pingPongRenderTarget = this._pingPongRenderTarget;
  9622. this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  9623. this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  9624. }
  9625. _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  9626. const renderer = this._renderer;
  9627. const blurMaterial = this._blurMaterial;
  9628. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  9629. console.error('blur direction must be either latitudinal or longitudinal!');
  9630. } // Number of standard deviations at which to cut off the discrete approximation.
  9631. const STANDARD_DEVIATIONS = 3;
  9632. const blurMesh = new Mesh(_lodPlanes[lodOut], blurMaterial);
  9633. const blurUniforms = blurMaterial.uniforms;
  9634. const pixels = _sizeLods[lodIn] - 1;
  9635. const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  9636. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9637. const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  9638. if (samples > MAX_SAMPLES) {
  9639. console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
  9640. }
  9641. const weights = [];
  9642. let sum = 0;
  9643. for (let i = 0; i < MAX_SAMPLES; ++i) {
  9644. const x = i / sigmaPixels;
  9645. const weight = Math.exp(-x * x / 2);
  9646. weights.push(weight);
  9647. if (i == 0) {
  9648. sum += weight;
  9649. } else if (i < samples) {
  9650. sum += 2 * weight;
  9651. }
  9652. }
  9653. for (let i = 0; i < weights.length; i++) {
  9654. weights[i] = weights[i] / sum;
  9655. }
  9656. blurUniforms['envMap'].value = targetIn.texture;
  9657. blurUniforms['samples'].value = samples;
  9658. blurUniforms['weights'].value = weights;
  9659. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  9660. if (poleAxis) {
  9661. blurUniforms['poleAxis'].value = poleAxis;
  9662. }
  9663. blurUniforms['dTheta'].value = radiansPerPixel;
  9664. blurUniforms['mipInt'].value = LOD_MAX - lodIn;
  9665. blurUniforms['inputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  9666. blurUniforms['outputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  9667. const outputSize = _sizeLods[lodOut];
  9668. const x = 3 * Math.max(0, SIZE_MAX - 2 * outputSize);
  9669. const y = (lodOut === 0 ? 0 : 2 * SIZE_MAX) + 2 * outputSize * (lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0);
  9670. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  9671. renderer.setRenderTarget(targetOut);
  9672. renderer.render(blurMesh, _flatCamera);
  9673. }
  9674. }
  9675. function _isLDR(texture) {
  9676. if (texture === undefined || texture.type !== UnsignedByteType) return false;
  9677. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  9678. }
  9679. function _createPlanes() {
  9680. const _lodPlanes = [];
  9681. const _sizeLods = [];
  9682. const _sigmas = [];
  9683. let lod = LOD_MAX;
  9684. for (let i = 0; i < TOTAL_LODS; i++) {
  9685. const sizeLod = Math.pow(2, lod);
  9686. _sizeLods.push(sizeLod);
  9687. let sigma = 1.0 / sizeLod;
  9688. if (i > LOD_MAX - LOD_MIN) {
  9689. sigma = EXTRA_LOD_SIGMA[i - LOD_MAX + LOD_MIN - 1];
  9690. } else if (i == 0) {
  9691. sigma = 0;
  9692. }
  9693. _sigmas.push(sigma);
  9694. const texelSize = 1.0 / (sizeLod - 1);
  9695. const min = -texelSize / 2;
  9696. const max = 1 + texelSize / 2;
  9697. const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  9698. const cubeFaces = 6;
  9699. const vertices = 6;
  9700. const positionSize = 3;
  9701. const uvSize = 2;
  9702. const faceIndexSize = 1;
  9703. const position = new Float32Array(positionSize * vertices * cubeFaces);
  9704. const uv = new Float32Array(uvSize * vertices * cubeFaces);
  9705. const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  9706. for (let face = 0; face < cubeFaces; face++) {
  9707. const x = face % 3 * 2 / 3 - 1;
  9708. const y = face > 2 ? 0 : -1;
  9709. 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];
  9710. position.set(coordinates, positionSize * vertices * face);
  9711. uv.set(uv1, uvSize * vertices * face);
  9712. const fill = [face, face, face, face, face, face];
  9713. faceIndex.set(fill, faceIndexSize * vertices * face);
  9714. }
  9715. const planes = new BufferGeometry();
  9716. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  9717. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  9718. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  9719. _lodPlanes.push(planes);
  9720. if (lod > LOD_MIN) {
  9721. lod--;
  9722. }
  9723. }
  9724. return {
  9725. _lodPlanes,
  9726. _sizeLods,
  9727. _sigmas
  9728. };
  9729. }
  9730. function _createRenderTarget(params) {
  9731. const cubeUVRenderTarget = new WebGLRenderTarget(3 * SIZE_MAX, 3 * SIZE_MAX, params);
  9732. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9733. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9734. cubeUVRenderTarget.scissorTest = true;
  9735. return cubeUVRenderTarget;
  9736. }
  9737. function _setViewport(target, x, y, width, height) {
  9738. target.viewport.set(x, y, width, height);
  9739. target.scissor.set(x, y, width, height);
  9740. }
  9741. function _getBlurShader(maxSamples) {
  9742. const weights = new Float32Array(maxSamples);
  9743. const poleAxis = new Vector3(0, 1, 0);
  9744. const shaderMaterial = new RawShaderMaterial({
  9745. name: 'SphericalGaussianBlur',
  9746. defines: {
  9747. 'n': maxSamples
  9748. },
  9749. uniforms: {
  9750. 'envMap': {
  9751. value: null
  9752. },
  9753. 'samples': {
  9754. value: 1
  9755. },
  9756. 'weights': {
  9757. value: weights
  9758. },
  9759. 'latitudinal': {
  9760. value: false
  9761. },
  9762. 'dTheta': {
  9763. value: 0
  9764. },
  9765. 'mipInt': {
  9766. value: 0
  9767. },
  9768. 'poleAxis': {
  9769. value: poleAxis
  9770. },
  9771. 'inputEncoding': {
  9772. value: ENCODINGS[LinearEncoding]
  9773. },
  9774. 'outputEncoding': {
  9775. value: ENCODINGS[LinearEncoding]
  9776. }
  9777. },
  9778. vertexShader: _getCommonVertexShader(),
  9779. fragmentShader:
  9780. /* glsl */
  9781. `
  9782. precision mediump float;
  9783. precision mediump int;
  9784. varying vec3 vOutputDirection;
  9785. uniform sampler2D envMap;
  9786. uniform int samples;
  9787. uniform float weights[ n ];
  9788. uniform bool latitudinal;
  9789. uniform float dTheta;
  9790. uniform float mipInt;
  9791. uniform vec3 poleAxis;
  9792. ${_getEncodings()}
  9793. #define ENVMAP_TYPE_CUBE_UV
  9794. #include <cube_uv_reflection_fragment>
  9795. vec3 getSample( float theta, vec3 axis ) {
  9796. float cosTheta = cos( theta );
  9797. // Rodrigues' axis-angle rotation
  9798. vec3 sampleDirection = vOutputDirection * cosTheta
  9799. + cross( axis, vOutputDirection ) * sin( theta )
  9800. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9801. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  9802. }
  9803. void main() {
  9804. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  9805. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  9806. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  9807. }
  9808. axis = normalize( axis );
  9809. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9810. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  9811. for ( int i = 1; i < n; i++ ) {
  9812. if ( i >= samples ) {
  9813. break;
  9814. }
  9815. float theta = dTheta * float( i );
  9816. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  9817. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  9818. }
  9819. gl_FragColor = linearToOutputTexel( gl_FragColor );
  9820. }
  9821. `,
  9822. blending: NoBlending,
  9823. depthTest: false,
  9824. depthWrite: false
  9825. });
  9826. return shaderMaterial;
  9827. }
  9828. function _getEquirectShader() {
  9829. const texelSize = new Vector2(1, 1);
  9830. const shaderMaterial = new RawShaderMaterial({
  9831. name: 'EquirectangularToCubeUV',
  9832. uniforms: {
  9833. 'envMap': {
  9834. value: null
  9835. },
  9836. 'texelSize': {
  9837. value: texelSize
  9838. },
  9839. 'inputEncoding': {
  9840. value: ENCODINGS[LinearEncoding]
  9841. },
  9842. 'outputEncoding': {
  9843. value: ENCODINGS[LinearEncoding]
  9844. }
  9845. },
  9846. vertexShader: _getCommonVertexShader(),
  9847. fragmentShader:
  9848. /* glsl */
  9849. `
  9850. precision mediump float;
  9851. precision mediump int;
  9852. varying vec3 vOutputDirection;
  9853. uniform sampler2D envMap;
  9854. uniform vec2 texelSize;
  9855. ${_getEncodings()}
  9856. #include <common>
  9857. void main() {
  9858. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9859. vec3 outputDirection = normalize( vOutputDirection );
  9860. vec2 uv = equirectUv( outputDirection );
  9861. vec2 f = fract( uv / texelSize - 0.5 );
  9862. uv -= f * texelSize;
  9863. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9864. uv.x += texelSize.x;
  9865. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9866. uv.y += texelSize.y;
  9867. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9868. uv.x -= texelSize.x;
  9869. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9870. vec3 tm = mix( tl, tr, f.x );
  9871. vec3 bm = mix( bl, br, f.x );
  9872. gl_FragColor.rgb = mix( tm, bm, f.y );
  9873. gl_FragColor = linearToOutputTexel( gl_FragColor );
  9874. }
  9875. `,
  9876. blending: NoBlending,
  9877. depthTest: false,
  9878. depthWrite: false
  9879. });
  9880. return shaderMaterial;
  9881. }
  9882. function _getCubemapShader() {
  9883. const shaderMaterial = new RawShaderMaterial({
  9884. name: 'CubemapToCubeUV',
  9885. uniforms: {
  9886. 'envMap': {
  9887. value: null
  9888. },
  9889. 'inputEncoding': {
  9890. value: ENCODINGS[LinearEncoding]
  9891. },
  9892. 'outputEncoding': {
  9893. value: ENCODINGS[LinearEncoding]
  9894. }
  9895. },
  9896. vertexShader: _getCommonVertexShader(),
  9897. fragmentShader:
  9898. /* glsl */
  9899. `
  9900. precision mediump float;
  9901. precision mediump int;
  9902. varying vec3 vOutputDirection;
  9903. uniform samplerCube envMap;
  9904. ${_getEncodings()}
  9905. void main() {
  9906. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9907. gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;
  9908. gl_FragColor = linearToOutputTexel( gl_FragColor );
  9909. }
  9910. `,
  9911. blending: NoBlending,
  9912. depthTest: false,
  9913. depthWrite: false
  9914. });
  9915. return shaderMaterial;
  9916. }
  9917. function _getCommonVertexShader() {
  9918. return (
  9919. /* glsl */
  9920. `
  9921. precision mediump float;
  9922. precision mediump int;
  9923. attribute vec3 position;
  9924. attribute vec2 uv;
  9925. attribute float faceIndex;
  9926. varying vec3 vOutputDirection;
  9927. // RH coordinate system; PMREM face-indexing convention
  9928. vec3 getDirection( vec2 uv, float face ) {
  9929. uv = 2.0 * uv - 1.0;
  9930. vec3 direction = vec3( uv, 1.0 );
  9931. if ( face == 0.0 ) {
  9932. direction = direction.zyx; // ( 1, v, u ) pos x
  9933. } else if ( face == 1.0 ) {
  9934. direction = direction.xzy;
  9935. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  9936. } else if ( face == 2.0 ) {
  9937. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  9938. } else if ( face == 3.0 ) {
  9939. direction = direction.zyx;
  9940. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  9941. } else if ( face == 4.0 ) {
  9942. direction = direction.xzy;
  9943. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  9944. } else if ( face == 5.0 ) {
  9945. direction.z *= -1.0; // ( u, v, -1 ) neg z
  9946. }
  9947. return direction;
  9948. }
  9949. void main() {
  9950. vOutputDirection = getDirection( uv, faceIndex );
  9951. gl_Position = vec4( position, 1.0 );
  9952. }
  9953. `
  9954. );
  9955. }
  9956. function _getEncodings() {
  9957. return (
  9958. /* glsl */
  9959. `
  9960. uniform int inputEncoding;
  9961. uniform int outputEncoding;
  9962. #include <encodings_pars_fragment>
  9963. vec4 inputTexelToLinear( vec4 value ) {
  9964. if ( inputEncoding == 0 ) {
  9965. return value;
  9966. } else if ( inputEncoding == 1 ) {
  9967. return sRGBToLinear( value );
  9968. } else if ( inputEncoding == 2 ) {
  9969. return RGBEToLinear( value );
  9970. } else if ( inputEncoding == 3 ) {
  9971. return RGBMToLinear( value, 7.0 );
  9972. } else if ( inputEncoding == 4 ) {
  9973. return RGBMToLinear( value, 16.0 );
  9974. } else if ( inputEncoding == 5 ) {
  9975. return RGBDToLinear( value, 256.0 );
  9976. } else {
  9977. return GammaToLinear( value, 2.2 );
  9978. }
  9979. }
  9980. vec4 linearToOutputTexel( vec4 value ) {
  9981. if ( outputEncoding == 0 ) {
  9982. return value;
  9983. } else if ( outputEncoding == 1 ) {
  9984. return LinearTosRGB( value );
  9985. } else if ( outputEncoding == 2 ) {
  9986. return LinearToRGBE( value );
  9987. } else if ( outputEncoding == 3 ) {
  9988. return LinearToRGBM( value, 7.0 );
  9989. } else if ( outputEncoding == 4 ) {
  9990. return LinearToRGBM( value, 16.0 );
  9991. } else if ( outputEncoding == 5 ) {
  9992. return LinearToRGBD( value, 256.0 );
  9993. } else {
  9994. return LinearToGamma( value, 2.2 );
  9995. }
  9996. }
  9997. vec4 envMapTexelToLinear( vec4 color ) {
  9998. return inputTexelToLinear( color );
  9999. }
  10000. `
  10001. );
  10002. }
  10003. function WebGLCubeUVMaps(renderer) {
  10004. let cubeUVmaps = new WeakMap();
  10005. let pmremGenerator = null;
  10006. function get(texture) {
  10007. if (texture && texture.isTexture && texture.isRenderTargetTexture === false) {
  10008. const mapping = texture.mapping;
  10009. const isEquirectMap = mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping;
  10010. const isCubeMap = mapping === CubeReflectionMapping || mapping === CubeRefractionMapping;
  10011. if (isEquirectMap || isCubeMap) {
  10012. // equirect/cube map to cubeUV conversion
  10013. if (cubeUVmaps.has(texture)) {
  10014. return cubeUVmaps.get(texture).texture;
  10015. } else {
  10016. const image = texture.image;
  10017. if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) {
  10018. const currentRenderTarget = renderer.getRenderTarget();
  10019. if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer);
  10020. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture);
  10021. cubeUVmaps.set(texture, renderTarget);
  10022. renderer.setRenderTarget(currentRenderTarget);
  10023. texture.addEventListener('dispose', onTextureDispose);
  10024. return renderTarget.texture;
  10025. } else {
  10026. // image not yet ready. try the conversion next frame
  10027. return null;
  10028. }
  10029. }
  10030. }
  10031. }
  10032. return texture;
  10033. }
  10034. function isCubeTextureComplete(image) {
  10035. let count = 0;
  10036. const length = 6;
  10037. for (let i = 0; i < length; i++) {
  10038. if (image[i] !== undefined) count++;
  10039. }
  10040. return count === length;
  10041. }
  10042. function onTextureDispose(event) {
  10043. const texture = event.target;
  10044. texture.removeEventListener('dispose', onTextureDispose);
  10045. const cubemapUV = cubeUVmaps.get(texture);
  10046. if (cubemapUV !== undefined) {
  10047. cubeUVmaps.delete(texture);
  10048. cubemapUV.dispose();
  10049. }
  10050. }
  10051. function dispose() {
  10052. cubeUVmaps = new WeakMap();
  10053. if (pmremGenerator !== null) {
  10054. pmremGenerator.dispose();
  10055. pmremGenerator = null;
  10056. }
  10057. }
  10058. return {
  10059. get: get,
  10060. dispose: dispose
  10061. };
  10062. }
  10063. function WebGLExtensions(gl) {
  10064. const extensions = {};
  10065. function getExtension(name) {
  10066. if (extensions[name] !== undefined) {
  10067. return extensions[name];
  10068. }
  10069. let extension;
  10070. switch (name) {
  10071. case 'WEBGL_depth_texture':
  10072. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  10073. break;
  10074. case 'EXT_texture_filter_anisotropic':
  10075. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  10076. break;
  10077. case 'WEBGL_compressed_texture_s3tc':
  10078. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10079. break;
  10080. case 'WEBGL_compressed_texture_pvrtc':
  10081. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10082. break;
  10083. default:
  10084. extension = gl.getExtension(name);
  10085. }
  10086. extensions[name] = extension;
  10087. return extension;
  10088. }
  10089. return {
  10090. has: function (name) {
  10091. return getExtension(name) !== null;
  10092. },
  10093. init: function (capabilities) {
  10094. if (capabilities.isWebGL2) {
  10095. getExtension('EXT_color_buffer_float');
  10096. } else {
  10097. getExtension('WEBGL_depth_texture');
  10098. getExtension('OES_texture_float');
  10099. getExtension('OES_texture_half_float');
  10100. getExtension('OES_texture_half_float_linear');
  10101. getExtension('OES_standard_derivatives');
  10102. getExtension('OES_element_index_uint');
  10103. getExtension('OES_vertex_array_object');
  10104. getExtension('ANGLE_instanced_arrays');
  10105. }
  10106. getExtension('OES_texture_float_linear');
  10107. getExtension('EXT_color_buffer_half_float');
  10108. },
  10109. get: function (name) {
  10110. const extension = getExtension(name);
  10111. if (extension === null) {
  10112. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  10113. }
  10114. return extension;
  10115. }
  10116. };
  10117. }
  10118. function WebGLGeometries(gl, attributes, info, bindingStates) {
  10119. const geometries = {};
  10120. const wireframeAttributes = new WeakMap();
  10121. function onGeometryDispose(event) {
  10122. const geometry = event.target;
  10123. if (geometry.index !== null) {
  10124. attributes.remove(geometry.index);
  10125. }
  10126. for (const name in geometry.attributes) {
  10127. attributes.remove(geometry.attributes[name]);
  10128. }
  10129. geometry.removeEventListener('dispose', onGeometryDispose);
  10130. delete geometries[geometry.id];
  10131. const attribute = wireframeAttributes.get(geometry);
  10132. if (attribute) {
  10133. attributes.remove(attribute);
  10134. wireframeAttributes.delete(geometry);
  10135. }
  10136. bindingStates.releaseStatesOfGeometry(geometry);
  10137. if (geometry.isInstancedBufferGeometry === true) {
  10138. delete geometry._maxInstanceCount;
  10139. } //
  10140. info.memory.geometries--;
  10141. }
  10142. function get(object, geometry) {
  10143. if (geometries[geometry.id] === true) return geometry;
  10144. geometry.addEventListener('dispose', onGeometryDispose);
  10145. geometries[geometry.id] = true;
  10146. info.memory.geometries++;
  10147. return geometry;
  10148. }
  10149. function update(geometry) {
  10150. const geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates.
  10151. for (const name in geometryAttributes) {
  10152. attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER);
  10153. } // morph targets
  10154. const morphAttributes = geometry.morphAttributes;
  10155. for (const name in morphAttributes) {
  10156. const array = morphAttributes[name];
  10157. for (let i = 0, l = array.length; i < l; i++) {
  10158. attributes.update(array[i], gl.ARRAY_BUFFER);
  10159. }
  10160. }
  10161. }
  10162. function updateWireframeAttribute(geometry) {
  10163. const indices = [];
  10164. const geometryIndex = geometry.index;
  10165. const geometryPosition = geometry.attributes.position;
  10166. let version = 0;
  10167. if (geometryIndex !== null) {
  10168. const array = geometryIndex.array;
  10169. version = geometryIndex.version;
  10170. for (let i = 0, l = array.length; i < l; i += 3) {
  10171. const a = array[i + 0];
  10172. const b = array[i + 1];
  10173. const c = array[i + 2];
  10174. indices.push(a, b, b, c, c, a);
  10175. }
  10176. } else {
  10177. const array = geometryPosition.array;
  10178. version = geometryPosition.version;
  10179. for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  10180. const a = i + 0;
  10181. const b = i + 1;
  10182. const c = i + 2;
  10183. indices.push(a, b, b, c, c, a);
  10184. }
  10185. }
  10186. const attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  10187. attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
  10188. //
  10189. const previousAttribute = wireframeAttributes.get(geometry);
  10190. if (previousAttribute) attributes.remove(previousAttribute); //
  10191. wireframeAttributes.set(geometry, attribute);
  10192. }
  10193. function getWireframeAttribute(geometry) {
  10194. const currentAttribute = wireframeAttributes.get(geometry);
  10195. if (currentAttribute) {
  10196. const geometryIndex = geometry.index;
  10197. if (geometryIndex !== null) {
  10198. // if the attribute is obsolete, create a new one
  10199. if (currentAttribute.version < geometryIndex.version) {
  10200. updateWireframeAttribute(geometry);
  10201. }
  10202. }
  10203. } else {
  10204. updateWireframeAttribute(geometry);
  10205. }
  10206. return wireframeAttributes.get(geometry);
  10207. }
  10208. return {
  10209. get: get,
  10210. update: update,
  10211. getWireframeAttribute: getWireframeAttribute
  10212. };
  10213. }
  10214. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  10215. const isWebGL2 = capabilities.isWebGL2;
  10216. let mode;
  10217. function setMode(value) {
  10218. mode = value;
  10219. }
  10220. let type, bytesPerElement;
  10221. function setIndex(value) {
  10222. type = value.type;
  10223. bytesPerElement = value.bytesPerElement;
  10224. }
  10225. function render(start, count) {
  10226. gl.drawElements(mode, count, type, start * bytesPerElement);
  10227. info.update(count, mode, 1);
  10228. }
  10229. function renderInstances(start, count, primcount) {
  10230. if (primcount === 0) return;
  10231. let extension, methodName;
  10232. if (isWebGL2) {
  10233. extension = gl;
  10234. methodName = 'drawElementsInstanced';
  10235. } else {
  10236. extension = extensions.get('ANGLE_instanced_arrays');
  10237. methodName = 'drawElementsInstancedANGLE';
  10238. if (extension === null) {
  10239. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  10240. return;
  10241. }
  10242. }
  10243. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  10244. info.update(count, mode, primcount);
  10245. } //
  10246. this.setMode = setMode;
  10247. this.setIndex = setIndex;
  10248. this.render = render;
  10249. this.renderInstances = renderInstances;
  10250. }
  10251. function WebGLInfo(gl) {
  10252. const memory = {
  10253. geometries: 0,
  10254. textures: 0
  10255. };
  10256. const render = {
  10257. frame: 0,
  10258. calls: 0,
  10259. triangles: 0,
  10260. points: 0,
  10261. lines: 0
  10262. };
  10263. function update(count, mode, instanceCount) {
  10264. render.calls++;
  10265. switch (mode) {
  10266. case gl.TRIANGLES:
  10267. render.triangles += instanceCount * (count / 3);
  10268. break;
  10269. case gl.LINES:
  10270. render.lines += instanceCount * (count / 2);
  10271. break;
  10272. case gl.LINE_STRIP:
  10273. render.lines += instanceCount * (count - 1);
  10274. break;
  10275. case gl.LINE_LOOP:
  10276. render.lines += instanceCount * count;
  10277. break;
  10278. case gl.POINTS:
  10279. render.points += instanceCount * count;
  10280. break;
  10281. default:
  10282. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  10283. break;
  10284. }
  10285. }
  10286. function reset() {
  10287. render.frame++;
  10288. render.calls = 0;
  10289. render.triangles = 0;
  10290. render.points = 0;
  10291. render.lines = 0;
  10292. }
  10293. return {
  10294. memory: memory,
  10295. render: render,
  10296. programs: null,
  10297. autoReset: true,
  10298. reset: reset,
  10299. update: update
  10300. };
  10301. }
  10302. function numericalSort(a, b) {
  10303. return a[0] - b[0];
  10304. }
  10305. function absNumericalSort(a, b) {
  10306. return Math.abs(b[1]) - Math.abs(a[1]);
  10307. }
  10308. function WebGLMorphtargets(gl) {
  10309. const influencesList = {};
  10310. const morphInfluences = new Float32Array(8);
  10311. const workInfluences = [];
  10312. for (let i = 0; i < 8; i++) {
  10313. workInfluences[i] = [i, 0];
  10314. }
  10315. function update(object, geometry, material, program) {
  10316. const objectInfluences = object.morphTargetInfluences; // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10317. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10318. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10319. let influences = influencesList[geometry.id];
  10320. if (influences === undefined || influences.length !== length) {
  10321. // initialise list
  10322. influences = [];
  10323. for (let i = 0; i < length; i++) {
  10324. influences[i] = [i, 0];
  10325. }
  10326. influencesList[geometry.id] = influences;
  10327. } // Collect influences
  10328. for (let i = 0; i < length; i++) {
  10329. const influence = influences[i];
  10330. influence[0] = i;
  10331. influence[1] = objectInfluences[i];
  10332. }
  10333. influences.sort(absNumericalSort);
  10334. for (let i = 0; i < 8; i++) {
  10335. if (i < length && influences[i][1]) {
  10336. workInfluences[i][0] = influences[i][0];
  10337. workInfluences[i][1] = influences[i][1];
  10338. } else {
  10339. workInfluences[i][0] = Number.MAX_SAFE_INTEGER;
  10340. workInfluences[i][1] = 0;
  10341. }
  10342. }
  10343. workInfluences.sort(numericalSort);
  10344. const morphTargets = geometry.morphAttributes.position;
  10345. const morphNormals = geometry.morphAttributes.normal;
  10346. let morphInfluencesSum = 0;
  10347. for (let i = 0; i < 8; i++) {
  10348. const influence = workInfluences[i];
  10349. const index = influence[0];
  10350. const value = influence[1];
  10351. if (index !== Number.MAX_SAFE_INTEGER && value) {
  10352. if (morphTargets && geometry.getAttribute('morphTarget' + i) !== morphTargets[index]) {
  10353. geometry.setAttribute('morphTarget' + i, morphTargets[index]);
  10354. }
  10355. if (morphNormals && geometry.getAttribute('morphNormal' + i) !== morphNormals[index]) {
  10356. geometry.setAttribute('morphNormal' + i, morphNormals[index]);
  10357. }
  10358. morphInfluences[i] = value;
  10359. morphInfluencesSum += value;
  10360. } else {
  10361. if (morphTargets && geometry.hasAttribute('morphTarget' + i) === true) {
  10362. geometry.deleteAttribute('morphTarget' + i);
  10363. }
  10364. if (morphNormals && geometry.hasAttribute('morphNormal' + i) === true) {
  10365. geometry.deleteAttribute('morphNormal' + i);
  10366. }
  10367. morphInfluences[i] = 0;
  10368. }
  10369. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10370. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10371. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10372. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10373. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10374. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  10375. }
  10376. return {
  10377. update: update
  10378. };
  10379. }
  10380. function WebGLObjects(gl, geometries, attributes, info) {
  10381. let updateMap = new WeakMap();
  10382. function update(object) {
  10383. const frame = info.render.frame;
  10384. const geometry = object.geometry;
  10385. const buffergeometry = geometries.get(object, geometry); // Update once per frame
  10386. if (updateMap.get(buffergeometry) !== frame) {
  10387. geometries.update(buffergeometry);
  10388. updateMap.set(buffergeometry, frame);
  10389. }
  10390. if (object.isInstancedMesh) {
  10391. if (object.hasEventListener('dispose', onInstancedMeshDispose) === false) {
  10392. object.addEventListener('dispose', onInstancedMeshDispose);
  10393. }
  10394. attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER);
  10395. if (object.instanceColor !== null) {
  10396. attributes.update(object.instanceColor, gl.ARRAY_BUFFER);
  10397. }
  10398. }
  10399. return buffergeometry;
  10400. }
  10401. function dispose() {
  10402. updateMap = new WeakMap();
  10403. }
  10404. function onInstancedMeshDispose(event) {
  10405. const instancedMesh = event.target;
  10406. instancedMesh.removeEventListener('dispose', onInstancedMeshDispose);
  10407. attributes.remove(instancedMesh.instanceMatrix);
  10408. if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor);
  10409. }
  10410. return {
  10411. update: update,
  10412. dispose: dispose
  10413. };
  10414. }
  10415. class DataTexture2DArray extends Texture {
  10416. constructor(data = null, width = 1, height = 1, depth = 1) {
  10417. super(null);
  10418. this.image = {
  10419. data,
  10420. width,
  10421. height,
  10422. depth
  10423. };
  10424. this.magFilter = NearestFilter;
  10425. this.minFilter = NearestFilter;
  10426. this.wrapR = ClampToEdgeWrapping;
  10427. this.generateMipmaps = false;
  10428. this.flipY = false;
  10429. this.unpackAlignment = 1;
  10430. this.needsUpdate = true;
  10431. }
  10432. }
  10433. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  10434. class DataTexture3D extends Texture {
  10435. constructor(data = null, width = 1, height = 1, depth = 1) {
  10436. // We're going to add .setXXX() methods for setting properties later.
  10437. // Users can still set in DataTexture3D directly.
  10438. //
  10439. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  10440. // texture.anisotropy = 16;
  10441. //
  10442. // See #14839
  10443. super(null);
  10444. this.image = {
  10445. data,
  10446. width,
  10447. height,
  10448. depth
  10449. };
  10450. this.magFilter = NearestFilter;
  10451. this.minFilter = NearestFilter;
  10452. this.wrapR = ClampToEdgeWrapping;
  10453. this.generateMipmaps = false;
  10454. this.flipY = false;
  10455. this.unpackAlignment = 1;
  10456. this.needsUpdate = true;
  10457. }
  10458. }
  10459. DataTexture3D.prototype.isDataTexture3D = true;
  10460. /**
  10461. * Uniforms of a program.
  10462. * Those form a tree structure with a special top-level container for the root,
  10463. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10464. *
  10465. *
  10466. * Properties of inner nodes including the top-level container:
  10467. *
  10468. * .seq - array of nested uniforms
  10469. * .map - nested uniforms by name
  10470. *
  10471. *
  10472. * Methods of all nodes except the top-level container:
  10473. *
  10474. * .setValue( gl, value, [textures] )
  10475. *
  10476. * uploads a uniform value(s)
  10477. * the 'textures' parameter is needed for sampler uniforms
  10478. *
  10479. *
  10480. * Static methods of the top-level container (textures factorizations):
  10481. *
  10482. * .upload( gl, seq, values, textures )
  10483. *
  10484. * sets uniforms in 'seq' to 'values[id].value'
  10485. *
  10486. * .seqWithValue( seq, values ) : filteredSeq
  10487. *
  10488. * filters 'seq' entries with corresponding entry in values
  10489. *
  10490. *
  10491. * Methods of the top-level container (textures factorizations):
  10492. *
  10493. * .setValue( gl, name, value, textures )
  10494. *
  10495. * sets uniform with name 'name' to 'value'
  10496. *
  10497. * .setOptional( gl, obj, prop )
  10498. *
  10499. * like .set for an optional property of the object
  10500. *
  10501. */
  10502. const emptyTexture = new Texture();
  10503. const emptyTexture2dArray = new DataTexture2DArray();
  10504. const emptyTexture3d = new DataTexture3D();
  10505. const emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  10506. // Array Caches (provide typed arrays for temporary by size)
  10507. const arrayCacheF32 = [];
  10508. const arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  10509. const mat4array = new Float32Array(16);
  10510. const mat3array = new Float32Array(9);
  10511. const mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  10512. function flatten(array, nBlocks, blockSize) {
  10513. const firstElem = array[0];
  10514. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  10515. // see http://jacksondunstan.com/articles/983
  10516. const n = nBlocks * blockSize;
  10517. let r = arrayCacheF32[n];
  10518. if (r === undefined) {
  10519. r = new Float32Array(n);
  10520. arrayCacheF32[n] = r;
  10521. }
  10522. if (nBlocks !== 0) {
  10523. firstElem.toArray(r, 0);
  10524. for (let i = 1, offset = 0; i !== nBlocks; ++i) {
  10525. offset += blockSize;
  10526. array[i].toArray(r, offset);
  10527. }
  10528. }
  10529. return r;
  10530. }
  10531. function arraysEqual(a, b) {
  10532. if (a.length !== b.length) return false;
  10533. for (let i = 0, l = a.length; i < l; i++) {
  10534. if (a[i] !== b[i]) return false;
  10535. }
  10536. return true;
  10537. }
  10538. function copyArray(a, b) {
  10539. for (let i = 0, l = b.length; i < l; i++) {
  10540. a[i] = b[i];
  10541. }
  10542. } // Texture unit allocation
  10543. function allocTexUnits(textures, n) {
  10544. let r = arrayCacheI32[n];
  10545. if (r === undefined) {
  10546. r = new Int32Array(n);
  10547. arrayCacheI32[n] = r;
  10548. }
  10549. for (let i = 0; i !== n; ++i) {
  10550. r[i] = textures.allocateTextureUnit();
  10551. }
  10552. return r;
  10553. } // --- Setters ---
  10554. // Note: Defining these methods externally, because they come in a bunch
  10555. // and this way their names minify.
  10556. // Single scalar
  10557. function setValueV1f(gl, v) {
  10558. const cache = this.cache;
  10559. if (cache[0] === v) return;
  10560. gl.uniform1f(this.addr, v);
  10561. cache[0] = v;
  10562. } // Single float vector (from flat array or THREE.VectorN)
  10563. function setValueV2f(gl, v) {
  10564. const cache = this.cache;
  10565. if (v.x !== undefined) {
  10566. if (cache[0] !== v.x || cache[1] !== v.y) {
  10567. gl.uniform2f(this.addr, v.x, v.y);
  10568. cache[0] = v.x;
  10569. cache[1] = v.y;
  10570. }
  10571. } else {
  10572. if (arraysEqual(cache, v)) return;
  10573. gl.uniform2fv(this.addr, v);
  10574. copyArray(cache, v);
  10575. }
  10576. }
  10577. function setValueV3f(gl, v) {
  10578. const cache = this.cache;
  10579. if (v.x !== undefined) {
  10580. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  10581. gl.uniform3f(this.addr, v.x, v.y, v.z);
  10582. cache[0] = v.x;
  10583. cache[1] = v.y;
  10584. cache[2] = v.z;
  10585. }
  10586. } else if (v.r !== undefined) {
  10587. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  10588. gl.uniform3f(this.addr, v.r, v.g, v.b);
  10589. cache[0] = v.r;
  10590. cache[1] = v.g;
  10591. cache[2] = v.b;
  10592. }
  10593. } else {
  10594. if (arraysEqual(cache, v)) return;
  10595. gl.uniform3fv(this.addr, v);
  10596. copyArray(cache, v);
  10597. }
  10598. }
  10599. function setValueV4f(gl, v) {
  10600. const cache = this.cache;
  10601. if (v.x !== undefined) {
  10602. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  10603. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  10604. cache[0] = v.x;
  10605. cache[1] = v.y;
  10606. cache[2] = v.z;
  10607. cache[3] = v.w;
  10608. }
  10609. } else {
  10610. if (arraysEqual(cache, v)) return;
  10611. gl.uniform4fv(this.addr, v);
  10612. copyArray(cache, v);
  10613. }
  10614. } // Single matrix (from flat array or THREE.MatrixN)
  10615. function setValueM2(gl, v) {
  10616. const cache = this.cache;
  10617. const elements = v.elements;
  10618. if (elements === undefined) {
  10619. if (arraysEqual(cache, v)) return;
  10620. gl.uniformMatrix2fv(this.addr, false, v);
  10621. copyArray(cache, v);
  10622. } else {
  10623. if (arraysEqual(cache, elements)) return;
  10624. mat2array.set(elements);
  10625. gl.uniformMatrix2fv(this.addr, false, mat2array);
  10626. copyArray(cache, elements);
  10627. }
  10628. }
  10629. function setValueM3(gl, v) {
  10630. const cache = this.cache;
  10631. const elements = v.elements;
  10632. if (elements === undefined) {
  10633. if (arraysEqual(cache, v)) return;
  10634. gl.uniformMatrix3fv(this.addr, false, v);
  10635. copyArray(cache, v);
  10636. } else {
  10637. if (arraysEqual(cache, elements)) return;
  10638. mat3array.set(elements);
  10639. gl.uniformMatrix3fv(this.addr, false, mat3array);
  10640. copyArray(cache, elements);
  10641. }
  10642. }
  10643. function setValueM4(gl, v) {
  10644. const cache = this.cache;
  10645. const elements = v.elements;
  10646. if (elements === undefined) {
  10647. if (arraysEqual(cache, v)) return;
  10648. gl.uniformMatrix4fv(this.addr, false, v);
  10649. copyArray(cache, v);
  10650. } else {
  10651. if (arraysEqual(cache, elements)) return;
  10652. mat4array.set(elements);
  10653. gl.uniformMatrix4fv(this.addr, false, mat4array);
  10654. copyArray(cache, elements);
  10655. }
  10656. } // Single integer / boolean
  10657. function setValueV1i(gl, v) {
  10658. const cache = this.cache;
  10659. if (cache[0] === v) return;
  10660. gl.uniform1i(this.addr, v);
  10661. cache[0] = v;
  10662. } // Single integer / boolean vector (from flat array)
  10663. function setValueV2i(gl, v) {
  10664. const cache = this.cache;
  10665. if (arraysEqual(cache, v)) return;
  10666. gl.uniform2iv(this.addr, v);
  10667. copyArray(cache, v);
  10668. }
  10669. function setValueV3i(gl, v) {
  10670. const cache = this.cache;
  10671. if (arraysEqual(cache, v)) return;
  10672. gl.uniform3iv(this.addr, v);
  10673. copyArray(cache, v);
  10674. }
  10675. function setValueV4i(gl, v) {
  10676. const cache = this.cache;
  10677. if (arraysEqual(cache, v)) return;
  10678. gl.uniform4iv(this.addr, v);
  10679. copyArray(cache, v);
  10680. } // Single unsigned integer
  10681. function setValueV1ui(gl, v) {
  10682. const cache = this.cache;
  10683. if (cache[0] === v) return;
  10684. gl.uniform1ui(this.addr, v);
  10685. cache[0] = v;
  10686. } // Single unsigned integer vector (from flat array)
  10687. function setValueV2ui(gl, v) {
  10688. const cache = this.cache;
  10689. if (arraysEqual(cache, v)) return;
  10690. gl.uniform2uiv(this.addr, v);
  10691. copyArray(cache, v);
  10692. }
  10693. function setValueV3ui(gl, v) {
  10694. const cache = this.cache;
  10695. if (arraysEqual(cache, v)) return;
  10696. gl.uniform3uiv(this.addr, v);
  10697. copyArray(cache, v);
  10698. }
  10699. function setValueV4ui(gl, v) {
  10700. const cache = this.cache;
  10701. if (arraysEqual(cache, v)) return;
  10702. gl.uniform4uiv(this.addr, v);
  10703. copyArray(cache, v);
  10704. } // Single texture (2D / Cube)
  10705. function setValueT1(gl, v, textures) {
  10706. const cache = this.cache;
  10707. const unit = textures.allocateTextureUnit();
  10708. if (cache[0] !== unit) {
  10709. gl.uniform1i(this.addr, unit);
  10710. cache[0] = unit;
  10711. }
  10712. textures.safeSetTexture2D(v || emptyTexture, unit);
  10713. }
  10714. function setValueT3D1(gl, v, textures) {
  10715. const cache = this.cache;
  10716. const unit = textures.allocateTextureUnit();
  10717. if (cache[0] !== unit) {
  10718. gl.uniform1i(this.addr, unit);
  10719. cache[0] = unit;
  10720. }
  10721. textures.setTexture3D(v || emptyTexture3d, unit);
  10722. }
  10723. function setValueT6(gl, v, textures) {
  10724. const cache = this.cache;
  10725. const unit = textures.allocateTextureUnit();
  10726. if (cache[0] !== unit) {
  10727. gl.uniform1i(this.addr, unit);
  10728. cache[0] = unit;
  10729. }
  10730. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  10731. }
  10732. function setValueT2DArray1(gl, v, textures) {
  10733. const cache = this.cache;
  10734. const unit = textures.allocateTextureUnit();
  10735. if (cache[0] !== unit) {
  10736. gl.uniform1i(this.addr, unit);
  10737. cache[0] = unit;
  10738. }
  10739. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  10740. } // Helper to pick the right setter for the singular case
  10741. function getSingularSetter(type) {
  10742. switch (type) {
  10743. case 0x1406:
  10744. return setValueV1f;
  10745. // FLOAT
  10746. case 0x8b50:
  10747. return setValueV2f;
  10748. // _VEC2
  10749. case 0x8b51:
  10750. return setValueV3f;
  10751. // _VEC3
  10752. case 0x8b52:
  10753. return setValueV4f;
  10754. // _VEC4
  10755. case 0x8b5a:
  10756. return setValueM2;
  10757. // _MAT2
  10758. case 0x8b5b:
  10759. return setValueM3;
  10760. // _MAT3
  10761. case 0x8b5c:
  10762. return setValueM4;
  10763. // _MAT4
  10764. case 0x1404:
  10765. case 0x8b56:
  10766. return setValueV1i;
  10767. // INT, BOOL
  10768. case 0x8b53:
  10769. case 0x8b57:
  10770. return setValueV2i;
  10771. // _VEC2
  10772. case 0x8b54:
  10773. case 0x8b58:
  10774. return setValueV3i;
  10775. // _VEC3
  10776. case 0x8b55:
  10777. case 0x8b59:
  10778. return setValueV4i;
  10779. // _VEC4
  10780. case 0x1405:
  10781. return setValueV1ui;
  10782. // UINT
  10783. case 0x8dc6:
  10784. return setValueV2ui;
  10785. // _VEC2
  10786. case 0x8dc7:
  10787. return setValueV3ui;
  10788. // _VEC3
  10789. case 0x8dc8:
  10790. return setValueV4ui;
  10791. // _VEC4
  10792. case 0x8b5e: // SAMPLER_2D
  10793. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10794. case 0x8dca: // INT_SAMPLER_2D
  10795. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10796. case 0x8b62:
  10797. // SAMPLER_2D_SHADOW
  10798. return setValueT1;
  10799. case 0x8b5f: // SAMPLER_3D
  10800. case 0x8dcb: // INT_SAMPLER_3D
  10801. case 0x8dd3:
  10802. // UNSIGNED_INT_SAMPLER_3D
  10803. return setValueT3D1;
  10804. case 0x8b60: // SAMPLER_CUBE
  10805. case 0x8dcc: // INT_SAMPLER_CUBE
  10806. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10807. case 0x8dc5:
  10808. // SAMPLER_CUBE_SHADOW
  10809. return setValueT6;
  10810. case 0x8dc1: // SAMPLER_2D_ARRAY
  10811. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10812. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10813. case 0x8dc4:
  10814. // SAMPLER_2D_ARRAY_SHADOW
  10815. return setValueT2DArray1;
  10816. }
  10817. } // Array of scalars
  10818. function setValueV1fArray(gl, v) {
  10819. gl.uniform1fv(this.addr, v);
  10820. } // Array of vectors (from flat array or array of THREE.VectorN)
  10821. function setValueV2fArray(gl, v) {
  10822. const data = flatten(v, this.size, 2);
  10823. gl.uniform2fv(this.addr, data);
  10824. }
  10825. function setValueV3fArray(gl, v) {
  10826. const data = flatten(v, this.size, 3);
  10827. gl.uniform3fv(this.addr, data);
  10828. }
  10829. function setValueV4fArray(gl, v) {
  10830. const data = flatten(v, this.size, 4);
  10831. gl.uniform4fv(this.addr, data);
  10832. } // Array of matrices (from flat array or array of THREE.MatrixN)
  10833. function setValueM2Array(gl, v) {
  10834. const data = flatten(v, this.size, 4);
  10835. gl.uniformMatrix2fv(this.addr, false, data);
  10836. }
  10837. function setValueM3Array(gl, v) {
  10838. const data = flatten(v, this.size, 9);
  10839. gl.uniformMatrix3fv(this.addr, false, data);
  10840. }
  10841. function setValueM4Array(gl, v) {
  10842. const data = flatten(v, this.size, 16);
  10843. gl.uniformMatrix4fv(this.addr, false, data);
  10844. } // Array of integer / boolean
  10845. function setValueV1iArray(gl, v) {
  10846. gl.uniform1iv(this.addr, v);
  10847. } // Array of integer / boolean vectors (from flat array)
  10848. function setValueV2iArray(gl, v) {
  10849. gl.uniform2iv(this.addr, v);
  10850. }
  10851. function setValueV3iArray(gl, v) {
  10852. gl.uniform3iv(this.addr, v);
  10853. }
  10854. function setValueV4iArray(gl, v) {
  10855. gl.uniform4iv(this.addr, v);
  10856. } // Array of unsigned integer
  10857. function setValueV1uiArray(gl, v) {
  10858. gl.uniform1uiv(this.addr, v);
  10859. } // Array of unsigned integer vectors (from flat array)
  10860. function setValueV2uiArray(gl, v) {
  10861. gl.uniform2uiv(this.addr, v);
  10862. }
  10863. function setValueV3uiArray(gl, v) {
  10864. gl.uniform3uiv(this.addr, v);
  10865. }
  10866. function setValueV4uiArray(gl, v) {
  10867. gl.uniform4uiv(this.addr, v);
  10868. } // Array of textures (2D / Cube)
  10869. function setValueT1Array(gl, v, textures) {
  10870. const n = v.length;
  10871. const units = allocTexUnits(textures, n);
  10872. gl.uniform1iv(this.addr, units);
  10873. for (let i = 0; i !== n; ++i) {
  10874. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  10875. }
  10876. }
  10877. function setValueT6Array(gl, v, textures) {
  10878. const n = v.length;
  10879. const units = allocTexUnits(textures, n);
  10880. gl.uniform1iv(this.addr, units);
  10881. for (let i = 0; i !== n; ++i) {
  10882. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  10883. }
  10884. } // Helper to pick the right setter for a pure (bottom-level) array
  10885. function getPureArraySetter(type) {
  10886. switch (type) {
  10887. case 0x1406:
  10888. return setValueV1fArray;
  10889. // FLOAT
  10890. case 0x8b50:
  10891. return setValueV2fArray;
  10892. // _VEC2
  10893. case 0x8b51:
  10894. return setValueV3fArray;
  10895. // _VEC3
  10896. case 0x8b52:
  10897. return setValueV4fArray;
  10898. // _VEC4
  10899. case 0x8b5a:
  10900. return setValueM2Array;
  10901. // _MAT2
  10902. case 0x8b5b:
  10903. return setValueM3Array;
  10904. // _MAT3
  10905. case 0x8b5c:
  10906. return setValueM4Array;
  10907. // _MAT4
  10908. case 0x1404:
  10909. case 0x8b56:
  10910. return setValueV1iArray;
  10911. // INT, BOOL
  10912. case 0x8b53:
  10913. case 0x8b57:
  10914. return setValueV2iArray;
  10915. // _VEC2
  10916. case 0x8b54:
  10917. case 0x8b58:
  10918. return setValueV3iArray;
  10919. // _VEC3
  10920. case 0x8b55:
  10921. case 0x8b59:
  10922. return setValueV4iArray;
  10923. // _VEC4
  10924. case 0x1405:
  10925. return setValueV1uiArray;
  10926. // UINT
  10927. case 0x8dc6:
  10928. return setValueV2uiArray;
  10929. // _VEC2
  10930. case 0x8dc7:
  10931. return setValueV3uiArray;
  10932. // _VEC3
  10933. case 0x8dc8:
  10934. return setValueV4uiArray;
  10935. // _VEC4
  10936. case 0x8b5e: // SAMPLER_2D
  10937. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10938. case 0x8dca: // INT_SAMPLER_2D
  10939. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10940. case 0x8b62:
  10941. // SAMPLER_2D_SHADOW
  10942. return setValueT1Array;
  10943. case 0x8b60: // SAMPLER_CUBE
  10944. case 0x8dcc: // INT_SAMPLER_CUBE
  10945. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10946. case 0x8dc5:
  10947. // SAMPLER_CUBE_SHADOW
  10948. return setValueT6Array;
  10949. }
  10950. } // --- Uniform Classes ---
  10951. function SingleUniform(id, activeInfo, addr) {
  10952. this.id = id;
  10953. this.addr = addr;
  10954. this.cache = [];
  10955. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  10956. }
  10957. function PureArrayUniform(id, activeInfo, addr) {
  10958. this.id = id;
  10959. this.addr = addr;
  10960. this.cache = [];
  10961. this.size = activeInfo.size;
  10962. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  10963. }
  10964. PureArrayUniform.prototype.updateCache = function (data) {
  10965. const cache = this.cache;
  10966. if (data instanceof Float32Array && cache.length !== data.length) {
  10967. this.cache = new Float32Array(data.length);
  10968. }
  10969. copyArray(cache, data);
  10970. };
  10971. function StructuredUniform(id) {
  10972. this.id = id;
  10973. this.seq = [];
  10974. this.map = {};
  10975. }
  10976. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  10977. const seq = this.seq;
  10978. for (let i = 0, n = seq.length; i !== n; ++i) {
  10979. const u = seq[i];
  10980. u.setValue(gl, value[u.id], textures);
  10981. }
  10982. }; // --- Top-level ---
  10983. // Parser - builds up the property tree from the path strings
  10984. const RePathPart = /(\w+)(\])?(\[|\.)?/g; // extracts
  10985. // - the identifier (member name or array index)
  10986. // - followed by an optional right bracket (found when array index)
  10987. // - followed by an optional left bracket or dot (type of subscript)
  10988. //
  10989. // Note: These portions can be read in a non-overlapping fashion and
  10990. // allow straightforward parsing of the hierarchy that WebGL encodes
  10991. // in the uniform names.
  10992. function addUniform(container, uniformObject) {
  10993. container.seq.push(uniformObject);
  10994. container.map[uniformObject.id] = uniformObject;
  10995. }
  10996. function parseUniform(activeInfo, addr, container) {
  10997. const path = activeInfo.name,
  10998. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  10999. RePathPart.lastIndex = 0;
  11000. while (true) {
  11001. const match = RePathPart.exec(path),
  11002. matchEnd = RePathPart.lastIndex;
  11003. let id = match[1];
  11004. const idIsIndex = match[2] === ']',
  11005. subscript = match[3];
  11006. if (idIsIndex) id = id | 0; // convert to integer
  11007. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  11008. // bare name or "pure" bottom-level array "[0]" suffix
  11009. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  11010. break;
  11011. } else {
  11012. // step into inner node / create it in case it doesn't exist
  11013. const map = container.map;
  11014. let next = map[id];
  11015. if (next === undefined) {
  11016. next = new StructuredUniform(id);
  11017. addUniform(container, next);
  11018. }
  11019. container = next;
  11020. }
  11021. }
  11022. } // Root Container
  11023. function WebGLUniforms(gl, program) {
  11024. this.seq = [];
  11025. this.map = {};
  11026. const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  11027. for (let i = 0; i < n; ++i) {
  11028. const info = gl.getActiveUniform(program, i),
  11029. addr = gl.getUniformLocation(program, info.name);
  11030. parseUniform(info, addr, this);
  11031. }
  11032. }
  11033. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  11034. const u = this.map[name];
  11035. if (u !== undefined) u.setValue(gl, value, textures);
  11036. };
  11037. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  11038. const v = object[name];
  11039. if (v !== undefined) this.setValue(gl, name, v);
  11040. }; // Static interface
  11041. WebGLUniforms.upload = function (gl, seq, values, textures) {
  11042. for (let i = 0, n = seq.length; i !== n; ++i) {
  11043. const u = seq[i],
  11044. v = values[u.id];
  11045. if (v.needsUpdate !== false) {
  11046. // note: always updating when .needsUpdate is undefined
  11047. u.setValue(gl, v.value, textures);
  11048. }
  11049. }
  11050. };
  11051. WebGLUniforms.seqWithValue = function (seq, values) {
  11052. const r = [];
  11053. for (let i = 0, n = seq.length; i !== n; ++i) {
  11054. const u = seq[i];
  11055. if (u.id in values) r.push(u);
  11056. }
  11057. return r;
  11058. };
  11059. function WebGLShader(gl, type, string) {
  11060. const shader = gl.createShader(type);
  11061. gl.shaderSource(shader, string);
  11062. gl.compileShader(shader);
  11063. return shader;
  11064. }
  11065. let programIdCount = 0;
  11066. function addLineNumbers(string) {
  11067. const lines = string.split('\n');
  11068. for (let i = 0; i < lines.length; i++) {
  11069. lines[i] = i + 1 + ': ' + lines[i];
  11070. }
  11071. return lines.join('\n');
  11072. }
  11073. function getEncodingComponents(encoding) {
  11074. switch (encoding) {
  11075. case LinearEncoding:
  11076. return ['Linear', '( value )'];
  11077. case sRGBEncoding:
  11078. return ['sRGB', '( value )'];
  11079. case RGBEEncoding:
  11080. return ['RGBE', '( value )'];
  11081. case RGBM7Encoding:
  11082. return ['RGBM', '( value, 7.0 )'];
  11083. case RGBM16Encoding:
  11084. return ['RGBM', '( value, 16.0 )'];
  11085. case RGBDEncoding:
  11086. return ['RGBD', '( value, 256.0 )'];
  11087. case GammaEncoding:
  11088. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  11089. case LogLuvEncoding:
  11090. return ['LogLuv', '( value )'];
  11091. default:
  11092. console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
  11093. return ['Linear', '( value )'];
  11094. }
  11095. }
  11096. function getShaderErrors(gl, shader, type) {
  11097. const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  11098. const errors = gl.getShaderInfoLog(shader).trim();
  11099. if (status && errors === '') return ''; // --enable-privileged-webgl-extension
  11100. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11101. return type.toUpperCase() + '\n\n' + errors + '\n\n' + addLineNumbers(gl.getShaderSource(shader));
  11102. }
  11103. function getTexelDecodingFunction(functionName, encoding) {
  11104. const components = getEncodingComponents(encoding);
  11105. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  11106. }
  11107. function getTexelEncodingFunction(functionName, encoding) {
  11108. const components = getEncodingComponents(encoding);
  11109. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  11110. }
  11111. function getToneMappingFunction(functionName, toneMapping) {
  11112. let toneMappingName;
  11113. switch (toneMapping) {
  11114. case LinearToneMapping:
  11115. toneMappingName = 'Linear';
  11116. break;
  11117. case ReinhardToneMapping:
  11118. toneMappingName = 'Reinhard';
  11119. break;
  11120. case CineonToneMapping:
  11121. toneMappingName = 'OptimizedCineon';
  11122. break;
  11123. case ACESFilmicToneMapping:
  11124. toneMappingName = 'ACESFilmic';
  11125. break;
  11126. case CustomToneMapping:
  11127. toneMappingName = 'Custom';
  11128. break;
  11129. default:
  11130. console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
  11131. toneMappingName = 'Linear';
  11132. }
  11133. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11134. }
  11135. function generateExtensions(parameters) {
  11136. const chunks = [parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ? '#extension GL_OES_standard_derivatives : enable' : '', (parameters.extensionFragDepth || parameters.logarithmicDepthBuffer) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ? '#extension GL_EXT_draw_buffers : require' : '', (parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''];
  11137. return chunks.filter(filterEmptyLine).join('\n');
  11138. }
  11139. function generateDefines(defines) {
  11140. const chunks = [];
  11141. for (const name in defines) {
  11142. const value = defines[name];
  11143. if (value === false) continue;
  11144. chunks.push('#define ' + name + ' ' + value);
  11145. }
  11146. return chunks.join('\n');
  11147. }
  11148. function fetchAttributeLocations(gl, program) {
  11149. const attributes = {};
  11150. const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  11151. for (let i = 0; i < n; i++) {
  11152. const info = gl.getActiveAttrib(program, i);
  11153. const name = info.name;
  11154. let locationSize = 1;
  11155. if (info.type === gl.FLOAT_MAT2) locationSize = 2;
  11156. if (info.type === gl.FLOAT_MAT3) locationSize = 3;
  11157. if (info.type === gl.FLOAT_MAT4) locationSize = 4; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11158. attributes[name] = {
  11159. type: info.type,
  11160. location: gl.getAttribLocation(program, name),
  11161. locationSize: locationSize
  11162. };
  11163. }
  11164. return attributes;
  11165. }
  11166. function filterEmptyLine(string) {
  11167. return string !== '';
  11168. }
  11169. function replaceLightNums(string, parameters) {
  11170. 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);
  11171. }
  11172. function replaceClippingPlaneNums(string, parameters) {
  11173. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  11174. } // Resolve Includes
  11175. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11176. function resolveIncludes(string) {
  11177. return string.replace(includePattern, includeReplacer);
  11178. }
  11179. function includeReplacer(match, include) {
  11180. const string = ShaderChunk[include];
  11181. if (string === undefined) {
  11182. throw new Error('Can not resolve #include <' + include + '>');
  11183. }
  11184. return resolveIncludes(string);
  11185. } // Unroll Loops
  11186. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  11187. 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;
  11188. function unrollLoops(string) {
  11189. return string.replace(unrollLoopPattern, loopReplacer).replace(deprecatedUnrollLoopPattern, deprecatedLoopReplacer);
  11190. }
  11191. function deprecatedLoopReplacer(match, start, end, snippet) {
  11192. console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');
  11193. return loopReplacer(match, start, end, snippet);
  11194. }
  11195. function loopReplacer(match, start, end, snippet) {
  11196. let string = '';
  11197. for (let i = parseInt(start); i < parseInt(end); i++) {
  11198. string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  11199. }
  11200. return string;
  11201. } //
  11202. function generatePrecision(parameters) {
  11203. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11204. if (parameters.precision === 'highp') {
  11205. precisionstring += '\n#define HIGH_PRECISION';
  11206. } else if (parameters.precision === 'mediump') {
  11207. precisionstring += '\n#define MEDIUM_PRECISION';
  11208. } else if (parameters.precision === 'lowp') {
  11209. precisionstring += '\n#define LOW_PRECISION';
  11210. }
  11211. return precisionstring;
  11212. }
  11213. function generateShadowMapTypeDefine(parameters) {
  11214. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11215. if (parameters.shadowMapType === PCFShadowMap) {
  11216. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11217. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  11218. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11219. } else if (parameters.shadowMapType === VSMShadowMap) {
  11220. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11221. }
  11222. return shadowMapTypeDefine;
  11223. }
  11224. function generateEnvMapTypeDefine(parameters) {
  11225. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11226. if (parameters.envMap) {
  11227. switch (parameters.envMapMode) {
  11228. case CubeReflectionMapping:
  11229. case CubeRefractionMapping:
  11230. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11231. break;
  11232. case CubeUVReflectionMapping:
  11233. case CubeUVRefractionMapping:
  11234. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11235. break;
  11236. }
  11237. }
  11238. return envMapTypeDefine;
  11239. }
  11240. function generateEnvMapModeDefine(parameters) {
  11241. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11242. if (parameters.envMap) {
  11243. switch (parameters.envMapMode) {
  11244. case CubeRefractionMapping:
  11245. case CubeUVRefractionMapping:
  11246. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11247. break;
  11248. }
  11249. }
  11250. return envMapModeDefine;
  11251. }
  11252. function generateEnvMapBlendingDefine(parameters) {
  11253. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11254. if (parameters.envMap) {
  11255. switch (parameters.combine) {
  11256. case MultiplyOperation:
  11257. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11258. break;
  11259. case MixOperation:
  11260. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11261. break;
  11262. case AddOperation:
  11263. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11264. break;
  11265. }
  11266. }
  11267. return envMapBlendingDefine;
  11268. }
  11269. function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
  11270. // TODO Send this event to Three.js DevTools
  11271. // console.log( 'WebGLProgram', cacheKey );
  11272. const gl = renderer.getContext();
  11273. const defines = parameters.defines;
  11274. let vertexShader = parameters.vertexShader;
  11275. let fragmentShader = parameters.fragmentShader;
  11276. const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  11277. const envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  11278. const envMapModeDefine = generateEnvMapModeDefine(parameters);
  11279. const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  11280. const gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  11281. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  11282. const customDefines = generateDefines(defines);
  11283. const program = gl.createProgram();
  11284. let prefixVertex, prefixFragment;
  11285. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11286. if (parameters.isRawShaderMaterial) {
  11287. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  11288. if (prefixVertex.length > 0) {
  11289. prefixVertex += '\n';
  11290. }
  11291. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  11292. if (prefixFragment.length > 0) {
  11293. prefixFragment += '\n';
  11294. }
  11295. } else {
  11296. prefixVertex = [generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.instancing ? '#define USE_INSTANCING' : '', parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', '#define GAMMA_FACTOR ' + gammaFactorDefine, '#define MAX_BONES ' + parameters.maxBones, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularTintMap ? '#define USE_SPECULARTINTMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.transmission ? '#define USE_TRANSMISSION' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', parameters.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');
  11297. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, '#define GAMMA_FACTOR ' + gammaFactorDefine, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.matcap ? '#define USE_MATCAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapTypeDefine : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.envMap ? '#define ' + envMapBlendingDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoat ? '#define USE_CLEARCOAT' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularTintMap ? '#define USE_SPECULARTINTMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.alphaTest ? '#define USE_ALPHATEST' : '', parameters.sheenTint ? '#define USE_SHEEN' : '', parameters.transmission ? '#define USE_TRANSMISSION' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '', parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', (parameters.extensionShaderTextureLOD || parameters.envMap) && parameters.rendererExtensionShaderTextureLod ? '#define TEXTURE_LOD_EXT' : '', 'uniform mat4 viewMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', parameters.toneMapping !== NoToneMapping ? '#define TONE_MAPPING' : '', parameters.toneMapping !== NoToneMapping ? ShaderChunk['tonemapping_pars_fragment'] : '', // this code is required here because it is used by the toneMapping() function defined below
  11298. parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', parameters.format === RGBFormat ? '#define OPAQUE' : '', ShaderChunk['encodings_pars_fragment'], // this code is required here because it is used by the various encoding/decoding function defined below
  11299. 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.specularTintMap ? getTexelDecodingFunction('specularTintMapTexelToLinear', parameters.specularTintMapEncoding) : '', parameters.lightMap ? getTexelDecodingFunction('lightMapTexelToLinear', parameters.lightMapEncoding) : '', getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  11300. }
  11301. vertexShader = resolveIncludes(vertexShader);
  11302. vertexShader = replaceLightNums(vertexShader, parameters);
  11303. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  11304. fragmentShader = resolveIncludes(fragmentShader);
  11305. fragmentShader = replaceLightNums(fragmentShader, parameters);
  11306. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  11307. vertexShader = unrollLoops(vertexShader);
  11308. fragmentShader = unrollLoops(fragmentShader);
  11309. if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
  11310. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11311. versionString = '#version 300 es\n';
  11312. prefixVertex = ['#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  11313. 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;
  11314. }
  11315. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11316. const fragmentGlsl = versionString + prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  11317. // console.log( '*FRAGMENT*', fragmentGlsl );
  11318. const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl);
  11319. const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl);
  11320. gl.attachShader(program, glVertexShader);
  11321. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  11322. if (parameters.index0AttributeName !== undefined) {
  11323. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  11324. } else if (parameters.morphTargets === true) {
  11325. // programs with morphTargets displace position out of attribute 0
  11326. gl.bindAttribLocation(program, 0, 'position');
  11327. }
  11328. gl.linkProgram(program); // check for link errors
  11329. if (renderer.debug.checkShaderErrors) {
  11330. const programLog = gl.getProgramInfoLog(program).trim();
  11331. const vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  11332. const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  11333. let runnable = true;
  11334. let haveDiagnostics = true;
  11335. if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {
  11336. runnable = false;
  11337. const vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  11338. const fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  11339. console.error('THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' + 'VALIDATE_STATUS ' + gl.getProgramParameter(program, gl.VALIDATE_STATUS) + '\n\n' + 'Program Info Log: ' + programLog + '\n' + vertexErrors + '\n' + fragmentErrors);
  11340. } else if (programLog !== '') {
  11341. console.warn('THREE.WebGLProgram: Program Info Log:', programLog);
  11342. } else if (vertexLog === '' || fragmentLog === '') {
  11343. haveDiagnostics = false;
  11344. }
  11345. if (haveDiagnostics) {
  11346. this.diagnostics = {
  11347. runnable: runnable,
  11348. programLog: programLog,
  11349. vertexShader: {
  11350. log: vertexLog,
  11351. prefix: prefixVertex
  11352. },
  11353. fragmentShader: {
  11354. log: fragmentLog,
  11355. prefix: prefixFragment
  11356. }
  11357. };
  11358. }
  11359. } // Clean up
  11360. // Crashes in iOS9 and iOS10. #18402
  11361. // gl.detachShader( program, glVertexShader );
  11362. // gl.detachShader( program, glFragmentShader );
  11363. gl.deleteShader(glVertexShader);
  11364. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  11365. let cachedUniforms;
  11366. this.getUniforms = function () {
  11367. if (cachedUniforms === undefined) {
  11368. cachedUniforms = new WebGLUniforms(gl, program);
  11369. }
  11370. return cachedUniforms;
  11371. }; // set up caching for attribute locations
  11372. let cachedAttributes;
  11373. this.getAttributes = function () {
  11374. if (cachedAttributes === undefined) {
  11375. cachedAttributes = fetchAttributeLocations(gl, program);
  11376. }
  11377. return cachedAttributes;
  11378. }; // free resource
  11379. this.destroy = function () {
  11380. bindingStates.releaseStatesOfProgram(this);
  11381. gl.deleteProgram(program);
  11382. this.program = undefined;
  11383. }; //
  11384. this.name = parameters.shaderName;
  11385. this.id = programIdCount++;
  11386. this.cacheKey = cacheKey;
  11387. this.usedTimes = 1;
  11388. this.program = program;
  11389. this.vertexShader = glVertexShader;
  11390. this.fragmentShader = glFragmentShader;
  11391. return this;
  11392. }
  11393. function WebGLPrograms(renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping) {
  11394. const programs = [];
  11395. const isWebGL2 = capabilities.isWebGL2;
  11396. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11397. const floatVertexTextures = capabilities.floatVertexTextures;
  11398. const maxVertexUniforms = capabilities.maxVertexUniforms;
  11399. const vertexTextures = capabilities.vertexTextures;
  11400. let precision = capabilities.precision;
  11401. const shaderIDs = {
  11402. MeshDepthMaterial: 'depth',
  11403. MeshDistanceMaterial: 'distanceRGBA',
  11404. MeshNormalMaterial: 'normal',
  11405. MeshBasicMaterial: 'basic',
  11406. MeshLambertMaterial: 'lambert',
  11407. MeshPhongMaterial: 'phong',
  11408. MeshToonMaterial: 'toon',
  11409. MeshStandardMaterial: 'physical',
  11410. MeshPhysicalMaterial: 'physical',
  11411. MeshMatcapMaterial: 'matcap',
  11412. LineBasicMaterial: 'basic',
  11413. LineDashedMaterial: 'dashed',
  11414. PointsMaterial: 'points',
  11415. ShadowMaterial: 'shadow',
  11416. SpriteMaterial: 'sprite'
  11417. };
  11418. 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', 'clearcoat', 'clearcoatMap', 'clearcoatRoughnessMap', 'clearcoatNormalMap', 'displacementMap', 'specularMap', 'specularIntensityMap', 'specularTintMap', 'specularTintMapEncoding', 'roughnessMap', 'metalnessMap', 'gradientMap', 'alphaMap', 'alphaTest', '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', 'doubleSided', 'flipSided', 'numClippingPlanes', 'numClipIntersection', 'depthPacking', 'dithering', 'format', 'sheenTint', 'transmission', 'transmissionMap', 'thicknessMap'];
  11419. function getMaxBones(object) {
  11420. const skeleton = object.skeleton;
  11421. const bones = skeleton.bones;
  11422. if (floatVertexTextures) {
  11423. return 1024;
  11424. } else {
  11425. // default for when object is not specified
  11426. // ( for example when prebuilding shader to be used with multiple objects )
  11427. //
  11428. // - leave some extra space for other uniforms
  11429. // - limit here is ANGLE's 254 max uniform vectors
  11430. // (up to 54 should be safe)
  11431. const nVertexUniforms = maxVertexUniforms;
  11432. const nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  11433. const maxBones = Math.min(nVertexMatrices, bones.length);
  11434. if (maxBones < bones.length) {
  11435. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  11436. return 0;
  11437. }
  11438. return maxBones;
  11439. }
  11440. }
  11441. function getTextureEncodingFromMap(map) {
  11442. let encoding;
  11443. if (map && map.isTexture) {
  11444. encoding = map.encoding;
  11445. } else if (map && map.isWebGLRenderTarget) {
  11446. console.warn('THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.');
  11447. encoding = map.texture.encoding;
  11448. } else {
  11449. encoding = LinearEncoding;
  11450. }
  11451. return encoding;
  11452. }
  11453. function getParameters(material, lights, shadows, scene, object) {
  11454. const fog = scene.fog;
  11455. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11456. const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
  11457. const shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  11458. // (not to blow over maxLights budget)
  11459. const maxBones = object.isSkinnedMesh ? getMaxBones(object) : 0;
  11460. if (material.precision !== null) {
  11461. precision = capabilities.getMaxPrecision(material.precision);
  11462. if (precision !== material.precision) {
  11463. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  11464. }
  11465. }
  11466. let vertexShader, fragmentShader;
  11467. if (shaderID) {
  11468. const shader = ShaderLib[shaderID];
  11469. vertexShader = shader.vertexShader;
  11470. fragmentShader = shader.fragmentShader;
  11471. } else {
  11472. vertexShader = material.vertexShader;
  11473. fragmentShader = material.fragmentShader;
  11474. }
  11475. const currentRenderTarget = renderer.getRenderTarget();
  11476. const useAlphaTest = material.alphaTest > 0;
  11477. const useClearcoat = material.clearcoat > 0;
  11478. const parameters = {
  11479. isWebGL2: isWebGL2,
  11480. shaderID: shaderID,
  11481. shaderName: material.type,
  11482. vertexShader: vertexShader,
  11483. fragmentShader: fragmentShader,
  11484. defines: material.defines,
  11485. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11486. glslVersion: material.glslVersion,
  11487. precision: precision,
  11488. instancing: object.isInstancedMesh === true,
  11489. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11490. supportsVertexTextures: vertexTextures,
  11491. outputEncoding: currentRenderTarget !== null ? getTextureEncodingFromMap(currentRenderTarget.texture) : renderer.outputEncoding,
  11492. map: !!material.map,
  11493. mapEncoding: getTextureEncodingFromMap(material.map),
  11494. matcap: !!material.matcap,
  11495. matcapEncoding: getTextureEncodingFromMap(material.matcap),
  11496. envMap: !!envMap,
  11497. envMapMode: envMap && envMap.mapping,
  11498. envMapEncoding: getTextureEncodingFromMap(envMap),
  11499. envMapCubeUV: !!envMap && (envMap.mapping === CubeUVReflectionMapping || envMap.mapping === CubeUVRefractionMapping),
  11500. lightMap: !!material.lightMap,
  11501. lightMapEncoding: getTextureEncodingFromMap(material.lightMap),
  11502. aoMap: !!material.aoMap,
  11503. emissiveMap: !!material.emissiveMap,
  11504. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap),
  11505. bumpMap: !!material.bumpMap,
  11506. normalMap: !!material.normalMap,
  11507. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11508. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11509. clearcoat: useClearcoat,
  11510. clearcoatMap: useClearcoat && !!material.clearcoatMap,
  11511. clearcoatRoughnessMap: useClearcoat && !!material.clearcoatRoughnessMap,
  11512. clearcoatNormalMap: useClearcoat && !!material.clearcoatNormalMap,
  11513. displacementMap: !!material.displacementMap,
  11514. roughnessMap: !!material.roughnessMap,
  11515. metalnessMap: !!material.metalnessMap,
  11516. specularMap: !!material.specularMap,
  11517. specularIntensityMap: !!material.specularIntensityMap,
  11518. specularTintMap: !!material.specularTintMap,
  11519. specularTintMapEncoding: getTextureEncodingFromMap(material.specularTintMap),
  11520. alphaMap: !!material.alphaMap,
  11521. alphaTest: useAlphaTest,
  11522. gradientMap: !!material.gradientMap,
  11523. sheenTint: !!material.sheenTint && (material.sheenTint.r > 0 || material.sheenTint.g > 0 || material.sheenTint.b > 0),
  11524. transmission: material.transmission > 0,
  11525. transmissionMap: !!material.transmissionMap,
  11526. thicknessMap: !!material.thicknessMap,
  11527. combine: material.combine,
  11528. vertexTangents: !!material.normalMap && !!object.geometry && !!object.geometry.attributes.tangent,
  11529. vertexColors: material.vertexColors,
  11530. vertexAlphas: material.vertexColors === true && !!object.geometry && !!object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4,
  11531. vertexUvs: !!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatMap || !!material.clearcoatRoughnessMap || !!material.clearcoatNormalMap || !!material.displacementMap || !!material.transmissionMap || !!material.thicknessMap || !!material.specularIntensityMap || !!material.specularTintMap,
  11532. uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap || material.transmission > 0 || !!material.transmissionMap || !!material.thicknessMap || !!material.specularIntensityMap || !!material.specularTintMap) && !!material.displacementMap,
  11533. fog: !!fog,
  11534. useFog: material.fog,
  11535. fogExp2: fog && fog.isFogExp2,
  11536. flatShading: !!material.flatShading,
  11537. sizeAttenuation: material.sizeAttenuation,
  11538. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11539. skinning: object.isSkinnedMesh === true && maxBones > 0,
  11540. maxBones: maxBones,
  11541. useVertexTexture: floatVertexTextures,
  11542. morphTargets: !!object.geometry && !!object.geometry.morphAttributes.position,
  11543. morphNormals: !!object.geometry && !!object.geometry.morphAttributes.normal,
  11544. numDirLights: lights.directional.length,
  11545. numPointLights: lights.point.length,
  11546. numSpotLights: lights.spot.length,
  11547. numRectAreaLights: lights.rectArea.length,
  11548. numHemiLights: lights.hemi.length,
  11549. numDirLightShadows: lights.directionalShadowMap.length,
  11550. numPointLightShadows: lights.pointShadowMap.length,
  11551. numSpotLightShadows: lights.spotShadowMap.length,
  11552. numClippingPlanes: clipping.numPlanes,
  11553. numClipIntersection: clipping.numIntersection,
  11554. format: material.format,
  11555. dithering: material.dithering,
  11556. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11557. shadowMapType: renderer.shadowMap.type,
  11558. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11559. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11560. premultipliedAlpha: material.premultipliedAlpha,
  11561. doubleSided: material.side === DoubleSide,
  11562. flipSided: material.side === BackSide,
  11563. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false,
  11564. index0AttributeName: material.index0AttributeName,
  11565. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11566. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11567. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11568. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11569. rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
  11570. rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
  11571. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
  11572. customProgramCacheKey: material.customProgramCacheKey()
  11573. };
  11574. return parameters;
  11575. }
  11576. function getProgramCacheKey(parameters) {
  11577. const array = [];
  11578. if (parameters.shaderID) {
  11579. array.push(parameters.shaderID);
  11580. } else {
  11581. array.push(parameters.fragmentShader);
  11582. array.push(parameters.vertexShader);
  11583. }
  11584. if (parameters.defines !== undefined) {
  11585. for (const name in parameters.defines) {
  11586. array.push(name);
  11587. array.push(parameters.defines[name]);
  11588. }
  11589. }
  11590. if (parameters.isRawShaderMaterial === false) {
  11591. for (let i = 0; i < parameterNames.length; i++) {
  11592. array.push(parameters[parameterNames[i]]);
  11593. }
  11594. array.push(renderer.outputEncoding);
  11595. array.push(renderer.gammaFactor);
  11596. }
  11597. array.push(parameters.customProgramCacheKey);
  11598. return array.join();
  11599. }
  11600. function getUniforms(material) {
  11601. const shaderID = shaderIDs[material.type];
  11602. let uniforms;
  11603. if (shaderID) {
  11604. const shader = ShaderLib[shaderID];
  11605. uniforms = UniformsUtils.clone(shader.uniforms);
  11606. } else {
  11607. uniforms = material.uniforms;
  11608. }
  11609. return uniforms;
  11610. }
  11611. function acquireProgram(parameters, cacheKey) {
  11612. let program; // Check if code has been already compiled
  11613. for (let p = 0, pl = programs.length; p < pl; p++) {
  11614. const preexistingProgram = programs[p];
  11615. if (preexistingProgram.cacheKey === cacheKey) {
  11616. program = preexistingProgram;
  11617. ++program.usedTimes;
  11618. break;
  11619. }
  11620. }
  11621. if (program === undefined) {
  11622. program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
  11623. programs.push(program);
  11624. }
  11625. return program;
  11626. }
  11627. function releaseProgram(program) {
  11628. if (--program.usedTimes === 0) {
  11629. // Remove from unordered set
  11630. const i = programs.indexOf(program);
  11631. programs[i] = programs[programs.length - 1];
  11632. programs.pop(); // Free WebGL resources
  11633. program.destroy();
  11634. }
  11635. }
  11636. return {
  11637. getParameters: getParameters,
  11638. getProgramCacheKey: getProgramCacheKey,
  11639. getUniforms: getUniforms,
  11640. acquireProgram: acquireProgram,
  11641. releaseProgram: releaseProgram,
  11642. // Exposed for resource monitoring & error feedback via renderer.info:
  11643. programs: programs
  11644. };
  11645. }
  11646. function WebGLProperties() {
  11647. let properties = new WeakMap();
  11648. function get(object) {
  11649. let map = properties.get(object);
  11650. if (map === undefined) {
  11651. map = {};
  11652. properties.set(object, map);
  11653. }
  11654. return map;
  11655. }
  11656. function remove(object) {
  11657. properties.delete(object);
  11658. }
  11659. function update(object, key, value) {
  11660. properties.get(object)[key] = value;
  11661. }
  11662. function dispose() {
  11663. properties = new WeakMap();
  11664. }
  11665. return {
  11666. get: get,
  11667. remove: remove,
  11668. update: update,
  11669. dispose: dispose
  11670. };
  11671. }
  11672. function painterSortStable(a, b) {
  11673. if (a.groupOrder !== b.groupOrder) {
  11674. return a.groupOrder - b.groupOrder;
  11675. } else if (a.renderOrder !== b.renderOrder) {
  11676. return a.renderOrder - b.renderOrder;
  11677. } else if (a.program !== b.program) {
  11678. return a.program.id - b.program.id;
  11679. } else if (a.material.id !== b.material.id) {
  11680. return a.material.id - b.material.id;
  11681. } else if (a.z !== b.z) {
  11682. return a.z - b.z;
  11683. } else {
  11684. return a.id - b.id;
  11685. }
  11686. }
  11687. function reversePainterSortStable(a, b) {
  11688. if (a.groupOrder !== b.groupOrder) {
  11689. return a.groupOrder - b.groupOrder;
  11690. } else if (a.renderOrder !== b.renderOrder) {
  11691. return a.renderOrder - b.renderOrder;
  11692. } else if (a.z !== b.z) {
  11693. return b.z - a.z;
  11694. } else {
  11695. return a.id - b.id;
  11696. }
  11697. }
  11698. function WebGLRenderList(properties) {
  11699. const renderItems = [];
  11700. let renderItemsIndex = 0;
  11701. const opaque = [];
  11702. const transmissive = [];
  11703. const transparent = [];
  11704. const defaultProgram = {
  11705. id: -1
  11706. };
  11707. function init() {
  11708. renderItemsIndex = 0;
  11709. opaque.length = 0;
  11710. transmissive.length = 0;
  11711. transparent.length = 0;
  11712. }
  11713. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  11714. let renderItem = renderItems[renderItemsIndex];
  11715. const materialProperties = properties.get(material);
  11716. if (renderItem === undefined) {
  11717. renderItem = {
  11718. id: object.id,
  11719. object: object,
  11720. geometry: geometry,
  11721. material: material,
  11722. program: materialProperties.program || defaultProgram,
  11723. groupOrder: groupOrder,
  11724. renderOrder: object.renderOrder,
  11725. z: z,
  11726. group: group
  11727. };
  11728. renderItems[renderItemsIndex] = renderItem;
  11729. } else {
  11730. renderItem.id = object.id;
  11731. renderItem.object = object;
  11732. renderItem.geometry = geometry;
  11733. renderItem.material = material;
  11734. renderItem.program = materialProperties.program || defaultProgram;
  11735. renderItem.groupOrder = groupOrder;
  11736. renderItem.renderOrder = object.renderOrder;
  11737. renderItem.z = z;
  11738. renderItem.group = group;
  11739. }
  11740. renderItemsIndex++;
  11741. return renderItem;
  11742. }
  11743. function push(object, geometry, material, groupOrder, z, group) {
  11744. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  11745. if (material.transmission > 0.0) {
  11746. transmissive.push(renderItem);
  11747. } else if (material.transparent === true) {
  11748. transparent.push(renderItem);
  11749. } else {
  11750. opaque.push(renderItem);
  11751. }
  11752. }
  11753. function unshift(object, geometry, material, groupOrder, z, group) {
  11754. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  11755. if (material.transmission > 0.0) {
  11756. transmissive.unshift(renderItem);
  11757. } else if (material.transparent === true) {
  11758. transparent.unshift(renderItem);
  11759. } else {
  11760. opaque.unshift(renderItem);
  11761. }
  11762. }
  11763. function sort(customOpaqueSort, customTransparentSort) {
  11764. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  11765. if (transmissive.length > 1) transmissive.sort(customTransparentSort || reversePainterSortStable);
  11766. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  11767. }
  11768. function finish() {
  11769. // Clear references from inactive renderItems in the list
  11770. for (let i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  11771. const renderItem = renderItems[i];
  11772. if (renderItem.id === null) break;
  11773. renderItem.id = null;
  11774. renderItem.object = null;
  11775. renderItem.geometry = null;
  11776. renderItem.material = null;
  11777. renderItem.program = null;
  11778. renderItem.group = null;
  11779. }
  11780. }
  11781. return {
  11782. opaque: opaque,
  11783. transmissive: transmissive,
  11784. transparent: transparent,
  11785. init: init,
  11786. push: push,
  11787. unshift: unshift,
  11788. finish: finish,
  11789. sort: sort
  11790. };
  11791. }
  11792. function WebGLRenderLists(properties) {
  11793. let lists = new WeakMap();
  11794. function get(scene, renderCallDepth) {
  11795. let list;
  11796. if (lists.has(scene) === false) {
  11797. list = new WebGLRenderList(properties);
  11798. lists.set(scene, [list]);
  11799. } else {
  11800. if (renderCallDepth >= lists.get(scene).length) {
  11801. list = new WebGLRenderList(properties);
  11802. lists.get(scene).push(list);
  11803. } else {
  11804. list = lists.get(scene)[renderCallDepth];
  11805. }
  11806. }
  11807. return list;
  11808. }
  11809. function dispose() {
  11810. lists = new WeakMap();
  11811. }
  11812. return {
  11813. get: get,
  11814. dispose: dispose
  11815. };
  11816. }
  11817. function UniformsCache() {
  11818. const lights = {};
  11819. return {
  11820. get: function (light) {
  11821. if (lights[light.id] !== undefined) {
  11822. return lights[light.id];
  11823. }
  11824. let uniforms;
  11825. switch (light.type) {
  11826. case 'DirectionalLight':
  11827. uniforms = {
  11828. direction: new Vector3(),
  11829. color: new Color()
  11830. };
  11831. break;
  11832. case 'SpotLight':
  11833. uniforms = {
  11834. position: new Vector3(),
  11835. direction: new Vector3(),
  11836. color: new Color(),
  11837. distance: 0,
  11838. coneCos: 0,
  11839. penumbraCos: 0,
  11840. decay: 0
  11841. };
  11842. break;
  11843. case 'PointLight':
  11844. uniforms = {
  11845. position: new Vector3(),
  11846. color: new Color(),
  11847. distance: 0,
  11848. decay: 0
  11849. };
  11850. break;
  11851. case 'HemisphereLight':
  11852. uniforms = {
  11853. direction: new Vector3(),
  11854. skyColor: new Color(),
  11855. groundColor: new Color()
  11856. };
  11857. break;
  11858. case 'RectAreaLight':
  11859. uniforms = {
  11860. color: new Color(),
  11861. position: new Vector3(),
  11862. halfWidth: new Vector3(),
  11863. halfHeight: new Vector3()
  11864. };
  11865. break;
  11866. }
  11867. lights[light.id] = uniforms;
  11868. return uniforms;
  11869. }
  11870. };
  11871. }
  11872. function ShadowUniformsCache() {
  11873. const lights = {};
  11874. return {
  11875. get: function (light) {
  11876. if (lights[light.id] !== undefined) {
  11877. return lights[light.id];
  11878. }
  11879. let uniforms;
  11880. switch (light.type) {
  11881. case 'DirectionalLight':
  11882. uniforms = {
  11883. shadowBias: 0,
  11884. shadowNormalBias: 0,
  11885. shadowRadius: 1,
  11886. shadowMapSize: new Vector2()
  11887. };
  11888. break;
  11889. case 'SpotLight':
  11890. uniforms = {
  11891. shadowBias: 0,
  11892. shadowNormalBias: 0,
  11893. shadowRadius: 1,
  11894. shadowMapSize: new Vector2()
  11895. };
  11896. break;
  11897. case 'PointLight':
  11898. uniforms = {
  11899. shadowBias: 0,
  11900. shadowNormalBias: 0,
  11901. shadowRadius: 1,
  11902. shadowMapSize: new Vector2(),
  11903. shadowCameraNear: 1,
  11904. shadowCameraFar: 1000
  11905. };
  11906. break;
  11907. // TODO (abelnation): set RectAreaLight shadow uniforms
  11908. }
  11909. lights[light.id] = uniforms;
  11910. return uniforms;
  11911. }
  11912. };
  11913. }
  11914. let nextVersion = 0;
  11915. function shadowCastingLightsFirst(lightA, lightB) {
  11916. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  11917. }
  11918. function WebGLLights(extensions, capabilities) {
  11919. const cache = new UniformsCache();
  11920. const shadowCache = ShadowUniformsCache();
  11921. const state = {
  11922. version: 0,
  11923. hash: {
  11924. directionalLength: -1,
  11925. pointLength: -1,
  11926. spotLength: -1,
  11927. rectAreaLength: -1,
  11928. hemiLength: -1,
  11929. numDirectionalShadows: -1,
  11930. numPointShadows: -1,
  11931. numSpotShadows: -1
  11932. },
  11933. ambient: [0, 0, 0],
  11934. probe: [],
  11935. directional: [],
  11936. directionalShadow: [],
  11937. directionalShadowMap: [],
  11938. directionalShadowMatrix: [],
  11939. spot: [],
  11940. spotShadow: [],
  11941. spotShadowMap: [],
  11942. spotShadowMatrix: [],
  11943. rectArea: [],
  11944. rectAreaLTC1: null,
  11945. rectAreaLTC2: null,
  11946. point: [],
  11947. pointShadow: [],
  11948. pointShadowMap: [],
  11949. pointShadowMatrix: [],
  11950. hemi: []
  11951. };
  11952. for (let i = 0; i < 9; i++) state.probe.push(new Vector3());
  11953. const vector3 = new Vector3();
  11954. const matrix4 = new Matrix4();
  11955. const matrix42 = new Matrix4();
  11956. function setup(lights, physicallyCorrectLights) {
  11957. let r = 0,
  11958. g = 0,
  11959. b = 0;
  11960. for (let i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  11961. let directionalLength = 0;
  11962. let pointLength = 0;
  11963. let spotLength = 0;
  11964. let rectAreaLength = 0;
  11965. let hemiLength = 0;
  11966. let numDirectionalShadows = 0;
  11967. let numPointShadows = 0;
  11968. let numSpotShadows = 0;
  11969. lights.sort(shadowCastingLightsFirst); // artist-friendly light intensity scaling factor
  11970. const scaleFactor = physicallyCorrectLights !== true ? Math.PI : 1;
  11971. for (let i = 0, l = lights.length; i < l; i++) {
  11972. const light = lights[i];
  11973. const color = light.color;
  11974. const intensity = light.intensity;
  11975. const distance = light.distance;
  11976. const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  11977. if (light.isAmbientLight) {
  11978. r += color.r * intensity * scaleFactor;
  11979. g += color.g * intensity * scaleFactor;
  11980. b += color.b * intensity * scaleFactor;
  11981. } else if (light.isLightProbe) {
  11982. for (let j = 0; j < 9; j++) {
  11983. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  11984. }
  11985. } else if (light.isDirectionalLight) {
  11986. const uniforms = cache.get(light);
  11987. uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
  11988. if (light.castShadow) {
  11989. const shadow = light.shadow;
  11990. const shadowUniforms = shadowCache.get(light);
  11991. shadowUniforms.shadowBias = shadow.bias;
  11992. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11993. shadowUniforms.shadowRadius = shadow.radius;
  11994. shadowUniforms.shadowMapSize = shadow.mapSize;
  11995. state.directionalShadow[directionalLength] = shadowUniforms;
  11996. state.directionalShadowMap[directionalLength] = shadowMap;
  11997. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  11998. numDirectionalShadows++;
  11999. }
  12000. state.directional[directionalLength] = uniforms;
  12001. directionalLength++;
  12002. } else if (light.isSpotLight) {
  12003. const uniforms = cache.get(light);
  12004. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12005. uniforms.color.copy(color).multiplyScalar(intensity * scaleFactor);
  12006. uniforms.distance = distance;
  12007. uniforms.coneCos = Math.cos(light.angle);
  12008. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  12009. uniforms.decay = light.decay;
  12010. if (light.castShadow) {
  12011. const shadow = light.shadow;
  12012. const shadowUniforms = shadowCache.get(light);
  12013. shadowUniforms.shadowBias = shadow.bias;
  12014. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12015. shadowUniforms.shadowRadius = shadow.radius;
  12016. shadowUniforms.shadowMapSize = shadow.mapSize;
  12017. state.spotShadow[spotLength] = shadowUniforms;
  12018. state.spotShadowMap[spotLength] = shadowMap;
  12019. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  12020. numSpotShadows++;
  12021. }
  12022. state.spot[spotLength] = uniforms;
  12023. spotLength++;
  12024. } else if (light.isRectAreaLight) {
  12025. const uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  12026. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  12027. // (b) intensity is the brightness of the light
  12028. uniforms.color.copy(color).multiplyScalar(intensity);
  12029. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12030. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12031. state.rectArea[rectAreaLength] = uniforms;
  12032. rectAreaLength++;
  12033. } else if (light.isPointLight) {
  12034. const uniforms = cache.get(light);
  12035. uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
  12036. uniforms.distance = light.distance;
  12037. uniforms.decay = light.decay;
  12038. if (light.castShadow) {
  12039. const shadow = light.shadow;
  12040. const shadowUniforms = shadowCache.get(light);
  12041. shadowUniforms.shadowBias = shadow.bias;
  12042. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12043. shadowUniforms.shadowRadius = shadow.radius;
  12044. shadowUniforms.shadowMapSize = shadow.mapSize;
  12045. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12046. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12047. state.pointShadow[pointLength] = shadowUniforms;
  12048. state.pointShadowMap[pointLength] = shadowMap;
  12049. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  12050. numPointShadows++;
  12051. }
  12052. state.point[pointLength] = uniforms;
  12053. pointLength++;
  12054. } else if (light.isHemisphereLight) {
  12055. const uniforms = cache.get(light);
  12056. uniforms.skyColor.copy(light.color).multiplyScalar(intensity * scaleFactor);
  12057. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity * scaleFactor);
  12058. state.hemi[hemiLength] = uniforms;
  12059. hemiLength++;
  12060. }
  12061. }
  12062. if (rectAreaLength > 0) {
  12063. if (capabilities.isWebGL2) {
  12064. // WebGL 2
  12065. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12066. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12067. } else {
  12068. // WebGL 1
  12069. if (extensions.has('OES_texture_float_linear') === true) {
  12070. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12071. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12072. } else if (extensions.has('OES_texture_half_float_linear') === true) {
  12073. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12074. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12075. } else {
  12076. console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
  12077. }
  12078. }
  12079. }
  12080. state.ambient[0] = r;
  12081. state.ambient[1] = g;
  12082. state.ambient[2] = b;
  12083. const hash = state.hash;
  12084. 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) {
  12085. state.directional.length = directionalLength;
  12086. state.spot.length = spotLength;
  12087. state.rectArea.length = rectAreaLength;
  12088. state.point.length = pointLength;
  12089. state.hemi.length = hemiLength;
  12090. state.directionalShadow.length = numDirectionalShadows;
  12091. state.directionalShadowMap.length = numDirectionalShadows;
  12092. state.pointShadow.length = numPointShadows;
  12093. state.pointShadowMap.length = numPointShadows;
  12094. state.spotShadow.length = numSpotShadows;
  12095. state.spotShadowMap.length = numSpotShadows;
  12096. state.directionalShadowMatrix.length = numDirectionalShadows;
  12097. state.pointShadowMatrix.length = numPointShadows;
  12098. state.spotShadowMatrix.length = numSpotShadows;
  12099. hash.directionalLength = directionalLength;
  12100. hash.pointLength = pointLength;
  12101. hash.spotLength = spotLength;
  12102. hash.rectAreaLength = rectAreaLength;
  12103. hash.hemiLength = hemiLength;
  12104. hash.numDirectionalShadows = numDirectionalShadows;
  12105. hash.numPointShadows = numPointShadows;
  12106. hash.numSpotShadows = numSpotShadows;
  12107. state.version = nextVersion++;
  12108. }
  12109. }
  12110. function setupView(lights, camera) {
  12111. let directionalLength = 0;
  12112. let pointLength = 0;
  12113. let spotLength = 0;
  12114. let rectAreaLength = 0;
  12115. let hemiLength = 0;
  12116. const viewMatrix = camera.matrixWorldInverse;
  12117. for (let i = 0, l = lights.length; i < l; i++) {
  12118. const light = lights[i];
  12119. if (light.isDirectionalLight) {
  12120. const uniforms = state.directional[directionalLength];
  12121. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12122. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12123. uniforms.direction.sub(vector3);
  12124. uniforms.direction.transformDirection(viewMatrix);
  12125. directionalLength++;
  12126. } else if (light.isSpotLight) {
  12127. const uniforms = state.spot[spotLength];
  12128. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12129. uniforms.position.applyMatrix4(viewMatrix);
  12130. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12131. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12132. uniforms.direction.sub(vector3);
  12133. uniforms.direction.transformDirection(viewMatrix);
  12134. spotLength++;
  12135. } else if (light.isRectAreaLight) {
  12136. const uniforms = state.rectArea[rectAreaLength];
  12137. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12138. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  12139. matrix42.identity();
  12140. matrix4.copy(light.matrixWorld);
  12141. matrix4.premultiply(viewMatrix);
  12142. matrix42.extractRotation(matrix4);
  12143. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12144. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12145. uniforms.halfWidth.applyMatrix4(matrix42);
  12146. uniforms.halfHeight.applyMatrix4(matrix42);
  12147. rectAreaLength++;
  12148. } else if (light.isPointLight) {
  12149. const uniforms = state.point[pointLength];
  12150. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12151. uniforms.position.applyMatrix4(viewMatrix);
  12152. pointLength++;
  12153. } else if (light.isHemisphereLight) {
  12154. const uniforms = state.hemi[hemiLength];
  12155. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12156. uniforms.direction.transformDirection(viewMatrix);
  12157. uniforms.direction.normalize();
  12158. hemiLength++;
  12159. }
  12160. }
  12161. }
  12162. return {
  12163. setup: setup,
  12164. setupView: setupView,
  12165. state: state
  12166. };
  12167. }
  12168. function WebGLRenderState(extensions, capabilities) {
  12169. const lights = new WebGLLights(extensions, capabilities);
  12170. const lightsArray = [];
  12171. const shadowsArray = [];
  12172. function init() {
  12173. lightsArray.length = 0;
  12174. shadowsArray.length = 0;
  12175. }
  12176. function pushLight(light) {
  12177. lightsArray.push(light);
  12178. }
  12179. function pushShadow(shadowLight) {
  12180. shadowsArray.push(shadowLight);
  12181. }
  12182. function setupLights(physicallyCorrectLights) {
  12183. lights.setup(lightsArray, physicallyCorrectLights);
  12184. }
  12185. function setupLightsView(camera) {
  12186. lights.setupView(lightsArray, camera);
  12187. }
  12188. const state = {
  12189. lightsArray: lightsArray,
  12190. shadowsArray: shadowsArray,
  12191. lights: lights
  12192. };
  12193. return {
  12194. init: init,
  12195. state: state,
  12196. setupLights: setupLights,
  12197. setupLightsView: setupLightsView,
  12198. pushLight: pushLight,
  12199. pushShadow: pushShadow
  12200. };
  12201. }
  12202. function WebGLRenderStates(extensions, capabilities) {
  12203. let renderStates = new WeakMap();
  12204. function get(scene, renderCallDepth = 0) {
  12205. let renderState;
  12206. if (renderStates.has(scene) === false) {
  12207. renderState = new WebGLRenderState(extensions, capabilities);
  12208. renderStates.set(scene, [renderState]);
  12209. } else {
  12210. if (renderCallDepth >= renderStates.get(scene).length) {
  12211. renderState = new WebGLRenderState(extensions, capabilities);
  12212. renderStates.get(scene).push(renderState);
  12213. } else {
  12214. renderState = renderStates.get(scene)[renderCallDepth];
  12215. }
  12216. }
  12217. return renderState;
  12218. }
  12219. function dispose() {
  12220. renderStates = new WeakMap();
  12221. }
  12222. return {
  12223. get: get,
  12224. dispose: dispose
  12225. };
  12226. }
  12227. /**
  12228. * parameters = {
  12229. *
  12230. * opacity: <float>,
  12231. *
  12232. * map: new THREE.Texture( <Image> ),
  12233. *
  12234. * alphaMap: new THREE.Texture( <Image> ),
  12235. *
  12236. * displacementMap: new THREE.Texture( <Image> ),
  12237. * displacementScale: <float>,
  12238. * displacementBias: <float>,
  12239. *
  12240. * wireframe: <boolean>,
  12241. * wireframeLinewidth: <float>
  12242. * }
  12243. */
  12244. class MeshDepthMaterial extends Material {
  12245. constructor(parameters) {
  12246. super();
  12247. this.type = 'MeshDepthMaterial';
  12248. this.depthPacking = BasicDepthPacking;
  12249. this.map = null;
  12250. this.alphaMap = null;
  12251. this.displacementMap = null;
  12252. this.displacementScale = 1;
  12253. this.displacementBias = 0;
  12254. this.wireframe = false;
  12255. this.wireframeLinewidth = 1;
  12256. this.fog = false;
  12257. this.setValues(parameters);
  12258. }
  12259. copy(source) {
  12260. super.copy(source);
  12261. this.depthPacking = source.depthPacking;
  12262. this.map = source.map;
  12263. this.alphaMap = source.alphaMap;
  12264. this.displacementMap = source.displacementMap;
  12265. this.displacementScale = source.displacementScale;
  12266. this.displacementBias = source.displacementBias;
  12267. this.wireframe = source.wireframe;
  12268. this.wireframeLinewidth = source.wireframeLinewidth;
  12269. return this;
  12270. }
  12271. }
  12272. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  12273. /**
  12274. * parameters = {
  12275. *
  12276. * referencePosition: <float>,
  12277. * nearDistance: <float>,
  12278. * farDistance: <float>,
  12279. *
  12280. * map: new THREE.Texture( <Image> ),
  12281. *
  12282. * alphaMap: new THREE.Texture( <Image> ),
  12283. *
  12284. * displacementMap: new THREE.Texture( <Image> ),
  12285. * displacementScale: <float>,
  12286. * displacementBias: <float>
  12287. *
  12288. * }
  12289. */
  12290. class MeshDistanceMaterial extends Material {
  12291. constructor(parameters) {
  12292. super();
  12293. this.type = 'MeshDistanceMaterial';
  12294. this.referencePosition = new Vector3();
  12295. this.nearDistance = 1;
  12296. this.farDistance = 1000;
  12297. this.map = null;
  12298. this.alphaMap = null;
  12299. this.displacementMap = null;
  12300. this.displacementScale = 1;
  12301. this.displacementBias = 0;
  12302. this.fog = false;
  12303. this.setValues(parameters);
  12304. }
  12305. copy(source) {
  12306. super.copy(source);
  12307. this.referencePosition.copy(source.referencePosition);
  12308. this.nearDistance = source.nearDistance;
  12309. this.farDistance = source.farDistance;
  12310. this.map = source.map;
  12311. this.alphaMap = source.alphaMap;
  12312. this.displacementMap = source.displacementMap;
  12313. this.displacementScale = source.displacementScale;
  12314. this.displacementBias = source.displacementBias;
  12315. return this;
  12316. }
  12317. }
  12318. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  12319. var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\nuniform float samples;\n#include <packing>\nvoid main() {\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  12320. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12321. function WebGLShadowMap(_renderer, _objects, _capabilities) {
  12322. let _frustum = new Frustum();
  12323. const _shadowMapSize = new Vector2(),
  12324. _viewportSize = new Vector2(),
  12325. _viewport = new Vector4(),
  12326. _depthMaterial = new MeshDepthMaterial({
  12327. depthPacking: RGBADepthPacking
  12328. }),
  12329. _distanceMaterial = new MeshDistanceMaterial(),
  12330. _materialCache = {},
  12331. _maxTextureSize = _capabilities.maxTextureSize;
  12332. const shadowSide = {
  12333. 0: BackSide,
  12334. 1: FrontSide,
  12335. 2: DoubleSide
  12336. };
  12337. const shadowMaterialVertical = new ShaderMaterial({
  12338. uniforms: {
  12339. shadow_pass: {
  12340. value: null
  12341. },
  12342. resolution: {
  12343. value: new Vector2()
  12344. },
  12345. radius: {
  12346. value: 4.0
  12347. },
  12348. samples: {
  12349. value: 8.0
  12350. }
  12351. },
  12352. vertexShader: vsm_vert,
  12353. fragmentShader: vsm_frag
  12354. });
  12355. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12356. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12357. const fullScreenTri = new BufferGeometry();
  12358. fullScreenTri.setAttribute('position', new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  12359. const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  12360. const scope = this;
  12361. this.enabled = false;
  12362. this.autoUpdate = true;
  12363. this.needsUpdate = false;
  12364. this.type = PCFShadowMap;
  12365. this.render = function (lights, scene, camera) {
  12366. if (scope.enabled === false) return;
  12367. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  12368. if (lights.length === 0) return;
  12369. const currentRenderTarget = _renderer.getRenderTarget();
  12370. const activeCubeFace = _renderer.getActiveCubeFace();
  12371. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12372. const _state = _renderer.state; // Set GL state for depth map.
  12373. _state.setBlending(NoBlending);
  12374. _state.buffers.color.setClear(1, 1, 1, 1);
  12375. _state.buffers.depth.setTest(true);
  12376. _state.setScissorTest(false); // render depth map
  12377. for (let i = 0, il = lights.length; i < il; i++) {
  12378. const light = lights[i];
  12379. const shadow = light.shadow;
  12380. if (shadow === undefined) {
  12381. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  12382. continue;
  12383. }
  12384. if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
  12385. _shadowMapSize.copy(shadow.mapSize);
  12386. const shadowFrameExtents = shadow.getFrameExtents();
  12387. _shadowMapSize.multiply(shadowFrameExtents);
  12388. _viewportSize.copy(shadow.mapSize);
  12389. if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) {
  12390. if (_shadowMapSize.x > _maxTextureSize) {
  12391. _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x);
  12392. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12393. shadow.mapSize.x = _viewportSize.x;
  12394. }
  12395. if (_shadowMapSize.y > _maxTextureSize) {
  12396. _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y);
  12397. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12398. shadow.mapSize.y = _viewportSize.y;
  12399. }
  12400. }
  12401. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12402. const pars = {
  12403. minFilter: LinearFilter,
  12404. magFilter: LinearFilter,
  12405. format: RGBAFormat
  12406. };
  12407. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12408. shadow.map.texture.name = light.name + '.shadowMap';
  12409. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12410. shadow.camera.updateProjectionMatrix();
  12411. }
  12412. if (shadow.map === null) {
  12413. const pars = {
  12414. minFilter: NearestFilter,
  12415. magFilter: NearestFilter,
  12416. format: RGBAFormat
  12417. };
  12418. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12419. shadow.map.texture.name = light.name + '.shadowMap';
  12420. shadow.camera.updateProjectionMatrix();
  12421. }
  12422. _renderer.setRenderTarget(shadow.map);
  12423. _renderer.clear();
  12424. const viewportCount = shadow.getViewportCount();
  12425. for (let vp = 0; vp < viewportCount; vp++) {
  12426. const viewport = shadow.getViewport(vp);
  12427. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  12428. _state.viewport(_viewport);
  12429. shadow.updateMatrices(light, vp);
  12430. _frustum = shadow.getFrustum();
  12431. renderObject(scene, camera, shadow.camera, light, this.type);
  12432. } // do blur pass for VSM
  12433. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12434. VSMPass(shadow, camera);
  12435. }
  12436. shadow.needsUpdate = false;
  12437. }
  12438. scope.needsUpdate = false;
  12439. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  12440. };
  12441. function VSMPass(shadow, camera) {
  12442. const geometry = _objects.update(fullScreenMesh); // vertical pass
  12443. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12444. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12445. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12446. shadowMaterialVertical.uniforms.samples.value = shadow.blurSamples;
  12447. _renderer.setRenderTarget(shadow.mapPass);
  12448. _renderer.clear();
  12449. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizontal pass
  12450. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12451. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12452. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12453. shadowMaterialHorizontal.uniforms.samples.value = shadow.blurSamples;
  12454. _renderer.setRenderTarget(shadow.map);
  12455. _renderer.clear();
  12456. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null);
  12457. }
  12458. function getDepthMaterial(object, geometry, material, light, shadowCameraNear, shadowCameraFar, type) {
  12459. let result = null;
  12460. const customMaterial = light.isPointLight === true ? object.customDistanceMaterial : object.customDepthMaterial;
  12461. if (customMaterial !== undefined) {
  12462. result = customMaterial;
  12463. } else {
  12464. result = light.isPointLight === true ? _distanceMaterial : _depthMaterial;
  12465. }
  12466. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0 || material.displacementMap && material.displacementScale !== 0 || material.alphaMap && material.alphaTest > 0) {
  12467. // in this case we need a unique material instance reflecting the
  12468. // appropriate state
  12469. const keyA = result.uuid,
  12470. keyB = material.uuid;
  12471. let materialsForVariant = _materialCache[keyA];
  12472. if (materialsForVariant === undefined) {
  12473. materialsForVariant = {};
  12474. _materialCache[keyA] = materialsForVariant;
  12475. }
  12476. let cachedMaterial = materialsForVariant[keyB];
  12477. if (cachedMaterial === undefined) {
  12478. cachedMaterial = result.clone();
  12479. materialsForVariant[keyB] = cachedMaterial;
  12480. }
  12481. result = cachedMaterial;
  12482. }
  12483. result.visible = material.visible;
  12484. result.wireframe = material.wireframe;
  12485. if (type === VSMShadowMap) {
  12486. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  12487. } else {
  12488. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  12489. }
  12490. result.alphaMap = material.alphaMap;
  12491. result.alphaTest = material.alphaTest;
  12492. result.clipShadows = material.clipShadows;
  12493. result.clippingPlanes = material.clippingPlanes;
  12494. result.clipIntersection = material.clipIntersection;
  12495. result.displacementMap = material.displacementMap;
  12496. result.displacementScale = material.displacementScale;
  12497. result.displacementBias = material.displacementBias;
  12498. result.wireframeLinewidth = material.wireframeLinewidth;
  12499. result.linewidth = material.linewidth;
  12500. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  12501. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  12502. result.nearDistance = shadowCameraNear;
  12503. result.farDistance = shadowCameraFar;
  12504. }
  12505. return result;
  12506. }
  12507. function renderObject(object, camera, shadowCamera, light, type) {
  12508. if (object.visible === false) return;
  12509. const visible = object.layers.test(camera.layers);
  12510. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  12511. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  12512. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  12513. const geometry = _objects.update(object);
  12514. const material = object.material;
  12515. if (Array.isArray(material)) {
  12516. const groups = geometry.groups;
  12517. for (let k = 0, kl = groups.length; k < kl; k++) {
  12518. const group = groups[k];
  12519. const groupMaterial = material[group.materialIndex];
  12520. if (groupMaterial && groupMaterial.visible) {
  12521. const depthMaterial = getDepthMaterial(object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  12522. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  12523. }
  12524. }
  12525. } else if (material.visible) {
  12526. const depthMaterial = getDepthMaterial(object, geometry, material, light, shadowCamera.near, shadowCamera.far, type);
  12527. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  12528. }
  12529. }
  12530. }
  12531. const children = object.children;
  12532. for (let i = 0, l = children.length; i < l; i++) {
  12533. renderObject(children[i], camera, shadowCamera, light, type);
  12534. }
  12535. }
  12536. }
  12537. function WebGLState(gl, extensions, capabilities) {
  12538. const isWebGL2 = capabilities.isWebGL2;
  12539. function ColorBuffer() {
  12540. let locked = false;
  12541. const color = new Vector4();
  12542. let currentColorMask = null;
  12543. const currentColorClear = new Vector4(0, 0, 0, 0);
  12544. return {
  12545. setMask: function (colorMask) {
  12546. if (currentColorMask !== colorMask && !locked) {
  12547. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  12548. currentColorMask = colorMask;
  12549. }
  12550. },
  12551. setLocked: function (lock) {
  12552. locked = lock;
  12553. },
  12554. setClear: function (r, g, b, a, premultipliedAlpha) {
  12555. if (premultipliedAlpha === true) {
  12556. r *= a;
  12557. g *= a;
  12558. b *= a;
  12559. }
  12560. color.set(r, g, b, a);
  12561. if (currentColorClear.equals(color) === false) {
  12562. gl.clearColor(r, g, b, a);
  12563. currentColorClear.copy(color);
  12564. }
  12565. },
  12566. reset: function () {
  12567. locked = false;
  12568. currentColorMask = null;
  12569. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  12570. }
  12571. };
  12572. }
  12573. function DepthBuffer() {
  12574. let locked = false;
  12575. let currentDepthMask = null;
  12576. let currentDepthFunc = null;
  12577. let currentDepthClear = null;
  12578. return {
  12579. setTest: function (depthTest) {
  12580. if (depthTest) {
  12581. enable(gl.DEPTH_TEST);
  12582. } else {
  12583. disable(gl.DEPTH_TEST);
  12584. }
  12585. },
  12586. setMask: function (depthMask) {
  12587. if (currentDepthMask !== depthMask && !locked) {
  12588. gl.depthMask(depthMask);
  12589. currentDepthMask = depthMask;
  12590. }
  12591. },
  12592. setFunc: function (depthFunc) {
  12593. if (currentDepthFunc !== depthFunc) {
  12594. if (depthFunc) {
  12595. switch (depthFunc) {
  12596. case NeverDepth:
  12597. gl.depthFunc(gl.NEVER);
  12598. break;
  12599. case AlwaysDepth:
  12600. gl.depthFunc(gl.ALWAYS);
  12601. break;
  12602. case LessDepth:
  12603. gl.depthFunc(gl.LESS);
  12604. break;
  12605. case LessEqualDepth:
  12606. gl.depthFunc(gl.LEQUAL);
  12607. break;
  12608. case EqualDepth:
  12609. gl.depthFunc(gl.EQUAL);
  12610. break;
  12611. case GreaterEqualDepth:
  12612. gl.depthFunc(gl.GEQUAL);
  12613. break;
  12614. case GreaterDepth:
  12615. gl.depthFunc(gl.GREATER);
  12616. break;
  12617. case NotEqualDepth:
  12618. gl.depthFunc(gl.NOTEQUAL);
  12619. break;
  12620. default:
  12621. gl.depthFunc(gl.LEQUAL);
  12622. }
  12623. } else {
  12624. gl.depthFunc(gl.LEQUAL);
  12625. }
  12626. currentDepthFunc = depthFunc;
  12627. }
  12628. },
  12629. setLocked: function (lock) {
  12630. locked = lock;
  12631. },
  12632. setClear: function (depth) {
  12633. if (currentDepthClear !== depth) {
  12634. gl.clearDepth(depth);
  12635. currentDepthClear = depth;
  12636. }
  12637. },
  12638. reset: function () {
  12639. locked = false;
  12640. currentDepthMask = null;
  12641. currentDepthFunc = null;
  12642. currentDepthClear = null;
  12643. }
  12644. };
  12645. }
  12646. function StencilBuffer() {
  12647. let locked = false;
  12648. let currentStencilMask = null;
  12649. let currentStencilFunc = null;
  12650. let currentStencilRef = null;
  12651. let currentStencilFuncMask = null;
  12652. let currentStencilFail = null;
  12653. let currentStencilZFail = null;
  12654. let currentStencilZPass = null;
  12655. let currentStencilClear = null;
  12656. return {
  12657. setTest: function (stencilTest) {
  12658. if (!locked) {
  12659. if (stencilTest) {
  12660. enable(gl.STENCIL_TEST);
  12661. } else {
  12662. disable(gl.STENCIL_TEST);
  12663. }
  12664. }
  12665. },
  12666. setMask: function (stencilMask) {
  12667. if (currentStencilMask !== stencilMask && !locked) {
  12668. gl.stencilMask(stencilMask);
  12669. currentStencilMask = stencilMask;
  12670. }
  12671. },
  12672. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  12673. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  12674. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  12675. currentStencilFunc = stencilFunc;
  12676. currentStencilRef = stencilRef;
  12677. currentStencilFuncMask = stencilMask;
  12678. }
  12679. },
  12680. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  12681. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  12682. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  12683. currentStencilFail = stencilFail;
  12684. currentStencilZFail = stencilZFail;
  12685. currentStencilZPass = stencilZPass;
  12686. }
  12687. },
  12688. setLocked: function (lock) {
  12689. locked = lock;
  12690. },
  12691. setClear: function (stencil) {
  12692. if (currentStencilClear !== stencil) {
  12693. gl.clearStencil(stencil);
  12694. currentStencilClear = stencil;
  12695. }
  12696. },
  12697. reset: function () {
  12698. locked = false;
  12699. currentStencilMask = null;
  12700. currentStencilFunc = null;
  12701. currentStencilRef = null;
  12702. currentStencilFuncMask = null;
  12703. currentStencilFail = null;
  12704. currentStencilZFail = null;
  12705. currentStencilZPass = null;
  12706. currentStencilClear = null;
  12707. }
  12708. };
  12709. } //
  12710. const colorBuffer = new ColorBuffer();
  12711. const depthBuffer = new DepthBuffer();
  12712. const stencilBuffer = new StencilBuffer();
  12713. let enabledCapabilities = {};
  12714. let xrFramebuffer = null;
  12715. let currentBoundFramebuffers = {};
  12716. let currentProgram = null;
  12717. let currentBlendingEnabled = false;
  12718. let currentBlending = null;
  12719. let currentBlendEquation = null;
  12720. let currentBlendSrc = null;
  12721. let currentBlendDst = null;
  12722. let currentBlendEquationAlpha = null;
  12723. let currentBlendSrcAlpha = null;
  12724. let currentBlendDstAlpha = null;
  12725. let currentPremultipledAlpha = false;
  12726. let currentFlipSided = null;
  12727. let currentCullFace = null;
  12728. let currentLineWidth = null;
  12729. let currentPolygonOffsetFactor = null;
  12730. let currentPolygonOffsetUnits = null;
  12731. const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12732. let lineWidthAvailable = false;
  12733. let version = 0;
  12734. const glVersion = gl.getParameter(gl.VERSION);
  12735. if (glVersion.indexOf('WebGL') !== -1) {
  12736. version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]);
  12737. lineWidthAvailable = version >= 1.0;
  12738. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  12739. version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);
  12740. lineWidthAvailable = version >= 2.0;
  12741. }
  12742. let currentTextureSlot = null;
  12743. let currentBoundTextures = {};
  12744. const scissorParam = gl.getParameter(gl.SCISSOR_BOX);
  12745. const viewportParam = gl.getParameter(gl.VIEWPORT);
  12746. const currentScissor = new Vector4().fromArray(scissorParam);
  12747. const currentViewport = new Vector4().fromArray(viewportParam);
  12748. function createTexture(type, target, count) {
  12749. const data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  12750. const texture = gl.createTexture();
  12751. gl.bindTexture(type, texture);
  12752. gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12753. gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12754. for (let i = 0; i < count; i++) {
  12755. gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
  12756. }
  12757. return texture;
  12758. }
  12759. const emptyTextures = {};
  12760. emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1);
  12761. emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); // init
  12762. colorBuffer.setClear(0, 0, 0, 1);
  12763. depthBuffer.setClear(1);
  12764. stencilBuffer.setClear(0);
  12765. enable(gl.DEPTH_TEST);
  12766. depthBuffer.setFunc(LessEqualDepth);
  12767. setFlipSided(false);
  12768. setCullFace(CullFaceBack);
  12769. enable(gl.CULL_FACE);
  12770. setBlending(NoBlending); //
  12771. function enable(id) {
  12772. if (enabledCapabilities[id] !== true) {
  12773. gl.enable(id);
  12774. enabledCapabilities[id] = true;
  12775. }
  12776. }
  12777. function disable(id) {
  12778. if (enabledCapabilities[id] !== false) {
  12779. gl.disable(id);
  12780. enabledCapabilities[id] = false;
  12781. }
  12782. }
  12783. function bindXRFramebuffer(framebuffer) {
  12784. if (framebuffer !== xrFramebuffer) {
  12785. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  12786. xrFramebuffer = framebuffer;
  12787. }
  12788. }
  12789. function bindFramebuffer(target, framebuffer) {
  12790. if (framebuffer === null && xrFramebuffer !== null) framebuffer = xrFramebuffer; // use active XR framebuffer if available
  12791. if (currentBoundFramebuffers[target] !== framebuffer) {
  12792. gl.bindFramebuffer(target, framebuffer);
  12793. currentBoundFramebuffers[target] = framebuffer;
  12794. if (isWebGL2) {
  12795. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  12796. if (target === gl.DRAW_FRAMEBUFFER) {
  12797. currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer;
  12798. }
  12799. if (target === gl.FRAMEBUFFER) {
  12800. currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer;
  12801. }
  12802. }
  12803. return true;
  12804. }
  12805. return false;
  12806. }
  12807. function useProgram(program) {
  12808. if (currentProgram !== program) {
  12809. gl.useProgram(program);
  12810. currentProgram = program;
  12811. return true;
  12812. }
  12813. return false;
  12814. }
  12815. const equationToGL = {
  12816. [AddEquation]: gl.FUNC_ADD,
  12817. [SubtractEquation]: gl.FUNC_SUBTRACT,
  12818. [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT
  12819. };
  12820. if (isWebGL2) {
  12821. equationToGL[MinEquation] = gl.MIN;
  12822. equationToGL[MaxEquation] = gl.MAX;
  12823. } else {
  12824. const extension = extensions.get('EXT_blend_minmax');
  12825. if (extension !== null) {
  12826. equationToGL[MinEquation] = extension.MIN_EXT;
  12827. equationToGL[MaxEquation] = extension.MAX_EXT;
  12828. }
  12829. }
  12830. const factorToGL = {
  12831. [ZeroFactor]: gl.ZERO,
  12832. [OneFactor]: gl.ONE,
  12833. [SrcColorFactor]: gl.SRC_COLOR,
  12834. [SrcAlphaFactor]: gl.SRC_ALPHA,
  12835. [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE,
  12836. [DstColorFactor]: gl.DST_COLOR,
  12837. [DstAlphaFactor]: gl.DST_ALPHA,
  12838. [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR,
  12839. [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA,
  12840. [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR,
  12841. [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA
  12842. };
  12843. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  12844. if (blending === NoBlending) {
  12845. if (currentBlendingEnabled === true) {
  12846. disable(gl.BLEND);
  12847. currentBlendingEnabled = false;
  12848. }
  12849. return;
  12850. }
  12851. if (currentBlendingEnabled === false) {
  12852. enable(gl.BLEND);
  12853. currentBlendingEnabled = true;
  12854. }
  12855. if (blending !== CustomBlending) {
  12856. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  12857. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  12858. gl.blendEquation(gl.FUNC_ADD);
  12859. currentBlendEquation = AddEquation;
  12860. currentBlendEquationAlpha = AddEquation;
  12861. }
  12862. if (premultipliedAlpha) {
  12863. switch (blending) {
  12864. case NormalBlending:
  12865. gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  12866. break;
  12867. case AdditiveBlending:
  12868. gl.blendFunc(gl.ONE, gl.ONE);
  12869. break;
  12870. case SubtractiveBlending:
  12871. gl.blendFuncSeparate(gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA);
  12872. break;
  12873. case MultiplyBlending:
  12874. gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA);
  12875. break;
  12876. default:
  12877. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12878. break;
  12879. }
  12880. } else {
  12881. switch (blending) {
  12882. case NormalBlending:
  12883. gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  12884. break;
  12885. case AdditiveBlending:
  12886. gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  12887. break;
  12888. case SubtractiveBlending:
  12889. gl.blendFunc(gl.ZERO, gl.ONE_MINUS_SRC_COLOR);
  12890. break;
  12891. case MultiplyBlending:
  12892. gl.blendFunc(gl.ZERO, gl.SRC_COLOR);
  12893. break;
  12894. default:
  12895. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12896. break;
  12897. }
  12898. }
  12899. currentBlendSrc = null;
  12900. currentBlendDst = null;
  12901. currentBlendSrcAlpha = null;
  12902. currentBlendDstAlpha = null;
  12903. currentBlending = blending;
  12904. currentPremultipledAlpha = premultipliedAlpha;
  12905. }
  12906. return;
  12907. } // custom blending
  12908. blendEquationAlpha = blendEquationAlpha || blendEquation;
  12909. blendSrcAlpha = blendSrcAlpha || blendSrc;
  12910. blendDstAlpha = blendDstAlpha || blendDst;
  12911. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  12912. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  12913. currentBlendEquation = blendEquation;
  12914. currentBlendEquationAlpha = blendEquationAlpha;
  12915. }
  12916. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  12917. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  12918. currentBlendSrc = blendSrc;
  12919. currentBlendDst = blendDst;
  12920. currentBlendSrcAlpha = blendSrcAlpha;
  12921. currentBlendDstAlpha = blendDstAlpha;
  12922. }
  12923. currentBlending = blending;
  12924. currentPremultipledAlpha = null;
  12925. }
  12926. function setMaterial(material, frontFaceCW) {
  12927. material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE);
  12928. let flipSided = material.side === BackSide;
  12929. if (frontFaceCW) flipSided = !flipSided;
  12930. setFlipSided(flipSided);
  12931. 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);
  12932. depthBuffer.setFunc(material.depthFunc);
  12933. depthBuffer.setTest(material.depthTest);
  12934. depthBuffer.setMask(material.depthWrite);
  12935. colorBuffer.setMask(material.colorWrite);
  12936. const stencilWrite = material.stencilWrite;
  12937. stencilBuffer.setTest(stencilWrite);
  12938. if (stencilWrite) {
  12939. stencilBuffer.setMask(material.stencilWriteMask);
  12940. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  12941. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  12942. }
  12943. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  12944. material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  12945. } //
  12946. function setFlipSided(flipSided) {
  12947. if (currentFlipSided !== flipSided) {
  12948. if (flipSided) {
  12949. gl.frontFace(gl.CW);
  12950. } else {
  12951. gl.frontFace(gl.CCW);
  12952. }
  12953. currentFlipSided = flipSided;
  12954. }
  12955. }
  12956. function setCullFace(cullFace) {
  12957. if (cullFace !== CullFaceNone) {
  12958. enable(gl.CULL_FACE);
  12959. if (cullFace !== currentCullFace) {
  12960. if (cullFace === CullFaceBack) {
  12961. gl.cullFace(gl.BACK);
  12962. } else if (cullFace === CullFaceFront) {
  12963. gl.cullFace(gl.FRONT);
  12964. } else {
  12965. gl.cullFace(gl.FRONT_AND_BACK);
  12966. }
  12967. }
  12968. } else {
  12969. disable(gl.CULL_FACE);
  12970. }
  12971. currentCullFace = cullFace;
  12972. }
  12973. function setLineWidth(width) {
  12974. if (width !== currentLineWidth) {
  12975. if (lineWidthAvailable) gl.lineWidth(width);
  12976. currentLineWidth = width;
  12977. }
  12978. }
  12979. function setPolygonOffset(polygonOffset, factor, units) {
  12980. if (polygonOffset) {
  12981. enable(gl.POLYGON_OFFSET_FILL);
  12982. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  12983. gl.polygonOffset(factor, units);
  12984. currentPolygonOffsetFactor = factor;
  12985. currentPolygonOffsetUnits = units;
  12986. }
  12987. } else {
  12988. disable(gl.POLYGON_OFFSET_FILL);
  12989. }
  12990. }
  12991. function setScissorTest(scissorTest) {
  12992. if (scissorTest) {
  12993. enable(gl.SCISSOR_TEST);
  12994. } else {
  12995. disable(gl.SCISSOR_TEST);
  12996. }
  12997. } // texture
  12998. function activeTexture(webglSlot) {
  12999. if (webglSlot === undefined) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13000. if (currentTextureSlot !== webglSlot) {
  13001. gl.activeTexture(webglSlot);
  13002. currentTextureSlot = webglSlot;
  13003. }
  13004. }
  13005. function bindTexture(webglType, webglTexture) {
  13006. if (currentTextureSlot === null) {
  13007. activeTexture();
  13008. }
  13009. let boundTexture = currentBoundTextures[currentTextureSlot];
  13010. if (boundTexture === undefined) {
  13011. boundTexture = {
  13012. type: undefined,
  13013. texture: undefined
  13014. };
  13015. currentBoundTextures[currentTextureSlot] = boundTexture;
  13016. }
  13017. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  13018. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  13019. boundTexture.type = webglType;
  13020. boundTexture.texture = webglTexture;
  13021. }
  13022. }
  13023. function unbindTexture() {
  13024. const boundTexture = currentBoundTextures[currentTextureSlot];
  13025. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  13026. gl.bindTexture(boundTexture.type, null);
  13027. boundTexture.type = undefined;
  13028. boundTexture.texture = undefined;
  13029. }
  13030. }
  13031. function compressedTexImage2D() {
  13032. try {
  13033. gl.compressedTexImage2D.apply(gl, arguments);
  13034. } catch (error) {
  13035. console.error('THREE.WebGLState:', error);
  13036. }
  13037. }
  13038. function texImage2D() {
  13039. try {
  13040. gl.texImage2D.apply(gl, arguments);
  13041. } catch (error) {
  13042. console.error('THREE.WebGLState:', error);
  13043. }
  13044. }
  13045. function texImage3D() {
  13046. try {
  13047. gl.texImage3D.apply(gl, arguments);
  13048. } catch (error) {
  13049. console.error('THREE.WebGLState:', error);
  13050. }
  13051. } //
  13052. function scissor(scissor) {
  13053. if (currentScissor.equals(scissor) === false) {
  13054. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  13055. currentScissor.copy(scissor);
  13056. }
  13057. }
  13058. function viewport(viewport) {
  13059. if (currentViewport.equals(viewport) === false) {
  13060. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  13061. currentViewport.copy(viewport);
  13062. }
  13063. } //
  13064. function reset() {
  13065. // reset state
  13066. gl.disable(gl.BLEND);
  13067. gl.disable(gl.CULL_FACE);
  13068. gl.disable(gl.DEPTH_TEST);
  13069. gl.disable(gl.POLYGON_OFFSET_FILL);
  13070. gl.disable(gl.SCISSOR_TEST);
  13071. gl.disable(gl.STENCIL_TEST);
  13072. gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  13073. gl.blendEquation(gl.FUNC_ADD);
  13074. gl.blendFunc(gl.ONE, gl.ZERO);
  13075. gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO);
  13076. gl.colorMask(true, true, true, true);
  13077. gl.clearColor(0, 0, 0, 0);
  13078. gl.depthMask(true);
  13079. gl.depthFunc(gl.LESS);
  13080. gl.clearDepth(1);
  13081. gl.stencilMask(0xffffffff);
  13082. gl.stencilFunc(gl.ALWAYS, 0, 0xffffffff);
  13083. gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
  13084. gl.clearStencil(0);
  13085. gl.cullFace(gl.BACK);
  13086. gl.frontFace(gl.CCW);
  13087. gl.polygonOffset(0, 0);
  13088. gl.activeTexture(gl.TEXTURE0);
  13089. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13090. if (isWebGL2 === true) {
  13091. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
  13092. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  13093. }
  13094. gl.useProgram(null);
  13095. gl.lineWidth(1);
  13096. gl.scissor(0, 0, gl.canvas.width, gl.canvas.height);
  13097. gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); // reset internals
  13098. enabledCapabilities = {};
  13099. currentTextureSlot = null;
  13100. currentBoundTextures = {};
  13101. xrFramebuffer = null;
  13102. currentBoundFramebuffers = {};
  13103. currentProgram = null;
  13104. currentBlendingEnabled = false;
  13105. currentBlending = null;
  13106. currentBlendEquation = null;
  13107. currentBlendSrc = null;
  13108. currentBlendDst = null;
  13109. currentBlendEquationAlpha = null;
  13110. currentBlendSrcAlpha = null;
  13111. currentBlendDstAlpha = null;
  13112. currentPremultipledAlpha = false;
  13113. currentFlipSided = null;
  13114. currentCullFace = null;
  13115. currentLineWidth = null;
  13116. currentPolygonOffsetFactor = null;
  13117. currentPolygonOffsetUnits = null;
  13118. currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height);
  13119. currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height);
  13120. colorBuffer.reset();
  13121. depthBuffer.reset();
  13122. stencilBuffer.reset();
  13123. }
  13124. return {
  13125. buffers: {
  13126. color: colorBuffer,
  13127. depth: depthBuffer,
  13128. stencil: stencilBuffer
  13129. },
  13130. enable: enable,
  13131. disable: disable,
  13132. bindFramebuffer: bindFramebuffer,
  13133. bindXRFramebuffer: bindXRFramebuffer,
  13134. useProgram: useProgram,
  13135. setBlending: setBlending,
  13136. setMaterial: setMaterial,
  13137. setFlipSided: setFlipSided,
  13138. setCullFace: setCullFace,
  13139. setLineWidth: setLineWidth,
  13140. setPolygonOffset: setPolygonOffset,
  13141. setScissorTest: setScissorTest,
  13142. activeTexture: activeTexture,
  13143. bindTexture: bindTexture,
  13144. unbindTexture: unbindTexture,
  13145. compressedTexImage2D: compressedTexImage2D,
  13146. texImage2D: texImage2D,
  13147. texImage3D: texImage3D,
  13148. scissor: scissor,
  13149. viewport: viewport,
  13150. reset: reset
  13151. };
  13152. }
  13153. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  13154. const isWebGL2 = capabilities.isWebGL2;
  13155. const maxTextures = capabilities.maxTextures;
  13156. const maxCubemapSize = capabilities.maxCubemapSize;
  13157. const maxTextureSize = capabilities.maxTextureSize;
  13158. const maxSamples = capabilities.maxSamples;
  13159. const _videoTextures = new WeakMap();
  13160. let _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13161. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13162. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13163. let useOffscreenCanvas = false;
  13164. try {
  13165. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext('2d') !== null;
  13166. } catch (err) {// Ignore any errors
  13167. }
  13168. function createCanvas(width, height) {
  13169. // Use OffscreenCanvas when available. Specially needed in web workers
  13170. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  13171. }
  13172. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  13173. let scale = 1; // handle case if texture exceeds max size
  13174. if (image.width > maxSize || image.height > maxSize) {
  13175. scale = maxSize / Math.max(image.width, image.height);
  13176. } // only perform resize if necessary
  13177. if (scale < 1 || needsPowerOfTwo === true) {
  13178. // only perform resize for certain image types
  13179. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  13180. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13181. const width = floor(scale * image.width);
  13182. const height = floor(scale * image.height);
  13183. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  13184. const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  13185. canvas.width = width;
  13186. canvas.height = height;
  13187. const context = canvas.getContext('2d');
  13188. context.drawImage(image, 0, 0, width, height);
  13189. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  13190. return canvas;
  13191. } else {
  13192. if ('data' in image) {
  13193. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  13194. }
  13195. return image;
  13196. }
  13197. }
  13198. return image;
  13199. }
  13200. function isPowerOfTwo$1(image) {
  13201. return isPowerOfTwo(image.width) && isPowerOfTwo(image.height);
  13202. }
  13203. function textureNeedsPowerOfTwo(texture) {
  13204. if (isWebGL2) return false;
  13205. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13206. }
  13207. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  13208. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13209. }
  13210. function generateMipmap(target, texture, width, height, depth = 1) {
  13211. _gl.generateMipmap(target);
  13212. const textureProperties = properties.get(texture);
  13213. textureProperties.__maxMipLevel = Math.log2(Math.max(width, height, depth));
  13214. }
  13215. function getInternalFormat(internalFormatName, glFormat, glType) {
  13216. if (isWebGL2 === false) return glFormat;
  13217. if (internalFormatName !== null) {
  13218. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  13219. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  13220. }
  13221. let internalFormat = glFormat;
  13222. if (glFormat === _gl.RED) {
  13223. if (glType === _gl.FLOAT) internalFormat = _gl.R32F;
  13224. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.R16F;
  13225. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8;
  13226. }
  13227. if (glFormat === _gl.RGB) {
  13228. if (glType === _gl.FLOAT) internalFormat = _gl.RGB32F;
  13229. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGB16F;
  13230. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGB8;
  13231. }
  13232. if (glFormat === _gl.RGBA) {
  13233. if (glType === _gl.FLOAT) internalFormat = _gl.RGBA32F;
  13234. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGBA16F;
  13235. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGBA8;
  13236. }
  13237. if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) {
  13238. extensions.get('EXT_color_buffer_float');
  13239. }
  13240. return internalFormat;
  13241. } // Fallback filters for non-power-of-2 textures
  13242. function filterFallback(f) {
  13243. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  13244. return _gl.NEAREST;
  13245. }
  13246. return _gl.LINEAR;
  13247. } //
  13248. function onTextureDispose(event) {
  13249. const texture = event.target;
  13250. texture.removeEventListener('dispose', onTextureDispose);
  13251. deallocateTexture(texture);
  13252. if (texture.isVideoTexture) {
  13253. _videoTextures.delete(texture);
  13254. }
  13255. info.memory.textures--;
  13256. }
  13257. function onRenderTargetDispose(event) {
  13258. const renderTarget = event.target;
  13259. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  13260. deallocateRenderTarget(renderTarget);
  13261. } //
  13262. function deallocateTexture(texture) {
  13263. const textureProperties = properties.get(texture);
  13264. if (textureProperties.__webglInit === undefined) return;
  13265. _gl.deleteTexture(textureProperties.__webglTexture);
  13266. properties.remove(texture);
  13267. }
  13268. function deallocateRenderTarget(renderTarget) {
  13269. const texture = renderTarget.texture;
  13270. const renderTargetProperties = properties.get(renderTarget);
  13271. const textureProperties = properties.get(texture);
  13272. if (!renderTarget) return;
  13273. if (textureProperties.__webglTexture !== undefined) {
  13274. _gl.deleteTexture(textureProperties.__webglTexture);
  13275. info.memory.textures--;
  13276. }
  13277. if (renderTarget.depthTexture) {
  13278. renderTarget.depthTexture.dispose();
  13279. }
  13280. if (renderTarget.isWebGLCubeRenderTarget) {
  13281. for (let i = 0; i < 6; i++) {
  13282. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  13283. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  13284. }
  13285. } else {
  13286. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  13287. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  13288. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  13289. if (renderTargetProperties.__webglColorRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);
  13290. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  13291. }
  13292. if (renderTarget.isWebGLMultipleRenderTargets) {
  13293. for (let i = 0, il = texture.length; i < il; i++) {
  13294. const attachmentProperties = properties.get(texture[i]);
  13295. if (attachmentProperties.__webglTexture) {
  13296. _gl.deleteTexture(attachmentProperties.__webglTexture);
  13297. info.memory.textures--;
  13298. }
  13299. properties.remove(texture[i]);
  13300. }
  13301. }
  13302. properties.remove(texture);
  13303. properties.remove(renderTarget);
  13304. } //
  13305. let textureUnits = 0;
  13306. function resetTextureUnits() {
  13307. textureUnits = 0;
  13308. }
  13309. function allocateTextureUnit() {
  13310. const textureUnit = textureUnits;
  13311. if (textureUnit >= maxTextures) {
  13312. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  13313. }
  13314. textureUnits += 1;
  13315. return textureUnit;
  13316. } //
  13317. function setTexture2D(texture, slot) {
  13318. const textureProperties = properties.get(texture);
  13319. if (texture.isVideoTexture) updateVideoTexture(texture);
  13320. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13321. const image = texture.image;
  13322. if (image === undefined) {
  13323. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  13324. } else if (image.complete === false) {
  13325. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  13326. } else {
  13327. uploadTexture(textureProperties, texture, slot);
  13328. return;
  13329. }
  13330. }
  13331. state.activeTexture(_gl.TEXTURE0 + slot);
  13332. state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture);
  13333. }
  13334. function setTexture2DArray(texture, slot) {
  13335. const textureProperties = properties.get(texture);
  13336. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13337. uploadTexture(textureProperties, texture, slot);
  13338. return;
  13339. }
  13340. state.activeTexture(_gl.TEXTURE0 + slot);
  13341. state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture);
  13342. }
  13343. function setTexture3D(texture, slot) {
  13344. const textureProperties = properties.get(texture);
  13345. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13346. uploadTexture(textureProperties, texture, slot);
  13347. return;
  13348. }
  13349. state.activeTexture(_gl.TEXTURE0 + slot);
  13350. state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture);
  13351. }
  13352. function setTextureCube(texture, slot) {
  13353. const textureProperties = properties.get(texture);
  13354. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13355. uploadCubeTexture(textureProperties, texture, slot);
  13356. return;
  13357. }
  13358. state.activeTexture(_gl.TEXTURE0 + slot);
  13359. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  13360. }
  13361. const wrappingToGL = {
  13362. [RepeatWrapping]: _gl.REPEAT,
  13363. [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE,
  13364. [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT
  13365. };
  13366. const filterToGL = {
  13367. [NearestFilter]: _gl.NEAREST,
  13368. [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST,
  13369. [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR,
  13370. [LinearFilter]: _gl.LINEAR,
  13371. [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST,
  13372. [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR
  13373. };
  13374. function setTextureParameters(textureType, texture, supportsMips) {
  13375. if (supportsMips) {
  13376. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]);
  13377. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]);
  13378. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  13379. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]);
  13380. }
  13381. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]);
  13382. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]);
  13383. } else {
  13384. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE);
  13385. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE);
  13386. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  13387. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE);
  13388. }
  13389. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  13390. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  13391. }
  13392. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterFallback(texture.magFilter));
  13393. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterFallback(texture.minFilter));
  13394. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13395. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  13396. }
  13397. }
  13398. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  13399. const extension = extensions.get('EXT_texture_filter_anisotropic');
  13400. if (texture.type === FloatType && extensions.has('OES_texture_float_linear') === false) return; // verify extension for WebGL 1 and WebGL 2
  13401. if (isWebGL2 === false && texture.type === HalfFloatType && extensions.has('OES_texture_half_float_linear') === false) return; // verify extension for WebGL 1 only
  13402. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  13403. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  13404. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  13405. }
  13406. }
  13407. }
  13408. function initTexture(textureProperties, texture) {
  13409. if (textureProperties.__webglInit === undefined) {
  13410. textureProperties.__webglInit = true;
  13411. texture.addEventListener('dispose', onTextureDispose);
  13412. textureProperties.__webglTexture = _gl.createTexture();
  13413. info.memory.textures++;
  13414. }
  13415. }
  13416. function uploadTexture(textureProperties, texture, slot) {
  13417. let textureType = _gl.TEXTURE_2D;
  13418. if (texture.isDataTexture2DArray) textureType = _gl.TEXTURE_2D_ARRAY;
  13419. if (texture.isDataTexture3D) textureType = _gl.TEXTURE_3D;
  13420. initTexture(textureProperties, texture);
  13421. state.activeTexture(_gl.TEXTURE0 + slot);
  13422. state.bindTexture(textureType, textureProperties.__webglTexture);
  13423. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  13424. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  13425. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  13426. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  13427. const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo$1(texture.image) === false;
  13428. const image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  13429. const supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  13430. glFormat = utils.convert(texture.format);
  13431. let glType = utils.convert(texture.type),
  13432. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13433. setTextureParameters(textureType, texture, supportsMips);
  13434. let mipmap;
  13435. const mipmaps = texture.mipmaps;
  13436. if (texture.isDepthTexture) {
  13437. // populate depth texture with dummy data
  13438. glInternalFormat = _gl.DEPTH_COMPONENT;
  13439. if (isWebGL2) {
  13440. if (texture.type === FloatType) {
  13441. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  13442. } else if (texture.type === UnsignedIntType) {
  13443. glInternalFormat = _gl.DEPTH_COMPONENT24;
  13444. } else if (texture.type === UnsignedInt248Type) {
  13445. glInternalFormat = _gl.DEPTH24_STENCIL8;
  13446. } else {
  13447. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  13448. }
  13449. } else {
  13450. if (texture.type === FloatType) {
  13451. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  13452. }
  13453. } // validation checks for WebGL 1
  13454. if (texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  13455. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13456. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13457. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13458. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  13459. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  13460. texture.type = UnsignedShortType;
  13461. glType = utils.convert(texture.type);
  13462. }
  13463. }
  13464. if (texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  13465. // Depth stencil textures need the DEPTH_STENCIL internal format
  13466. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13467. glInternalFormat = _gl.DEPTH_STENCIL; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13468. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13469. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13470. if (texture.type !== UnsignedInt248Type) {
  13471. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  13472. texture.type = UnsignedInt248Type;
  13473. glType = utils.convert(texture.type);
  13474. }
  13475. } //
  13476. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  13477. } else if (texture.isDataTexture) {
  13478. // use manually created mipmaps if available
  13479. // if there are no manual mipmaps
  13480. // set 0 level mipmap and then use GL to generate other mipmap levels
  13481. if (mipmaps.length > 0 && supportsMips) {
  13482. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13483. mipmap = mipmaps[i];
  13484. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13485. }
  13486. texture.generateMipmaps = false;
  13487. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13488. } else {
  13489. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  13490. textureProperties.__maxMipLevel = 0;
  13491. }
  13492. } else if (texture.isCompressedTexture) {
  13493. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13494. mipmap = mipmaps[i];
  13495. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13496. if (glFormat !== null) {
  13497. state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13498. } else {
  13499. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  13500. }
  13501. } else {
  13502. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13503. }
  13504. }
  13505. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13506. } else if (texture.isDataTexture2DArray) {
  13507. state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13508. textureProperties.__maxMipLevel = 0;
  13509. } else if (texture.isDataTexture3D) {
  13510. state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13511. textureProperties.__maxMipLevel = 0;
  13512. } else {
  13513. // regular Texture (image, video, canvas)
  13514. // use manually created mipmaps if available
  13515. // if there are no manual mipmaps
  13516. // set 0 level mipmap and then use GL to generate other mipmap levels
  13517. if (mipmaps.length > 0 && supportsMips) {
  13518. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13519. mipmap = mipmaps[i];
  13520. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap);
  13521. }
  13522. texture.generateMipmaps = false;
  13523. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13524. } else {
  13525. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image);
  13526. textureProperties.__maxMipLevel = 0;
  13527. }
  13528. }
  13529. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13530. generateMipmap(textureType, texture, image.width, image.height);
  13531. }
  13532. textureProperties.__version = texture.version;
  13533. if (texture.onUpdate) texture.onUpdate(texture);
  13534. }
  13535. function uploadCubeTexture(textureProperties, texture, slot) {
  13536. if (texture.image.length !== 6) return;
  13537. initTexture(textureProperties, texture);
  13538. state.activeTexture(_gl.TEXTURE0 + slot);
  13539. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  13540. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  13541. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  13542. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  13543. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  13544. const isCompressed = texture && (texture.isCompressedTexture || texture.image[0].isCompressedTexture);
  13545. const isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  13546. const cubeImage = [];
  13547. for (let i = 0; i < 6; i++) {
  13548. if (!isCompressed && !isDataTexture) {
  13549. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  13550. } else {
  13551. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  13552. }
  13553. }
  13554. const image = cubeImage[0],
  13555. supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  13556. glFormat = utils.convert(texture.format),
  13557. glType = utils.convert(texture.type),
  13558. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13559. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  13560. let mipmaps;
  13561. if (isCompressed) {
  13562. for (let i = 0; i < 6; i++) {
  13563. mipmaps = cubeImage[i].mipmaps;
  13564. for (let j = 0; j < mipmaps.length; j++) {
  13565. const mipmap = mipmaps[j];
  13566. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13567. if (glFormat !== null) {
  13568. state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13569. } else {
  13570. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  13571. }
  13572. } else {
  13573. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13574. }
  13575. }
  13576. }
  13577. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13578. } else {
  13579. mipmaps = texture.mipmaps;
  13580. for (let i = 0; i < 6; i++) {
  13581. if (isDataTexture) {
  13582. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  13583. for (let j = 0; j < mipmaps.length; j++) {
  13584. const mipmap = mipmaps[j];
  13585. const mipmapImage = mipmap.image[i].image;
  13586. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  13587. }
  13588. } else {
  13589. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  13590. for (let j = 0; j < mipmaps.length; j++) {
  13591. const mipmap = mipmaps[j];
  13592. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  13593. }
  13594. }
  13595. }
  13596. textureProperties.__maxMipLevel = mipmaps.length;
  13597. }
  13598. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13599. // We assume images for cube map have the same size.
  13600. generateMipmap(_gl.TEXTURE_CUBE_MAP, texture, image.width, image.height);
  13601. }
  13602. textureProperties.__version = texture.version;
  13603. if (texture.onUpdate) texture.onUpdate(texture);
  13604. } // Render targets
  13605. // Setup storage for target texture and bind it to correct framebuffer
  13606. function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget) {
  13607. const glFormat = utils.convert(texture.format);
  13608. const glType = utils.convert(texture.type);
  13609. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13610. if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) {
  13611. state.texImage3D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null);
  13612. } else {
  13613. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  13614. }
  13615. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  13616. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0);
  13617. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  13618. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  13619. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  13620. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer);
  13621. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  13622. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  13623. if (isMultisample) {
  13624. const depthTexture = renderTarget.depthTexture;
  13625. if (depthTexture && depthTexture.isDepthTexture) {
  13626. if (depthTexture.type === FloatType) {
  13627. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  13628. } else if (depthTexture.type === UnsignedIntType) {
  13629. glInternalFormat = _gl.DEPTH_COMPONENT24;
  13630. }
  13631. }
  13632. const samples = getRenderTargetSamples(renderTarget);
  13633. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13634. } else {
  13635. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  13636. }
  13637. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  13638. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  13639. if (isMultisample) {
  13640. const samples = getRenderTargetSamples(renderTarget);
  13641. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  13642. } else {
  13643. _gl.renderbufferStorage(_gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height);
  13644. }
  13645. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  13646. } else {
  13647. // Use the first texture for MRT so far
  13648. const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[0] : renderTarget.texture;
  13649. const glFormat = utils.convert(texture.format);
  13650. const glType = utils.convert(texture.type);
  13651. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13652. if (isMultisample) {
  13653. const samples = getRenderTargetSamples(renderTarget);
  13654. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13655. } else {
  13656. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  13657. }
  13658. }
  13659. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  13660. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  13661. function setupDepthTexture(framebuffer, renderTarget) {
  13662. const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  13663. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  13664. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  13665. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  13666. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  13667. } // upload an empty depth texture with framebuffer size
  13668. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  13669. renderTarget.depthTexture.image.width = renderTarget.width;
  13670. renderTarget.depthTexture.image.height = renderTarget.height;
  13671. renderTarget.depthTexture.needsUpdate = true;
  13672. }
  13673. setTexture2D(renderTarget.depthTexture, 0);
  13674. const webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  13675. if (renderTarget.depthTexture.format === DepthFormat) {
  13676. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  13677. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  13678. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  13679. } else {
  13680. throw new Error('Unknown depthTexture format');
  13681. }
  13682. } // Setup GL resources for a non-texture depth buffer
  13683. function setupDepthRenderbuffer(renderTarget) {
  13684. const renderTargetProperties = properties.get(renderTarget);
  13685. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  13686. if (renderTarget.depthTexture) {
  13687. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  13688. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  13689. } else {
  13690. if (isCube) {
  13691. renderTargetProperties.__webglDepthbuffer = [];
  13692. for (let i = 0; i < 6; i++) {
  13693. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]);
  13694. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  13695. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  13696. }
  13697. } else {
  13698. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  13699. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  13700. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  13701. }
  13702. }
  13703. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  13704. } // Set up GL resources for the render target
  13705. function setupRenderTarget(renderTarget) {
  13706. const texture = renderTarget.texture;
  13707. const renderTargetProperties = properties.get(renderTarget);
  13708. const textureProperties = properties.get(texture);
  13709. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  13710. if (renderTarget.isWebGLMultipleRenderTargets !== true) {
  13711. textureProperties.__webglTexture = _gl.createTexture();
  13712. textureProperties.__version = texture.version;
  13713. info.memory.textures++;
  13714. }
  13715. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  13716. const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true;
  13717. const isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
  13718. const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray;
  13719. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2; // Handles WebGL2 RGBFormat fallback - #18858
  13720. if (isWebGL2 && texture.format === RGBFormat && (texture.type === FloatType || texture.type === HalfFloatType)) {
  13721. texture.format = RGBAFormat;
  13722. console.warn('THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.');
  13723. } // Setup framebuffer
  13724. if (isCube) {
  13725. renderTargetProperties.__webglFramebuffer = [];
  13726. for (let i = 0; i < 6; i++) {
  13727. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  13728. }
  13729. } else {
  13730. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  13731. if (isMultipleRenderTargets) {
  13732. if (capabilities.drawBuffers) {
  13733. const textures = renderTarget.texture;
  13734. for (let i = 0, il = textures.length; i < il; i++) {
  13735. const attachmentProperties = properties.get(textures[i]);
  13736. if (attachmentProperties.__webglTexture === undefined) {
  13737. attachmentProperties.__webglTexture = _gl.createTexture();
  13738. info.memory.textures++;
  13739. }
  13740. }
  13741. } else {
  13742. console.warn('THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.');
  13743. }
  13744. } else if (isMultisample) {
  13745. if (isWebGL2) {
  13746. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  13747. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  13748. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  13749. const glFormat = utils.convert(texture.format);
  13750. const glType = utils.convert(texture.type);
  13751. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13752. const samples = getRenderTargetSamples(renderTarget);
  13753. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13754. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  13755. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  13756. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  13757. if (renderTarget.depthBuffer) {
  13758. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  13759. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  13760. }
  13761. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  13762. } else {
  13763. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  13764. }
  13765. }
  13766. } // Setup color buffer
  13767. if (isCube) {
  13768. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  13769. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  13770. for (let i = 0; i < 6; i++) {
  13771. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i);
  13772. }
  13773. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13774. generateMipmap(_gl.TEXTURE_CUBE_MAP, texture, renderTarget.width, renderTarget.height);
  13775. }
  13776. state.unbindTexture();
  13777. } else if (isMultipleRenderTargets) {
  13778. const textures = renderTarget.texture;
  13779. for (let i = 0, il = textures.length; i < il; i++) {
  13780. const attachment = textures[i];
  13781. const attachmentProperties = properties.get(attachment);
  13782. state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture);
  13783. setTextureParameters(_gl.TEXTURE_2D, attachment, supportsMips);
  13784. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D);
  13785. if (textureNeedsGenerateMipmaps(attachment, supportsMips)) {
  13786. generateMipmap(_gl.TEXTURE_2D, attachment, renderTarget.width, renderTarget.height);
  13787. }
  13788. }
  13789. state.unbindTexture();
  13790. } else {
  13791. let glTextureType = _gl.TEXTURE_2D;
  13792. if (isRenderTarget3D) {
  13793. // Render targets containing layers, i.e: Texture 3D and 2d arrays
  13794. if (isWebGL2) {
  13795. const isTexture3D = texture.isDataTexture3D;
  13796. glTextureType = isTexture3D ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  13797. } else {
  13798. console.warn('THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.');
  13799. }
  13800. }
  13801. state.bindTexture(glTextureType, textureProperties.__webglTexture);
  13802. setTextureParameters(glTextureType, texture, supportsMips);
  13803. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType);
  13804. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13805. generateMipmap(glTextureType, texture, renderTarget.width, renderTarget.height, renderTarget.depth);
  13806. }
  13807. state.unbindTexture();
  13808. } // Setup depth and stencil buffers
  13809. if (renderTarget.depthBuffer) {
  13810. setupDepthRenderbuffer(renderTarget);
  13811. }
  13812. }
  13813. function updateRenderTargetMipmap(renderTarget) {
  13814. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2;
  13815. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture];
  13816. for (let i = 0, il = textures.length; i < il; i++) {
  13817. const texture = textures[i];
  13818. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13819. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  13820. const webglTexture = properties.get(texture).__webglTexture;
  13821. state.bindTexture(target, webglTexture);
  13822. generateMipmap(target, texture, renderTarget.width, renderTarget.height);
  13823. state.unbindTexture();
  13824. }
  13825. }
  13826. }
  13827. function updateMultisampleRenderTarget(renderTarget) {
  13828. if (renderTarget.isWebGLMultisampleRenderTarget) {
  13829. if (isWebGL2) {
  13830. const width = renderTarget.width;
  13831. const height = renderTarget.height;
  13832. let mask = _gl.COLOR_BUFFER_BIT;
  13833. if (renderTarget.depthBuffer) mask |= _gl.DEPTH_BUFFER_BIT;
  13834. if (renderTarget.stencilBuffer) mask |= _gl.STENCIL_BUFFER_BIT;
  13835. const renderTargetProperties = properties.get(renderTarget);
  13836. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  13837. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  13838. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST);
  13839. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null);
  13840. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  13841. } else {
  13842. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  13843. }
  13844. }
  13845. }
  13846. function getRenderTargetSamples(renderTarget) {
  13847. return isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(maxSamples, renderTarget.samples) : 0;
  13848. }
  13849. function updateVideoTexture(texture) {
  13850. const frame = info.render.frame; // Check the last frame we updated the VideoTexture
  13851. if (_videoTextures.get(texture) !== frame) {
  13852. _videoTextures.set(texture, frame);
  13853. texture.update();
  13854. }
  13855. } // backwards compatibility
  13856. let warnedTexture2D = false;
  13857. let warnedTextureCube = false;
  13858. function safeSetTexture2D(texture, slot) {
  13859. if (texture && texture.isWebGLRenderTarget) {
  13860. if (warnedTexture2D === false) {
  13861. console.warn('THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.');
  13862. warnedTexture2D = true;
  13863. }
  13864. texture = texture.texture;
  13865. }
  13866. setTexture2D(texture, slot);
  13867. }
  13868. function safeSetTextureCube(texture, slot) {
  13869. if (texture && texture.isWebGLCubeRenderTarget) {
  13870. if (warnedTextureCube === false) {
  13871. console.warn('THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.');
  13872. warnedTextureCube = true;
  13873. }
  13874. texture = texture.texture;
  13875. }
  13876. setTextureCube(texture, slot);
  13877. } //
  13878. this.allocateTextureUnit = allocateTextureUnit;
  13879. this.resetTextureUnits = resetTextureUnits;
  13880. this.setTexture2D = setTexture2D;
  13881. this.setTexture2DArray = setTexture2DArray;
  13882. this.setTexture3D = setTexture3D;
  13883. this.setTextureCube = setTextureCube;
  13884. this.setupRenderTarget = setupRenderTarget;
  13885. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  13886. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  13887. this.safeSetTexture2D = safeSetTexture2D;
  13888. this.safeSetTextureCube = safeSetTextureCube;
  13889. }
  13890. function WebGLUtils(gl, extensions, capabilities) {
  13891. const isWebGL2 = capabilities.isWebGL2;
  13892. function convert(p) {
  13893. let extension;
  13894. if (p === UnsignedByteType) return gl.UNSIGNED_BYTE;
  13895. if (p === UnsignedShort4444Type) return gl.UNSIGNED_SHORT_4_4_4_4;
  13896. if (p === UnsignedShort5551Type) return gl.UNSIGNED_SHORT_5_5_5_1;
  13897. if (p === UnsignedShort565Type) return gl.UNSIGNED_SHORT_5_6_5;
  13898. if (p === ByteType) return gl.BYTE;
  13899. if (p === ShortType) return gl.SHORT;
  13900. if (p === UnsignedShortType) return gl.UNSIGNED_SHORT;
  13901. if (p === IntType) return gl.INT;
  13902. if (p === UnsignedIntType) return gl.UNSIGNED_INT;
  13903. if (p === FloatType) return gl.FLOAT;
  13904. if (p === HalfFloatType) {
  13905. if (isWebGL2) return gl.HALF_FLOAT;
  13906. extension = extensions.get('OES_texture_half_float');
  13907. if (extension !== null) {
  13908. return extension.HALF_FLOAT_OES;
  13909. } else {
  13910. return null;
  13911. }
  13912. }
  13913. if (p === AlphaFormat) return gl.ALPHA;
  13914. if (p === RGBFormat) return gl.RGB;
  13915. if (p === RGBAFormat) return gl.RGBA;
  13916. if (p === LuminanceFormat) return gl.LUMINANCE;
  13917. if (p === LuminanceAlphaFormat) return gl.LUMINANCE_ALPHA;
  13918. if (p === DepthFormat) return gl.DEPTH_COMPONENT;
  13919. if (p === DepthStencilFormat) return gl.DEPTH_STENCIL;
  13920. if (p === RedFormat) return gl.RED; // WebGL2 formats.
  13921. if (p === RedIntegerFormat) return gl.RED_INTEGER;
  13922. if (p === RGFormat) return gl.RG;
  13923. if (p === RGIntegerFormat) return gl.RG_INTEGER;
  13924. if (p === RGBIntegerFormat) return gl.RGB_INTEGER;
  13925. if (p === RGBAIntegerFormat) return gl.RGBA_INTEGER;
  13926. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  13927. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  13928. if (extension !== null) {
  13929. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13930. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13931. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13932. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13933. } else {
  13934. return null;
  13935. }
  13936. }
  13937. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  13938. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  13939. if (extension !== null) {
  13940. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13941. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13942. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13943. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13944. } else {
  13945. return null;
  13946. }
  13947. }
  13948. if (p === RGB_ETC1_Format) {
  13949. extension = extensions.get('WEBGL_compressed_texture_etc1');
  13950. if (extension !== null) {
  13951. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13952. } else {
  13953. return null;
  13954. }
  13955. }
  13956. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  13957. extension = extensions.get('WEBGL_compressed_texture_etc');
  13958. if (extension !== null) {
  13959. if (p === RGB_ETC2_Format) return extension.COMPRESSED_RGB8_ETC2;
  13960. if (p === RGBA_ETC2_EAC_Format) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  13961. }
  13962. }
  13963. 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) {
  13964. extension = extensions.get('WEBGL_compressed_texture_astc');
  13965. if (extension !== null) {
  13966. // TODO Complete?
  13967. return p;
  13968. } else {
  13969. return null;
  13970. }
  13971. }
  13972. if (p === RGBA_BPTC_Format) {
  13973. extension = extensions.get('EXT_texture_compression_bptc');
  13974. if (extension !== null) {
  13975. // TODO Complete?
  13976. return p;
  13977. } else {
  13978. return null;
  13979. }
  13980. }
  13981. if (p === UnsignedInt248Type) {
  13982. if (isWebGL2) return gl.UNSIGNED_INT_24_8;
  13983. extension = extensions.get('WEBGL_depth_texture');
  13984. if (extension !== null) {
  13985. return extension.UNSIGNED_INT_24_8_WEBGL;
  13986. } else {
  13987. return null;
  13988. }
  13989. }
  13990. }
  13991. return {
  13992. convert: convert
  13993. };
  13994. }
  13995. class ArrayCamera extends PerspectiveCamera {
  13996. constructor(array = []) {
  13997. super();
  13998. this.cameras = array;
  13999. }
  14000. }
  14001. ArrayCamera.prototype.isArrayCamera = true;
  14002. class Group extends Object3D {
  14003. constructor() {
  14004. super();
  14005. this.type = 'Group';
  14006. }
  14007. }
  14008. Group.prototype.isGroup = true;
  14009. const _moveEvent = {
  14010. type: 'move'
  14011. };
  14012. class WebXRController {
  14013. constructor() {
  14014. this._targetRay = null;
  14015. this._grip = null;
  14016. this._hand = null;
  14017. }
  14018. getHandSpace() {
  14019. if (this._hand === null) {
  14020. this._hand = new Group();
  14021. this._hand.matrixAutoUpdate = false;
  14022. this._hand.visible = false;
  14023. this._hand.joints = {};
  14024. this._hand.inputState = {
  14025. pinching: false
  14026. };
  14027. }
  14028. return this._hand;
  14029. }
  14030. getTargetRaySpace() {
  14031. if (this._targetRay === null) {
  14032. this._targetRay = new Group();
  14033. this._targetRay.matrixAutoUpdate = false;
  14034. this._targetRay.visible = false;
  14035. this._targetRay.hasLinearVelocity = false;
  14036. this._targetRay.linearVelocity = new Vector3();
  14037. this._targetRay.hasAngularVelocity = false;
  14038. this._targetRay.angularVelocity = new Vector3();
  14039. }
  14040. return this._targetRay;
  14041. }
  14042. getGripSpace() {
  14043. if (this._grip === null) {
  14044. this._grip = new Group();
  14045. this._grip.matrixAutoUpdate = false;
  14046. this._grip.visible = false;
  14047. this._grip.hasLinearVelocity = false;
  14048. this._grip.linearVelocity = new Vector3();
  14049. this._grip.hasAngularVelocity = false;
  14050. this._grip.angularVelocity = new Vector3();
  14051. }
  14052. return this._grip;
  14053. }
  14054. dispatchEvent(event) {
  14055. if (this._targetRay !== null) {
  14056. this._targetRay.dispatchEvent(event);
  14057. }
  14058. if (this._grip !== null) {
  14059. this._grip.dispatchEvent(event);
  14060. }
  14061. if (this._hand !== null) {
  14062. this._hand.dispatchEvent(event);
  14063. }
  14064. return this;
  14065. }
  14066. disconnect(inputSource) {
  14067. this.dispatchEvent({
  14068. type: 'disconnected',
  14069. data: inputSource
  14070. });
  14071. if (this._targetRay !== null) {
  14072. this._targetRay.visible = false;
  14073. }
  14074. if (this._grip !== null) {
  14075. this._grip.visible = false;
  14076. }
  14077. if (this._hand !== null) {
  14078. this._hand.visible = false;
  14079. }
  14080. return this;
  14081. }
  14082. update(inputSource, frame, referenceSpace) {
  14083. let inputPose = null;
  14084. let gripPose = null;
  14085. let handPose = null;
  14086. const targetRay = this._targetRay;
  14087. const grip = this._grip;
  14088. const hand = this._hand;
  14089. if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
  14090. if (targetRay !== null) {
  14091. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  14092. if (inputPose !== null) {
  14093. targetRay.matrix.fromArray(inputPose.transform.matrix);
  14094. targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
  14095. if (inputPose.linearVelocity) {
  14096. targetRay.hasLinearVelocity = true;
  14097. targetRay.linearVelocity.copy(inputPose.linearVelocity);
  14098. } else {
  14099. targetRay.hasLinearVelocity = false;
  14100. }
  14101. if (inputPose.angularVelocity) {
  14102. targetRay.hasAngularVelocity = true;
  14103. targetRay.angularVelocity.copy(inputPose.angularVelocity);
  14104. } else {
  14105. targetRay.hasAngularVelocity = false;
  14106. }
  14107. this.dispatchEvent(_moveEvent);
  14108. }
  14109. }
  14110. if (hand && inputSource.hand) {
  14111. handPose = true;
  14112. for (const inputjoint of inputSource.hand.values()) {
  14113. // Update the joints groups with the XRJoint poses
  14114. const jointPose = frame.getJointPose(inputjoint, referenceSpace);
  14115. if (hand.joints[inputjoint.jointName] === undefined) {
  14116. // The transform of this joint will be updated with the joint pose on each frame
  14117. const joint = new Group();
  14118. joint.matrixAutoUpdate = false;
  14119. joint.visible = false;
  14120. hand.joints[inputjoint.jointName] = joint; // ??
  14121. hand.add(joint);
  14122. }
  14123. const joint = hand.joints[inputjoint.jointName];
  14124. if (jointPose !== null) {
  14125. joint.matrix.fromArray(jointPose.transform.matrix);
  14126. joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
  14127. joint.jointRadius = jointPose.radius;
  14128. }
  14129. joint.visible = jointPose !== null;
  14130. } // Custom events
  14131. // Check pinchz
  14132. const indexTip = hand.joints['index-finger-tip'];
  14133. const thumbTip = hand.joints['thumb-tip'];
  14134. const distance = indexTip.position.distanceTo(thumbTip.position);
  14135. const distanceToPinch = 0.02;
  14136. const threshold = 0.005;
  14137. if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
  14138. hand.inputState.pinching = false;
  14139. this.dispatchEvent({
  14140. type: 'pinchend',
  14141. handedness: inputSource.handedness,
  14142. target: this
  14143. });
  14144. } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
  14145. hand.inputState.pinching = true;
  14146. this.dispatchEvent({
  14147. type: 'pinchstart',
  14148. handedness: inputSource.handedness,
  14149. target: this
  14150. });
  14151. }
  14152. } else {
  14153. if (grip !== null && inputSource.gripSpace) {
  14154. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  14155. if (gripPose !== null) {
  14156. grip.matrix.fromArray(gripPose.transform.matrix);
  14157. grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
  14158. if (gripPose.linearVelocity) {
  14159. grip.hasLinearVelocity = true;
  14160. grip.linearVelocity.copy(gripPose.linearVelocity);
  14161. } else {
  14162. grip.hasLinearVelocity = false;
  14163. }
  14164. if (gripPose.angularVelocity) {
  14165. grip.hasAngularVelocity = true;
  14166. grip.angularVelocity.copy(gripPose.angularVelocity);
  14167. } else {
  14168. grip.hasAngularVelocity = false;
  14169. }
  14170. }
  14171. }
  14172. }
  14173. }
  14174. if (targetRay !== null) {
  14175. targetRay.visible = inputPose !== null;
  14176. }
  14177. if (grip !== null) {
  14178. grip.visible = gripPose !== null;
  14179. }
  14180. if (hand !== null) {
  14181. hand.visible = handPose !== null;
  14182. }
  14183. return this;
  14184. }
  14185. }
  14186. class WebXRManager extends EventDispatcher {
  14187. constructor(renderer, gl) {
  14188. super();
  14189. const scope = this;
  14190. const state = renderer.state;
  14191. let session = null;
  14192. let framebufferScaleFactor = 1.0;
  14193. let referenceSpace = null;
  14194. let referenceSpaceType = 'local-floor';
  14195. let pose = null;
  14196. let glBinding = null;
  14197. let glFramebuffer = null;
  14198. let glProjLayer = null;
  14199. let glBaseLayer = null;
  14200. let isMultisample = false;
  14201. let glMultisampledFramebuffer = null;
  14202. let glColorRenderbuffer = null;
  14203. let glDepthRenderbuffer = null;
  14204. let xrFrame = null;
  14205. let depthStyle = null;
  14206. let clearStyle = null;
  14207. const controllers = [];
  14208. const inputSourcesMap = new Map(); //
  14209. const cameraL = new PerspectiveCamera();
  14210. cameraL.layers.enable(1);
  14211. cameraL.viewport = new Vector4();
  14212. const cameraR = new PerspectiveCamera();
  14213. cameraR.layers.enable(2);
  14214. cameraR.viewport = new Vector4();
  14215. const cameras = [cameraL, cameraR];
  14216. const cameraVR = new ArrayCamera();
  14217. cameraVR.layers.enable(1);
  14218. cameraVR.layers.enable(2);
  14219. let _currentDepthNear = null;
  14220. let _currentDepthFar = null; //
  14221. this.cameraAutoUpdate = true;
  14222. this.enabled = false;
  14223. this.isPresenting = false;
  14224. this.getController = function (index) {
  14225. let controller = controllers[index];
  14226. if (controller === undefined) {
  14227. controller = new WebXRController();
  14228. controllers[index] = controller;
  14229. }
  14230. return controller.getTargetRaySpace();
  14231. };
  14232. this.getControllerGrip = function (index) {
  14233. let controller = controllers[index];
  14234. if (controller === undefined) {
  14235. controller = new WebXRController();
  14236. controllers[index] = controller;
  14237. }
  14238. return controller.getGripSpace();
  14239. };
  14240. this.getHand = function (index) {
  14241. let controller = controllers[index];
  14242. if (controller === undefined) {
  14243. controller = new WebXRController();
  14244. controllers[index] = controller;
  14245. }
  14246. return controller.getHandSpace();
  14247. }; //
  14248. function onSessionEvent(event) {
  14249. const controller = inputSourcesMap.get(event.inputSource);
  14250. if (controller) {
  14251. controller.dispatchEvent({
  14252. type: event.type,
  14253. data: event.inputSource
  14254. });
  14255. }
  14256. }
  14257. function onSessionEnd() {
  14258. inputSourcesMap.forEach(function (controller, inputSource) {
  14259. controller.disconnect(inputSource);
  14260. });
  14261. inputSourcesMap.clear();
  14262. _currentDepthNear = null;
  14263. _currentDepthFar = null; // restore framebuffer/rendering state
  14264. state.bindXRFramebuffer(null);
  14265. renderer.setRenderTarget(renderer.getRenderTarget());
  14266. if (glFramebuffer) gl.deleteFramebuffer(glFramebuffer);
  14267. if (glMultisampledFramebuffer) gl.deleteFramebuffer(glMultisampledFramebuffer);
  14268. if (glColorRenderbuffer) gl.deleteRenderbuffer(glColorRenderbuffer);
  14269. if (glDepthRenderbuffer) gl.deleteRenderbuffer(glDepthRenderbuffer);
  14270. glFramebuffer = null;
  14271. glMultisampledFramebuffer = null;
  14272. glColorRenderbuffer = null;
  14273. glDepthRenderbuffer = null;
  14274. glBaseLayer = null;
  14275. glProjLayer = null;
  14276. glBinding = null;
  14277. session = null; //
  14278. animation.stop();
  14279. scope.isPresenting = false;
  14280. scope.dispatchEvent({
  14281. type: 'sessionend'
  14282. });
  14283. }
  14284. this.setFramebufferScaleFactor = function (value) {
  14285. framebufferScaleFactor = value;
  14286. if (scope.isPresenting === true) {
  14287. console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
  14288. }
  14289. };
  14290. this.setReferenceSpaceType = function (value) {
  14291. referenceSpaceType = value;
  14292. if (scope.isPresenting === true) {
  14293. console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
  14294. }
  14295. };
  14296. this.getReferenceSpace = function () {
  14297. return referenceSpace;
  14298. };
  14299. this.getBaseLayer = function () {
  14300. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  14301. };
  14302. this.getBinding = function () {
  14303. return glBinding;
  14304. };
  14305. this.getFrame = function () {
  14306. return xrFrame;
  14307. };
  14308. this.getSession = function () {
  14309. return session;
  14310. };
  14311. this.setSession = async function (value) {
  14312. session = value;
  14313. if (session !== null) {
  14314. session.addEventListener('select', onSessionEvent);
  14315. session.addEventListener('selectstart', onSessionEvent);
  14316. session.addEventListener('selectend', onSessionEvent);
  14317. session.addEventListener('squeeze', onSessionEvent);
  14318. session.addEventListener('squeezestart', onSessionEvent);
  14319. session.addEventListener('squeezeend', onSessionEvent);
  14320. session.addEventListener('end', onSessionEnd);
  14321. session.addEventListener('inputsourceschange', onInputSourcesChange);
  14322. const attributes = gl.getContextAttributes();
  14323. if (attributes.xrCompatible !== true) {
  14324. await gl.makeXRCompatible();
  14325. }
  14326. if (session.renderState.layers === undefined) {
  14327. const layerInit = {
  14328. antialias: attributes.antialias,
  14329. alpha: attributes.alpha,
  14330. depth: attributes.depth,
  14331. stencil: attributes.stencil,
  14332. framebufferScaleFactor: framebufferScaleFactor
  14333. };
  14334. glBaseLayer = new XRWebGLLayer(session, gl, layerInit);
  14335. session.updateRenderState({
  14336. baseLayer: glBaseLayer
  14337. });
  14338. } else if (gl instanceof WebGLRenderingContext) {
  14339. // Use old style webgl layer because we can't use MSAA
  14340. // WebGL2 support.
  14341. const layerInit = {
  14342. antialias: true,
  14343. alpha: attributes.alpha,
  14344. depth: attributes.depth,
  14345. stencil: attributes.stencil,
  14346. framebufferScaleFactor: framebufferScaleFactor
  14347. };
  14348. glBaseLayer = new XRWebGLLayer(session, gl, layerInit);
  14349. session.updateRenderState({
  14350. layers: [glBaseLayer]
  14351. });
  14352. } else {
  14353. isMultisample = attributes.antialias;
  14354. let depthFormat = null;
  14355. if (attributes.depth) {
  14356. clearStyle = gl.DEPTH_BUFFER_BIT;
  14357. if (attributes.stencil) clearStyle |= gl.STENCIL_BUFFER_BIT;
  14358. depthStyle = attributes.stencil ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  14359. depthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  14360. }
  14361. const projectionlayerInit = {
  14362. colorFormat: attributes.alpha ? gl.RGBA8 : gl.RGB8,
  14363. depthFormat: depthFormat,
  14364. scaleFactor: framebufferScaleFactor
  14365. };
  14366. glBinding = new XRWebGLBinding(session, gl);
  14367. glProjLayer = glBinding.createProjectionLayer(projectionlayerInit);
  14368. glFramebuffer = gl.createFramebuffer();
  14369. session.updateRenderState({
  14370. layers: [glProjLayer]
  14371. });
  14372. if (isMultisample) {
  14373. glMultisampledFramebuffer = gl.createFramebuffer();
  14374. glColorRenderbuffer = gl.createRenderbuffer();
  14375. gl.bindRenderbuffer(gl.RENDERBUFFER, glColorRenderbuffer);
  14376. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, 4, gl.RGBA8, glProjLayer.textureWidth, glProjLayer.textureHeight);
  14377. state.bindFramebuffer(gl.FRAMEBUFFER, glMultisampledFramebuffer);
  14378. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, glColorRenderbuffer);
  14379. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14380. if (depthFormat !== null) {
  14381. glDepthRenderbuffer = gl.createRenderbuffer();
  14382. gl.bindRenderbuffer(gl.RENDERBUFFER, glDepthRenderbuffer);
  14383. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, 4, depthFormat, glProjLayer.textureWidth, glProjLayer.textureHeight);
  14384. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, glDepthRenderbuffer);
  14385. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14386. }
  14387. state.bindFramebuffer(gl.FRAMEBUFFER, null);
  14388. }
  14389. }
  14390. referenceSpace = await session.requestReferenceSpace(referenceSpaceType);
  14391. animation.setContext(session);
  14392. animation.start();
  14393. scope.isPresenting = true;
  14394. scope.dispatchEvent({
  14395. type: 'sessionstart'
  14396. });
  14397. }
  14398. };
  14399. function onInputSourcesChange(event) {
  14400. const inputSources = session.inputSources; // Assign inputSources to available controllers
  14401. for (let i = 0; i < controllers.length; i++) {
  14402. inputSourcesMap.set(inputSources[i], controllers[i]);
  14403. } // Notify disconnected
  14404. for (let i = 0; i < event.removed.length; i++) {
  14405. const inputSource = event.removed[i];
  14406. const controller = inputSourcesMap.get(inputSource);
  14407. if (controller) {
  14408. controller.dispatchEvent({
  14409. type: 'disconnected',
  14410. data: inputSource
  14411. });
  14412. inputSourcesMap.delete(inputSource);
  14413. }
  14414. } // Notify connected
  14415. for (let i = 0; i < event.added.length; i++) {
  14416. const inputSource = event.added[i];
  14417. const controller = inputSourcesMap.get(inputSource);
  14418. if (controller) {
  14419. controller.dispatchEvent({
  14420. type: 'connected',
  14421. data: inputSource
  14422. });
  14423. }
  14424. }
  14425. } //
  14426. const cameraLPos = new Vector3();
  14427. const cameraRPos = new Vector3();
  14428. /**
  14429. * Assumes 2 cameras that are parallel and share an X-axis, and that
  14430. * the cameras' projection and world matrices have already been set.
  14431. * And that near and far planes are identical for both cameras.
  14432. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  14433. */
  14434. function setProjectionFromUnion(camera, cameraL, cameraR) {
  14435. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  14436. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  14437. const ipd = cameraLPos.distanceTo(cameraRPos);
  14438. const projL = cameraL.projectionMatrix.elements;
  14439. const projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  14440. // most likely identical top and bottom frustum extents.
  14441. // Use the left camera for these values.
  14442. const near = projL[14] / (projL[10] - 1);
  14443. const far = projL[14] / (projL[10] + 1);
  14444. const topFov = (projL[9] + 1) / projL[5];
  14445. const bottomFov = (projL[9] - 1) / projL[5];
  14446. const leftFov = (projL[8] - 1) / projL[0];
  14447. const rightFov = (projR[8] + 1) / projR[0];
  14448. const left = near * leftFov;
  14449. const right = near * rightFov; // Calculate the new camera's position offset from the
  14450. // left camera. xOffset should be roughly half `ipd`.
  14451. const zOffset = ipd / (-leftFov + rightFov);
  14452. const xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  14453. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  14454. camera.translateX(xOffset);
  14455. camera.translateZ(zOffset);
  14456. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  14457. camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); // Find the union of the frustum values of the cameras and scale
  14458. // the values so that the near plane's position does not change in world space,
  14459. // although must now be relative to the new union camera.
  14460. const near2 = near + zOffset;
  14461. const far2 = far + zOffset;
  14462. const left2 = left - xOffset;
  14463. const right2 = right + (ipd - xOffset);
  14464. const top2 = topFov * far / far2 * near2;
  14465. const bottom2 = bottomFov * far / far2 * near2;
  14466. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  14467. }
  14468. function updateCamera(camera, parent) {
  14469. if (parent === null) {
  14470. camera.matrixWorld.copy(camera.matrix);
  14471. } else {
  14472. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  14473. }
  14474. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  14475. }
  14476. this.updateCamera = function (camera) {
  14477. if (session === null) return;
  14478. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  14479. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  14480. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  14481. // Note that the new renderState won't apply until the next frame. See #18320
  14482. session.updateRenderState({
  14483. depthNear: cameraVR.near,
  14484. depthFar: cameraVR.far
  14485. });
  14486. _currentDepthNear = cameraVR.near;
  14487. _currentDepthFar = cameraVR.far;
  14488. }
  14489. const parent = camera.parent;
  14490. const cameras = cameraVR.cameras;
  14491. updateCamera(cameraVR, parent);
  14492. for (let i = 0; i < cameras.length; i++) {
  14493. updateCamera(cameras[i], parent);
  14494. }
  14495. cameraVR.matrixWorld.decompose(cameraVR.position, cameraVR.quaternion, cameraVR.scale); // update user camera and its children
  14496. camera.position.copy(cameraVR.position);
  14497. camera.quaternion.copy(cameraVR.quaternion);
  14498. camera.scale.copy(cameraVR.scale);
  14499. camera.matrix.copy(cameraVR.matrix);
  14500. camera.matrixWorld.copy(cameraVR.matrixWorld);
  14501. const children = camera.children;
  14502. for (let i = 0, l = children.length; i < l; i++) {
  14503. children[i].updateMatrixWorld(true);
  14504. } // update projection matrix for proper view frustum culling
  14505. if (cameras.length === 2) {
  14506. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  14507. } else {
  14508. // assume single camera setup (AR)
  14509. cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
  14510. }
  14511. };
  14512. this.getCamera = function () {
  14513. return cameraVR;
  14514. };
  14515. this.getFoveation = function () {
  14516. if (glProjLayer !== null) {
  14517. return glProjLayer.fixedFoveation;
  14518. }
  14519. if (glBaseLayer !== null) {
  14520. return glBaseLayer.fixedFoveation;
  14521. }
  14522. return undefined;
  14523. };
  14524. this.setFoveation = function (foveation) {
  14525. // 0 = no foveation = full resolution
  14526. // 1 = maximum foveation = the edges render at lower resolution
  14527. if (glProjLayer !== null) {
  14528. glProjLayer.fixedFoveation = foveation;
  14529. }
  14530. if (glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined) {
  14531. glBaseLayer.fixedFoveation = foveation;
  14532. }
  14533. }; // Animation Loop
  14534. let onAnimationFrameCallback = null;
  14535. function onAnimationFrame(time, frame) {
  14536. pose = frame.getViewerPose(referenceSpace);
  14537. xrFrame = frame;
  14538. if (pose !== null) {
  14539. const views = pose.views;
  14540. if (glBaseLayer !== null) {
  14541. state.bindXRFramebuffer(glBaseLayer.framebuffer);
  14542. }
  14543. let cameraVRNeedsUpdate = false; // check if it's necessary to rebuild cameraVR's camera list
  14544. if (views.length !== cameraVR.cameras.length) {
  14545. cameraVR.cameras.length = 0;
  14546. cameraVRNeedsUpdate = true;
  14547. }
  14548. for (let i = 0; i < views.length; i++) {
  14549. const view = views[i];
  14550. let viewport = null;
  14551. if (glBaseLayer !== null) {
  14552. viewport = glBaseLayer.getViewport(view);
  14553. } else {
  14554. const glSubImage = glBinding.getViewSubImage(glProjLayer, view);
  14555. state.bindXRFramebuffer(glFramebuffer);
  14556. if (glSubImage.depthStencilTexture !== undefined) {
  14557. gl.framebufferTexture2D(gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, glSubImage.depthStencilTexture, 0);
  14558. }
  14559. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, glSubImage.colorTexture, 0);
  14560. viewport = glSubImage.viewport;
  14561. }
  14562. const camera = cameras[i];
  14563. camera.matrix.fromArray(view.transform.matrix);
  14564. camera.projectionMatrix.fromArray(view.projectionMatrix);
  14565. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  14566. if (i === 0) {
  14567. cameraVR.matrix.copy(camera.matrix);
  14568. }
  14569. if (cameraVRNeedsUpdate === true) {
  14570. cameraVR.cameras.push(camera);
  14571. }
  14572. }
  14573. if (isMultisample) {
  14574. state.bindXRFramebuffer(glMultisampledFramebuffer);
  14575. if (clearStyle !== null) gl.clear(clearStyle);
  14576. }
  14577. } //
  14578. const inputSources = session.inputSources;
  14579. for (let i = 0; i < controllers.length; i++) {
  14580. const controller = controllers[i];
  14581. const inputSource = inputSources[i];
  14582. controller.update(inputSource, frame, referenceSpace);
  14583. }
  14584. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  14585. if (isMultisample) {
  14586. const width = glProjLayer.textureWidth;
  14587. const height = glProjLayer.textureHeight;
  14588. state.bindFramebuffer(gl.READ_FRAMEBUFFER, glMultisampledFramebuffer);
  14589. state.bindFramebuffer(gl.DRAW_FRAMEBUFFER, glFramebuffer); // Invalidate the depth here to avoid flush of the depth data to main memory.
  14590. gl.invalidateFramebuffer(gl.READ_FRAMEBUFFER, [depthStyle]);
  14591. gl.invalidateFramebuffer(gl.DRAW_FRAMEBUFFER, [depthStyle]);
  14592. gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, gl.COLOR_BUFFER_BIT, gl.NEAREST); // Invalidate the MSAA buffer because it's not needed anymore.
  14593. gl.invalidateFramebuffer(gl.READ_FRAMEBUFFER, [gl.COLOR_ATTACHMENT0]);
  14594. state.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  14595. state.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
  14596. state.bindFramebuffer(gl.FRAMEBUFFER, glMultisampledFramebuffer);
  14597. }
  14598. xrFrame = null;
  14599. }
  14600. const animation = new WebGLAnimation();
  14601. animation.setAnimationLoop(onAnimationFrame);
  14602. this.setAnimationLoop = function (callback) {
  14603. onAnimationFrameCallback = callback;
  14604. };
  14605. this.dispose = function () {};
  14606. }
  14607. }
  14608. function WebGLMaterials(properties) {
  14609. function refreshFogUniforms(uniforms, fog) {
  14610. uniforms.fogColor.value.copy(fog.color);
  14611. if (fog.isFog) {
  14612. uniforms.fogNear.value = fog.near;
  14613. uniforms.fogFar.value = fog.far;
  14614. } else if (fog.isFogExp2) {
  14615. uniforms.fogDensity.value = fog.density;
  14616. }
  14617. }
  14618. function refreshMaterialUniforms(uniforms, material, pixelRatio, height, transmissionRenderTarget) {
  14619. if (material.isMeshBasicMaterial) {
  14620. refreshUniformsCommon(uniforms, material);
  14621. } else if (material.isMeshLambertMaterial) {
  14622. refreshUniformsCommon(uniforms, material);
  14623. refreshUniformsLambert(uniforms, material);
  14624. } else if (material.isMeshToonMaterial) {
  14625. refreshUniformsCommon(uniforms, material);
  14626. refreshUniformsToon(uniforms, material);
  14627. } else if (material.isMeshPhongMaterial) {
  14628. refreshUniformsCommon(uniforms, material);
  14629. refreshUniformsPhong(uniforms, material);
  14630. } else if (material.isMeshStandardMaterial) {
  14631. refreshUniformsCommon(uniforms, material);
  14632. if (material.isMeshPhysicalMaterial) {
  14633. refreshUniformsPhysical(uniforms, material, transmissionRenderTarget);
  14634. } else {
  14635. refreshUniformsStandard(uniforms, material);
  14636. }
  14637. } else if (material.isMeshMatcapMaterial) {
  14638. refreshUniformsCommon(uniforms, material);
  14639. refreshUniformsMatcap(uniforms, material);
  14640. } else if (material.isMeshDepthMaterial) {
  14641. refreshUniformsCommon(uniforms, material);
  14642. refreshUniformsDepth(uniforms, material);
  14643. } else if (material.isMeshDistanceMaterial) {
  14644. refreshUniformsCommon(uniforms, material);
  14645. refreshUniformsDistance(uniforms, material);
  14646. } else if (material.isMeshNormalMaterial) {
  14647. refreshUniformsCommon(uniforms, material);
  14648. refreshUniformsNormal(uniforms, material);
  14649. } else if (material.isLineBasicMaterial) {
  14650. refreshUniformsLine(uniforms, material);
  14651. if (material.isLineDashedMaterial) {
  14652. refreshUniformsDash(uniforms, material);
  14653. }
  14654. } else if (material.isPointsMaterial) {
  14655. refreshUniformsPoints(uniforms, material, pixelRatio, height);
  14656. } else if (material.isSpriteMaterial) {
  14657. refreshUniformsSprites(uniforms, material);
  14658. } else if (material.isShadowMaterial) {
  14659. uniforms.color.value.copy(material.color);
  14660. uniforms.opacity.value = material.opacity;
  14661. } else if (material.isShaderMaterial) {
  14662. material.uniformsNeedUpdate = false; // #15581
  14663. }
  14664. }
  14665. function refreshUniformsCommon(uniforms, material) {
  14666. uniforms.opacity.value = material.opacity;
  14667. if (material.color) {
  14668. uniforms.diffuse.value.copy(material.color);
  14669. }
  14670. if (material.emissive) {
  14671. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  14672. }
  14673. if (material.map) {
  14674. uniforms.map.value = material.map;
  14675. }
  14676. if (material.alphaMap) {
  14677. uniforms.alphaMap.value = material.alphaMap;
  14678. }
  14679. if (material.specularMap) {
  14680. uniforms.specularMap.value = material.specularMap;
  14681. }
  14682. if (material.alphaTest > 0) {
  14683. uniforms.alphaTest.value = material.alphaTest;
  14684. }
  14685. const envMap = properties.get(material).envMap;
  14686. if (envMap) {
  14687. uniforms.envMap.value = envMap;
  14688. uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1;
  14689. uniforms.reflectivity.value = material.reflectivity;
  14690. uniforms.ior.value = material.ior;
  14691. uniforms.refractionRatio.value = material.refractionRatio;
  14692. const maxMipLevel = properties.get(envMap).__maxMipLevel;
  14693. if (maxMipLevel !== undefined) {
  14694. uniforms.maxMipLevel.value = maxMipLevel;
  14695. }
  14696. }
  14697. if (material.lightMap) {
  14698. uniforms.lightMap.value = material.lightMap;
  14699. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  14700. }
  14701. if (material.aoMap) {
  14702. uniforms.aoMap.value = material.aoMap;
  14703. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  14704. } // uv repeat and offset setting priorities
  14705. // 1. color map
  14706. // 2. specular map
  14707. // 3. displacementMap map
  14708. // 4. normal map
  14709. // 5. bump map
  14710. // 6. roughnessMap map
  14711. // 7. metalnessMap map
  14712. // 8. alphaMap map
  14713. // 9. emissiveMap map
  14714. // 10. clearcoat map
  14715. // 11. clearcoat normal map
  14716. // 12. clearcoat roughnessMap map
  14717. // 13. specular intensity map
  14718. // 14. specular tint map
  14719. // 15. transmission map
  14720. // 16. thickness map
  14721. let uvScaleMap;
  14722. if (material.map) {
  14723. uvScaleMap = material.map;
  14724. } else if (material.specularMap) {
  14725. uvScaleMap = material.specularMap;
  14726. } else if (material.displacementMap) {
  14727. uvScaleMap = material.displacementMap;
  14728. } else if (material.normalMap) {
  14729. uvScaleMap = material.normalMap;
  14730. } else if (material.bumpMap) {
  14731. uvScaleMap = material.bumpMap;
  14732. } else if (material.roughnessMap) {
  14733. uvScaleMap = material.roughnessMap;
  14734. } else if (material.metalnessMap) {
  14735. uvScaleMap = material.metalnessMap;
  14736. } else if (material.alphaMap) {
  14737. uvScaleMap = material.alphaMap;
  14738. } else if (material.emissiveMap) {
  14739. uvScaleMap = material.emissiveMap;
  14740. } else if (material.clearcoatMap) {
  14741. uvScaleMap = material.clearcoatMap;
  14742. } else if (material.clearcoatNormalMap) {
  14743. uvScaleMap = material.clearcoatNormalMap;
  14744. } else if (material.clearcoatRoughnessMap) {
  14745. uvScaleMap = material.clearcoatRoughnessMap;
  14746. } else if (material.specularIntensityMap) {
  14747. uvScaleMap = material.specularIntensityMap;
  14748. } else if (material.specularTintMap) {
  14749. uvScaleMap = material.specularTintMap;
  14750. } else if (material.transmissionMap) {
  14751. uvScaleMap = material.transmissionMap;
  14752. } else if (material.thicknessMap) {
  14753. uvScaleMap = material.thicknessMap;
  14754. }
  14755. if (uvScaleMap !== undefined) {
  14756. // backwards compatibility
  14757. if (uvScaleMap.isWebGLRenderTarget) {
  14758. uvScaleMap = uvScaleMap.texture;
  14759. }
  14760. if (uvScaleMap.matrixAutoUpdate === true) {
  14761. uvScaleMap.updateMatrix();
  14762. }
  14763. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  14764. } // uv repeat and offset setting priorities for uv2
  14765. // 1. ao map
  14766. // 2. light map
  14767. let uv2ScaleMap;
  14768. if (material.aoMap) {
  14769. uv2ScaleMap = material.aoMap;
  14770. } else if (material.lightMap) {
  14771. uv2ScaleMap = material.lightMap;
  14772. }
  14773. if (uv2ScaleMap !== undefined) {
  14774. // backwards compatibility
  14775. if (uv2ScaleMap.isWebGLRenderTarget) {
  14776. uv2ScaleMap = uv2ScaleMap.texture;
  14777. }
  14778. if (uv2ScaleMap.matrixAutoUpdate === true) {
  14779. uv2ScaleMap.updateMatrix();
  14780. }
  14781. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  14782. }
  14783. }
  14784. function refreshUniformsLine(uniforms, material) {
  14785. uniforms.diffuse.value.copy(material.color);
  14786. uniforms.opacity.value = material.opacity;
  14787. }
  14788. function refreshUniformsDash(uniforms, material) {
  14789. uniforms.dashSize.value = material.dashSize;
  14790. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14791. uniforms.scale.value = material.scale;
  14792. }
  14793. function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
  14794. uniforms.diffuse.value.copy(material.color);
  14795. uniforms.opacity.value = material.opacity;
  14796. uniforms.size.value = material.size * pixelRatio;
  14797. uniforms.scale.value = height * 0.5;
  14798. if (material.map) {
  14799. uniforms.map.value = material.map;
  14800. }
  14801. if (material.alphaMap) {
  14802. uniforms.alphaMap.value = material.alphaMap;
  14803. }
  14804. if (material.alphaTest > 0) {
  14805. uniforms.alphaTest.value = material.alphaTest;
  14806. } // uv repeat and offset setting priorities
  14807. // 1. color map
  14808. // 2. alpha map
  14809. let uvScaleMap;
  14810. if (material.map) {
  14811. uvScaleMap = material.map;
  14812. } else if (material.alphaMap) {
  14813. uvScaleMap = material.alphaMap;
  14814. }
  14815. if (uvScaleMap !== undefined) {
  14816. if (uvScaleMap.matrixAutoUpdate === true) {
  14817. uvScaleMap.updateMatrix();
  14818. }
  14819. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  14820. }
  14821. }
  14822. function refreshUniformsSprites(uniforms, material) {
  14823. uniforms.diffuse.value.copy(material.color);
  14824. uniforms.opacity.value = material.opacity;
  14825. uniforms.rotation.value = material.rotation;
  14826. if (material.map) {
  14827. uniforms.map.value = material.map;
  14828. }
  14829. if (material.alphaMap) {
  14830. uniforms.alphaMap.value = material.alphaMap;
  14831. }
  14832. if (material.alphaTest > 0) {
  14833. uniforms.alphaTest.value = material.alphaTest;
  14834. } // uv repeat and offset setting priorities
  14835. // 1. color map
  14836. // 2. alpha map
  14837. let uvScaleMap;
  14838. if (material.map) {
  14839. uvScaleMap = material.map;
  14840. } else if (material.alphaMap) {
  14841. uvScaleMap = material.alphaMap;
  14842. }
  14843. if (uvScaleMap !== undefined) {
  14844. if (uvScaleMap.matrixAutoUpdate === true) {
  14845. uvScaleMap.updateMatrix();
  14846. }
  14847. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  14848. }
  14849. }
  14850. function refreshUniformsLambert(uniforms, material) {
  14851. if (material.emissiveMap) {
  14852. uniforms.emissiveMap.value = material.emissiveMap;
  14853. }
  14854. }
  14855. function refreshUniformsPhong(uniforms, material) {
  14856. uniforms.specular.value.copy(material.specular);
  14857. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  14858. if (material.emissiveMap) {
  14859. uniforms.emissiveMap.value = material.emissiveMap;
  14860. }
  14861. if (material.bumpMap) {
  14862. uniforms.bumpMap.value = material.bumpMap;
  14863. uniforms.bumpScale.value = material.bumpScale;
  14864. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14865. }
  14866. if (material.normalMap) {
  14867. uniforms.normalMap.value = material.normalMap;
  14868. uniforms.normalScale.value.copy(material.normalScale);
  14869. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14870. }
  14871. if (material.displacementMap) {
  14872. uniforms.displacementMap.value = material.displacementMap;
  14873. uniforms.displacementScale.value = material.displacementScale;
  14874. uniforms.displacementBias.value = material.displacementBias;
  14875. }
  14876. }
  14877. function refreshUniformsToon(uniforms, material) {
  14878. if (material.gradientMap) {
  14879. uniforms.gradientMap.value = material.gradientMap;
  14880. }
  14881. if (material.emissiveMap) {
  14882. uniforms.emissiveMap.value = material.emissiveMap;
  14883. }
  14884. if (material.bumpMap) {
  14885. uniforms.bumpMap.value = material.bumpMap;
  14886. uniforms.bumpScale.value = material.bumpScale;
  14887. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14888. }
  14889. if (material.normalMap) {
  14890. uniforms.normalMap.value = material.normalMap;
  14891. uniforms.normalScale.value.copy(material.normalScale);
  14892. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14893. }
  14894. if (material.displacementMap) {
  14895. uniforms.displacementMap.value = material.displacementMap;
  14896. uniforms.displacementScale.value = material.displacementScale;
  14897. uniforms.displacementBias.value = material.displacementBias;
  14898. }
  14899. }
  14900. function refreshUniformsStandard(uniforms, material) {
  14901. uniforms.roughness.value = material.roughness;
  14902. uniforms.metalness.value = material.metalness;
  14903. if (material.roughnessMap) {
  14904. uniforms.roughnessMap.value = material.roughnessMap;
  14905. }
  14906. if (material.metalnessMap) {
  14907. uniforms.metalnessMap.value = material.metalnessMap;
  14908. }
  14909. if (material.emissiveMap) {
  14910. uniforms.emissiveMap.value = material.emissiveMap;
  14911. }
  14912. if (material.bumpMap) {
  14913. uniforms.bumpMap.value = material.bumpMap;
  14914. uniforms.bumpScale.value = material.bumpScale;
  14915. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14916. }
  14917. if (material.normalMap) {
  14918. uniforms.normalMap.value = material.normalMap;
  14919. uniforms.normalScale.value.copy(material.normalScale);
  14920. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14921. }
  14922. if (material.displacementMap) {
  14923. uniforms.displacementMap.value = material.displacementMap;
  14924. uniforms.displacementScale.value = material.displacementScale;
  14925. uniforms.displacementBias.value = material.displacementBias;
  14926. }
  14927. const envMap = properties.get(material).envMap;
  14928. if (envMap) {
  14929. //uniforms.envMap.value = material.envMap; // part of uniforms common
  14930. uniforms.envMapIntensity.value = material.envMapIntensity;
  14931. }
  14932. }
  14933. function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) {
  14934. refreshUniformsStandard(uniforms, material);
  14935. uniforms.ior.value = material.ior; // also part of uniforms common
  14936. if (material.sheenTint) uniforms.sheenTint.value.copy(material.sheenTint);
  14937. if (material.clearcoat > 0) {
  14938. uniforms.clearcoat.value = material.clearcoat;
  14939. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  14940. if (material.clearcoatMap) {
  14941. uniforms.clearcoatMap.value = material.clearcoatMap;
  14942. }
  14943. if (material.clearcoatRoughnessMap) {
  14944. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  14945. }
  14946. if (material.clearcoatNormalMap) {
  14947. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  14948. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  14949. if (material.side === BackSide) {
  14950. uniforms.clearcoatNormalScale.value.negate();
  14951. }
  14952. }
  14953. }
  14954. if (material.transmission > 0) {
  14955. uniforms.transmission.value = material.transmission;
  14956. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  14957. uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height);
  14958. if (material.transmissionMap) {
  14959. uniforms.transmissionMap.value = material.transmissionMap;
  14960. }
  14961. uniforms.thickness.value = material.thickness;
  14962. if (material.thicknessMap) {
  14963. uniforms.thicknessMap.value = material.thicknessMap;
  14964. }
  14965. uniforms.attenuationDistance.value = material.attenuationDistance;
  14966. uniforms.attenuationTint.value.copy(material.attenuationTint);
  14967. }
  14968. uniforms.specularIntensity.value = material.specularIntensity;
  14969. uniforms.specularTint.value.copy(material.specularTint);
  14970. if (material.specularIntensityMap) {
  14971. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  14972. }
  14973. if (material.specularTintMap) {
  14974. uniforms.specularTintMap.value = material.specularTintMap;
  14975. }
  14976. }
  14977. function refreshUniformsMatcap(uniforms, material) {
  14978. if (material.matcap) {
  14979. uniforms.matcap.value = material.matcap;
  14980. }
  14981. if (material.bumpMap) {
  14982. uniforms.bumpMap.value = material.bumpMap;
  14983. uniforms.bumpScale.value = material.bumpScale;
  14984. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14985. }
  14986. if (material.normalMap) {
  14987. uniforms.normalMap.value = material.normalMap;
  14988. uniforms.normalScale.value.copy(material.normalScale);
  14989. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14990. }
  14991. if (material.displacementMap) {
  14992. uniforms.displacementMap.value = material.displacementMap;
  14993. uniforms.displacementScale.value = material.displacementScale;
  14994. uniforms.displacementBias.value = material.displacementBias;
  14995. }
  14996. }
  14997. function refreshUniformsDepth(uniforms, material) {
  14998. if (material.displacementMap) {
  14999. uniforms.displacementMap.value = material.displacementMap;
  15000. uniforms.displacementScale.value = material.displacementScale;
  15001. uniforms.displacementBias.value = material.displacementBias;
  15002. }
  15003. }
  15004. function refreshUniformsDistance(uniforms, material) {
  15005. if (material.displacementMap) {
  15006. uniforms.displacementMap.value = material.displacementMap;
  15007. uniforms.displacementScale.value = material.displacementScale;
  15008. uniforms.displacementBias.value = material.displacementBias;
  15009. }
  15010. uniforms.referencePosition.value.copy(material.referencePosition);
  15011. uniforms.nearDistance.value = material.nearDistance;
  15012. uniforms.farDistance.value = material.farDistance;
  15013. }
  15014. function refreshUniformsNormal(uniforms, material) {
  15015. if (material.bumpMap) {
  15016. uniforms.bumpMap.value = material.bumpMap;
  15017. uniforms.bumpScale.value = material.bumpScale;
  15018. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15019. }
  15020. if (material.normalMap) {
  15021. uniforms.normalMap.value = material.normalMap;
  15022. uniforms.normalScale.value.copy(material.normalScale);
  15023. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15024. }
  15025. if (material.displacementMap) {
  15026. uniforms.displacementMap.value = material.displacementMap;
  15027. uniforms.displacementScale.value = material.displacementScale;
  15028. uniforms.displacementBias.value = material.displacementBias;
  15029. }
  15030. }
  15031. return {
  15032. refreshFogUniforms: refreshFogUniforms,
  15033. refreshMaterialUniforms: refreshMaterialUniforms
  15034. };
  15035. }
  15036. function createCanvasElement() {
  15037. const canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  15038. canvas.style.display = 'block';
  15039. return canvas;
  15040. }
  15041. function WebGLRenderer(parameters = {}) {
  15042. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  15043. _context = parameters.context !== undefined ? parameters.context : null,
  15044. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  15045. _depth = parameters.depth !== undefined ? parameters.depth : true,
  15046. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  15047. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  15048. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  15049. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  15050. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  15051. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  15052. let currentRenderList = null;
  15053. let currentRenderState = null; // render() can be called from within a callback triggered by another render.
  15054. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  15055. const renderListStack = [];
  15056. const renderStateStack = []; // public properties
  15057. this.domElement = _canvas; // Debug configuration container
  15058. this.debug = {
  15059. /**
  15060. * Enables error checking and reporting when shader programs are being compiled
  15061. * @type {boolean}
  15062. */
  15063. checkShaderErrors: true
  15064. }; // clearing
  15065. this.autoClear = true;
  15066. this.autoClearColor = true;
  15067. this.autoClearDepth = true;
  15068. this.autoClearStencil = true; // scene graph
  15069. this.sortObjects = true; // user-defined clipping
  15070. this.clippingPlanes = [];
  15071. this.localClippingEnabled = false; // physically based shading
  15072. this.gammaFactor = 2.0; // for backwards compatibility
  15073. this.outputEncoding = LinearEncoding; // physical lights
  15074. this.physicallyCorrectLights = false; // tone mapping
  15075. this.toneMapping = NoToneMapping;
  15076. this.toneMappingExposure = 1.0; // internal properties
  15077. const _this = this;
  15078. let _isContextLost = false; // internal state cache
  15079. let _currentActiveCubeFace = 0;
  15080. let _currentActiveMipmapLevel = 0;
  15081. let _currentRenderTarget = null;
  15082. let _currentMaterialId = -1;
  15083. let _currentCamera = null;
  15084. const _currentViewport = new Vector4();
  15085. const _currentScissor = new Vector4();
  15086. let _currentScissorTest = null; //
  15087. let _width = _canvas.width;
  15088. let _height = _canvas.height;
  15089. let _pixelRatio = 1;
  15090. let _opaqueSort = null;
  15091. let _transparentSort = null;
  15092. const _viewport = new Vector4(0, 0, _width, _height);
  15093. const _scissor = new Vector4(0, 0, _width, _height);
  15094. let _scissorTest = false; //
  15095. const _currentDrawBuffers = []; // frustum
  15096. const _frustum = new Frustum(); // clipping
  15097. let _clippingEnabled = false;
  15098. let _localClippingEnabled = false; // transmission
  15099. let _transmissionRenderTarget = null; // camera matrices cache
  15100. const _projScreenMatrix = new Matrix4();
  15101. const _vector3 = new Vector3();
  15102. const _emptyScene = {
  15103. background: null,
  15104. fog: null,
  15105. environment: null,
  15106. overrideMaterial: null,
  15107. isScene: true
  15108. };
  15109. function getTargetPixelRatio() {
  15110. return _currentRenderTarget === null ? _pixelRatio : 1;
  15111. } // initialize
  15112. let _gl = _context;
  15113. function getContext(contextNames, contextAttributes) {
  15114. for (let i = 0; i < contextNames.length; i++) {
  15115. const contextName = contextNames[i];
  15116. const context = _canvas.getContext(contextName, contextAttributes);
  15117. if (context !== null) return context;
  15118. }
  15119. return null;
  15120. }
  15121. try {
  15122. const contextAttributes = {
  15123. alpha: _alpha,
  15124. depth: _depth,
  15125. stencil: _stencil,
  15126. antialias: _antialias,
  15127. premultipliedAlpha: _premultipliedAlpha,
  15128. preserveDrawingBuffer: _preserveDrawingBuffer,
  15129. powerPreference: _powerPreference,
  15130. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  15131. }; // event listeners must be registered before WebGL context is created, see #12753
  15132. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  15133. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  15134. if (_gl === null) {
  15135. const contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
  15136. if (_this.isWebGL1Renderer === true) {
  15137. contextNames.shift();
  15138. }
  15139. _gl = getContext(contextNames, contextAttributes);
  15140. if (_gl === null) {
  15141. if (getContext(contextNames)) {
  15142. throw new Error('Error creating WebGL context with your selected attributes.');
  15143. } else {
  15144. throw new Error('Error creating WebGL context.');
  15145. }
  15146. }
  15147. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  15148. if (_gl.getShaderPrecisionFormat === undefined) {
  15149. _gl.getShaderPrecisionFormat = function () {
  15150. return {
  15151. 'rangeMin': 1,
  15152. 'rangeMax': 1,
  15153. 'precision': 1
  15154. };
  15155. };
  15156. }
  15157. } catch (error) {
  15158. console.error('THREE.WebGLRenderer: ' + error.message);
  15159. throw error;
  15160. }
  15161. let extensions, capabilities, state, info;
  15162. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  15163. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  15164. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  15165. let utils, bindingStates;
  15166. function initGLContext() {
  15167. extensions = new WebGLExtensions(_gl);
  15168. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  15169. extensions.init(capabilities);
  15170. utils = new WebGLUtils(_gl, extensions, capabilities);
  15171. state = new WebGLState(_gl, extensions, capabilities);
  15172. _currentDrawBuffers[0] = _gl.BACK;
  15173. info = new WebGLInfo(_gl);
  15174. properties = new WebGLProperties();
  15175. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  15176. cubemaps = new WebGLCubeMaps(_this);
  15177. cubeuvmaps = new WebGLCubeUVMaps(_this);
  15178. attributes = new WebGLAttributes(_gl, capabilities);
  15179. bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
  15180. geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
  15181. objects = new WebGLObjects(_gl, geometries, attributes, info);
  15182. morphtargets = new WebGLMorphtargets(_gl);
  15183. clipping = new WebGLClipping(properties);
  15184. programCache = new WebGLPrograms(_this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping);
  15185. materials = new WebGLMaterials(properties);
  15186. renderLists = new WebGLRenderLists(properties);
  15187. renderStates = new WebGLRenderStates(extensions, capabilities);
  15188. background = new WebGLBackground(_this, cubemaps, state, objects, _premultipliedAlpha);
  15189. shadowMap = new WebGLShadowMap(_this, objects, capabilities);
  15190. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  15191. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  15192. info.programs = programCache.programs;
  15193. _this.capabilities = capabilities;
  15194. _this.extensions = extensions;
  15195. _this.properties = properties;
  15196. _this.renderLists = renderLists;
  15197. _this.shadowMap = shadowMap;
  15198. _this.state = state;
  15199. _this.info = info;
  15200. }
  15201. initGLContext(); // xr
  15202. const xr = new WebXRManager(_this, _gl);
  15203. this.xr = xr; // API
  15204. this.getContext = function () {
  15205. return _gl;
  15206. };
  15207. this.getContextAttributes = function () {
  15208. return _gl.getContextAttributes();
  15209. };
  15210. this.forceContextLoss = function () {
  15211. const extension = extensions.get('WEBGL_lose_context');
  15212. if (extension) extension.loseContext();
  15213. };
  15214. this.forceContextRestore = function () {
  15215. const extension = extensions.get('WEBGL_lose_context');
  15216. if (extension) extension.restoreContext();
  15217. };
  15218. this.getPixelRatio = function () {
  15219. return _pixelRatio;
  15220. };
  15221. this.setPixelRatio = function (value) {
  15222. if (value === undefined) return;
  15223. _pixelRatio = value;
  15224. this.setSize(_width, _height, false);
  15225. };
  15226. this.getSize = function (target) {
  15227. return target.set(_width, _height);
  15228. };
  15229. this.setSize = function (width, height, updateStyle) {
  15230. if (xr.isPresenting) {
  15231. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  15232. return;
  15233. }
  15234. _width = width;
  15235. _height = height;
  15236. _canvas.width = Math.floor(width * _pixelRatio);
  15237. _canvas.height = Math.floor(height * _pixelRatio);
  15238. if (updateStyle !== false) {
  15239. _canvas.style.width = width + 'px';
  15240. _canvas.style.height = height + 'px';
  15241. }
  15242. this.setViewport(0, 0, width, height);
  15243. };
  15244. this.getDrawingBufferSize = function (target) {
  15245. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  15246. };
  15247. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  15248. _width = width;
  15249. _height = height;
  15250. _pixelRatio = pixelRatio;
  15251. _canvas.width = Math.floor(width * pixelRatio);
  15252. _canvas.height = Math.floor(height * pixelRatio);
  15253. this.setViewport(0, 0, width, height);
  15254. };
  15255. this.getCurrentViewport = function (target) {
  15256. return target.copy(_currentViewport);
  15257. };
  15258. this.getViewport = function (target) {
  15259. return target.copy(_viewport);
  15260. };
  15261. this.setViewport = function (x, y, width, height) {
  15262. if (x.isVector4) {
  15263. _viewport.set(x.x, x.y, x.z, x.w);
  15264. } else {
  15265. _viewport.set(x, y, width, height);
  15266. }
  15267. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  15268. };
  15269. this.getScissor = function (target) {
  15270. return target.copy(_scissor);
  15271. };
  15272. this.setScissor = function (x, y, width, height) {
  15273. if (x.isVector4) {
  15274. _scissor.set(x.x, x.y, x.z, x.w);
  15275. } else {
  15276. _scissor.set(x, y, width, height);
  15277. }
  15278. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  15279. };
  15280. this.getScissorTest = function () {
  15281. return _scissorTest;
  15282. };
  15283. this.setScissorTest = function (boolean) {
  15284. state.setScissorTest(_scissorTest = boolean);
  15285. };
  15286. this.setOpaqueSort = function (method) {
  15287. _opaqueSort = method;
  15288. };
  15289. this.setTransparentSort = function (method) {
  15290. _transparentSort = method;
  15291. }; // Clearing
  15292. this.getClearColor = function (target) {
  15293. return target.copy(background.getClearColor());
  15294. };
  15295. this.setClearColor = function () {
  15296. background.setClearColor.apply(background, arguments);
  15297. };
  15298. this.getClearAlpha = function () {
  15299. return background.getClearAlpha();
  15300. };
  15301. this.setClearAlpha = function () {
  15302. background.setClearAlpha.apply(background, arguments);
  15303. };
  15304. this.clear = function (color, depth, stencil) {
  15305. let bits = 0;
  15306. if (color === undefined || color) bits |= _gl.COLOR_BUFFER_BIT;
  15307. if (depth === undefined || depth) bits |= _gl.DEPTH_BUFFER_BIT;
  15308. if (stencil === undefined || stencil) bits |= _gl.STENCIL_BUFFER_BIT;
  15309. _gl.clear(bits);
  15310. };
  15311. this.clearColor = function () {
  15312. this.clear(true, false, false);
  15313. };
  15314. this.clearDepth = function () {
  15315. this.clear(false, true, false);
  15316. };
  15317. this.clearStencil = function () {
  15318. this.clear(false, false, true);
  15319. }; //
  15320. this.dispose = function () {
  15321. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  15322. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  15323. renderLists.dispose();
  15324. renderStates.dispose();
  15325. properties.dispose();
  15326. cubemaps.dispose();
  15327. cubeuvmaps.dispose();
  15328. objects.dispose();
  15329. bindingStates.dispose();
  15330. xr.dispose();
  15331. xr.removeEventListener('sessionstart', onXRSessionStart);
  15332. xr.removeEventListener('sessionend', onXRSessionEnd);
  15333. if (_transmissionRenderTarget) {
  15334. _transmissionRenderTarget.dispose();
  15335. _transmissionRenderTarget = null;
  15336. }
  15337. animation.stop();
  15338. }; // Events
  15339. function onContextLost(event) {
  15340. event.preventDefault();
  15341. console.log('THREE.WebGLRenderer: Context Lost.');
  15342. _isContextLost = true;
  15343. }
  15344. function onContextRestore() {
  15345. console.log('THREE.WebGLRenderer: Context Restored.');
  15346. _isContextLost = false;
  15347. const infoAutoReset = info.autoReset;
  15348. const shadowMapEnabled = shadowMap.enabled;
  15349. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  15350. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  15351. const shadowMapType = shadowMap.type;
  15352. initGLContext();
  15353. info.autoReset = infoAutoReset;
  15354. shadowMap.enabled = shadowMapEnabled;
  15355. shadowMap.autoUpdate = shadowMapAutoUpdate;
  15356. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  15357. shadowMap.type = shadowMapType;
  15358. }
  15359. function onMaterialDispose(event) {
  15360. const material = event.target;
  15361. material.removeEventListener('dispose', onMaterialDispose);
  15362. deallocateMaterial(material);
  15363. } // Buffer deallocation
  15364. function deallocateMaterial(material) {
  15365. releaseMaterialProgramReferences(material);
  15366. properties.remove(material);
  15367. }
  15368. function releaseMaterialProgramReferences(material) {
  15369. const programs = properties.get(material).programs;
  15370. if (programs !== undefined) {
  15371. programs.forEach(function (program) {
  15372. programCache.releaseProgram(program);
  15373. });
  15374. }
  15375. } // Buffer rendering
  15376. function renderObjectImmediate(object, program) {
  15377. object.render(function (object) {
  15378. _this.renderBufferImmediate(object, program);
  15379. });
  15380. }
  15381. this.renderBufferImmediate = function (object, program) {
  15382. bindingStates.initAttributes();
  15383. const buffers = properties.get(object);
  15384. if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
  15385. if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
  15386. if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
  15387. if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
  15388. const programAttributes = program.getAttributes();
  15389. if (object.hasPositions) {
  15390. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.position);
  15391. _gl.bufferData(_gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW);
  15392. bindingStates.enableAttribute(programAttributes.position.location);
  15393. _gl.vertexAttribPointer(programAttributes.position.location, 3, _gl.FLOAT, false, 0, 0);
  15394. }
  15395. if (object.hasNormals) {
  15396. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.normal);
  15397. _gl.bufferData(_gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW);
  15398. bindingStates.enableAttribute(programAttributes.normal.location);
  15399. _gl.vertexAttribPointer(programAttributes.normal.location, 3, _gl.FLOAT, false, 0, 0);
  15400. }
  15401. if (object.hasUvs) {
  15402. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.uv);
  15403. _gl.bufferData(_gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW);
  15404. bindingStates.enableAttribute(programAttributes.uv.location);
  15405. _gl.vertexAttribPointer(programAttributes.uv.location, 2, _gl.FLOAT, false, 0, 0);
  15406. }
  15407. if (object.hasColors) {
  15408. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.color);
  15409. _gl.bufferData(_gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW);
  15410. bindingStates.enableAttribute(programAttributes.color.location);
  15411. _gl.vertexAttribPointer(programAttributes.color.location, 3, _gl.FLOAT, false, 0, 0);
  15412. }
  15413. bindingStates.disableUnusedAttributes();
  15414. _gl.drawArrays(_gl.TRIANGLES, 0, object.count);
  15415. object.count = 0;
  15416. };
  15417. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  15418. if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  15419. const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  15420. const program = setProgram(camera, scene, material, object);
  15421. state.setMaterial(material, frontFaceCW); //
  15422. let index = geometry.index;
  15423. const position = geometry.attributes.position; //
  15424. if (index === null) {
  15425. if (position === undefined || position.count === 0) return;
  15426. } else if (index.count === 0) {
  15427. return;
  15428. } //
  15429. let rangeFactor = 1;
  15430. if (material.wireframe === true) {
  15431. index = geometries.getWireframeAttribute(geometry);
  15432. rangeFactor = 2;
  15433. }
  15434. if (geometry.morphAttributes.position !== undefined || geometry.morphAttributes.normal !== undefined) {
  15435. morphtargets.update(object, geometry, material, program);
  15436. }
  15437. bindingStates.setup(object, material, program, geometry, index);
  15438. let attribute;
  15439. let renderer = bufferRenderer;
  15440. if (index !== null) {
  15441. attribute = attributes.get(index);
  15442. renderer = indexedBufferRenderer;
  15443. renderer.setIndex(attribute);
  15444. } //
  15445. const dataCount = index !== null ? index.count : position.count;
  15446. const rangeStart = geometry.drawRange.start * rangeFactor;
  15447. const rangeCount = geometry.drawRange.count * rangeFactor;
  15448. const groupStart = group !== null ? group.start * rangeFactor : 0;
  15449. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  15450. const drawStart = Math.max(rangeStart, groupStart);
  15451. const drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  15452. const drawCount = Math.max(0, drawEnd - drawStart + 1);
  15453. if (drawCount === 0) return; //
  15454. if (object.isMesh) {
  15455. if (material.wireframe === true) {
  15456. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  15457. renderer.setMode(_gl.LINES);
  15458. } else {
  15459. renderer.setMode(_gl.TRIANGLES);
  15460. }
  15461. } else if (object.isLine) {
  15462. let lineWidth = material.linewidth;
  15463. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  15464. state.setLineWidth(lineWidth * getTargetPixelRatio());
  15465. if (object.isLineSegments) {
  15466. renderer.setMode(_gl.LINES);
  15467. } else if (object.isLineLoop) {
  15468. renderer.setMode(_gl.LINE_LOOP);
  15469. } else {
  15470. renderer.setMode(_gl.LINE_STRIP);
  15471. }
  15472. } else if (object.isPoints) {
  15473. renderer.setMode(_gl.POINTS);
  15474. } else if (object.isSprite) {
  15475. renderer.setMode(_gl.TRIANGLES);
  15476. }
  15477. if (object.isInstancedMesh) {
  15478. renderer.renderInstances(drawStart, drawCount, object.count);
  15479. } else if (geometry.isInstancedBufferGeometry) {
  15480. const instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount);
  15481. renderer.renderInstances(drawStart, drawCount, instanceCount);
  15482. } else {
  15483. renderer.render(drawStart, drawCount);
  15484. }
  15485. }; // Compile
  15486. this.compile = function (scene, camera) {
  15487. currentRenderState = renderStates.get(scene);
  15488. currentRenderState.init();
  15489. renderStateStack.push(currentRenderState);
  15490. scene.traverseVisible(function (object) {
  15491. if (object.isLight && object.layers.test(camera.layers)) {
  15492. currentRenderState.pushLight(object);
  15493. if (object.castShadow) {
  15494. currentRenderState.pushShadow(object);
  15495. }
  15496. }
  15497. });
  15498. currentRenderState.setupLights(_this.physicallyCorrectLights);
  15499. scene.traverse(function (object) {
  15500. const material = object.material;
  15501. if (material) {
  15502. if (Array.isArray(material)) {
  15503. for (let i = 0; i < material.length; i++) {
  15504. const material2 = material[i];
  15505. getProgram(material2, scene, object);
  15506. }
  15507. } else {
  15508. getProgram(material, scene, object);
  15509. }
  15510. }
  15511. });
  15512. renderStateStack.pop();
  15513. currentRenderState = null;
  15514. }; // Animation Loop
  15515. let onAnimationFrameCallback = null;
  15516. function onAnimationFrame(time) {
  15517. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  15518. }
  15519. function onXRSessionStart() {
  15520. animation.stop();
  15521. }
  15522. function onXRSessionEnd() {
  15523. animation.start();
  15524. }
  15525. const animation = new WebGLAnimation();
  15526. animation.setAnimationLoop(onAnimationFrame);
  15527. if (typeof window !== 'undefined') animation.setContext(window);
  15528. this.setAnimationLoop = function (callback) {
  15529. onAnimationFrameCallback = callback;
  15530. xr.setAnimationLoop(callback);
  15531. callback === null ? animation.stop() : animation.start();
  15532. };
  15533. xr.addEventListener('sessionstart', onXRSessionStart);
  15534. xr.addEventListener('sessionend', onXRSessionEnd); // Rendering
  15535. this.render = function (scene, camera) {
  15536. if (camera !== undefined && camera.isCamera !== true) {
  15537. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  15538. return;
  15539. }
  15540. if (_isContextLost === true) return; // update scene graph
  15541. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  15542. if (camera.parent === null) camera.updateMatrixWorld();
  15543. if (xr.enabled === true && xr.isPresenting === true) {
  15544. if (xr.cameraAutoUpdate === true) xr.updateCamera(camera);
  15545. camera = xr.getCamera(); // use XR camera for rendering
  15546. } //
  15547. if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, _currentRenderTarget);
  15548. currentRenderState = renderStates.get(scene, renderStateStack.length);
  15549. currentRenderState.init();
  15550. renderStateStack.push(currentRenderState);
  15551. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  15552. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  15553. _localClippingEnabled = this.localClippingEnabled;
  15554. _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  15555. currentRenderList = renderLists.get(scene, renderListStack.length);
  15556. currentRenderList.init();
  15557. renderListStack.push(currentRenderList);
  15558. projectObject(scene, camera, 0, _this.sortObjects);
  15559. currentRenderList.finish();
  15560. if (_this.sortObjects === true) {
  15561. currentRenderList.sort(_opaqueSort, _transparentSort);
  15562. } //
  15563. if (_clippingEnabled === true) clipping.beginShadows();
  15564. const shadowsArray = currentRenderState.state.shadowsArray;
  15565. shadowMap.render(shadowsArray, scene, camera);
  15566. if (_clippingEnabled === true) clipping.endShadows(); //
  15567. if (this.info.autoReset === true) this.info.reset(); //
  15568. background.render(currentRenderList, scene); // render scene
  15569. currentRenderState.setupLights(_this.physicallyCorrectLights);
  15570. if (camera.isArrayCamera) {
  15571. const cameras = camera.cameras;
  15572. for (let i = 0, l = cameras.length; i < l; i++) {
  15573. const camera2 = cameras[i];
  15574. renderScene(currentRenderList, scene, camera2, camera2.viewport);
  15575. }
  15576. } else {
  15577. renderScene(currentRenderList, scene, camera);
  15578. } //
  15579. if (_currentRenderTarget !== null) {
  15580. // resolve multisample renderbuffers to a single-sample texture if necessary
  15581. textures.updateMultisampleRenderTarget(_currentRenderTarget); // Generate mipmap if we're using any kind of mipmap filtering
  15582. textures.updateRenderTargetMipmap(_currentRenderTarget);
  15583. } //
  15584. if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); // Ensure depth buffer writing is enabled so it can be cleared on next render
  15585. state.buffers.depth.setTest(true);
  15586. state.buffers.depth.setMask(true);
  15587. state.buffers.color.setMask(true);
  15588. state.setPolygonOffset(false); // _gl.finish();
  15589. bindingStates.resetDefaultState();
  15590. _currentMaterialId = -1;
  15591. _currentCamera = null;
  15592. renderStateStack.pop();
  15593. if (renderStateStack.length > 0) {
  15594. currentRenderState = renderStateStack[renderStateStack.length - 1];
  15595. } else {
  15596. currentRenderState = null;
  15597. }
  15598. renderListStack.pop();
  15599. if (renderListStack.length > 0) {
  15600. currentRenderList = renderListStack[renderListStack.length - 1];
  15601. } else {
  15602. currentRenderList = null;
  15603. }
  15604. };
  15605. function projectObject(object, camera, groupOrder, sortObjects) {
  15606. if (object.visible === false) return;
  15607. const visible = object.layers.test(camera.layers);
  15608. if (visible) {
  15609. if (object.isGroup) {
  15610. groupOrder = object.renderOrder;
  15611. } else if (object.isLOD) {
  15612. if (object.autoUpdate === true) object.update(camera);
  15613. } else if (object.isLight) {
  15614. currentRenderState.pushLight(object);
  15615. if (object.castShadow) {
  15616. currentRenderState.pushShadow(object);
  15617. }
  15618. } else if (object.isSprite) {
  15619. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  15620. if (sortObjects) {
  15621. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15622. }
  15623. const geometry = objects.update(object);
  15624. const material = object.material;
  15625. if (material.visible) {
  15626. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  15627. }
  15628. }
  15629. } else if (object.isImmediateRenderObject) {
  15630. if (sortObjects) {
  15631. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15632. }
  15633. currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
  15634. } else if (object.isMesh || object.isLine || object.isPoints) {
  15635. if (object.isSkinnedMesh) {
  15636. // update skeleton only once in a frame
  15637. if (object.skeleton.frame !== info.render.frame) {
  15638. object.skeleton.update();
  15639. object.skeleton.frame = info.render.frame;
  15640. }
  15641. }
  15642. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  15643. if (sortObjects) {
  15644. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15645. }
  15646. const geometry = objects.update(object);
  15647. const material = object.material;
  15648. if (Array.isArray(material)) {
  15649. const groups = geometry.groups;
  15650. for (let i = 0, l = groups.length; i < l; i++) {
  15651. const group = groups[i];
  15652. const groupMaterial = material[group.materialIndex];
  15653. if (groupMaterial && groupMaterial.visible) {
  15654. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  15655. }
  15656. }
  15657. } else if (material.visible) {
  15658. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  15659. }
  15660. }
  15661. }
  15662. }
  15663. const children = object.children;
  15664. for (let i = 0, l = children.length; i < l; i++) {
  15665. projectObject(children[i], camera, groupOrder, sortObjects);
  15666. }
  15667. }
  15668. function renderScene(currentRenderList, scene, camera, viewport) {
  15669. const opaqueObjects = currentRenderList.opaque;
  15670. const transmissiveObjects = currentRenderList.transmissive;
  15671. const transparentObjects = currentRenderList.transparent;
  15672. currentRenderState.setupLightsView(camera);
  15673. if (transmissiveObjects.length > 0) renderTransmissionPass(opaqueObjects, scene, camera);
  15674. if (viewport) state.viewport(_currentViewport.copy(viewport));
  15675. if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
  15676. if (transmissiveObjects.length > 0) renderObjects(transmissiveObjects, scene, camera);
  15677. if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera);
  15678. }
  15679. function renderTransmissionPass(opaqueObjects, scene, camera) {
  15680. if (_transmissionRenderTarget === null) {
  15681. const needsAntialias = _antialias === true && capabilities.isWebGL2 === true;
  15682. const renderTargetType = needsAntialias ? WebGLMultisampleRenderTarget : WebGLRenderTarget;
  15683. _transmissionRenderTarget = new renderTargetType(1024, 1024, {
  15684. generateMipmaps: true,
  15685. type: utils.convert(HalfFloatType) !== null ? HalfFloatType : UnsignedByteType,
  15686. minFilter: LinearMipmapLinearFilter,
  15687. magFilter: NearestFilter,
  15688. wrapS: ClampToEdgeWrapping,
  15689. wrapT: ClampToEdgeWrapping
  15690. });
  15691. }
  15692. const currentRenderTarget = _this.getRenderTarget();
  15693. _this.setRenderTarget(_transmissionRenderTarget);
  15694. _this.clear(); // Turn off the features which can affect the frag color for opaque objects pass.
  15695. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  15696. const currentToneMapping = _this.toneMapping;
  15697. _this.toneMapping = NoToneMapping;
  15698. renderObjects(opaqueObjects, scene, camera);
  15699. _this.toneMapping = currentToneMapping;
  15700. textures.updateMultisampleRenderTarget(_transmissionRenderTarget);
  15701. textures.updateRenderTargetMipmap(_transmissionRenderTarget);
  15702. _this.setRenderTarget(currentRenderTarget);
  15703. }
  15704. function renderObjects(renderList, scene, camera) {
  15705. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  15706. for (let i = 0, l = renderList.length; i < l; i++) {
  15707. const renderItem = renderList[i];
  15708. const object = renderItem.object;
  15709. const geometry = renderItem.geometry;
  15710. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  15711. const group = renderItem.group;
  15712. if (object.layers.test(camera.layers)) {
  15713. renderObject(object, scene, camera, geometry, material, group);
  15714. }
  15715. }
  15716. }
  15717. function renderObject(object, scene, camera, geometry, material, group) {
  15718. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  15719. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  15720. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  15721. if (object.isImmediateRenderObject) {
  15722. const program = setProgram(camera, scene, material, object);
  15723. state.setMaterial(material);
  15724. bindingStates.reset();
  15725. renderObjectImmediate(object, program);
  15726. } else {
  15727. if (material.transparent === true && material.side === DoubleSide) {
  15728. material.side = BackSide;
  15729. material.needsUpdate = true;
  15730. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  15731. material.side = FrontSide;
  15732. material.needsUpdate = true;
  15733. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  15734. material.side = DoubleSide;
  15735. } else {
  15736. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  15737. }
  15738. }
  15739. object.onAfterRender(_this, scene, camera, geometry, material, group);
  15740. }
  15741. function getProgram(material, scene, object) {
  15742. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  15743. const materialProperties = properties.get(material);
  15744. const lights = currentRenderState.state.lights;
  15745. const shadowsArray = currentRenderState.state.shadowsArray;
  15746. const lightsStateVersion = lights.state.version;
  15747. const parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
  15748. const programCacheKey = programCache.getProgramCacheKey(parameters);
  15749. 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
  15750. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  15751. materialProperties.fog = scene.fog;
  15752. materialProperties.envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || materialProperties.environment);
  15753. if (programs === undefined) {
  15754. // new material
  15755. material.addEventListener('dispose', onMaterialDispose);
  15756. programs = new Map();
  15757. materialProperties.programs = programs;
  15758. }
  15759. let program = programs.get(programCacheKey);
  15760. if (program !== undefined) {
  15761. // early out if program and light state is identical
  15762. if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) {
  15763. updateCommonMaterialProperties(material, parameters);
  15764. return program;
  15765. }
  15766. } else {
  15767. parameters.uniforms = programCache.getUniforms(material);
  15768. material.onBuild(parameters, _this);
  15769. material.onBeforeCompile(parameters, _this);
  15770. program = programCache.acquireProgram(parameters, programCacheKey);
  15771. programs.set(programCacheKey, program);
  15772. materialProperties.uniforms = parameters.uniforms;
  15773. }
  15774. const uniforms = materialProperties.uniforms;
  15775. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  15776. uniforms.clippingPlanes = clipping.uniform;
  15777. }
  15778. updateCommonMaterialProperties(material, parameters); // store the light setup it was created for
  15779. materialProperties.needsLights = materialNeedsLights(material);
  15780. materialProperties.lightsStateVersion = lightsStateVersion;
  15781. if (materialProperties.needsLights) {
  15782. // wire up the material to this renderer's lighting state
  15783. uniforms.ambientLightColor.value = lights.state.ambient;
  15784. uniforms.lightProbe.value = lights.state.probe;
  15785. uniforms.directionalLights.value = lights.state.directional;
  15786. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  15787. uniforms.spotLights.value = lights.state.spot;
  15788. uniforms.spotLightShadows.value = lights.state.spotShadow;
  15789. uniforms.rectAreaLights.value = lights.state.rectArea;
  15790. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  15791. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  15792. uniforms.pointLights.value = lights.state.point;
  15793. uniforms.pointLightShadows.value = lights.state.pointShadow;
  15794. uniforms.hemisphereLights.value = lights.state.hemi;
  15795. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  15796. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  15797. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  15798. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  15799. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  15800. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  15801. }
  15802. const progUniforms = program.getUniforms();
  15803. const uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  15804. materialProperties.currentProgram = program;
  15805. materialProperties.uniformsList = uniformsList;
  15806. return program;
  15807. }
  15808. function updateCommonMaterialProperties(material, parameters) {
  15809. const materialProperties = properties.get(material);
  15810. materialProperties.outputEncoding = parameters.outputEncoding;
  15811. materialProperties.instancing = parameters.instancing;
  15812. materialProperties.skinning = parameters.skinning;
  15813. materialProperties.morphTargets = parameters.morphTargets;
  15814. materialProperties.morphNormals = parameters.morphNormals;
  15815. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  15816. materialProperties.numIntersection = parameters.numClipIntersection;
  15817. materialProperties.vertexAlphas = parameters.vertexAlphas;
  15818. materialProperties.vertexTangents = parameters.vertexTangents;
  15819. }
  15820. function setProgram(camera, scene, material, object) {
  15821. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  15822. textures.resetTextureUnits();
  15823. const fog = scene.fog;
  15824. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  15825. const encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  15826. const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
  15827. const vertexAlphas = material.vertexColors === true && !!object.geometry && !!object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4;
  15828. const vertexTangents = !!object.geometry && !!object.geometry.attributes.tangent;
  15829. const morphTargets = !!object.geometry && !!object.geometry.morphAttributes.position;
  15830. const morphNormals = !!object.geometry && !!object.geometry.morphAttributes.normal;
  15831. const materialProperties = properties.get(material);
  15832. const lights = currentRenderState.state.lights;
  15833. if (_clippingEnabled === true) {
  15834. if (_localClippingEnabled === true || camera !== _currentCamera) {
  15835. const useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  15836. // object instead of the material, once it becomes feasible
  15837. // (#8465, #8379)
  15838. clipping.setState(material, camera, useCache);
  15839. }
  15840. } //
  15841. let needsProgramChange = false;
  15842. if (material.version === materialProperties.__version) {
  15843. if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  15844. needsProgramChange = true;
  15845. } else if (materialProperties.outputEncoding !== encoding) {
  15846. needsProgramChange = true;
  15847. } else if (object.isInstancedMesh && materialProperties.instancing === false) {
  15848. needsProgramChange = true;
  15849. } else if (!object.isInstancedMesh && materialProperties.instancing === true) {
  15850. needsProgramChange = true;
  15851. } else if (object.isSkinnedMesh && materialProperties.skinning === false) {
  15852. needsProgramChange = true;
  15853. } else if (!object.isSkinnedMesh && materialProperties.skinning === true) {
  15854. needsProgramChange = true;
  15855. } else if (materialProperties.envMap !== envMap) {
  15856. needsProgramChange = true;
  15857. } else if (material.fog && materialProperties.fog !== fog) {
  15858. needsProgramChange = true;
  15859. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
  15860. needsProgramChange = true;
  15861. } else if (materialProperties.vertexAlphas !== vertexAlphas) {
  15862. needsProgramChange = true;
  15863. } else if (materialProperties.vertexTangents !== vertexTangents) {
  15864. needsProgramChange = true;
  15865. } else if (materialProperties.morphTargets !== morphTargets) {
  15866. needsProgramChange = true;
  15867. } else if (materialProperties.morphNormals !== morphNormals) {
  15868. needsProgramChange = true;
  15869. }
  15870. } else {
  15871. needsProgramChange = true;
  15872. materialProperties.__version = material.version;
  15873. } //
  15874. let program = materialProperties.currentProgram;
  15875. if (needsProgramChange === true) {
  15876. program = getProgram(material, scene, object);
  15877. }
  15878. let refreshProgram = false;
  15879. let refreshMaterial = false;
  15880. let refreshLights = false;
  15881. const p_uniforms = program.getUniforms(),
  15882. m_uniforms = materialProperties.uniforms;
  15883. if (state.useProgram(program.program)) {
  15884. refreshProgram = true;
  15885. refreshMaterial = true;
  15886. refreshLights = true;
  15887. }
  15888. if (material.id !== _currentMaterialId) {
  15889. _currentMaterialId = material.id;
  15890. refreshMaterial = true;
  15891. }
  15892. if (refreshProgram || _currentCamera !== camera) {
  15893. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  15894. if (capabilities.logarithmicDepthBuffer) {
  15895. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  15896. }
  15897. if (_currentCamera !== camera) {
  15898. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  15899. // now, in case this material supports lights - or later, when
  15900. // the next material that does gets activated:
  15901. refreshMaterial = true; // set to true on material change
  15902. refreshLights = true; // remains set until update done
  15903. } // load material specific uniforms
  15904. // (shader material also gets them for the sake of genericity)
  15905. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  15906. const uCamPos = p_uniforms.map.cameraPosition;
  15907. if (uCamPos !== undefined) {
  15908. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  15909. }
  15910. }
  15911. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  15912. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  15913. }
  15914. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || object.isSkinnedMesh) {
  15915. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  15916. }
  15917. } // skinning uniforms must be set even if material didn't change
  15918. // auto-setting of texture unit for bone texture must go before other textures
  15919. // otherwise textures used for skinning can take over texture units reserved for other material textures
  15920. if (object.isSkinnedMesh) {
  15921. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  15922. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  15923. const skeleton = object.skeleton;
  15924. if (skeleton) {
  15925. if (capabilities.floatVertexTextures) {
  15926. if (skeleton.boneTexture === null) skeleton.computeBoneTexture();
  15927. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  15928. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  15929. } else {
  15930. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  15931. }
  15932. }
  15933. }
  15934. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  15935. materialProperties.receiveShadow = object.receiveShadow;
  15936. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  15937. }
  15938. if (refreshMaterial) {
  15939. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  15940. if (materialProperties.needsLights) {
  15941. // the current material requires lighting info
  15942. // note: all lighting uniforms are always set correctly
  15943. // they simply reference the renderer's state for their
  15944. // values
  15945. //
  15946. // use the current material's .needsUpdate flags to set
  15947. // the GL state when required
  15948. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  15949. } // refresh uniforms common to several materials
  15950. if (fog && material.fog) {
  15951. materials.refreshFogUniforms(m_uniforms, fog);
  15952. }
  15953. materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget);
  15954. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  15955. }
  15956. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  15957. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  15958. material.uniformsNeedUpdate = false;
  15959. }
  15960. if (material.isSpriteMaterial) {
  15961. p_uniforms.setValue(_gl, 'center', object.center);
  15962. } // common matrices
  15963. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  15964. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  15965. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  15966. return program;
  15967. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  15968. function markUniformsLightsNeedsUpdate(uniforms, value) {
  15969. uniforms.ambientLightColor.needsUpdate = value;
  15970. uniforms.lightProbe.needsUpdate = value;
  15971. uniforms.directionalLights.needsUpdate = value;
  15972. uniforms.directionalLightShadows.needsUpdate = value;
  15973. uniforms.pointLights.needsUpdate = value;
  15974. uniforms.pointLightShadows.needsUpdate = value;
  15975. uniforms.spotLights.needsUpdate = value;
  15976. uniforms.spotLightShadows.needsUpdate = value;
  15977. uniforms.rectAreaLights.needsUpdate = value;
  15978. uniforms.hemisphereLights.needsUpdate = value;
  15979. }
  15980. function materialNeedsLights(material) {
  15981. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  15982. }
  15983. this.getActiveCubeFace = function () {
  15984. return _currentActiveCubeFace;
  15985. };
  15986. this.getActiveMipmapLevel = function () {
  15987. return _currentActiveMipmapLevel;
  15988. };
  15989. this.getRenderTarget = function () {
  15990. return _currentRenderTarget;
  15991. };
  15992. this.setRenderTarget = function (renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) {
  15993. _currentRenderTarget = renderTarget;
  15994. _currentActiveCubeFace = activeCubeFace;
  15995. _currentActiveMipmapLevel = activeMipmapLevel;
  15996. if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
  15997. textures.setupRenderTarget(renderTarget);
  15998. }
  15999. let framebuffer = null;
  16000. let isCube = false;
  16001. let isRenderTarget3D = false;
  16002. if (renderTarget) {
  16003. const texture = renderTarget.texture;
  16004. if (texture.isDataTexture3D || texture.isDataTexture2DArray) {
  16005. isRenderTarget3D = true;
  16006. }
  16007. const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  16008. if (renderTarget.isWebGLCubeRenderTarget) {
  16009. framebuffer = __webglFramebuffer[activeCubeFace];
  16010. isCube = true;
  16011. } else if (renderTarget.isWebGLMultisampleRenderTarget) {
  16012. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  16013. } else {
  16014. framebuffer = __webglFramebuffer;
  16015. }
  16016. _currentViewport.copy(renderTarget.viewport);
  16017. _currentScissor.copy(renderTarget.scissor);
  16018. _currentScissorTest = renderTarget.scissorTest;
  16019. } else {
  16020. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  16021. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  16022. _currentScissorTest = _scissorTest;
  16023. }
  16024. const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16025. if (framebufferBound && capabilities.drawBuffers) {
  16026. let needsUpdate = false;
  16027. if (renderTarget) {
  16028. if (renderTarget.isWebGLMultipleRenderTargets) {
  16029. const textures = renderTarget.texture;
  16030. if (_currentDrawBuffers.length !== textures.length || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
  16031. for (let i = 0, il = textures.length; i < il; i++) {
  16032. _currentDrawBuffers[i] = _gl.COLOR_ATTACHMENT0 + i;
  16033. }
  16034. _currentDrawBuffers.length = textures.length;
  16035. needsUpdate = true;
  16036. }
  16037. } else {
  16038. if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
  16039. _currentDrawBuffers[0] = _gl.COLOR_ATTACHMENT0;
  16040. _currentDrawBuffers.length = 1;
  16041. needsUpdate = true;
  16042. }
  16043. }
  16044. } else {
  16045. if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.BACK) {
  16046. _currentDrawBuffers[0] = _gl.BACK;
  16047. _currentDrawBuffers.length = 1;
  16048. needsUpdate = true;
  16049. }
  16050. }
  16051. if (needsUpdate) {
  16052. if (capabilities.isWebGL2) {
  16053. _gl.drawBuffers(_currentDrawBuffers);
  16054. } else {
  16055. extensions.get('WEBGL_draw_buffers').drawBuffersWEBGL(_currentDrawBuffers);
  16056. }
  16057. }
  16058. }
  16059. state.viewport(_currentViewport);
  16060. state.scissor(_currentScissor);
  16061. state.setScissorTest(_currentScissorTest);
  16062. if (isCube) {
  16063. const textureProperties = properties.get(renderTarget.texture);
  16064. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
  16065. } else if (isRenderTarget3D) {
  16066. const textureProperties = properties.get(renderTarget.texture);
  16067. const layer = activeCubeFace || 0;
  16068. _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer);
  16069. }
  16070. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  16071. };
  16072. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  16073. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  16074. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  16075. return;
  16076. }
  16077. let framebuffer = properties.get(renderTarget).__webglFramebuffer;
  16078. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  16079. framebuffer = framebuffer[activeCubeFaceIndex];
  16080. }
  16081. if (framebuffer) {
  16082. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16083. try {
  16084. const texture = renderTarget.texture;
  16085. const textureFormat = texture.format;
  16086. const textureType = texture.type;
  16087. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_FORMAT)) {
  16088. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  16089. return;
  16090. }
  16091. const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has('EXT_color_buffer_half_float') || capabilities.isWebGL2 && extensions.has('EXT_color_buffer_float'));
  16092. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513)
  16093. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.has('OES_texture_float') || extensions.has('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  16094. !halfFloatSupportedByExt) {
  16095. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  16096. return;
  16097. }
  16098. if (_gl.checkFramebufferStatus(_gl.FRAMEBUFFER) === _gl.FRAMEBUFFER_COMPLETE) {
  16099. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  16100. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  16101. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  16102. }
  16103. } else {
  16104. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  16105. }
  16106. } finally {
  16107. // restore framebuffer of current render target if necessary
  16108. const framebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null;
  16109. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16110. }
  16111. }
  16112. };
  16113. this.copyFramebufferToTexture = function (position, texture, level = 0) {
  16114. const levelScale = Math.pow(2, -level);
  16115. const width = Math.floor(texture.image.width * levelScale);
  16116. const height = Math.floor(texture.image.height * levelScale);
  16117. let glFormat = utils.convert(texture.format);
  16118. if (capabilities.isWebGL2) {
  16119. // Workaround for https://bugs.chromium.org/p/chromium/issues/detail?id=1120100
  16120. // Not needed in Chrome 93+
  16121. if (glFormat === _gl.RGB) glFormat = _gl.RGB8;
  16122. if (glFormat === _gl.RGBA) glFormat = _gl.RGBA8;
  16123. }
  16124. textures.setTexture2D(texture, 0);
  16125. _gl.copyTexImage2D(_gl.TEXTURE_2D, level, glFormat, position.x, position.y, width, height, 0);
  16126. state.unbindTexture();
  16127. };
  16128. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level = 0) {
  16129. const width = srcTexture.image.width;
  16130. const height = srcTexture.image.height;
  16131. const glFormat = utils.convert(dstTexture.format);
  16132. const glType = utils.convert(dstTexture.type);
  16133. textures.setTexture2D(dstTexture, 0); // As another texture upload may have changed pixelStorei
  16134. // parameters, make sure they are correct for the dstTexture
  16135. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  16136. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  16137. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  16138. if (srcTexture.isDataTexture) {
  16139. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  16140. } else {
  16141. if (srcTexture.isCompressedTexture) {
  16142. _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
  16143. } else {
  16144. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image);
  16145. }
  16146. } // Generate mipmaps only when copying level 0
  16147. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(_gl.TEXTURE_2D);
  16148. state.unbindTexture();
  16149. };
  16150. this.copyTextureToTexture3D = function (sourceBox, position, srcTexture, dstTexture, level = 0) {
  16151. if (_this.isWebGL1Renderer) {
  16152. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.');
  16153. return;
  16154. }
  16155. const width = sourceBox.max.x - sourceBox.min.x + 1;
  16156. const height = sourceBox.max.y - sourceBox.min.y + 1;
  16157. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  16158. const glFormat = utils.convert(dstTexture.format);
  16159. const glType = utils.convert(dstTexture.type);
  16160. let glTarget;
  16161. if (dstTexture.isDataTexture3D) {
  16162. textures.setTexture3D(dstTexture, 0);
  16163. glTarget = _gl.TEXTURE_3D;
  16164. } else if (dstTexture.isDataTexture2DArray) {
  16165. textures.setTexture2DArray(dstTexture, 0);
  16166. glTarget = _gl.TEXTURE_2D_ARRAY;
  16167. } else {
  16168. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.');
  16169. return;
  16170. }
  16171. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  16172. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  16173. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  16174. const unpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH);
  16175. const unpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT);
  16176. const unpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS);
  16177. const unpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS);
  16178. const unpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES);
  16179. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[0] : srcTexture.image;
  16180. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width);
  16181. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, image.height);
  16182. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, sourceBox.min.x);
  16183. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, sourceBox.min.y);
  16184. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, sourceBox.min.z);
  16185. if (srcTexture.isDataTexture || srcTexture.isDataTexture3D) {
  16186. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data);
  16187. } else {
  16188. if (srcTexture.isCompressedTexture) {
  16189. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.');
  16190. _gl.compressedTexSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data);
  16191. } else {
  16192. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image);
  16193. }
  16194. }
  16195. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, unpackRowLen);
  16196. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight);
  16197. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, unpackSkipPixels);
  16198. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, unpackSkipRows);
  16199. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, unpackSkipImages); // Generate mipmaps only when copying level 0
  16200. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(glTarget);
  16201. state.unbindTexture();
  16202. };
  16203. this.initTexture = function (texture) {
  16204. textures.setTexture2D(texture, 0);
  16205. state.unbindTexture();
  16206. };
  16207. this.resetState = function () {
  16208. _currentActiveCubeFace = 0;
  16209. _currentActiveMipmapLevel = 0;
  16210. _currentRenderTarget = null;
  16211. state.reset();
  16212. bindingStates.reset();
  16213. };
  16214. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  16215. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  16216. detail: this
  16217. })); // eslint-disable-line no-undef
  16218. }
  16219. }
  16220. class WebGL1Renderer extends WebGLRenderer {}
  16221. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  16222. class FogExp2 {
  16223. constructor(color, density = 0.00025) {
  16224. this.name = '';
  16225. this.color = new Color(color);
  16226. this.density = density;
  16227. }
  16228. clone() {
  16229. return new FogExp2(this.color, this.density);
  16230. }
  16231. toJSON() {
  16232. return {
  16233. type: 'FogExp2',
  16234. color: this.color.getHex(),
  16235. density: this.density
  16236. };
  16237. }
  16238. }
  16239. FogExp2.prototype.isFogExp2 = true;
  16240. class Fog {
  16241. constructor(color, near = 1, far = 1000) {
  16242. this.name = '';
  16243. this.color = new Color(color);
  16244. this.near = near;
  16245. this.far = far;
  16246. }
  16247. clone() {
  16248. return new Fog(this.color, this.near, this.far);
  16249. }
  16250. toJSON() {
  16251. return {
  16252. type: 'Fog',
  16253. color: this.color.getHex(),
  16254. near: this.near,
  16255. far: this.far
  16256. };
  16257. }
  16258. }
  16259. Fog.prototype.isFog = true;
  16260. class Scene extends Object3D {
  16261. constructor() {
  16262. super();
  16263. this.type = 'Scene';
  16264. this.background = null;
  16265. this.environment = null;
  16266. this.fog = null;
  16267. this.overrideMaterial = null;
  16268. this.autoUpdate = true; // checked by the renderer
  16269. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  16270. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  16271. detail: this
  16272. })); // eslint-disable-line no-undef
  16273. }
  16274. }
  16275. copy(source, recursive) {
  16276. super.copy(source, recursive);
  16277. if (source.background !== null) this.background = source.background.clone();
  16278. if (source.environment !== null) this.environment = source.environment.clone();
  16279. if (source.fog !== null) this.fog = source.fog.clone();
  16280. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  16281. this.autoUpdate = source.autoUpdate;
  16282. this.matrixAutoUpdate = source.matrixAutoUpdate;
  16283. return this;
  16284. }
  16285. toJSON(meta) {
  16286. const data = super.toJSON(meta);
  16287. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  16288. return data;
  16289. }
  16290. }
  16291. Scene.prototype.isScene = true;
  16292. class InterleavedBuffer {
  16293. constructor(array, stride) {
  16294. this.array = array;
  16295. this.stride = stride;
  16296. this.count = array !== undefined ? array.length / stride : 0;
  16297. this.usage = StaticDrawUsage;
  16298. this.updateRange = {
  16299. offset: 0,
  16300. count: -1
  16301. };
  16302. this.version = 0;
  16303. this.uuid = generateUUID();
  16304. }
  16305. onUploadCallback() {}
  16306. set needsUpdate(value) {
  16307. if (value === true) this.version++;
  16308. }
  16309. setUsage(value) {
  16310. this.usage = value;
  16311. return this;
  16312. }
  16313. copy(source) {
  16314. this.array = new source.array.constructor(source.array);
  16315. this.count = source.count;
  16316. this.stride = source.stride;
  16317. this.usage = source.usage;
  16318. return this;
  16319. }
  16320. copyAt(index1, attribute, index2) {
  16321. index1 *= this.stride;
  16322. index2 *= attribute.stride;
  16323. for (let i = 0, l = this.stride; i < l; i++) {
  16324. this.array[index1 + i] = attribute.array[index2 + i];
  16325. }
  16326. return this;
  16327. }
  16328. set(value, offset = 0) {
  16329. this.array.set(value, offset);
  16330. return this;
  16331. }
  16332. clone(data) {
  16333. if (data.arrayBuffers === undefined) {
  16334. data.arrayBuffers = {};
  16335. }
  16336. if (this.array.buffer._uuid === undefined) {
  16337. this.array.buffer._uuid = generateUUID();
  16338. }
  16339. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  16340. data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
  16341. }
  16342. const array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
  16343. const ib = new this.constructor(array, this.stride);
  16344. ib.setUsage(this.usage);
  16345. return ib;
  16346. }
  16347. onUpload(callback) {
  16348. this.onUploadCallback = callback;
  16349. return this;
  16350. }
  16351. toJSON(data) {
  16352. if (data.arrayBuffers === undefined) {
  16353. data.arrayBuffers = {};
  16354. } // generate UUID for array buffer if necessary
  16355. if (this.array.buffer._uuid === undefined) {
  16356. this.array.buffer._uuid = generateUUID();
  16357. }
  16358. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  16359. data.arrayBuffers[this.array.buffer._uuid] = Array.prototype.slice.call(new Uint32Array(this.array.buffer));
  16360. } //
  16361. return {
  16362. uuid: this.uuid,
  16363. buffer: this.array.buffer._uuid,
  16364. type: this.array.constructor.name,
  16365. stride: this.stride
  16366. };
  16367. }
  16368. }
  16369. InterleavedBuffer.prototype.isInterleavedBuffer = true;
  16370. const _vector$6 = /*@__PURE__*/new Vector3();
  16371. class InterleavedBufferAttribute {
  16372. constructor(interleavedBuffer, itemSize, offset, normalized = false) {
  16373. this.name = '';
  16374. this.data = interleavedBuffer;
  16375. this.itemSize = itemSize;
  16376. this.offset = offset;
  16377. this.normalized = normalized === true;
  16378. }
  16379. get count() {
  16380. return this.data.count;
  16381. }
  16382. get array() {
  16383. return this.data.array;
  16384. }
  16385. set needsUpdate(value) {
  16386. this.data.needsUpdate = value;
  16387. }
  16388. applyMatrix4(m) {
  16389. for (let i = 0, l = this.data.count; i < l; i++) {
  16390. _vector$6.x = this.getX(i);
  16391. _vector$6.y = this.getY(i);
  16392. _vector$6.z = this.getZ(i);
  16393. _vector$6.applyMatrix4(m);
  16394. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  16395. }
  16396. return this;
  16397. }
  16398. applyNormalMatrix(m) {
  16399. for (let i = 0, l = this.count; i < l; i++) {
  16400. _vector$6.x = this.getX(i);
  16401. _vector$6.y = this.getY(i);
  16402. _vector$6.z = this.getZ(i);
  16403. _vector$6.applyNormalMatrix(m);
  16404. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  16405. }
  16406. return this;
  16407. }
  16408. transformDirection(m) {
  16409. for (let i = 0, l = this.count; i < l; i++) {
  16410. _vector$6.x = this.getX(i);
  16411. _vector$6.y = this.getY(i);
  16412. _vector$6.z = this.getZ(i);
  16413. _vector$6.transformDirection(m);
  16414. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  16415. }
  16416. return this;
  16417. }
  16418. setX(index, x) {
  16419. this.data.array[index * this.data.stride + this.offset] = x;
  16420. return this;
  16421. }
  16422. setY(index, y) {
  16423. this.data.array[index * this.data.stride + this.offset + 1] = y;
  16424. return this;
  16425. }
  16426. setZ(index, z) {
  16427. this.data.array[index * this.data.stride + this.offset + 2] = z;
  16428. return this;
  16429. }
  16430. setW(index, w) {
  16431. this.data.array[index * this.data.stride + this.offset + 3] = w;
  16432. return this;
  16433. }
  16434. getX(index) {
  16435. return this.data.array[index * this.data.stride + this.offset];
  16436. }
  16437. getY(index) {
  16438. return this.data.array[index * this.data.stride + this.offset + 1];
  16439. }
  16440. getZ(index) {
  16441. return this.data.array[index * this.data.stride + this.offset + 2];
  16442. }
  16443. getW(index) {
  16444. return this.data.array[index * this.data.stride + this.offset + 3];
  16445. }
  16446. setXY(index, x, y) {
  16447. index = index * this.data.stride + this.offset;
  16448. this.data.array[index + 0] = x;
  16449. this.data.array[index + 1] = y;
  16450. return this;
  16451. }
  16452. setXYZ(index, x, y, z) {
  16453. index = index * this.data.stride + this.offset;
  16454. this.data.array[index + 0] = x;
  16455. this.data.array[index + 1] = y;
  16456. this.data.array[index + 2] = z;
  16457. return this;
  16458. }
  16459. setXYZW(index, x, y, z, w) {
  16460. index = index * this.data.stride + this.offset;
  16461. this.data.array[index + 0] = x;
  16462. this.data.array[index + 1] = y;
  16463. this.data.array[index + 2] = z;
  16464. this.data.array[index + 3] = w;
  16465. return this;
  16466. }
  16467. clone(data) {
  16468. if (data === undefined) {
  16469. console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.');
  16470. const array = [];
  16471. for (let i = 0; i < this.count; i++) {
  16472. const index = i * this.data.stride + this.offset;
  16473. for (let j = 0; j < this.itemSize; j++) {
  16474. array.push(this.data.array[index + j]);
  16475. }
  16476. }
  16477. return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
  16478. } else {
  16479. if (data.interleavedBuffers === undefined) {
  16480. data.interleavedBuffers = {};
  16481. }
  16482. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  16483. data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
  16484. }
  16485. return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  16486. }
  16487. }
  16488. toJSON(data) {
  16489. if (data === undefined) {
  16490. console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.');
  16491. const array = [];
  16492. for (let i = 0; i < this.count; i++) {
  16493. const index = i * this.data.stride + this.offset;
  16494. for (let j = 0; j < this.itemSize; j++) {
  16495. array.push(this.data.array[index + j]);
  16496. }
  16497. } // deinterleave data and save it as an ordinary buffer attribute for now
  16498. return {
  16499. itemSize: this.itemSize,
  16500. type: this.array.constructor.name,
  16501. array: array,
  16502. normalized: this.normalized
  16503. };
  16504. } else {
  16505. // save as true interlaved attribtue
  16506. if (data.interleavedBuffers === undefined) {
  16507. data.interleavedBuffers = {};
  16508. }
  16509. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  16510. data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
  16511. }
  16512. return {
  16513. isInterleavedBufferAttribute: true,
  16514. itemSize: this.itemSize,
  16515. data: this.data.uuid,
  16516. offset: this.offset,
  16517. normalized: this.normalized
  16518. };
  16519. }
  16520. }
  16521. }
  16522. InterleavedBufferAttribute.prototype.isInterleavedBufferAttribute = true;
  16523. /**
  16524. * parameters = {
  16525. * color: <hex>,
  16526. * map: new THREE.Texture( <Image> ),
  16527. * alphaMap: new THREE.Texture( <Image> ),
  16528. * rotation: <float>,
  16529. * sizeAttenuation: <bool>
  16530. * }
  16531. */
  16532. class SpriteMaterial extends Material {
  16533. constructor(parameters) {
  16534. super();
  16535. this.type = 'SpriteMaterial';
  16536. this.color = new Color(0xffffff);
  16537. this.map = null;
  16538. this.alphaMap = null;
  16539. this.rotation = 0;
  16540. this.sizeAttenuation = true;
  16541. this.transparent = true;
  16542. this.setValues(parameters);
  16543. }
  16544. copy(source) {
  16545. super.copy(source);
  16546. this.color.copy(source.color);
  16547. this.map = source.map;
  16548. this.alphaMap = source.alphaMap;
  16549. this.rotation = source.rotation;
  16550. this.sizeAttenuation = source.sizeAttenuation;
  16551. return this;
  16552. }
  16553. }
  16554. SpriteMaterial.prototype.isSpriteMaterial = true;
  16555. let _geometry;
  16556. const _intersectPoint = /*@__PURE__*/new Vector3();
  16557. const _worldScale = /*@__PURE__*/new Vector3();
  16558. const _mvPosition = /*@__PURE__*/new Vector3();
  16559. const _alignedPosition = /*@__PURE__*/new Vector2();
  16560. const _rotatedPosition = /*@__PURE__*/new Vector2();
  16561. const _viewWorldMatrix = /*@__PURE__*/new Matrix4();
  16562. const _vA = /*@__PURE__*/new Vector3();
  16563. const _vB = /*@__PURE__*/new Vector3();
  16564. const _vC = /*@__PURE__*/new Vector3();
  16565. const _uvA = /*@__PURE__*/new Vector2();
  16566. const _uvB = /*@__PURE__*/new Vector2();
  16567. const _uvC = /*@__PURE__*/new Vector2();
  16568. class Sprite extends Object3D {
  16569. constructor(material) {
  16570. super();
  16571. this.type = 'Sprite';
  16572. if (_geometry === undefined) {
  16573. _geometry = new BufferGeometry();
  16574. 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]);
  16575. const interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  16576. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  16577. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  16578. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  16579. }
  16580. this.geometry = _geometry;
  16581. this.material = material !== undefined ? material : new SpriteMaterial();
  16582. this.center = new Vector2(0.5, 0.5);
  16583. }
  16584. raycast(raycaster, intersects) {
  16585. if (raycaster.camera === null) {
  16586. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  16587. }
  16588. _worldScale.setFromMatrixScale(this.matrixWorld);
  16589. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  16590. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  16591. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  16592. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  16593. _worldScale.multiplyScalar(-_mvPosition.z);
  16594. }
  16595. const rotation = this.material.rotation;
  16596. let sin, cos;
  16597. if (rotation !== 0) {
  16598. cos = Math.cos(rotation);
  16599. sin = Math.sin(rotation);
  16600. }
  16601. const center = this.center;
  16602. transformVertex(_vA.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16603. transformVertex(_vB.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16604. transformVertex(_vC.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16605. _uvA.set(0, 0);
  16606. _uvB.set(1, 0);
  16607. _uvC.set(1, 1); // check first triangle
  16608. let intersect = raycaster.ray.intersectTriangle(_vA, _vB, _vC, false, _intersectPoint);
  16609. if (intersect === null) {
  16610. // check second triangle
  16611. transformVertex(_vB.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16612. _uvB.set(0, 1);
  16613. intersect = raycaster.ray.intersectTriangle(_vA, _vC, _vB, false, _intersectPoint);
  16614. if (intersect === null) {
  16615. return;
  16616. }
  16617. }
  16618. const distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  16619. if (distance < raycaster.near || distance > raycaster.far) return;
  16620. intersects.push({
  16621. distance: distance,
  16622. point: _intersectPoint.clone(),
  16623. uv: Triangle.getUV(_intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2()),
  16624. face: null,
  16625. object: this
  16626. });
  16627. }
  16628. copy(source) {
  16629. super.copy(source);
  16630. if (source.center !== undefined) this.center.copy(source.center);
  16631. this.material = source.material;
  16632. return this;
  16633. }
  16634. }
  16635. Sprite.prototype.isSprite = true;
  16636. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  16637. // compute position in camera space
  16638. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  16639. if (sin !== undefined) {
  16640. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  16641. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  16642. } else {
  16643. _rotatedPosition.copy(_alignedPosition);
  16644. }
  16645. vertexPosition.copy(mvPosition);
  16646. vertexPosition.x += _rotatedPosition.x;
  16647. vertexPosition.y += _rotatedPosition.y; // transform to world space
  16648. vertexPosition.applyMatrix4(_viewWorldMatrix);
  16649. }
  16650. const _v1$2 = /*@__PURE__*/new Vector3();
  16651. const _v2$1 = /*@__PURE__*/new Vector3();
  16652. class LOD extends Object3D {
  16653. constructor() {
  16654. super();
  16655. this._currentLevel = 0;
  16656. this.type = 'LOD';
  16657. Object.defineProperties(this, {
  16658. levels: {
  16659. enumerable: true,
  16660. value: []
  16661. },
  16662. isLOD: {
  16663. value: true
  16664. }
  16665. });
  16666. this.autoUpdate = true;
  16667. }
  16668. copy(source) {
  16669. super.copy(source, false);
  16670. const levels = source.levels;
  16671. for (let i = 0, l = levels.length; i < l; i++) {
  16672. const level = levels[i];
  16673. this.addLevel(level.object.clone(), level.distance);
  16674. }
  16675. this.autoUpdate = source.autoUpdate;
  16676. return this;
  16677. }
  16678. addLevel(object, distance = 0) {
  16679. distance = Math.abs(distance);
  16680. const levels = this.levels;
  16681. let l;
  16682. for (l = 0; l < levels.length; l++) {
  16683. if (distance < levels[l].distance) {
  16684. break;
  16685. }
  16686. }
  16687. levels.splice(l, 0, {
  16688. distance: distance,
  16689. object: object
  16690. });
  16691. this.add(object);
  16692. return this;
  16693. }
  16694. getCurrentLevel() {
  16695. return this._currentLevel;
  16696. }
  16697. getObjectForDistance(distance) {
  16698. const levels = this.levels;
  16699. if (levels.length > 0) {
  16700. let i, l;
  16701. for (i = 1, l = levels.length; i < l; i++) {
  16702. if (distance < levels[i].distance) {
  16703. break;
  16704. }
  16705. }
  16706. return levels[i - 1].object;
  16707. }
  16708. return null;
  16709. }
  16710. raycast(raycaster, intersects) {
  16711. const levels = this.levels;
  16712. if (levels.length > 0) {
  16713. _v1$2.setFromMatrixPosition(this.matrixWorld);
  16714. const distance = raycaster.ray.origin.distanceTo(_v1$2);
  16715. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  16716. }
  16717. }
  16718. update(camera) {
  16719. const levels = this.levels;
  16720. if (levels.length > 1) {
  16721. _v1$2.setFromMatrixPosition(camera.matrixWorld);
  16722. _v2$1.setFromMatrixPosition(this.matrixWorld);
  16723. const distance = _v1$2.distanceTo(_v2$1) / camera.zoom;
  16724. levels[0].object.visible = true;
  16725. let i, l;
  16726. for (i = 1, l = levels.length; i < l; i++) {
  16727. if (distance >= levels[i].distance) {
  16728. levels[i - 1].object.visible = false;
  16729. levels[i].object.visible = true;
  16730. } else {
  16731. break;
  16732. }
  16733. }
  16734. this._currentLevel = i - 1;
  16735. for (; i < l; i++) {
  16736. levels[i].object.visible = false;
  16737. }
  16738. }
  16739. }
  16740. toJSON(meta) {
  16741. const data = super.toJSON(meta);
  16742. if (this.autoUpdate === false) data.object.autoUpdate = false;
  16743. data.object.levels = [];
  16744. const levels = this.levels;
  16745. for (let i = 0, l = levels.length; i < l; i++) {
  16746. const level = levels[i];
  16747. data.object.levels.push({
  16748. object: level.object.uuid,
  16749. distance: level.distance
  16750. });
  16751. }
  16752. return data;
  16753. }
  16754. }
  16755. const _basePosition = /*@__PURE__*/new Vector3();
  16756. const _skinIndex = /*@__PURE__*/new Vector4();
  16757. const _skinWeight = /*@__PURE__*/new Vector4();
  16758. const _vector$5 = /*@__PURE__*/new Vector3();
  16759. const _matrix = /*@__PURE__*/new Matrix4();
  16760. class SkinnedMesh extends Mesh {
  16761. constructor(geometry, material) {
  16762. super(geometry, material);
  16763. this.type = 'SkinnedMesh';
  16764. this.bindMode = 'attached';
  16765. this.bindMatrix = new Matrix4();
  16766. this.bindMatrixInverse = new Matrix4();
  16767. }
  16768. copy(source) {
  16769. super.copy(source);
  16770. this.bindMode = source.bindMode;
  16771. this.bindMatrix.copy(source.bindMatrix);
  16772. this.bindMatrixInverse.copy(source.bindMatrixInverse);
  16773. this.skeleton = source.skeleton;
  16774. return this;
  16775. }
  16776. bind(skeleton, bindMatrix) {
  16777. this.skeleton = skeleton;
  16778. if (bindMatrix === undefined) {
  16779. this.updateMatrixWorld(true);
  16780. this.skeleton.calculateInverses();
  16781. bindMatrix = this.matrixWorld;
  16782. }
  16783. this.bindMatrix.copy(bindMatrix);
  16784. this.bindMatrixInverse.copy(bindMatrix).invert();
  16785. }
  16786. pose() {
  16787. this.skeleton.pose();
  16788. }
  16789. normalizeSkinWeights() {
  16790. const vector = new Vector4();
  16791. const skinWeight = this.geometry.attributes.skinWeight;
  16792. for (let i = 0, l = skinWeight.count; i < l; i++) {
  16793. vector.x = skinWeight.getX(i);
  16794. vector.y = skinWeight.getY(i);
  16795. vector.z = skinWeight.getZ(i);
  16796. vector.w = skinWeight.getW(i);
  16797. const scale = 1.0 / vector.manhattanLength();
  16798. if (scale !== Infinity) {
  16799. vector.multiplyScalar(scale);
  16800. } else {
  16801. vector.set(1, 0, 0, 0); // do something reasonable
  16802. }
  16803. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  16804. }
  16805. }
  16806. updateMatrixWorld(force) {
  16807. super.updateMatrixWorld(force);
  16808. if (this.bindMode === 'attached') {
  16809. this.bindMatrixInverse.copy(this.matrixWorld).invert();
  16810. } else if (this.bindMode === 'detached') {
  16811. this.bindMatrixInverse.copy(this.bindMatrix).invert();
  16812. } else {
  16813. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  16814. }
  16815. }
  16816. boneTransform(index, target) {
  16817. const skeleton = this.skeleton;
  16818. const geometry = this.geometry;
  16819. _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
  16820. _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
  16821. _basePosition.fromBufferAttribute(geometry.attributes.position, index).applyMatrix4(this.bindMatrix);
  16822. target.set(0, 0, 0);
  16823. for (let i = 0; i < 4; i++) {
  16824. const weight = _skinWeight.getComponent(i);
  16825. if (weight !== 0) {
  16826. const boneIndex = _skinIndex.getComponent(i);
  16827. _matrix.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
  16828. target.addScaledVector(_vector$5.copy(_basePosition).applyMatrix4(_matrix), weight);
  16829. }
  16830. }
  16831. return target.applyMatrix4(this.bindMatrixInverse);
  16832. }
  16833. }
  16834. SkinnedMesh.prototype.isSkinnedMesh = true;
  16835. class Bone extends Object3D {
  16836. constructor() {
  16837. super();
  16838. this.type = 'Bone';
  16839. }
  16840. }
  16841. Bone.prototype.isBone = true;
  16842. class DataTexture extends Texture {
  16843. constructor(data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding) {
  16844. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  16845. this.image = {
  16846. data: data,
  16847. width: width,
  16848. height: height
  16849. };
  16850. this.magFilter = magFilter;
  16851. this.minFilter = minFilter;
  16852. this.generateMipmaps = false;
  16853. this.flipY = false;
  16854. this.unpackAlignment = 1;
  16855. this.needsUpdate = true;
  16856. }
  16857. }
  16858. DataTexture.prototype.isDataTexture = true;
  16859. const _offsetMatrix = /*@__PURE__*/new Matrix4();
  16860. const _identityMatrix = /*@__PURE__*/new Matrix4();
  16861. class Skeleton {
  16862. constructor(bones = [], boneInverses = []) {
  16863. this.uuid = generateUUID();
  16864. this.bones = bones.slice(0);
  16865. this.boneInverses = boneInverses;
  16866. this.boneMatrices = null;
  16867. this.boneTexture = null;
  16868. this.boneTextureSize = 0;
  16869. this.frame = -1;
  16870. this.init();
  16871. }
  16872. init() {
  16873. const bones = this.bones;
  16874. const boneInverses = this.boneInverses;
  16875. this.boneMatrices = new Float32Array(bones.length * 16); // calculate inverse bone matrices if necessary
  16876. if (boneInverses.length === 0) {
  16877. this.calculateInverses();
  16878. } else {
  16879. // handle special case
  16880. if (bones.length !== boneInverses.length) {
  16881. console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
  16882. this.boneInverses = [];
  16883. for (let i = 0, il = this.bones.length; i < il; i++) {
  16884. this.boneInverses.push(new Matrix4());
  16885. }
  16886. }
  16887. }
  16888. }
  16889. calculateInverses() {
  16890. this.boneInverses.length = 0;
  16891. for (let i = 0, il = this.bones.length; i < il; i++) {
  16892. const inverse = new Matrix4();
  16893. if (this.bones[i]) {
  16894. inverse.copy(this.bones[i].matrixWorld).invert();
  16895. }
  16896. this.boneInverses.push(inverse);
  16897. }
  16898. }
  16899. pose() {
  16900. // recover the bind-time world matrices
  16901. for (let i = 0, il = this.bones.length; i < il; i++) {
  16902. const bone = this.bones[i];
  16903. if (bone) {
  16904. bone.matrixWorld.copy(this.boneInverses[i]).invert();
  16905. }
  16906. } // compute the local matrices, positions, rotations and scales
  16907. for (let i = 0, il = this.bones.length; i < il; i++) {
  16908. const bone = this.bones[i];
  16909. if (bone) {
  16910. if (bone.parent && bone.parent.isBone) {
  16911. bone.matrix.copy(bone.parent.matrixWorld).invert();
  16912. bone.matrix.multiply(bone.matrixWorld);
  16913. } else {
  16914. bone.matrix.copy(bone.matrixWorld);
  16915. }
  16916. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  16917. }
  16918. }
  16919. }
  16920. update() {
  16921. const bones = this.bones;
  16922. const boneInverses = this.boneInverses;
  16923. const boneMatrices = this.boneMatrices;
  16924. const boneTexture = this.boneTexture; // flatten bone matrices to array
  16925. for (let i = 0, il = bones.length; i < il; i++) {
  16926. // compute the offset between the current and the original transform
  16927. const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  16928. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  16929. _offsetMatrix.toArray(boneMatrices, i * 16);
  16930. }
  16931. if (boneTexture !== null) {
  16932. boneTexture.needsUpdate = true;
  16933. }
  16934. }
  16935. clone() {
  16936. return new Skeleton(this.bones, this.boneInverses);
  16937. }
  16938. computeBoneTexture() {
  16939. // layout (1 matrix = 4 pixels)
  16940. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  16941. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  16942. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  16943. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  16944. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  16945. let size = Math.sqrt(this.bones.length * 4); // 4 pixels needed for 1 matrix
  16946. size = ceilPowerOfTwo(size);
  16947. size = Math.max(size, 4);
  16948. const boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  16949. boneMatrices.set(this.boneMatrices); // copy current values
  16950. const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  16951. this.boneMatrices = boneMatrices;
  16952. this.boneTexture = boneTexture;
  16953. this.boneTextureSize = size;
  16954. return this;
  16955. }
  16956. getBoneByName(name) {
  16957. for (let i = 0, il = this.bones.length; i < il; i++) {
  16958. const bone = this.bones[i];
  16959. if (bone.name === name) {
  16960. return bone;
  16961. }
  16962. }
  16963. return undefined;
  16964. }
  16965. dispose() {
  16966. if (this.boneTexture !== null) {
  16967. this.boneTexture.dispose();
  16968. this.boneTexture = null;
  16969. }
  16970. }
  16971. fromJSON(json, bones) {
  16972. this.uuid = json.uuid;
  16973. for (let i = 0, l = json.bones.length; i < l; i++) {
  16974. const uuid = json.bones[i];
  16975. let bone = bones[uuid];
  16976. if (bone === undefined) {
  16977. console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
  16978. bone = new Bone();
  16979. }
  16980. this.bones.push(bone);
  16981. this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
  16982. }
  16983. this.init();
  16984. return this;
  16985. }
  16986. toJSON() {
  16987. const data = {
  16988. metadata: {
  16989. version: 4.5,
  16990. type: 'Skeleton',
  16991. generator: 'Skeleton.toJSON'
  16992. },
  16993. bones: [],
  16994. boneInverses: []
  16995. };
  16996. data.uuid = this.uuid;
  16997. const bones = this.bones;
  16998. const boneInverses = this.boneInverses;
  16999. for (let i = 0, l = bones.length; i < l; i++) {
  17000. const bone = bones[i];
  17001. data.bones.push(bone.uuid);
  17002. const boneInverse = boneInverses[i];
  17003. data.boneInverses.push(boneInverse.toArray());
  17004. }
  17005. return data;
  17006. }
  17007. }
  17008. class InstancedBufferAttribute extends BufferAttribute {
  17009. constructor(array, itemSize, normalized, meshPerAttribute = 1) {
  17010. if (typeof normalized === 'number') {
  17011. meshPerAttribute = normalized;
  17012. normalized = false;
  17013. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  17014. }
  17015. super(array, itemSize, normalized);
  17016. this.meshPerAttribute = meshPerAttribute;
  17017. }
  17018. copy(source) {
  17019. super.copy(source);
  17020. this.meshPerAttribute = source.meshPerAttribute;
  17021. return this;
  17022. }
  17023. toJSON() {
  17024. const data = super.toJSON();
  17025. data.meshPerAttribute = this.meshPerAttribute;
  17026. data.isInstancedBufferAttribute = true;
  17027. return data;
  17028. }
  17029. }
  17030. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  17031. const _instanceLocalMatrix = /*@__PURE__*/new Matrix4();
  17032. const _instanceWorldMatrix = /*@__PURE__*/new Matrix4();
  17033. const _instanceIntersects = [];
  17034. const _mesh = /*@__PURE__*/new Mesh();
  17035. class InstancedMesh extends Mesh {
  17036. constructor(geometry, material, count) {
  17037. super(geometry, material);
  17038. this.instanceMatrix = new InstancedBufferAttribute(new Float32Array(count * 16), 16);
  17039. this.instanceColor = null;
  17040. this.count = count;
  17041. this.frustumCulled = false;
  17042. }
  17043. copy(source) {
  17044. super.copy(source);
  17045. this.instanceMatrix.copy(source.instanceMatrix);
  17046. if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone();
  17047. this.count = source.count;
  17048. return this;
  17049. }
  17050. getColorAt(index, color) {
  17051. color.fromArray(this.instanceColor.array, index * 3);
  17052. }
  17053. getMatrixAt(index, matrix) {
  17054. matrix.fromArray(this.instanceMatrix.array, index * 16);
  17055. }
  17056. raycast(raycaster, intersects) {
  17057. const matrixWorld = this.matrixWorld;
  17058. const raycastTimes = this.count;
  17059. _mesh.geometry = this.geometry;
  17060. _mesh.material = this.material;
  17061. if (_mesh.material === undefined) return;
  17062. for (let instanceId = 0; instanceId < raycastTimes; instanceId++) {
  17063. // calculate the world matrix for each instance
  17064. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  17065. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
  17066. _mesh.matrixWorld = _instanceWorldMatrix;
  17067. _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
  17068. for (let i = 0, l = _instanceIntersects.length; i < l; i++) {
  17069. const intersect = _instanceIntersects[i];
  17070. intersect.instanceId = instanceId;
  17071. intersect.object = this;
  17072. intersects.push(intersect);
  17073. }
  17074. _instanceIntersects.length = 0;
  17075. }
  17076. }
  17077. setColorAt(index, color) {
  17078. if (this.instanceColor === null) {
  17079. this.instanceColor = new InstancedBufferAttribute(new Float32Array(this.instanceMatrix.count * 3), 3);
  17080. }
  17081. color.toArray(this.instanceColor.array, index * 3);
  17082. }
  17083. setMatrixAt(index, matrix) {
  17084. matrix.toArray(this.instanceMatrix.array, index * 16);
  17085. }
  17086. updateMorphTargets() {}
  17087. dispose() {
  17088. this.dispatchEvent({
  17089. type: 'dispose'
  17090. });
  17091. }
  17092. }
  17093. InstancedMesh.prototype.isInstancedMesh = true;
  17094. /**
  17095. * parameters = {
  17096. * color: <hex>,
  17097. * opacity: <float>,
  17098. *
  17099. * linewidth: <float>,
  17100. * linecap: "round",
  17101. * linejoin: "round"
  17102. * }
  17103. */
  17104. class LineBasicMaterial extends Material {
  17105. constructor(parameters) {
  17106. super();
  17107. this.type = 'LineBasicMaterial';
  17108. this.color = new Color(0xffffff);
  17109. this.linewidth = 1;
  17110. this.linecap = 'round';
  17111. this.linejoin = 'round';
  17112. this.setValues(parameters);
  17113. }
  17114. copy(source) {
  17115. super.copy(source);
  17116. this.color.copy(source.color);
  17117. this.linewidth = source.linewidth;
  17118. this.linecap = source.linecap;
  17119. this.linejoin = source.linejoin;
  17120. return this;
  17121. }
  17122. }
  17123. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  17124. const _start$1 = /*@__PURE__*/new Vector3();
  17125. const _end$1 = /*@__PURE__*/new Vector3();
  17126. const _inverseMatrix$1 = /*@__PURE__*/new Matrix4();
  17127. const _ray$1 = /*@__PURE__*/new Ray();
  17128. const _sphere$1 = /*@__PURE__*/new Sphere();
  17129. class Line extends Object3D {
  17130. constructor(geometry = new BufferGeometry(), material = new LineBasicMaterial()) {
  17131. super();
  17132. this.type = 'Line';
  17133. this.geometry = geometry;
  17134. this.material = material;
  17135. this.updateMorphTargets();
  17136. }
  17137. copy(source) {
  17138. super.copy(source);
  17139. this.material = source.material;
  17140. this.geometry = source.geometry;
  17141. return this;
  17142. }
  17143. computeLineDistances() {
  17144. const geometry = this.geometry;
  17145. if (geometry.isBufferGeometry) {
  17146. // we assume non-indexed geometry
  17147. if (geometry.index === null) {
  17148. const positionAttribute = geometry.attributes.position;
  17149. const lineDistances = [0];
  17150. for (let i = 1, l = positionAttribute.count; i < l; i++) {
  17151. _start$1.fromBufferAttribute(positionAttribute, i - 1);
  17152. _end$1.fromBufferAttribute(positionAttribute, i);
  17153. lineDistances[i] = lineDistances[i - 1];
  17154. lineDistances[i] += _start$1.distanceTo(_end$1);
  17155. }
  17156. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  17157. } else {
  17158. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  17159. }
  17160. } else if (geometry.isGeometry) {
  17161. console.error('THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17162. }
  17163. return this;
  17164. }
  17165. raycast(raycaster, intersects) {
  17166. const geometry = this.geometry;
  17167. const matrixWorld = this.matrixWorld;
  17168. const threshold = raycaster.params.Line.threshold;
  17169. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  17170. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  17171. _sphere$1.copy(geometry.boundingSphere);
  17172. _sphere$1.applyMatrix4(matrixWorld);
  17173. _sphere$1.radius += threshold;
  17174. if (raycaster.ray.intersectsSphere(_sphere$1) === false) return; //
  17175. _inverseMatrix$1.copy(matrixWorld).invert();
  17176. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  17177. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  17178. const localThresholdSq = localThreshold * localThreshold;
  17179. const vStart = new Vector3();
  17180. const vEnd = new Vector3();
  17181. const interSegment = new Vector3();
  17182. const interRay = new Vector3();
  17183. const step = this.isLineSegments ? 2 : 1;
  17184. if (geometry.isBufferGeometry) {
  17185. const index = geometry.index;
  17186. const attributes = geometry.attributes;
  17187. const positionAttribute = attributes.position;
  17188. if (index !== null) {
  17189. const start = Math.max(0, drawRange.start);
  17190. const end = Math.min(index.count, drawRange.start + drawRange.count);
  17191. for (let i = start, l = end - 1; i < l; i += step) {
  17192. const a = index.getX(i);
  17193. const b = index.getX(i + 1);
  17194. vStart.fromBufferAttribute(positionAttribute, a);
  17195. vEnd.fromBufferAttribute(positionAttribute, b);
  17196. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  17197. if (distSq > localThresholdSq) continue;
  17198. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17199. const distance = raycaster.ray.origin.distanceTo(interRay);
  17200. if (distance < raycaster.near || distance > raycaster.far) continue;
  17201. intersects.push({
  17202. distance: distance,
  17203. // What do we want? intersection point on the ray or on the segment??
  17204. // point: raycaster.ray.at( distance ),
  17205. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17206. index: i,
  17207. face: null,
  17208. faceIndex: null,
  17209. object: this
  17210. });
  17211. }
  17212. } else {
  17213. const start = Math.max(0, drawRange.start);
  17214. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  17215. for (let i = start, l = end - 1; i < l; i += step) {
  17216. vStart.fromBufferAttribute(positionAttribute, i);
  17217. vEnd.fromBufferAttribute(positionAttribute, i + 1);
  17218. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  17219. if (distSq > localThresholdSq) continue;
  17220. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17221. const distance = raycaster.ray.origin.distanceTo(interRay);
  17222. if (distance < raycaster.near || distance > raycaster.far) continue;
  17223. intersects.push({
  17224. distance: distance,
  17225. // What do we want? intersection point on the ray or on the segment??
  17226. // point: raycaster.ray.at( distance ),
  17227. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17228. index: i,
  17229. face: null,
  17230. faceIndex: null,
  17231. object: this
  17232. });
  17233. }
  17234. }
  17235. } else if (geometry.isGeometry) {
  17236. console.error('THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17237. }
  17238. }
  17239. updateMorphTargets() {
  17240. const geometry = this.geometry;
  17241. if (geometry.isBufferGeometry) {
  17242. const morphAttributes = geometry.morphAttributes;
  17243. const keys = Object.keys(morphAttributes);
  17244. if (keys.length > 0) {
  17245. const morphAttribute = morphAttributes[keys[0]];
  17246. if (morphAttribute !== undefined) {
  17247. this.morphTargetInfluences = [];
  17248. this.morphTargetDictionary = {};
  17249. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  17250. const name = morphAttribute[m].name || String(m);
  17251. this.morphTargetInfluences.push(0);
  17252. this.morphTargetDictionary[name] = m;
  17253. }
  17254. }
  17255. }
  17256. } else {
  17257. const morphTargets = geometry.morphTargets;
  17258. if (morphTargets !== undefined && morphTargets.length > 0) {
  17259. console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  17260. }
  17261. }
  17262. }
  17263. }
  17264. Line.prototype.isLine = true;
  17265. const _start = /*@__PURE__*/new Vector3();
  17266. const _end = /*@__PURE__*/new Vector3();
  17267. class LineSegments extends Line {
  17268. constructor(geometry, material) {
  17269. super(geometry, material);
  17270. this.type = 'LineSegments';
  17271. }
  17272. computeLineDistances() {
  17273. const geometry = this.geometry;
  17274. if (geometry.isBufferGeometry) {
  17275. // we assume non-indexed geometry
  17276. if (geometry.index === null) {
  17277. const positionAttribute = geometry.attributes.position;
  17278. const lineDistances = [];
  17279. for (let i = 0, l = positionAttribute.count; i < l; i += 2) {
  17280. _start.fromBufferAttribute(positionAttribute, i);
  17281. _end.fromBufferAttribute(positionAttribute, i + 1);
  17282. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  17283. lineDistances[i + 1] = lineDistances[i] + _start.distanceTo(_end);
  17284. }
  17285. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  17286. } else {
  17287. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  17288. }
  17289. } else if (geometry.isGeometry) {
  17290. console.error('THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17291. }
  17292. return this;
  17293. }
  17294. }
  17295. LineSegments.prototype.isLineSegments = true;
  17296. class LineLoop extends Line {
  17297. constructor(geometry, material) {
  17298. super(geometry, material);
  17299. this.type = 'LineLoop';
  17300. }
  17301. }
  17302. LineLoop.prototype.isLineLoop = true;
  17303. /**
  17304. * parameters = {
  17305. * color: <hex>,
  17306. * opacity: <float>,
  17307. * map: new THREE.Texture( <Image> ),
  17308. * alphaMap: new THREE.Texture( <Image> ),
  17309. *
  17310. * size: <float>,
  17311. * sizeAttenuation: <bool>
  17312. *
  17313. * }
  17314. */
  17315. class PointsMaterial extends Material {
  17316. constructor(parameters) {
  17317. super();
  17318. this.type = 'PointsMaterial';
  17319. this.color = new Color(0xffffff);
  17320. this.map = null;
  17321. this.alphaMap = null;
  17322. this.size = 1;
  17323. this.sizeAttenuation = true;
  17324. this.setValues(parameters);
  17325. }
  17326. copy(source) {
  17327. super.copy(source);
  17328. this.color.copy(source.color);
  17329. this.map = source.map;
  17330. this.alphaMap = source.alphaMap;
  17331. this.size = source.size;
  17332. this.sizeAttenuation = source.sizeAttenuation;
  17333. return this;
  17334. }
  17335. }
  17336. PointsMaterial.prototype.isPointsMaterial = true;
  17337. const _inverseMatrix = /*@__PURE__*/new Matrix4();
  17338. const _ray = /*@__PURE__*/new Ray();
  17339. const _sphere = /*@__PURE__*/new Sphere();
  17340. const _position$2 = /*@__PURE__*/new Vector3();
  17341. class Points extends Object3D {
  17342. constructor(geometry = new BufferGeometry(), material = new PointsMaterial()) {
  17343. super();
  17344. this.type = 'Points';
  17345. this.geometry = geometry;
  17346. this.material = material;
  17347. this.updateMorphTargets();
  17348. }
  17349. copy(source) {
  17350. super.copy(source);
  17351. this.material = source.material;
  17352. this.geometry = source.geometry;
  17353. return this;
  17354. }
  17355. raycast(raycaster, intersects) {
  17356. const geometry = this.geometry;
  17357. const matrixWorld = this.matrixWorld;
  17358. const threshold = raycaster.params.Points.threshold;
  17359. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  17360. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  17361. _sphere.copy(geometry.boundingSphere);
  17362. _sphere.applyMatrix4(matrixWorld);
  17363. _sphere.radius += threshold;
  17364. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  17365. _inverseMatrix.copy(matrixWorld).invert();
  17366. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix);
  17367. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  17368. const localThresholdSq = localThreshold * localThreshold;
  17369. if (geometry.isBufferGeometry) {
  17370. const index = geometry.index;
  17371. const attributes = geometry.attributes;
  17372. const positionAttribute = attributes.position;
  17373. if (index !== null) {
  17374. const start = Math.max(0, drawRange.start);
  17375. const end = Math.min(index.count, drawRange.start + drawRange.count);
  17376. for (let i = start, il = end; i < il; i++) {
  17377. const a = index.getX(i);
  17378. _position$2.fromBufferAttribute(positionAttribute, a);
  17379. testPoint(_position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17380. }
  17381. } else {
  17382. const start = Math.max(0, drawRange.start);
  17383. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  17384. for (let i = start, l = end; i < l; i++) {
  17385. _position$2.fromBufferAttribute(positionAttribute, i);
  17386. testPoint(_position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17387. }
  17388. }
  17389. } else {
  17390. console.error('THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17391. }
  17392. }
  17393. updateMorphTargets() {
  17394. const geometry = this.geometry;
  17395. if (geometry.isBufferGeometry) {
  17396. const morphAttributes = geometry.morphAttributes;
  17397. const keys = Object.keys(morphAttributes);
  17398. if (keys.length > 0) {
  17399. const morphAttribute = morphAttributes[keys[0]];
  17400. if (morphAttribute !== undefined) {
  17401. this.morphTargetInfluences = [];
  17402. this.morphTargetDictionary = {};
  17403. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  17404. const name = morphAttribute[m].name || String(m);
  17405. this.morphTargetInfluences.push(0);
  17406. this.morphTargetDictionary[name] = m;
  17407. }
  17408. }
  17409. }
  17410. } else {
  17411. const morphTargets = geometry.morphTargets;
  17412. if (morphTargets !== undefined && morphTargets.length > 0) {
  17413. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  17414. }
  17415. }
  17416. }
  17417. }
  17418. Points.prototype.isPoints = true;
  17419. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  17420. const rayPointDistanceSq = _ray.distanceSqToPoint(point);
  17421. if (rayPointDistanceSq < localThresholdSq) {
  17422. const intersectPoint = new Vector3();
  17423. _ray.closestPointToPoint(point, intersectPoint);
  17424. intersectPoint.applyMatrix4(matrixWorld);
  17425. const distance = raycaster.ray.origin.distanceTo(intersectPoint);
  17426. if (distance < raycaster.near || distance > raycaster.far) return;
  17427. intersects.push({
  17428. distance: distance,
  17429. distanceToRay: Math.sqrt(rayPointDistanceSq),
  17430. point: intersectPoint,
  17431. index: index,
  17432. face: null,
  17433. object: object
  17434. });
  17435. }
  17436. }
  17437. class VideoTexture extends Texture {
  17438. constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  17439. super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17440. this.format = format !== undefined ? format : RGBFormat;
  17441. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  17442. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  17443. this.generateMipmaps = false;
  17444. const scope = this;
  17445. function updateVideo() {
  17446. scope.needsUpdate = true;
  17447. video.requestVideoFrameCallback(updateVideo);
  17448. }
  17449. if ('requestVideoFrameCallback' in video) {
  17450. video.requestVideoFrameCallback(updateVideo);
  17451. }
  17452. }
  17453. clone() {
  17454. return new this.constructor(this.image).copy(this);
  17455. }
  17456. update() {
  17457. const video = this.image;
  17458. const hasVideoFrameCallback = ('requestVideoFrameCallback' in video);
  17459. if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
  17460. this.needsUpdate = true;
  17461. }
  17462. }
  17463. }
  17464. VideoTexture.prototype.isVideoTexture = true;
  17465. class CompressedTexture extends Texture {
  17466. constructor(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  17467. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  17468. this.image = {
  17469. width: width,
  17470. height: height
  17471. };
  17472. this.mipmaps = mipmaps; // no flipping for cube textures
  17473. // (also flipping doesn't work for compressed textures )
  17474. this.flipY = false; // can't generate mipmaps for compressed textures
  17475. // mips must be embedded in DDS files
  17476. this.generateMipmaps = false;
  17477. }
  17478. }
  17479. CompressedTexture.prototype.isCompressedTexture = true;
  17480. class CanvasTexture extends Texture {
  17481. constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  17482. super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17483. this.needsUpdate = true;
  17484. }
  17485. }
  17486. CanvasTexture.prototype.isCanvasTexture = true;
  17487. class DepthTexture extends Texture {
  17488. constructor(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  17489. format = format !== undefined ? format : DepthFormat;
  17490. if (format !== DepthFormat && format !== DepthStencilFormat) {
  17491. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  17492. }
  17493. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  17494. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  17495. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17496. this.image = {
  17497. width: width,
  17498. height: height
  17499. };
  17500. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  17501. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  17502. this.flipY = false;
  17503. this.generateMipmaps = false;
  17504. }
  17505. }
  17506. DepthTexture.prototype.isDepthTexture = true;
  17507. class CircleGeometry extends BufferGeometry {
  17508. constructor(radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2) {
  17509. super();
  17510. this.type = 'CircleGeometry';
  17511. this.parameters = {
  17512. radius: radius,
  17513. segments: segments,
  17514. thetaStart: thetaStart,
  17515. thetaLength: thetaLength
  17516. };
  17517. segments = Math.max(3, segments); // buffers
  17518. const indices = [];
  17519. const vertices = [];
  17520. const normals = [];
  17521. const uvs = []; // helper variables
  17522. const vertex = new Vector3();
  17523. const uv = new Vector2(); // center point
  17524. vertices.push(0, 0, 0);
  17525. normals.push(0, 0, 1);
  17526. uvs.push(0.5, 0.5);
  17527. for (let s = 0, i = 3; s <= segments; s++, i += 3) {
  17528. const segment = thetaStart + s / segments * thetaLength; // vertex
  17529. vertex.x = radius * Math.cos(segment);
  17530. vertex.y = radius * Math.sin(segment);
  17531. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17532. normals.push(0, 0, 1); // uvs
  17533. uv.x = (vertices[i] / radius + 1) / 2;
  17534. uv.y = (vertices[i + 1] / radius + 1) / 2;
  17535. uvs.push(uv.x, uv.y);
  17536. } // indices
  17537. for (let i = 1; i <= segments; i++) {
  17538. indices.push(i, i + 1, 0);
  17539. } // build geometry
  17540. this.setIndex(indices);
  17541. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17542. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17543. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17544. }
  17545. static fromJSON(data) {
  17546. return new CircleGeometry(data.radius, data.segments, data.thetaStart, data.thetaLength);
  17547. }
  17548. }
  17549. class CylinderGeometry extends BufferGeometry {
  17550. constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  17551. super();
  17552. this.type = 'CylinderGeometry';
  17553. this.parameters = {
  17554. radiusTop: radiusTop,
  17555. radiusBottom: radiusBottom,
  17556. height: height,
  17557. radialSegments: radialSegments,
  17558. heightSegments: heightSegments,
  17559. openEnded: openEnded,
  17560. thetaStart: thetaStart,
  17561. thetaLength: thetaLength
  17562. };
  17563. const scope = this;
  17564. radialSegments = Math.floor(radialSegments);
  17565. heightSegments = Math.floor(heightSegments); // buffers
  17566. const indices = [];
  17567. const vertices = [];
  17568. const normals = [];
  17569. const uvs = []; // helper variables
  17570. let index = 0;
  17571. const indexArray = [];
  17572. const halfHeight = height / 2;
  17573. let groupStart = 0; // generate geometry
  17574. generateTorso();
  17575. if (openEnded === false) {
  17576. if (radiusTop > 0) generateCap(true);
  17577. if (radiusBottom > 0) generateCap(false);
  17578. } // build geometry
  17579. this.setIndex(indices);
  17580. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17581. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17582. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17583. function generateTorso() {
  17584. const normal = new Vector3();
  17585. const vertex = new Vector3();
  17586. let groupCount = 0; // this will be used to calculate the normal
  17587. const slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  17588. for (let y = 0; y <= heightSegments; y++) {
  17589. const indexRow = [];
  17590. const v = y / heightSegments; // calculate the radius of the current row
  17591. const radius = v * (radiusBottom - radiusTop) + radiusTop;
  17592. for (let x = 0; x <= radialSegments; x++) {
  17593. const u = x / radialSegments;
  17594. const theta = u * thetaLength + thetaStart;
  17595. const sinTheta = Math.sin(theta);
  17596. const cosTheta = Math.cos(theta); // vertex
  17597. vertex.x = radius * sinTheta;
  17598. vertex.y = -v * height + halfHeight;
  17599. vertex.z = radius * cosTheta;
  17600. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17601. normal.set(sinTheta, slope, cosTheta).normalize();
  17602. normals.push(normal.x, normal.y, normal.z); // uv
  17603. uvs.push(u, 1 - v); // save index of vertex in respective row
  17604. indexRow.push(index++);
  17605. } // now save vertices of the row in our index array
  17606. indexArray.push(indexRow);
  17607. } // generate indices
  17608. for (let x = 0; x < radialSegments; x++) {
  17609. for (let y = 0; y < heightSegments; y++) {
  17610. // we use the index array to access the correct indices
  17611. const a = indexArray[y][x];
  17612. const b = indexArray[y + 1][x];
  17613. const c = indexArray[y + 1][x + 1];
  17614. const d = indexArray[y][x + 1]; // faces
  17615. indices.push(a, b, d);
  17616. indices.push(b, c, d); // update group counter
  17617. groupCount += 6;
  17618. }
  17619. } // add a group to the geometry. this will ensure multi material support
  17620. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  17621. groupStart += groupCount;
  17622. }
  17623. function generateCap(top) {
  17624. // save the index of the first center vertex
  17625. const centerIndexStart = index;
  17626. const uv = new Vector2();
  17627. const vertex = new Vector3();
  17628. let groupCount = 0;
  17629. const radius = top === true ? radiusTop : radiusBottom;
  17630. const sign = top === true ? 1 : -1; // first we generate the center vertex data of the cap.
  17631. // because the geometry needs one set of uvs per face,
  17632. // we must generate a center vertex per face/segment
  17633. for (let x = 1; x <= radialSegments; x++) {
  17634. // vertex
  17635. vertices.push(0, halfHeight * sign, 0); // normal
  17636. normals.push(0, sign, 0); // uv
  17637. uvs.push(0.5, 0.5); // increase index
  17638. index++;
  17639. } // save the index of the last center vertex
  17640. const centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  17641. for (let x = 0; x <= radialSegments; x++) {
  17642. const u = x / radialSegments;
  17643. const theta = u * thetaLength + thetaStart;
  17644. const cosTheta = Math.cos(theta);
  17645. const sinTheta = Math.sin(theta); // vertex
  17646. vertex.x = radius * sinTheta;
  17647. vertex.y = halfHeight * sign;
  17648. vertex.z = radius * cosTheta;
  17649. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17650. normals.push(0, sign, 0); // uv
  17651. uv.x = cosTheta * 0.5 + 0.5;
  17652. uv.y = sinTheta * 0.5 * sign + 0.5;
  17653. uvs.push(uv.x, uv.y); // increase index
  17654. index++;
  17655. } // generate indices
  17656. for (let x = 0; x < radialSegments; x++) {
  17657. const c = centerIndexStart + x;
  17658. const i = centerIndexEnd + x;
  17659. if (top === true) {
  17660. // face top
  17661. indices.push(i, i + 1, c);
  17662. } else {
  17663. // face bottom
  17664. indices.push(i + 1, i, c);
  17665. }
  17666. groupCount += 3;
  17667. } // add a group to the geometry. this will ensure multi material support
  17668. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  17669. groupStart += groupCount;
  17670. }
  17671. }
  17672. static fromJSON(data) {
  17673. return new CylinderGeometry(data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  17674. }
  17675. }
  17676. class ConeGeometry extends CylinderGeometry {
  17677. constructor(radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  17678. super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  17679. this.type = 'ConeGeometry';
  17680. this.parameters = {
  17681. radius: radius,
  17682. height: height,
  17683. radialSegments: radialSegments,
  17684. heightSegments: heightSegments,
  17685. openEnded: openEnded,
  17686. thetaStart: thetaStart,
  17687. thetaLength: thetaLength
  17688. };
  17689. }
  17690. static fromJSON(data) {
  17691. return new ConeGeometry(data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  17692. }
  17693. }
  17694. class PolyhedronGeometry extends BufferGeometry {
  17695. constructor(vertices, indices, radius = 1, detail = 0) {
  17696. super();
  17697. this.type = 'PolyhedronGeometry';
  17698. this.parameters = {
  17699. vertices: vertices,
  17700. indices: indices,
  17701. radius: radius,
  17702. detail: detail
  17703. }; // default buffer data
  17704. const vertexBuffer = [];
  17705. const uvBuffer = []; // the subdivision creates the vertex buffer data
  17706. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  17707. applyRadius(radius); // finally, create the uv data
  17708. generateUVs(); // build non-indexed geometry
  17709. this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  17710. this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  17711. this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  17712. if (detail === 0) {
  17713. this.computeVertexNormals(); // flat normals
  17714. } else {
  17715. this.normalizeNormals(); // smooth normals
  17716. } // helper functions
  17717. function subdivide(detail) {
  17718. const a = new Vector3();
  17719. const b = new Vector3();
  17720. const c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  17721. for (let i = 0; i < indices.length; i += 3) {
  17722. // get the vertices of the face
  17723. getVertexByIndex(indices[i + 0], a);
  17724. getVertexByIndex(indices[i + 1], b);
  17725. getVertexByIndex(indices[i + 2], c); // perform subdivision
  17726. subdivideFace(a, b, c, detail);
  17727. }
  17728. }
  17729. function subdivideFace(a, b, c, detail) {
  17730. const cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision
  17731. const v = []; // construct all of the vertices for this subdivision
  17732. for (let i = 0; i <= cols; i++) {
  17733. v[i] = [];
  17734. const aj = a.clone().lerp(c, i / cols);
  17735. const bj = b.clone().lerp(c, i / cols);
  17736. const rows = cols - i;
  17737. for (let j = 0; j <= rows; j++) {
  17738. if (j === 0 && i === cols) {
  17739. v[i][j] = aj;
  17740. } else {
  17741. v[i][j] = aj.clone().lerp(bj, j / rows);
  17742. }
  17743. }
  17744. } // construct all of the faces
  17745. for (let i = 0; i < cols; i++) {
  17746. for (let j = 0; j < 2 * (cols - i) - 1; j++) {
  17747. const k = Math.floor(j / 2);
  17748. if (j % 2 === 0) {
  17749. pushVertex(v[i][k + 1]);
  17750. pushVertex(v[i + 1][k]);
  17751. pushVertex(v[i][k]);
  17752. } else {
  17753. pushVertex(v[i][k + 1]);
  17754. pushVertex(v[i + 1][k + 1]);
  17755. pushVertex(v[i + 1][k]);
  17756. }
  17757. }
  17758. }
  17759. }
  17760. function applyRadius(radius) {
  17761. const vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  17762. for (let i = 0; i < vertexBuffer.length; i += 3) {
  17763. vertex.x = vertexBuffer[i + 0];
  17764. vertex.y = vertexBuffer[i + 1];
  17765. vertex.z = vertexBuffer[i + 2];
  17766. vertex.normalize().multiplyScalar(radius);
  17767. vertexBuffer[i + 0] = vertex.x;
  17768. vertexBuffer[i + 1] = vertex.y;
  17769. vertexBuffer[i + 2] = vertex.z;
  17770. }
  17771. }
  17772. function generateUVs() {
  17773. const vertex = new Vector3();
  17774. for (let i = 0; i < vertexBuffer.length; i += 3) {
  17775. vertex.x = vertexBuffer[i + 0];
  17776. vertex.y = vertexBuffer[i + 1];
  17777. vertex.z = vertexBuffer[i + 2];
  17778. const u = azimuth(vertex) / 2 / Math.PI + 0.5;
  17779. const v = inclination(vertex) / Math.PI + 0.5;
  17780. uvBuffer.push(u, 1 - v);
  17781. }
  17782. correctUVs();
  17783. correctSeam();
  17784. }
  17785. function correctSeam() {
  17786. // handle case when face straddles the seam, see #3269
  17787. for (let i = 0; i < uvBuffer.length; i += 6) {
  17788. // uv data of a single face
  17789. const x0 = uvBuffer[i + 0];
  17790. const x1 = uvBuffer[i + 2];
  17791. const x2 = uvBuffer[i + 4];
  17792. const max = Math.max(x0, x1, x2);
  17793. const min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  17794. if (max > 0.9 && min < 0.1) {
  17795. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  17796. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  17797. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  17798. }
  17799. }
  17800. }
  17801. function pushVertex(vertex) {
  17802. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  17803. }
  17804. function getVertexByIndex(index, vertex) {
  17805. const stride = index * 3;
  17806. vertex.x = vertices[stride + 0];
  17807. vertex.y = vertices[stride + 1];
  17808. vertex.z = vertices[stride + 2];
  17809. }
  17810. function correctUVs() {
  17811. const a = new Vector3();
  17812. const b = new Vector3();
  17813. const c = new Vector3();
  17814. const centroid = new Vector3();
  17815. const uvA = new Vector2();
  17816. const uvB = new Vector2();
  17817. const uvC = new Vector2();
  17818. for (let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  17819. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  17820. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  17821. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  17822. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  17823. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  17824. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  17825. centroid.copy(a).add(b).add(c).divideScalar(3);
  17826. const azi = azimuth(centroid);
  17827. correctUV(uvA, j + 0, a, azi);
  17828. correctUV(uvB, j + 2, b, azi);
  17829. correctUV(uvC, j + 4, c, azi);
  17830. }
  17831. }
  17832. function correctUV(uv, stride, vector, azimuth) {
  17833. if (azimuth < 0 && uv.x === 1) {
  17834. uvBuffer[stride] = uv.x - 1;
  17835. }
  17836. if (vector.x === 0 && vector.z === 0) {
  17837. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  17838. }
  17839. } // Angle around the Y axis, counter-clockwise when looking from above.
  17840. function azimuth(vector) {
  17841. return Math.atan2(vector.z, -vector.x);
  17842. } // Angle above the XZ plane.
  17843. function inclination(vector) {
  17844. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  17845. }
  17846. }
  17847. static fromJSON(data) {
  17848. return new PolyhedronGeometry(data.vertices, data.indices, data.radius, data.details);
  17849. }
  17850. }
  17851. class DodecahedronGeometry extends PolyhedronGeometry {
  17852. constructor(radius = 1, detail = 0) {
  17853. const t = (1 + Math.sqrt(5)) / 2;
  17854. const r = 1 / t;
  17855. const vertices = [// (±1, ±1, ±1)
  17856. -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/φ, ±φ)
  17857. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  17858. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  17859. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  17860. 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];
  17861. super(vertices, indices, radius, detail);
  17862. this.type = 'DodecahedronGeometry';
  17863. this.parameters = {
  17864. radius: radius,
  17865. detail: detail
  17866. };
  17867. }
  17868. static fromJSON(data) {
  17869. return new DodecahedronGeometry(data.radius, data.detail);
  17870. }
  17871. }
  17872. const _v0 = new Vector3();
  17873. const _v1$1 = new Vector3();
  17874. const _normal = new Vector3();
  17875. const _triangle = new Triangle();
  17876. class EdgesGeometry extends BufferGeometry {
  17877. constructor(geometry, thresholdAngle) {
  17878. super();
  17879. this.type = 'EdgesGeometry';
  17880. this.parameters = {
  17881. thresholdAngle: thresholdAngle
  17882. };
  17883. thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1;
  17884. if (geometry.isGeometry === true) {
  17885. console.error('THREE.EdgesGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17886. return;
  17887. }
  17888. const precisionPoints = 4;
  17889. const precision = Math.pow(10, precisionPoints);
  17890. const thresholdDot = Math.cos(DEG2RAD * thresholdAngle);
  17891. const indexAttr = geometry.getIndex();
  17892. const positionAttr = geometry.getAttribute('position');
  17893. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  17894. const indexArr = [0, 0, 0];
  17895. const vertKeys = ['a', 'b', 'c'];
  17896. const hashes = new Array(3);
  17897. const edgeData = {};
  17898. const vertices = [];
  17899. for (let i = 0; i < indexCount; i += 3) {
  17900. if (indexAttr) {
  17901. indexArr[0] = indexAttr.getX(i);
  17902. indexArr[1] = indexAttr.getX(i + 1);
  17903. indexArr[2] = indexAttr.getX(i + 2);
  17904. } else {
  17905. indexArr[0] = i;
  17906. indexArr[1] = i + 1;
  17907. indexArr[2] = i + 2;
  17908. }
  17909. const {
  17910. a,
  17911. b,
  17912. c
  17913. } = _triangle;
  17914. a.fromBufferAttribute(positionAttr, indexArr[0]);
  17915. b.fromBufferAttribute(positionAttr, indexArr[1]);
  17916. c.fromBufferAttribute(positionAttr, indexArr[2]);
  17917. _triangle.getNormal(_normal); // create hashes for the edge from the vertices
  17918. hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`;
  17919. hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`;
  17920. hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`; // skip degenerate triangles
  17921. if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
  17922. continue;
  17923. } // iterate over every edge
  17924. for (let j = 0; j < 3; j++) {
  17925. // get the first and next vertex making up the edge
  17926. const jNext = (j + 1) % 3;
  17927. const vecHash0 = hashes[j];
  17928. const vecHash1 = hashes[jNext];
  17929. const v0 = _triangle[vertKeys[j]];
  17930. const v1 = _triangle[vertKeys[jNext]];
  17931. const hash = `${vecHash0}_${vecHash1}`;
  17932. const reverseHash = `${vecHash1}_${vecHash0}`;
  17933. if (reverseHash in edgeData && edgeData[reverseHash]) {
  17934. // if we found a sibling edge add it into the vertex array if
  17935. // it meets the angle threshold and delete the edge from the map.
  17936. if (_normal.dot(edgeData[reverseHash].normal) <= thresholdDot) {
  17937. vertices.push(v0.x, v0.y, v0.z);
  17938. vertices.push(v1.x, v1.y, v1.z);
  17939. }
  17940. edgeData[reverseHash] = null;
  17941. } else if (!(hash in edgeData)) {
  17942. // if we've already got an edge here then skip adding a new one
  17943. edgeData[hash] = {
  17944. index0: indexArr[j],
  17945. index1: indexArr[jNext],
  17946. normal: _normal.clone()
  17947. };
  17948. }
  17949. }
  17950. } // iterate over all remaining, unmatched edges and add them to the vertex array
  17951. for (const key in edgeData) {
  17952. if (edgeData[key]) {
  17953. const {
  17954. index0,
  17955. index1
  17956. } = edgeData[key];
  17957. _v0.fromBufferAttribute(positionAttr, index0);
  17958. _v1$1.fromBufferAttribute(positionAttr, index1);
  17959. vertices.push(_v0.x, _v0.y, _v0.z);
  17960. vertices.push(_v1$1.x, _v1$1.y, _v1$1.z);
  17961. }
  17962. }
  17963. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17964. }
  17965. }
  17966. /**
  17967. * Extensible curve object.
  17968. *
  17969. * Some common of curve methods:
  17970. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  17971. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  17972. * .getPoints(), .getSpacedPoints()
  17973. * .getLength()
  17974. * .updateArcLengths()
  17975. *
  17976. * This following curves inherit from THREE.Curve:
  17977. *
  17978. * -- 2D curves --
  17979. * THREE.ArcCurve
  17980. * THREE.CubicBezierCurve
  17981. * THREE.EllipseCurve
  17982. * THREE.LineCurve
  17983. * THREE.QuadraticBezierCurve
  17984. * THREE.SplineCurve
  17985. *
  17986. * -- 3D curves --
  17987. * THREE.CatmullRomCurve3
  17988. * THREE.CubicBezierCurve3
  17989. * THREE.LineCurve3
  17990. * THREE.QuadraticBezierCurve3
  17991. *
  17992. * A series of curves can be represented as a THREE.CurvePath.
  17993. *
  17994. **/
  17995. class Curve {
  17996. constructor() {
  17997. this.type = 'Curve';
  17998. this.arcLengthDivisions = 200;
  17999. } // Virtual base class method to overwrite and implement in subclasses
  18000. // - t [0 .. 1]
  18001. getPoint() {
  18002. console.warn('THREE.Curve: .getPoint() not implemented.');
  18003. return null;
  18004. } // Get point at relative position in curve according to arc length
  18005. // - u [0 .. 1]
  18006. getPointAt(u, optionalTarget) {
  18007. const t = this.getUtoTmapping(u);
  18008. return this.getPoint(t, optionalTarget);
  18009. } // Get sequence of points using getPoint( t )
  18010. getPoints(divisions = 5) {
  18011. const points = [];
  18012. for (let d = 0; d <= divisions; d++) {
  18013. points.push(this.getPoint(d / divisions));
  18014. }
  18015. return points;
  18016. } // Get sequence of points using getPointAt( u )
  18017. getSpacedPoints(divisions = 5) {
  18018. const points = [];
  18019. for (let d = 0; d <= divisions; d++) {
  18020. points.push(this.getPointAt(d / divisions));
  18021. }
  18022. return points;
  18023. } // Get total curve arc length
  18024. getLength() {
  18025. const lengths = this.getLengths();
  18026. return lengths[lengths.length - 1];
  18027. } // Get list of cumulative segment lengths
  18028. getLengths(divisions = this.arcLengthDivisions) {
  18029. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  18030. return this.cacheArcLengths;
  18031. }
  18032. this.needsUpdate = false;
  18033. const cache = [];
  18034. let current,
  18035. last = this.getPoint(0);
  18036. let sum = 0;
  18037. cache.push(0);
  18038. for (let p = 1; p <= divisions; p++) {
  18039. current = this.getPoint(p / divisions);
  18040. sum += current.distanceTo(last);
  18041. cache.push(sum);
  18042. last = current;
  18043. }
  18044. this.cacheArcLengths = cache;
  18045. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  18046. }
  18047. updateArcLengths() {
  18048. this.needsUpdate = true;
  18049. this.getLengths();
  18050. } // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  18051. getUtoTmapping(u, distance) {
  18052. const arcLengths = this.getLengths();
  18053. let i = 0;
  18054. const il = arcLengths.length;
  18055. let targetArcLength; // The targeted u distance value to get
  18056. if (distance) {
  18057. targetArcLength = distance;
  18058. } else {
  18059. targetArcLength = u * arcLengths[il - 1];
  18060. } // binary search for the index with largest value smaller than target u distance
  18061. let low = 0,
  18062. high = il - 1,
  18063. comparison;
  18064. while (low <= high) {
  18065. 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
  18066. comparison = arcLengths[i] - targetArcLength;
  18067. if (comparison < 0) {
  18068. low = i + 1;
  18069. } else if (comparison > 0) {
  18070. high = i - 1;
  18071. } else {
  18072. high = i;
  18073. break; // DONE
  18074. }
  18075. }
  18076. i = high;
  18077. if (arcLengths[i] === targetArcLength) {
  18078. return i / (il - 1);
  18079. } // we could get finer grain at lengths, or use simple interpolation between two points
  18080. const lengthBefore = arcLengths[i];
  18081. const lengthAfter = arcLengths[i + 1];
  18082. const segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  18083. const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  18084. const t = (i + segmentFraction) / (il - 1);
  18085. return t;
  18086. } // Returns a unit vector tangent at t
  18087. // In case any sub curve does not implement its tangent derivation,
  18088. // 2 points a small delta apart will be used to find its gradient
  18089. // which seems to give a reasonable approximation
  18090. getTangent(t, optionalTarget) {
  18091. const delta = 0.0001;
  18092. let t1 = t - delta;
  18093. let t2 = t + delta; // Capping in case of danger
  18094. if (t1 < 0) t1 = 0;
  18095. if (t2 > 1) t2 = 1;
  18096. const pt1 = this.getPoint(t1);
  18097. const pt2 = this.getPoint(t2);
  18098. const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
  18099. tangent.copy(pt2).sub(pt1).normalize();
  18100. return tangent;
  18101. }
  18102. getTangentAt(u, optionalTarget) {
  18103. const t = this.getUtoTmapping(u);
  18104. return this.getTangent(t, optionalTarget);
  18105. }
  18106. computeFrenetFrames(segments, closed) {
  18107. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18108. const normal = new Vector3();
  18109. const tangents = [];
  18110. const normals = [];
  18111. const binormals = [];
  18112. const vec = new Vector3();
  18113. const mat = new Matrix4(); // compute the tangent vectors for each segment on the curve
  18114. for (let i = 0; i <= segments; i++) {
  18115. const u = i / segments;
  18116. tangents[i] = this.getTangentAt(u, new Vector3());
  18117. tangents[i].normalize();
  18118. } // select an initial normal vector perpendicular to the first tangent vector,
  18119. // and in the direction of the minimum tangent xyz component
  18120. normals[0] = new Vector3();
  18121. binormals[0] = new Vector3();
  18122. let min = Number.MAX_VALUE;
  18123. const tx = Math.abs(tangents[0].x);
  18124. const ty = Math.abs(tangents[0].y);
  18125. const tz = Math.abs(tangents[0].z);
  18126. if (tx <= min) {
  18127. min = tx;
  18128. normal.set(1, 0, 0);
  18129. }
  18130. if (ty <= min) {
  18131. min = ty;
  18132. normal.set(0, 1, 0);
  18133. }
  18134. if (tz <= min) {
  18135. normal.set(0, 0, 1);
  18136. }
  18137. vec.crossVectors(tangents[0], normal).normalize();
  18138. normals[0].crossVectors(tangents[0], vec);
  18139. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  18140. for (let i = 1; i <= segments; i++) {
  18141. normals[i] = normals[i - 1].clone();
  18142. binormals[i] = binormals[i - 1].clone();
  18143. vec.crossVectors(tangents[i - 1], tangents[i]);
  18144. if (vec.length() > Number.EPSILON) {
  18145. vec.normalize();
  18146. const theta = Math.acos(clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  18147. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  18148. }
  18149. binormals[i].crossVectors(tangents[i], normals[i]);
  18150. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18151. if (closed === true) {
  18152. let theta = Math.acos(clamp(normals[0].dot(normals[segments]), -1, 1));
  18153. theta /= segments;
  18154. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  18155. theta = -theta;
  18156. }
  18157. for (let i = 1; i <= segments; i++) {
  18158. // twist a little...
  18159. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  18160. binormals[i].crossVectors(tangents[i], normals[i]);
  18161. }
  18162. }
  18163. return {
  18164. tangents: tangents,
  18165. normals: normals,
  18166. binormals: binormals
  18167. };
  18168. }
  18169. clone() {
  18170. return new this.constructor().copy(this);
  18171. }
  18172. copy(source) {
  18173. this.arcLengthDivisions = source.arcLengthDivisions;
  18174. return this;
  18175. }
  18176. toJSON() {
  18177. const data = {
  18178. metadata: {
  18179. version: 4.5,
  18180. type: 'Curve',
  18181. generator: 'Curve.toJSON'
  18182. }
  18183. };
  18184. data.arcLengthDivisions = this.arcLengthDivisions;
  18185. data.type = this.type;
  18186. return data;
  18187. }
  18188. fromJSON(json) {
  18189. this.arcLengthDivisions = json.arcLengthDivisions;
  18190. return this;
  18191. }
  18192. }
  18193. class EllipseCurve extends Curve {
  18194. constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) {
  18195. super();
  18196. this.type = 'EllipseCurve';
  18197. this.aX = aX;
  18198. this.aY = aY;
  18199. this.xRadius = xRadius;
  18200. this.yRadius = yRadius;
  18201. this.aStartAngle = aStartAngle;
  18202. this.aEndAngle = aEndAngle;
  18203. this.aClockwise = aClockwise;
  18204. this.aRotation = aRotation;
  18205. }
  18206. getPoint(t, optionalTarget) {
  18207. const point = optionalTarget || new Vector2();
  18208. const twoPi = Math.PI * 2;
  18209. let deltaAngle = this.aEndAngle - this.aStartAngle;
  18210. const samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  18211. while (deltaAngle < 0) deltaAngle += twoPi;
  18212. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  18213. if (deltaAngle < Number.EPSILON) {
  18214. if (samePoints) {
  18215. deltaAngle = 0;
  18216. } else {
  18217. deltaAngle = twoPi;
  18218. }
  18219. }
  18220. if (this.aClockwise === true && !samePoints) {
  18221. if (deltaAngle === twoPi) {
  18222. deltaAngle = -twoPi;
  18223. } else {
  18224. deltaAngle = deltaAngle - twoPi;
  18225. }
  18226. }
  18227. const angle = this.aStartAngle + t * deltaAngle;
  18228. let x = this.aX + this.xRadius * Math.cos(angle);
  18229. let y = this.aY + this.yRadius * Math.sin(angle);
  18230. if (this.aRotation !== 0) {
  18231. const cos = Math.cos(this.aRotation);
  18232. const sin = Math.sin(this.aRotation);
  18233. const tx = x - this.aX;
  18234. const ty = y - this.aY; // Rotate the point about the center of the ellipse.
  18235. x = tx * cos - ty * sin + this.aX;
  18236. y = tx * sin + ty * cos + this.aY;
  18237. }
  18238. return point.set(x, y);
  18239. }
  18240. copy(source) {
  18241. super.copy(source);
  18242. this.aX = source.aX;
  18243. this.aY = source.aY;
  18244. this.xRadius = source.xRadius;
  18245. this.yRadius = source.yRadius;
  18246. this.aStartAngle = source.aStartAngle;
  18247. this.aEndAngle = source.aEndAngle;
  18248. this.aClockwise = source.aClockwise;
  18249. this.aRotation = source.aRotation;
  18250. return this;
  18251. }
  18252. toJSON() {
  18253. const data = super.toJSON();
  18254. data.aX = this.aX;
  18255. data.aY = this.aY;
  18256. data.xRadius = this.xRadius;
  18257. data.yRadius = this.yRadius;
  18258. data.aStartAngle = this.aStartAngle;
  18259. data.aEndAngle = this.aEndAngle;
  18260. data.aClockwise = this.aClockwise;
  18261. data.aRotation = this.aRotation;
  18262. return data;
  18263. }
  18264. fromJSON(json) {
  18265. super.fromJSON(json);
  18266. this.aX = json.aX;
  18267. this.aY = json.aY;
  18268. this.xRadius = json.xRadius;
  18269. this.yRadius = json.yRadius;
  18270. this.aStartAngle = json.aStartAngle;
  18271. this.aEndAngle = json.aEndAngle;
  18272. this.aClockwise = json.aClockwise;
  18273. this.aRotation = json.aRotation;
  18274. return this;
  18275. }
  18276. }
  18277. EllipseCurve.prototype.isEllipseCurve = true;
  18278. class ArcCurve extends EllipseCurve {
  18279. constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  18280. super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  18281. this.type = 'ArcCurve';
  18282. }
  18283. }
  18284. ArcCurve.prototype.isArcCurve = true;
  18285. /**
  18286. * Centripetal CatmullRom Curve - which is useful for avoiding
  18287. * cusps and self-intersections in non-uniform catmull rom curves.
  18288. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  18289. *
  18290. * curve.type accepts centripetal(default), chordal and catmullrom
  18291. * curve.tension is used for catmullrom which defaults to 0.5
  18292. */
  18293. /*
  18294. Based on an optimized c++ solution in
  18295. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  18296. - http://ideone.com/NoEbVM
  18297. This CubicPoly class could be used for reusing some variables and calculations,
  18298. but for three.js curve use, it could be possible inlined and flatten into a single function call
  18299. which can be placed in CurveUtils.
  18300. */
  18301. function CubicPoly() {
  18302. let c0 = 0,
  18303. c1 = 0,
  18304. c2 = 0,
  18305. c3 = 0;
  18306. /*
  18307. * Compute coefficients for a cubic polynomial
  18308. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  18309. * such that
  18310. * p(0) = x0, p(1) = x1
  18311. * and
  18312. * p'(0) = t0, p'(1) = t1.
  18313. */
  18314. function init(x0, x1, t0, t1) {
  18315. c0 = x0;
  18316. c1 = t0;
  18317. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  18318. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  18319. }
  18320. return {
  18321. initCatmullRom: function (x0, x1, x2, x3, tension) {
  18322. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  18323. },
  18324. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  18325. // compute tangents when parameterized in [t1,t2]
  18326. let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  18327. let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  18328. t1 *= dt1;
  18329. t2 *= dt1;
  18330. init(x1, x2, t1, t2);
  18331. },
  18332. calc: function (t) {
  18333. const t2 = t * t;
  18334. const t3 = t2 * t;
  18335. return c0 + c1 * t + c2 * t2 + c3 * t3;
  18336. }
  18337. };
  18338. } //
  18339. const tmp = new Vector3();
  18340. const px = new CubicPoly(),
  18341. py = new CubicPoly(),
  18342. pz = new CubicPoly();
  18343. class CatmullRomCurve3 extends Curve {
  18344. constructor(points = [], closed = false, curveType = 'centripetal', tension = 0.5) {
  18345. super();
  18346. this.type = 'CatmullRomCurve3';
  18347. this.points = points;
  18348. this.closed = closed;
  18349. this.curveType = curveType;
  18350. this.tension = tension;
  18351. }
  18352. getPoint(t, optionalTarget = new Vector3()) {
  18353. const point = optionalTarget;
  18354. const points = this.points;
  18355. const l = points.length;
  18356. const p = (l - (this.closed ? 0 : 1)) * t;
  18357. let intPoint = Math.floor(p);
  18358. let weight = p - intPoint;
  18359. if (this.closed) {
  18360. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  18361. } else if (weight === 0 && intPoint === l - 1) {
  18362. intPoint = l - 2;
  18363. weight = 1;
  18364. }
  18365. let p0, p3; // 4 points (p1 & p2 defined below)
  18366. if (this.closed || intPoint > 0) {
  18367. p0 = points[(intPoint - 1) % l];
  18368. } else {
  18369. // extrapolate first point
  18370. tmp.subVectors(points[0], points[1]).add(points[0]);
  18371. p0 = tmp;
  18372. }
  18373. const p1 = points[intPoint % l];
  18374. const p2 = points[(intPoint + 1) % l];
  18375. if (this.closed || intPoint + 2 < l) {
  18376. p3 = points[(intPoint + 2) % l];
  18377. } else {
  18378. // extrapolate last point
  18379. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  18380. p3 = tmp;
  18381. }
  18382. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  18383. // init Centripetal / Chordal Catmull-Rom
  18384. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  18385. let dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  18386. let dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  18387. let dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  18388. if (dt1 < 1e-4) dt1 = 1.0;
  18389. if (dt0 < 1e-4) dt0 = dt1;
  18390. if (dt2 < 1e-4) dt2 = dt1;
  18391. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  18392. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  18393. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  18394. } else if (this.curveType === 'catmullrom') {
  18395. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  18396. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  18397. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  18398. }
  18399. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  18400. return point;
  18401. }
  18402. copy(source) {
  18403. super.copy(source);
  18404. this.points = [];
  18405. for (let i = 0, l = source.points.length; i < l; i++) {
  18406. const point = source.points[i];
  18407. this.points.push(point.clone());
  18408. }
  18409. this.closed = source.closed;
  18410. this.curveType = source.curveType;
  18411. this.tension = source.tension;
  18412. return this;
  18413. }
  18414. toJSON() {
  18415. const data = super.toJSON();
  18416. data.points = [];
  18417. for (let i = 0, l = this.points.length; i < l; i++) {
  18418. const point = this.points[i];
  18419. data.points.push(point.toArray());
  18420. }
  18421. data.closed = this.closed;
  18422. data.curveType = this.curveType;
  18423. data.tension = this.tension;
  18424. return data;
  18425. }
  18426. fromJSON(json) {
  18427. super.fromJSON(json);
  18428. this.points = [];
  18429. for (let i = 0, l = json.points.length; i < l; i++) {
  18430. const point = json.points[i];
  18431. this.points.push(new Vector3().fromArray(point));
  18432. }
  18433. this.closed = json.closed;
  18434. this.curveType = json.curveType;
  18435. this.tension = json.tension;
  18436. return this;
  18437. }
  18438. }
  18439. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  18440. /**
  18441. * Bezier Curves formulas obtained from
  18442. * http://en.wikipedia.org/wiki/Bézier_curve
  18443. */
  18444. function CatmullRom(t, p0, p1, p2, p3) {
  18445. const v0 = (p2 - p0) * 0.5;
  18446. const v1 = (p3 - p1) * 0.5;
  18447. const t2 = t * t;
  18448. const t3 = t * t2;
  18449. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  18450. } //
  18451. function QuadraticBezierP0(t, p) {
  18452. const k = 1 - t;
  18453. return k * k * p;
  18454. }
  18455. function QuadraticBezierP1(t, p) {
  18456. return 2 * (1 - t) * t * p;
  18457. }
  18458. function QuadraticBezierP2(t, p) {
  18459. return t * t * p;
  18460. }
  18461. function QuadraticBezier(t, p0, p1, p2) {
  18462. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  18463. } //
  18464. function CubicBezierP0(t, p) {
  18465. const k = 1 - t;
  18466. return k * k * k * p;
  18467. }
  18468. function CubicBezierP1(t, p) {
  18469. const k = 1 - t;
  18470. return 3 * k * k * t * p;
  18471. }
  18472. function CubicBezierP2(t, p) {
  18473. return 3 * (1 - t) * t * t * p;
  18474. }
  18475. function CubicBezierP3(t, p) {
  18476. return t * t * t * p;
  18477. }
  18478. function CubicBezier(t, p0, p1, p2, p3) {
  18479. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  18480. }
  18481. class CubicBezierCurve extends Curve {
  18482. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) {
  18483. super();
  18484. this.type = 'CubicBezierCurve';
  18485. this.v0 = v0;
  18486. this.v1 = v1;
  18487. this.v2 = v2;
  18488. this.v3 = v3;
  18489. }
  18490. getPoint(t, optionalTarget = new Vector2()) {
  18491. const point = optionalTarget;
  18492. const v0 = this.v0,
  18493. v1 = this.v1,
  18494. v2 = this.v2,
  18495. v3 = this.v3;
  18496. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  18497. return point;
  18498. }
  18499. copy(source) {
  18500. super.copy(source);
  18501. this.v0.copy(source.v0);
  18502. this.v1.copy(source.v1);
  18503. this.v2.copy(source.v2);
  18504. this.v3.copy(source.v3);
  18505. return this;
  18506. }
  18507. toJSON() {
  18508. const data = super.toJSON();
  18509. data.v0 = this.v0.toArray();
  18510. data.v1 = this.v1.toArray();
  18511. data.v2 = this.v2.toArray();
  18512. data.v3 = this.v3.toArray();
  18513. return data;
  18514. }
  18515. fromJSON(json) {
  18516. super.fromJSON(json);
  18517. this.v0.fromArray(json.v0);
  18518. this.v1.fromArray(json.v1);
  18519. this.v2.fromArray(json.v2);
  18520. this.v3.fromArray(json.v3);
  18521. return this;
  18522. }
  18523. }
  18524. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  18525. class CubicBezierCurve3 extends Curve {
  18526. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) {
  18527. super();
  18528. this.type = 'CubicBezierCurve3';
  18529. this.v0 = v0;
  18530. this.v1 = v1;
  18531. this.v2 = v2;
  18532. this.v3 = v3;
  18533. }
  18534. getPoint(t, optionalTarget = new Vector3()) {
  18535. const point = optionalTarget;
  18536. const v0 = this.v0,
  18537. v1 = this.v1,
  18538. v2 = this.v2,
  18539. v3 = this.v3;
  18540. 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));
  18541. return point;
  18542. }
  18543. copy(source) {
  18544. super.copy(source);
  18545. this.v0.copy(source.v0);
  18546. this.v1.copy(source.v1);
  18547. this.v2.copy(source.v2);
  18548. this.v3.copy(source.v3);
  18549. return this;
  18550. }
  18551. toJSON() {
  18552. const data = super.toJSON();
  18553. data.v0 = this.v0.toArray();
  18554. data.v1 = this.v1.toArray();
  18555. data.v2 = this.v2.toArray();
  18556. data.v3 = this.v3.toArray();
  18557. return data;
  18558. }
  18559. fromJSON(json) {
  18560. super.fromJSON(json);
  18561. this.v0.fromArray(json.v0);
  18562. this.v1.fromArray(json.v1);
  18563. this.v2.fromArray(json.v2);
  18564. this.v3.fromArray(json.v3);
  18565. return this;
  18566. }
  18567. }
  18568. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  18569. class LineCurve extends Curve {
  18570. constructor(v1 = new Vector2(), v2 = new Vector2()) {
  18571. super();
  18572. this.type = 'LineCurve';
  18573. this.v1 = v1;
  18574. this.v2 = v2;
  18575. }
  18576. getPoint(t, optionalTarget = new Vector2()) {
  18577. const point = optionalTarget;
  18578. if (t === 1) {
  18579. point.copy(this.v2);
  18580. } else {
  18581. point.copy(this.v2).sub(this.v1);
  18582. point.multiplyScalar(t).add(this.v1);
  18583. }
  18584. return point;
  18585. } // Line curve is linear, so we can overwrite default getPointAt
  18586. getPointAt(u, optionalTarget) {
  18587. return this.getPoint(u, optionalTarget);
  18588. }
  18589. getTangent(t, optionalTarget) {
  18590. const tangent = optionalTarget || new Vector2();
  18591. tangent.copy(this.v2).sub(this.v1).normalize();
  18592. return tangent;
  18593. }
  18594. copy(source) {
  18595. super.copy(source);
  18596. this.v1.copy(source.v1);
  18597. this.v2.copy(source.v2);
  18598. return this;
  18599. }
  18600. toJSON() {
  18601. const data = super.toJSON();
  18602. data.v1 = this.v1.toArray();
  18603. data.v2 = this.v2.toArray();
  18604. return data;
  18605. }
  18606. fromJSON(json) {
  18607. super.fromJSON(json);
  18608. this.v1.fromArray(json.v1);
  18609. this.v2.fromArray(json.v2);
  18610. return this;
  18611. }
  18612. }
  18613. LineCurve.prototype.isLineCurve = true;
  18614. class LineCurve3 extends Curve {
  18615. constructor(v1 = new Vector3(), v2 = new Vector3()) {
  18616. super();
  18617. this.type = 'LineCurve3';
  18618. this.isLineCurve3 = true;
  18619. this.v1 = v1;
  18620. this.v2 = v2;
  18621. }
  18622. getPoint(t, optionalTarget = new Vector3()) {
  18623. const point = optionalTarget;
  18624. if (t === 1) {
  18625. point.copy(this.v2);
  18626. } else {
  18627. point.copy(this.v2).sub(this.v1);
  18628. point.multiplyScalar(t).add(this.v1);
  18629. }
  18630. return point;
  18631. } // Line curve is linear, so we can overwrite default getPointAt
  18632. getPointAt(u, optionalTarget) {
  18633. return this.getPoint(u, optionalTarget);
  18634. }
  18635. copy(source) {
  18636. super.copy(source);
  18637. this.v1.copy(source.v1);
  18638. this.v2.copy(source.v2);
  18639. return this;
  18640. }
  18641. toJSON() {
  18642. const data = super.toJSON();
  18643. data.v1 = this.v1.toArray();
  18644. data.v2 = this.v2.toArray();
  18645. return data;
  18646. }
  18647. fromJSON(json) {
  18648. super.fromJSON(json);
  18649. this.v1.fromArray(json.v1);
  18650. this.v2.fromArray(json.v2);
  18651. return this;
  18652. }
  18653. }
  18654. class QuadraticBezierCurve extends Curve {
  18655. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) {
  18656. super();
  18657. this.type = 'QuadraticBezierCurve';
  18658. this.v0 = v0;
  18659. this.v1 = v1;
  18660. this.v2 = v2;
  18661. }
  18662. getPoint(t, optionalTarget = new Vector2()) {
  18663. const point = optionalTarget;
  18664. const v0 = this.v0,
  18665. v1 = this.v1,
  18666. v2 = this.v2;
  18667. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  18668. return point;
  18669. }
  18670. copy(source) {
  18671. super.copy(source);
  18672. this.v0.copy(source.v0);
  18673. this.v1.copy(source.v1);
  18674. this.v2.copy(source.v2);
  18675. return this;
  18676. }
  18677. toJSON() {
  18678. const data = super.toJSON();
  18679. data.v0 = this.v0.toArray();
  18680. data.v1 = this.v1.toArray();
  18681. data.v2 = this.v2.toArray();
  18682. return data;
  18683. }
  18684. fromJSON(json) {
  18685. super.fromJSON(json);
  18686. this.v0.fromArray(json.v0);
  18687. this.v1.fromArray(json.v1);
  18688. this.v2.fromArray(json.v2);
  18689. return this;
  18690. }
  18691. }
  18692. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  18693. class QuadraticBezierCurve3 extends Curve {
  18694. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) {
  18695. super();
  18696. this.type = 'QuadraticBezierCurve3';
  18697. this.v0 = v0;
  18698. this.v1 = v1;
  18699. this.v2 = v2;
  18700. }
  18701. getPoint(t, optionalTarget = new Vector3()) {
  18702. const point = optionalTarget;
  18703. const v0 = this.v0,
  18704. v1 = this.v1,
  18705. v2 = this.v2;
  18706. 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));
  18707. return point;
  18708. }
  18709. copy(source) {
  18710. super.copy(source);
  18711. this.v0.copy(source.v0);
  18712. this.v1.copy(source.v1);
  18713. this.v2.copy(source.v2);
  18714. return this;
  18715. }
  18716. toJSON() {
  18717. const data = super.toJSON();
  18718. data.v0 = this.v0.toArray();
  18719. data.v1 = this.v1.toArray();
  18720. data.v2 = this.v2.toArray();
  18721. return data;
  18722. }
  18723. fromJSON(json) {
  18724. super.fromJSON(json);
  18725. this.v0.fromArray(json.v0);
  18726. this.v1.fromArray(json.v1);
  18727. this.v2.fromArray(json.v2);
  18728. return this;
  18729. }
  18730. }
  18731. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  18732. class SplineCurve extends Curve {
  18733. constructor(points = []) {
  18734. super();
  18735. this.type = 'SplineCurve';
  18736. this.points = points;
  18737. }
  18738. getPoint(t, optionalTarget = new Vector2()) {
  18739. const point = optionalTarget;
  18740. const points = this.points;
  18741. const p = (points.length - 1) * t;
  18742. const intPoint = Math.floor(p);
  18743. const weight = p - intPoint;
  18744. const p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  18745. const p1 = points[intPoint];
  18746. const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  18747. const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  18748. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  18749. return point;
  18750. }
  18751. copy(source) {
  18752. super.copy(source);
  18753. this.points = [];
  18754. for (let i = 0, l = source.points.length; i < l; i++) {
  18755. const point = source.points[i];
  18756. this.points.push(point.clone());
  18757. }
  18758. return this;
  18759. }
  18760. toJSON() {
  18761. const data = super.toJSON();
  18762. data.points = [];
  18763. for (let i = 0, l = this.points.length; i < l; i++) {
  18764. const point = this.points[i];
  18765. data.points.push(point.toArray());
  18766. }
  18767. return data;
  18768. }
  18769. fromJSON(json) {
  18770. super.fromJSON(json);
  18771. this.points = [];
  18772. for (let i = 0, l = json.points.length; i < l; i++) {
  18773. const point = json.points[i];
  18774. this.points.push(new Vector2().fromArray(point));
  18775. }
  18776. return this;
  18777. }
  18778. }
  18779. SplineCurve.prototype.isSplineCurve = true;
  18780. var Curves = /*#__PURE__*/Object.freeze({
  18781. __proto__: null,
  18782. ArcCurve: ArcCurve,
  18783. CatmullRomCurve3: CatmullRomCurve3,
  18784. CubicBezierCurve: CubicBezierCurve,
  18785. CubicBezierCurve3: CubicBezierCurve3,
  18786. EllipseCurve: EllipseCurve,
  18787. LineCurve: LineCurve,
  18788. LineCurve3: LineCurve3,
  18789. QuadraticBezierCurve: QuadraticBezierCurve,
  18790. QuadraticBezierCurve3: QuadraticBezierCurve3,
  18791. SplineCurve: SplineCurve
  18792. });
  18793. /**
  18794. * Port from https://github.com/mapbox/earcut (v2.2.2)
  18795. */
  18796. const Earcut = {
  18797. triangulate: function (data, holeIndices, dim = 2) {
  18798. const hasHoles = holeIndices && holeIndices.length;
  18799. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  18800. let outerNode = linkedList(data, 0, outerLen, dim, true);
  18801. const triangles = [];
  18802. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  18803. let minX, minY, maxX, maxY, x, y, invSize;
  18804. 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
  18805. if (data.length > 80 * dim) {
  18806. minX = maxX = data[0];
  18807. minY = maxY = data[1];
  18808. for (let i = dim; i < outerLen; i += dim) {
  18809. x = data[i];
  18810. y = data[i + 1];
  18811. if (x < minX) minX = x;
  18812. if (y < minY) minY = y;
  18813. if (x > maxX) maxX = x;
  18814. if (y > maxY) maxY = y;
  18815. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  18816. invSize = Math.max(maxX - minX, maxY - minY);
  18817. invSize = invSize !== 0 ? 1 / invSize : 0;
  18818. }
  18819. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  18820. return triangles;
  18821. }
  18822. }; // create a circular doubly linked list from polygon points in the specified winding order
  18823. function linkedList(data, start, end, dim, clockwise) {
  18824. let i, last;
  18825. if (clockwise === signedArea(data, start, end, dim) > 0) {
  18826. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  18827. } else {
  18828. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  18829. }
  18830. if (last && equals(last, last.next)) {
  18831. removeNode(last);
  18832. last = last.next;
  18833. }
  18834. return last;
  18835. } // eliminate colinear or duplicate points
  18836. function filterPoints(start, end) {
  18837. if (!start) return start;
  18838. if (!end) end = start;
  18839. let p = start,
  18840. again;
  18841. do {
  18842. again = false;
  18843. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  18844. removeNode(p);
  18845. p = end = p.prev;
  18846. if (p === p.next) break;
  18847. again = true;
  18848. } else {
  18849. p = p.next;
  18850. }
  18851. } while (again || p !== end);
  18852. return end;
  18853. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  18854. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  18855. if (!ear) return; // interlink polygon nodes in z-order
  18856. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  18857. let stop = ear,
  18858. prev,
  18859. next; // iterate through ears, slicing them one by one
  18860. while (ear.prev !== ear.next) {
  18861. prev = ear.prev;
  18862. next = ear.next;
  18863. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  18864. // cut off the triangle
  18865. triangles.push(prev.i / dim);
  18866. triangles.push(ear.i / dim);
  18867. triangles.push(next.i / dim);
  18868. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  18869. ear = next.next;
  18870. stop = next.next;
  18871. continue;
  18872. }
  18873. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  18874. if (ear === stop) {
  18875. // try filtering points and slicing again
  18876. if (!pass) {
  18877. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  18878. } else if (pass === 1) {
  18879. ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
  18880. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  18881. } else if (pass === 2) {
  18882. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  18883. }
  18884. break;
  18885. }
  18886. }
  18887. } // check whether a polygon node forms a valid ear with adjacent nodes
  18888. function isEar(ear) {
  18889. const a = ear.prev,
  18890. b = ear,
  18891. c = ear.next;
  18892. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18893. // now make sure we don't have other points inside the potential ear
  18894. let p = ear.next.next;
  18895. while (p !== ear.prev) {
  18896. 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;
  18897. p = p.next;
  18898. }
  18899. return true;
  18900. }
  18901. function isEarHashed(ear, minX, minY, invSize) {
  18902. const a = ear.prev,
  18903. b = ear,
  18904. c = ear.next;
  18905. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18906. // triangle bbox; min & max are calculated like this for speed
  18907. const minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  18908. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  18909. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  18910. 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;
  18911. const minZ = zOrder(minTX, minTY, minX, minY, invSize),
  18912. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  18913. let p = ear.prevZ,
  18914. n = ear.nextZ; // look for points inside the triangle in both directions
  18915. while (p && p.z >= minZ && n && n.z <= maxZ) {
  18916. 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;
  18917. p = p.prevZ;
  18918. 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;
  18919. n = n.nextZ;
  18920. } // look for remaining points in decreasing z-order
  18921. while (p && p.z >= minZ) {
  18922. 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;
  18923. p = p.prevZ;
  18924. } // look for remaining points in increasing z-order
  18925. while (n && n.z <= maxZ) {
  18926. 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;
  18927. n = n.nextZ;
  18928. }
  18929. return true;
  18930. } // go through all polygon nodes and cure small local self-intersections
  18931. function cureLocalIntersections(start, triangles, dim) {
  18932. let p = start;
  18933. do {
  18934. const a = p.prev,
  18935. b = p.next.next;
  18936. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  18937. triangles.push(a.i / dim);
  18938. triangles.push(p.i / dim);
  18939. triangles.push(b.i / dim); // remove two nodes involved
  18940. removeNode(p);
  18941. removeNode(p.next);
  18942. p = start = b;
  18943. }
  18944. p = p.next;
  18945. } while (p !== start);
  18946. return filterPoints(p);
  18947. } // try splitting polygon into two and triangulate them independently
  18948. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  18949. // look for a valid diagonal that divides the polygon into two
  18950. let a = start;
  18951. do {
  18952. let b = a.next.next;
  18953. while (b !== a.prev) {
  18954. if (a.i !== b.i && isValidDiagonal(a, b)) {
  18955. // split the polygon in two by the diagonal
  18956. let c = splitPolygon(a, b); // filter colinear points around the cuts
  18957. a = filterPoints(a, a.next);
  18958. c = filterPoints(c, c.next); // run earcut on each half
  18959. earcutLinked(a, triangles, dim, minX, minY, invSize);
  18960. earcutLinked(c, triangles, dim, minX, minY, invSize);
  18961. return;
  18962. }
  18963. b = b.next;
  18964. }
  18965. a = a.next;
  18966. } while (a !== start);
  18967. } // link every hole into the outer loop, producing a single-ring polygon without holes
  18968. function eliminateHoles(data, holeIndices, outerNode, dim) {
  18969. const queue = [];
  18970. let i, len, start, end, list;
  18971. for (i = 0, len = holeIndices.length; i < len; i++) {
  18972. start = holeIndices[i] * dim;
  18973. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  18974. list = linkedList(data, start, end, dim, false);
  18975. if (list === list.next) list.steiner = true;
  18976. queue.push(getLeftmost(list));
  18977. }
  18978. queue.sort(compareX); // process holes from left to right
  18979. for (i = 0; i < queue.length; i++) {
  18980. eliminateHole(queue[i], outerNode);
  18981. outerNode = filterPoints(outerNode, outerNode.next);
  18982. }
  18983. return outerNode;
  18984. }
  18985. function compareX(a, b) {
  18986. return a.x - b.x;
  18987. } // find a bridge between vertices that connects hole with an outer ring and and link it
  18988. function eliminateHole(hole, outerNode) {
  18989. outerNode = findHoleBridge(hole, outerNode);
  18990. if (outerNode) {
  18991. const b = splitPolygon(outerNode, hole); // filter collinear points around the cuts
  18992. filterPoints(outerNode, outerNode.next);
  18993. filterPoints(b, b.next);
  18994. }
  18995. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  18996. function findHoleBridge(hole, outerNode) {
  18997. let p = outerNode;
  18998. const hx = hole.x;
  18999. const hy = hole.y;
  19000. let qx = -Infinity,
  19001. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  19002. // segment's endpoint with lesser x will be potential connection point
  19003. do {
  19004. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  19005. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  19006. if (x <= hx && x > qx) {
  19007. qx = x;
  19008. if (x === hx) {
  19009. if (hy === p.y) return p;
  19010. if (hy === p.next.y) return p.next;
  19011. }
  19012. m = p.x < p.next.x ? p : p.next;
  19013. }
  19014. }
  19015. p = p.next;
  19016. } while (p !== outerNode);
  19017. if (!m) return null;
  19018. if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint
  19019. // look for points inside the triangle of hole point, segment intersection and endpoint;
  19020. // if there are no points found, we have a valid connection;
  19021. // otherwise choose the point of the minimum angle with the ray as connection point
  19022. const stop = m,
  19023. mx = m.x,
  19024. my = m.y;
  19025. let tanMin = Infinity,
  19026. tan;
  19027. p = m;
  19028. do {
  19029. 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)) {
  19030. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  19031. if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
  19032. m = p;
  19033. tanMin = tan;
  19034. }
  19035. }
  19036. p = p.next;
  19037. } while (p !== stop);
  19038. return m;
  19039. } // whether sector in vertex m contains sector in vertex p in the same coordinates
  19040. function sectorContainsSector(m, p) {
  19041. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  19042. } // interlink polygon nodes in z-order
  19043. function indexCurve(start, minX, minY, invSize) {
  19044. let p = start;
  19045. do {
  19046. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  19047. p.prevZ = p.prev;
  19048. p.nextZ = p.next;
  19049. p = p.next;
  19050. } while (p !== start);
  19051. p.prevZ.nextZ = null;
  19052. p.prevZ = null;
  19053. sortLinked(p);
  19054. } // Simon Tatham's linked list merge sort algorithm
  19055. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  19056. function sortLinked(list) {
  19057. let i,
  19058. p,
  19059. q,
  19060. e,
  19061. tail,
  19062. numMerges,
  19063. pSize,
  19064. qSize,
  19065. inSize = 1;
  19066. do {
  19067. p = list;
  19068. list = null;
  19069. tail = null;
  19070. numMerges = 0;
  19071. while (p) {
  19072. numMerges++;
  19073. q = p;
  19074. pSize = 0;
  19075. for (i = 0; i < inSize; i++) {
  19076. pSize++;
  19077. q = q.nextZ;
  19078. if (!q) break;
  19079. }
  19080. qSize = inSize;
  19081. while (pSize > 0 || qSize > 0 && q) {
  19082. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  19083. e = p;
  19084. p = p.nextZ;
  19085. pSize--;
  19086. } else {
  19087. e = q;
  19088. q = q.nextZ;
  19089. qSize--;
  19090. }
  19091. if (tail) tail.nextZ = e;else list = e;
  19092. e.prevZ = tail;
  19093. tail = e;
  19094. }
  19095. p = q;
  19096. }
  19097. tail.nextZ = null;
  19098. inSize *= 2;
  19099. } while (numMerges > 1);
  19100. return list;
  19101. } // z-order of a point given coords and inverse of the longer side of data bbox
  19102. function zOrder(x, y, minX, minY, invSize) {
  19103. // coords are transformed into non-negative 15-bit integer range
  19104. x = 32767 * (x - minX) * invSize;
  19105. y = 32767 * (y - minY) * invSize;
  19106. x = (x | x << 8) & 0x00FF00FF;
  19107. x = (x | x << 4) & 0x0F0F0F0F;
  19108. x = (x | x << 2) & 0x33333333;
  19109. x = (x | x << 1) & 0x55555555;
  19110. y = (y | y << 8) & 0x00FF00FF;
  19111. y = (y | y << 4) & 0x0F0F0F0F;
  19112. y = (y | y << 2) & 0x33333333;
  19113. y = (y | y << 1) & 0x55555555;
  19114. return x | y << 1;
  19115. } // find the leftmost node of a polygon ring
  19116. function getLeftmost(start) {
  19117. let p = start,
  19118. leftmost = start;
  19119. do {
  19120. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  19121. p = p.next;
  19122. } while (p !== start);
  19123. return leftmost;
  19124. } // check if a point lies within a convex triangle
  19125. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  19126. 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;
  19127. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  19128. function isValidDiagonal(a, b) {
  19129. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  19130. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  19131. } // signed area of a triangle
  19132. function area(p, q, r) {
  19133. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  19134. } // check if two points are equal
  19135. function equals(p1, p2) {
  19136. return p1.x === p2.x && p1.y === p2.y;
  19137. } // check if two segments intersect
  19138. function intersects(p1, q1, p2, q2) {
  19139. const o1 = sign(area(p1, q1, p2));
  19140. const o2 = sign(area(p1, q1, q2));
  19141. const o3 = sign(area(p2, q2, p1));
  19142. const o4 = sign(area(p2, q2, q1));
  19143. if (o1 !== o2 && o3 !== o4) return true; // general case
  19144. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  19145. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  19146. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  19147. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  19148. return false;
  19149. } // for collinear points p, q, r, check if point q lies on segment pr
  19150. function onSegment(p, q, r) {
  19151. 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);
  19152. }
  19153. function sign(num) {
  19154. return num > 0 ? 1 : num < 0 ? -1 : 0;
  19155. } // check if a polygon diagonal intersects any polygon segments
  19156. function intersectsPolygon(a, b) {
  19157. let p = a;
  19158. do {
  19159. 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;
  19160. p = p.next;
  19161. } while (p !== a);
  19162. return false;
  19163. } // check if a polygon diagonal is locally inside the polygon
  19164. function locallyInside(a, b) {
  19165. 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;
  19166. } // check if the middle point of a polygon diagonal is inside the polygon
  19167. function middleInside(a, b) {
  19168. let p = a,
  19169. inside = false;
  19170. const px = (a.x + b.x) / 2,
  19171. py = (a.y + b.y) / 2;
  19172. do {
  19173. 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;
  19174. p = p.next;
  19175. } while (p !== a);
  19176. return inside;
  19177. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  19178. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  19179. function splitPolygon(a, b) {
  19180. const a2 = new Node(a.i, a.x, a.y),
  19181. b2 = new Node(b.i, b.x, b.y),
  19182. an = a.next,
  19183. bp = b.prev;
  19184. a.next = b;
  19185. b.prev = a;
  19186. a2.next = an;
  19187. an.prev = a2;
  19188. b2.next = a2;
  19189. a2.prev = b2;
  19190. bp.next = b2;
  19191. b2.prev = bp;
  19192. return b2;
  19193. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  19194. function insertNode(i, x, y, last) {
  19195. const p = new Node(i, x, y);
  19196. if (!last) {
  19197. p.prev = p;
  19198. p.next = p;
  19199. } else {
  19200. p.next = last.next;
  19201. p.prev = last;
  19202. last.next.prev = p;
  19203. last.next = p;
  19204. }
  19205. return p;
  19206. }
  19207. function removeNode(p) {
  19208. p.next.prev = p.prev;
  19209. p.prev.next = p.next;
  19210. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  19211. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  19212. }
  19213. function Node(i, x, y) {
  19214. // vertex index in coordinates array
  19215. this.i = i; // vertex coordinates
  19216. this.x = x;
  19217. this.y = y; // previous and next vertex nodes in a polygon ring
  19218. this.prev = null;
  19219. this.next = null; // z-order curve value
  19220. this.z = null; // previous and next nodes in z-order
  19221. this.prevZ = null;
  19222. this.nextZ = null; // indicates whether this is a steiner point
  19223. this.steiner = false;
  19224. }
  19225. function signedArea(data, start, end, dim) {
  19226. let sum = 0;
  19227. for (let i = start, j = end - dim; i < end; i += dim) {
  19228. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  19229. j = i;
  19230. }
  19231. return sum;
  19232. }
  19233. class ShapeUtils {
  19234. // calculate area of the contour polygon
  19235. static area(contour) {
  19236. const n = contour.length;
  19237. let a = 0.0;
  19238. for (let p = n - 1, q = 0; q < n; p = q++) {
  19239. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  19240. }
  19241. return a * 0.5;
  19242. }
  19243. static isClockWise(pts) {
  19244. return ShapeUtils.area(pts) < 0;
  19245. }
  19246. static triangulateShape(contour, holes) {
  19247. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  19248. const holeIndices = []; // array of hole indices
  19249. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  19250. removeDupEndPts(contour);
  19251. addContour(vertices, contour); //
  19252. let holeIndex = contour.length;
  19253. holes.forEach(removeDupEndPts);
  19254. for (let i = 0; i < holes.length; i++) {
  19255. holeIndices.push(holeIndex);
  19256. holeIndex += holes[i].length;
  19257. addContour(vertices, holes[i]);
  19258. } //
  19259. const triangles = Earcut.triangulate(vertices, holeIndices); //
  19260. for (let i = 0; i < triangles.length; i += 3) {
  19261. faces.push(triangles.slice(i, i + 3));
  19262. }
  19263. return faces;
  19264. }
  19265. }
  19266. function removeDupEndPts(points) {
  19267. const l = points.length;
  19268. if (l > 2 && points[l - 1].equals(points[0])) {
  19269. points.pop();
  19270. }
  19271. }
  19272. function addContour(vertices, contour) {
  19273. for (let i = 0; i < contour.length; i++) {
  19274. vertices.push(contour[i].x);
  19275. vertices.push(contour[i].y);
  19276. }
  19277. }
  19278. /**
  19279. * Creates extruded geometry from a path shape.
  19280. *
  19281. * parameters = {
  19282. *
  19283. * curveSegments: <int>, // number of points on the curves
  19284. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  19285. * depth: <float>, // Depth to extrude the shape
  19286. *
  19287. * bevelEnabled: <bool>, // turn on bevel
  19288. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19289. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  19290. * bevelOffset: <float>, // how far from shape outline does bevel start
  19291. * bevelSegments: <int>, // number of bevel layers
  19292. *
  19293. * extrudePath: <THREE.Curve> // curve to extrude shape along
  19294. *
  19295. * UVGenerator: <Object> // object that provides UV generator functions
  19296. *
  19297. * }
  19298. */
  19299. class ExtrudeGeometry extends BufferGeometry {
  19300. constructor(shapes, options) {
  19301. super();
  19302. this.type = 'ExtrudeGeometry';
  19303. this.parameters = {
  19304. shapes: shapes,
  19305. options: options
  19306. };
  19307. shapes = Array.isArray(shapes) ? shapes : [shapes];
  19308. const scope = this;
  19309. const verticesArray = [];
  19310. const uvArray = [];
  19311. for (let i = 0, l = shapes.length; i < l; i++) {
  19312. const shape = shapes[i];
  19313. addShape(shape);
  19314. } // build geometry
  19315. this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  19316. this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  19317. this.computeVertexNormals(); // functions
  19318. function addShape(shape) {
  19319. const placeholder = []; // options
  19320. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19321. const steps = options.steps !== undefined ? options.steps : 1;
  19322. let depth = options.depth !== undefined ? options.depth : 100;
  19323. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  19324. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  19325. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  19326. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  19327. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19328. const extrudePath = options.extrudePath;
  19329. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  19330. if (options.amount !== undefined) {
  19331. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  19332. depth = options.amount;
  19333. } //
  19334. let extrudePts,
  19335. extrudeByPath = false;
  19336. let splineTube, binormal, normal, position2;
  19337. if (extrudePath) {
  19338. extrudePts = extrudePath.getSpacedPoints(steps);
  19339. extrudeByPath = true;
  19340. bevelEnabled = false; // bevels not supported for path extrusion
  19341. // SETUP TNB variables
  19342. // TODO1 - have a .isClosed in spline?
  19343. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19344. binormal = new Vector3();
  19345. normal = new Vector3();
  19346. position2 = new Vector3();
  19347. } // Safeguards if bevels are not enabled
  19348. if (!bevelEnabled) {
  19349. bevelSegments = 0;
  19350. bevelThickness = 0;
  19351. bevelSize = 0;
  19352. bevelOffset = 0;
  19353. } // Variables initialization
  19354. const shapePoints = shape.extractPoints(curveSegments);
  19355. let vertices = shapePoints.shape;
  19356. const holes = shapePoints.holes;
  19357. const reverse = !ShapeUtils.isClockWise(vertices);
  19358. if (reverse) {
  19359. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19360. for (let h = 0, hl = holes.length; h < hl; h++) {
  19361. const ahole = holes[h];
  19362. if (ShapeUtils.isClockWise(ahole)) {
  19363. holes[h] = ahole.reverse();
  19364. }
  19365. }
  19366. }
  19367. const faces = ShapeUtils.triangulateShape(vertices, holes);
  19368. /* Vertices */
  19369. const contour = vertices; // vertices has all points but contour has only points of circumference
  19370. for (let h = 0, hl = holes.length; h < hl; h++) {
  19371. const ahole = holes[h];
  19372. vertices = vertices.concat(ahole);
  19373. }
  19374. function scalePt2(pt, vec, size) {
  19375. if (!vec) console.error('THREE.ExtrudeGeometry: vec does not exist');
  19376. return vec.clone().multiplyScalar(size).add(pt);
  19377. }
  19378. const vlen = vertices.length,
  19379. flen = faces.length; // Find directions for point movement
  19380. function getBevelVec(inPt, inPrev, inNext) {
  19381. // computes for inPt the corresponding point inPt' on a new contour
  19382. // shifted by 1 unit (length of normalized vector) to the left
  19383. // if we walk along contour clockwise, this new contour is outside the old one
  19384. //
  19385. // inPt' is the intersection of the two lines parallel to the two
  19386. // adjacent edges of inPt at a distance of 1 unit on the left side.
  19387. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  19388. // good reading for geometry algorithms (here: line-line intersection)
  19389. // http://geomalgorithms.com/a05-_intersect-1.html
  19390. const v_prev_x = inPt.x - inPrev.x,
  19391. v_prev_y = inPt.y - inPrev.y;
  19392. const v_next_x = inNext.x - inPt.x,
  19393. v_next_y = inNext.y - inPt.y;
  19394. const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  19395. const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  19396. if (Math.abs(collinear0) > Number.EPSILON) {
  19397. // not collinear
  19398. // length of vectors for normalizing
  19399. const v_prev_len = Math.sqrt(v_prev_lensq);
  19400. 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
  19401. const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  19402. const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  19403. const ptNextShift_x = inNext.x - v_next_y / v_next_len;
  19404. const ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  19405. 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
  19406. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  19407. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  19408. // but prevent crazy spikes
  19409. const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  19410. if (v_trans_lensq <= 2) {
  19411. return new Vector2(v_trans_x, v_trans_y);
  19412. } else {
  19413. shrink_by = Math.sqrt(v_trans_lensq / 2);
  19414. }
  19415. } else {
  19416. // handle special case of collinear edges
  19417. let direction_eq = false; // assumes: opposite
  19418. if (v_prev_x > Number.EPSILON) {
  19419. if (v_next_x > Number.EPSILON) {
  19420. direction_eq = true;
  19421. }
  19422. } else {
  19423. if (v_prev_x < -Number.EPSILON) {
  19424. if (v_next_x < -Number.EPSILON) {
  19425. direction_eq = true;
  19426. }
  19427. } else {
  19428. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  19429. direction_eq = true;
  19430. }
  19431. }
  19432. }
  19433. if (direction_eq) {
  19434. // console.log("Warning: lines are a straight sequence");
  19435. v_trans_x = -v_prev_y;
  19436. v_trans_y = v_prev_x;
  19437. shrink_by = Math.sqrt(v_prev_lensq);
  19438. } else {
  19439. // console.log("Warning: lines are a straight spike");
  19440. v_trans_x = v_prev_x;
  19441. v_trans_y = v_prev_y;
  19442. shrink_by = Math.sqrt(v_prev_lensq / 2);
  19443. }
  19444. }
  19445. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  19446. }
  19447. const contourMovements = [];
  19448. for (let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  19449. if (j === il) j = 0;
  19450. if (k === il) k = 0; // (j)---(i)---(k)
  19451. // console.log('i,j,k', i, j , k)
  19452. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  19453. }
  19454. const holesMovements = [];
  19455. let oneHoleMovements,
  19456. verticesMovements = contourMovements.concat();
  19457. for (let h = 0, hl = holes.length; h < hl; h++) {
  19458. const ahole = holes[h];
  19459. oneHoleMovements = [];
  19460. for (let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  19461. if (j === il) j = 0;
  19462. if (k === il) k = 0; // (j)---(i)---(k)
  19463. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  19464. }
  19465. holesMovements.push(oneHoleMovements);
  19466. verticesMovements = verticesMovements.concat(oneHoleMovements);
  19467. } // Loop bevelSegments, 1 for the front, 1 for the back
  19468. for (let b = 0; b < bevelSegments; b++) {
  19469. //for ( b = bevelSegments; b > 0; b -- ) {
  19470. const t = b / bevelSegments;
  19471. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  19472. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  19473. for (let i = 0, il = contour.length; i < il; i++) {
  19474. const vert = scalePt2(contour[i], contourMovements[i], bs);
  19475. v(vert.x, vert.y, -z);
  19476. } // expand holes
  19477. for (let h = 0, hl = holes.length; h < hl; h++) {
  19478. const ahole = holes[h];
  19479. oneHoleMovements = holesMovements[h];
  19480. for (let i = 0, il = ahole.length; i < il; i++) {
  19481. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  19482. v(vert.x, vert.y, -z);
  19483. }
  19484. }
  19485. }
  19486. const bs = bevelSize + bevelOffset; // Back facing vertices
  19487. for (let i = 0; i < vlen; i++) {
  19488. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  19489. if (!extrudeByPath) {
  19490. v(vert.x, vert.y, 0);
  19491. } else {
  19492. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19493. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  19494. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  19495. position2.copy(extrudePts[0]).add(normal).add(binormal);
  19496. v(position2.x, position2.y, position2.z);
  19497. }
  19498. } // Add stepped vertices...
  19499. // Including front facing vertices
  19500. for (let s = 1; s <= steps; s++) {
  19501. for (let i = 0; i < vlen; i++) {
  19502. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  19503. if (!extrudeByPath) {
  19504. v(vert.x, vert.y, depth / steps * s);
  19505. } else {
  19506. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19507. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  19508. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  19509. position2.copy(extrudePts[s]).add(normal).add(binormal);
  19510. v(position2.x, position2.y, position2.z);
  19511. }
  19512. }
  19513. } // Add bevel segments planes
  19514. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19515. for (let b = bevelSegments - 1; b >= 0; b--) {
  19516. const t = b / bevelSegments;
  19517. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  19518. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  19519. for (let i = 0, il = contour.length; i < il; i++) {
  19520. const vert = scalePt2(contour[i], contourMovements[i], bs);
  19521. v(vert.x, vert.y, depth + z);
  19522. } // expand holes
  19523. for (let h = 0, hl = holes.length; h < hl; h++) {
  19524. const ahole = holes[h];
  19525. oneHoleMovements = holesMovements[h];
  19526. for (let i = 0, il = ahole.length; i < il; i++) {
  19527. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  19528. if (!extrudeByPath) {
  19529. v(vert.x, vert.y, depth + z);
  19530. } else {
  19531. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  19532. }
  19533. }
  19534. }
  19535. }
  19536. /* Faces */
  19537. // Top and bottom faces
  19538. buildLidFaces(); // Sides faces
  19539. buildSideFaces(); ///// Internal functions
  19540. function buildLidFaces() {
  19541. const start = verticesArray.length / 3;
  19542. if (bevelEnabled) {
  19543. let layer = 0; // steps + 1
  19544. let offset = vlen * layer; // Bottom faces
  19545. for (let i = 0; i < flen; i++) {
  19546. const face = faces[i];
  19547. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  19548. }
  19549. layer = steps + bevelSegments * 2;
  19550. offset = vlen * layer; // Top faces
  19551. for (let i = 0; i < flen; i++) {
  19552. const face = faces[i];
  19553. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  19554. }
  19555. } else {
  19556. // Bottom faces
  19557. for (let i = 0; i < flen; i++) {
  19558. const face = faces[i];
  19559. f3(face[2], face[1], face[0]);
  19560. } // Top faces
  19561. for (let i = 0; i < flen; i++) {
  19562. const face = faces[i];
  19563. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  19564. }
  19565. }
  19566. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  19567. } // Create faces for the z-sides of the shape
  19568. function buildSideFaces() {
  19569. const start = verticesArray.length / 3;
  19570. let layeroffset = 0;
  19571. sidewalls(contour, layeroffset);
  19572. layeroffset += contour.length;
  19573. for (let h = 0, hl = holes.length; h < hl; h++) {
  19574. const ahole = holes[h];
  19575. sidewalls(ahole, layeroffset); //, true
  19576. layeroffset += ahole.length;
  19577. }
  19578. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  19579. }
  19580. function sidewalls(contour, layeroffset) {
  19581. let i = contour.length;
  19582. while (--i >= 0) {
  19583. const j = i;
  19584. let k = i - 1;
  19585. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  19586. for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) {
  19587. const slen1 = vlen * s;
  19588. const slen2 = vlen * (s + 1);
  19589. const a = layeroffset + j + slen1,
  19590. b = layeroffset + k + slen1,
  19591. c = layeroffset + k + slen2,
  19592. d = layeroffset + j + slen2;
  19593. f4(a, b, c, d);
  19594. }
  19595. }
  19596. }
  19597. function v(x, y, z) {
  19598. placeholder.push(x);
  19599. placeholder.push(y);
  19600. placeholder.push(z);
  19601. }
  19602. function f3(a, b, c) {
  19603. addVertex(a);
  19604. addVertex(b);
  19605. addVertex(c);
  19606. const nextIndex = verticesArray.length / 3;
  19607. const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  19608. addUV(uvs[0]);
  19609. addUV(uvs[1]);
  19610. addUV(uvs[2]);
  19611. }
  19612. function f4(a, b, c, d) {
  19613. addVertex(a);
  19614. addVertex(b);
  19615. addVertex(d);
  19616. addVertex(b);
  19617. addVertex(c);
  19618. addVertex(d);
  19619. const nextIndex = verticesArray.length / 3;
  19620. const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  19621. addUV(uvs[0]);
  19622. addUV(uvs[1]);
  19623. addUV(uvs[3]);
  19624. addUV(uvs[1]);
  19625. addUV(uvs[2]);
  19626. addUV(uvs[3]);
  19627. }
  19628. function addVertex(index) {
  19629. verticesArray.push(placeholder[index * 3 + 0]);
  19630. verticesArray.push(placeholder[index * 3 + 1]);
  19631. verticesArray.push(placeholder[index * 3 + 2]);
  19632. }
  19633. function addUV(vector2) {
  19634. uvArray.push(vector2.x);
  19635. uvArray.push(vector2.y);
  19636. }
  19637. }
  19638. }
  19639. toJSON() {
  19640. const data = super.toJSON();
  19641. const shapes = this.parameters.shapes;
  19642. const options = this.parameters.options;
  19643. return toJSON$1(shapes, options, data);
  19644. }
  19645. static fromJSON(data, shapes) {
  19646. const geometryShapes = [];
  19647. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  19648. const shape = shapes[data.shapes[j]];
  19649. geometryShapes.push(shape);
  19650. }
  19651. const extrudePath = data.options.extrudePath;
  19652. if (extrudePath !== undefined) {
  19653. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  19654. }
  19655. return new ExtrudeGeometry(geometryShapes, data.options);
  19656. }
  19657. }
  19658. const WorldUVGenerator = {
  19659. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  19660. const a_x = vertices[indexA * 3];
  19661. const a_y = vertices[indexA * 3 + 1];
  19662. const b_x = vertices[indexB * 3];
  19663. const b_y = vertices[indexB * 3 + 1];
  19664. const c_x = vertices[indexC * 3];
  19665. const c_y = vertices[indexC * 3 + 1];
  19666. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  19667. },
  19668. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  19669. const a_x = vertices[indexA * 3];
  19670. const a_y = vertices[indexA * 3 + 1];
  19671. const a_z = vertices[indexA * 3 + 2];
  19672. const b_x = vertices[indexB * 3];
  19673. const b_y = vertices[indexB * 3 + 1];
  19674. const b_z = vertices[indexB * 3 + 2];
  19675. const c_x = vertices[indexC * 3];
  19676. const c_y = vertices[indexC * 3 + 1];
  19677. const c_z = vertices[indexC * 3 + 2];
  19678. const d_x = vertices[indexD * 3];
  19679. const d_y = vertices[indexD * 3 + 1];
  19680. const d_z = vertices[indexD * 3 + 2];
  19681. if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) {
  19682. 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)];
  19683. } else {
  19684. 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)];
  19685. }
  19686. }
  19687. };
  19688. function toJSON$1(shapes, options, data) {
  19689. data.shapes = [];
  19690. if (Array.isArray(shapes)) {
  19691. for (let i = 0, l = shapes.length; i < l; i++) {
  19692. const shape = shapes[i];
  19693. data.shapes.push(shape.uuid);
  19694. }
  19695. } else {
  19696. data.shapes.push(shapes.uuid);
  19697. }
  19698. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  19699. return data;
  19700. }
  19701. class IcosahedronGeometry extends PolyhedronGeometry {
  19702. constructor(radius = 1, detail = 0) {
  19703. const t = (1 + Math.sqrt(5)) / 2;
  19704. 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];
  19705. 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];
  19706. super(vertices, indices, radius, detail);
  19707. this.type = 'IcosahedronGeometry';
  19708. this.parameters = {
  19709. radius: radius,
  19710. detail: detail
  19711. };
  19712. }
  19713. static fromJSON(data) {
  19714. return new IcosahedronGeometry(data.radius, data.detail);
  19715. }
  19716. }
  19717. class LatheGeometry extends BufferGeometry {
  19718. constructor(points, segments = 12, phiStart = 0, phiLength = Math.PI * 2) {
  19719. super();
  19720. this.type = 'LatheGeometry';
  19721. this.parameters = {
  19722. points: points,
  19723. segments: segments,
  19724. phiStart: phiStart,
  19725. phiLength: phiLength
  19726. };
  19727. segments = Math.floor(segments); // clamp phiLength so it's in range of [ 0, 2PI ]
  19728. phiLength = clamp(phiLength, 0, Math.PI * 2); // buffers
  19729. const indices = [];
  19730. const vertices = [];
  19731. const uvs = []; // helper variables
  19732. const inverseSegments = 1.0 / segments;
  19733. const vertex = new Vector3();
  19734. const uv = new Vector2(); // generate vertices and uvs
  19735. for (let i = 0; i <= segments; i++) {
  19736. const phi = phiStart + i * inverseSegments * phiLength;
  19737. const sin = Math.sin(phi);
  19738. const cos = Math.cos(phi);
  19739. for (let j = 0; j <= points.length - 1; j++) {
  19740. // vertex
  19741. vertex.x = points[j].x * sin;
  19742. vertex.y = points[j].y;
  19743. vertex.z = points[j].x * cos;
  19744. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  19745. uv.x = i / segments;
  19746. uv.y = j / (points.length - 1);
  19747. uvs.push(uv.x, uv.y);
  19748. }
  19749. } // indices
  19750. for (let i = 0; i < segments; i++) {
  19751. for (let j = 0; j < points.length - 1; j++) {
  19752. const base = j + i * points.length;
  19753. const a = base;
  19754. const b = base + points.length;
  19755. const c = base + points.length + 1;
  19756. const d = base + 1; // faces
  19757. indices.push(a, b, d);
  19758. indices.push(b, c, d);
  19759. }
  19760. } // build geometry
  19761. this.setIndex(indices);
  19762. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19763. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
  19764. this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
  19765. // because the corresponding vertices are identical (but still have different UVs).
  19766. if (phiLength === Math.PI * 2) {
  19767. const normals = this.attributes.normal.array;
  19768. const n1 = new Vector3();
  19769. const n2 = new Vector3();
  19770. const n = new Vector3(); // this is the buffer offset for the last line of vertices
  19771. const base = segments * points.length * 3;
  19772. for (let i = 0, j = 0; i < points.length; i++, j += 3) {
  19773. // select the normal of the vertex in the first line
  19774. n1.x = normals[j + 0];
  19775. n1.y = normals[j + 1];
  19776. n1.z = normals[j + 2]; // select the normal of the vertex in the last line
  19777. n2.x = normals[base + j + 0];
  19778. n2.y = normals[base + j + 1];
  19779. n2.z = normals[base + j + 2]; // average normals
  19780. n.addVectors(n1, n2).normalize(); // assign the new values to both normals
  19781. normals[j + 0] = normals[base + j + 0] = n.x;
  19782. normals[j + 1] = normals[base + j + 1] = n.y;
  19783. normals[j + 2] = normals[base + j + 2] = n.z;
  19784. }
  19785. }
  19786. }
  19787. static fromJSON(data) {
  19788. return new LatheGeometry(data.points, data.segments, data.phiStart, data.phiLength);
  19789. }
  19790. }
  19791. class OctahedronGeometry extends PolyhedronGeometry {
  19792. constructor(radius = 1, detail = 0) {
  19793. const vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  19794. 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];
  19795. super(vertices, indices, radius, detail);
  19796. this.type = 'OctahedronGeometry';
  19797. this.parameters = {
  19798. radius: radius,
  19799. detail: detail
  19800. };
  19801. }
  19802. static fromJSON(data) {
  19803. return new OctahedronGeometry(data.radius, data.detail);
  19804. }
  19805. }
  19806. /**
  19807. * Parametric Surfaces Geometry
  19808. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  19809. */
  19810. class ParametricGeometry extends BufferGeometry {
  19811. constructor(func, slices, stacks) {
  19812. super();
  19813. this.type = 'ParametricGeometry';
  19814. this.parameters = {
  19815. func: func,
  19816. slices: slices,
  19817. stacks: stacks
  19818. }; // buffers
  19819. const indices = [];
  19820. const vertices = [];
  19821. const normals = [];
  19822. const uvs = [];
  19823. const EPS = 0.00001;
  19824. const normal = new Vector3();
  19825. const p0 = new Vector3(),
  19826. p1 = new Vector3();
  19827. const pu = new Vector3(),
  19828. pv = new Vector3();
  19829. if (func.length < 3) {
  19830. console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');
  19831. } // generate vertices, normals and uvs
  19832. const sliceCount = slices + 1;
  19833. for (let i = 0; i <= stacks; i++) {
  19834. const v = i / stacks;
  19835. for (let j = 0; j <= slices; j++) {
  19836. const u = j / slices; // vertex
  19837. func(u, v, p0);
  19838. vertices.push(p0.x, p0.y, p0.z); // normal
  19839. // approximate tangent vectors via finite differences
  19840. if (u - EPS >= 0) {
  19841. func(u - EPS, v, p1);
  19842. pu.subVectors(p0, p1);
  19843. } else {
  19844. func(u + EPS, v, p1);
  19845. pu.subVectors(p1, p0);
  19846. }
  19847. if (v - EPS >= 0) {
  19848. func(u, v - EPS, p1);
  19849. pv.subVectors(p0, p1);
  19850. } else {
  19851. func(u, v + EPS, p1);
  19852. pv.subVectors(p1, p0);
  19853. } // cross product of tangent vectors returns surface normal
  19854. normal.crossVectors(pu, pv).normalize();
  19855. normals.push(normal.x, normal.y, normal.z); // uv
  19856. uvs.push(u, v);
  19857. }
  19858. } // generate indices
  19859. for (let i = 0; i < stacks; i++) {
  19860. for (let j = 0; j < slices; j++) {
  19861. const a = i * sliceCount + j;
  19862. const b = i * sliceCount + j + 1;
  19863. const c = (i + 1) * sliceCount + j + 1;
  19864. const d = (i + 1) * sliceCount + j; // faces one and two
  19865. indices.push(a, b, d);
  19866. indices.push(b, c, d);
  19867. }
  19868. } // build geometry
  19869. this.setIndex(indices);
  19870. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19871. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19872. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19873. }
  19874. }
  19875. class RingGeometry extends BufferGeometry {
  19876. constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) {
  19877. super();
  19878. this.type = 'RingGeometry';
  19879. this.parameters = {
  19880. innerRadius: innerRadius,
  19881. outerRadius: outerRadius,
  19882. thetaSegments: thetaSegments,
  19883. phiSegments: phiSegments,
  19884. thetaStart: thetaStart,
  19885. thetaLength: thetaLength
  19886. };
  19887. thetaSegments = Math.max(3, thetaSegments);
  19888. phiSegments = Math.max(1, phiSegments); // buffers
  19889. const indices = [];
  19890. const vertices = [];
  19891. const normals = [];
  19892. const uvs = []; // some helper variables
  19893. let radius = innerRadius;
  19894. const radiusStep = (outerRadius - innerRadius) / phiSegments;
  19895. const vertex = new Vector3();
  19896. const uv = new Vector2(); // generate vertices, normals and uvs
  19897. for (let j = 0; j <= phiSegments; j++) {
  19898. for (let i = 0; i <= thetaSegments; i++) {
  19899. // values are generate from the inside of the ring to the outside
  19900. const segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  19901. vertex.x = radius * Math.cos(segment);
  19902. vertex.y = radius * Math.sin(segment);
  19903. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19904. normals.push(0, 0, 1); // uv
  19905. uv.x = (vertex.x / outerRadius + 1) / 2;
  19906. uv.y = (vertex.y / outerRadius + 1) / 2;
  19907. uvs.push(uv.x, uv.y);
  19908. } // increase the radius for next row of vertices
  19909. radius += radiusStep;
  19910. } // indices
  19911. for (let j = 0; j < phiSegments; j++) {
  19912. const thetaSegmentLevel = j * (thetaSegments + 1);
  19913. for (let i = 0; i < thetaSegments; i++) {
  19914. const segment = i + thetaSegmentLevel;
  19915. const a = segment;
  19916. const b = segment + thetaSegments + 1;
  19917. const c = segment + thetaSegments + 2;
  19918. const d = segment + 1; // faces
  19919. indices.push(a, b, d);
  19920. indices.push(b, c, d);
  19921. }
  19922. } // build geometry
  19923. this.setIndex(indices);
  19924. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19925. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19926. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19927. }
  19928. static fromJSON(data) {
  19929. return new RingGeometry(data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  19930. }
  19931. }
  19932. class ShapeGeometry extends BufferGeometry {
  19933. constructor(shapes, curveSegments = 12) {
  19934. super();
  19935. this.type = 'ShapeGeometry';
  19936. this.parameters = {
  19937. shapes: shapes,
  19938. curveSegments: curveSegments
  19939. }; // buffers
  19940. const indices = [];
  19941. const vertices = [];
  19942. const normals = [];
  19943. const uvs = []; // helper variables
  19944. let groupStart = 0;
  19945. let groupCount = 0; // allow single and array values for "shapes" parameter
  19946. if (Array.isArray(shapes) === false) {
  19947. addShape(shapes);
  19948. } else {
  19949. for (let i = 0; i < shapes.length; i++) {
  19950. addShape(shapes[i]);
  19951. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  19952. groupStart += groupCount;
  19953. groupCount = 0;
  19954. }
  19955. } // build geometry
  19956. this.setIndex(indices);
  19957. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19958. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19959. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  19960. function addShape(shape) {
  19961. const indexOffset = vertices.length / 3;
  19962. const points = shape.extractPoints(curveSegments);
  19963. let shapeVertices = points.shape;
  19964. const shapeHoles = points.holes; // check direction of vertices
  19965. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  19966. shapeVertices = shapeVertices.reverse();
  19967. }
  19968. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  19969. const shapeHole = shapeHoles[i];
  19970. if (ShapeUtils.isClockWise(shapeHole) === true) {
  19971. shapeHoles[i] = shapeHole.reverse();
  19972. }
  19973. }
  19974. const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  19975. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  19976. const shapeHole = shapeHoles[i];
  19977. shapeVertices = shapeVertices.concat(shapeHole);
  19978. } // vertices, normals, uvs
  19979. for (let i = 0, l = shapeVertices.length; i < l; i++) {
  19980. const vertex = shapeVertices[i];
  19981. vertices.push(vertex.x, vertex.y, 0);
  19982. normals.push(0, 0, 1);
  19983. uvs.push(vertex.x, vertex.y); // world uvs
  19984. } // incides
  19985. for (let i = 0, l = faces.length; i < l; i++) {
  19986. const face = faces[i];
  19987. const a = face[0] + indexOffset;
  19988. const b = face[1] + indexOffset;
  19989. const c = face[2] + indexOffset;
  19990. indices.push(a, b, c);
  19991. groupCount += 3;
  19992. }
  19993. }
  19994. }
  19995. toJSON() {
  19996. const data = super.toJSON();
  19997. const shapes = this.parameters.shapes;
  19998. return toJSON(shapes, data);
  19999. }
  20000. static fromJSON(data, shapes) {
  20001. const geometryShapes = [];
  20002. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  20003. const shape = shapes[data.shapes[j]];
  20004. geometryShapes.push(shape);
  20005. }
  20006. return new ShapeGeometry(geometryShapes, data.curveSegments);
  20007. }
  20008. }
  20009. function toJSON(shapes, data) {
  20010. data.shapes = [];
  20011. if (Array.isArray(shapes)) {
  20012. for (let i = 0, l = shapes.length; i < l; i++) {
  20013. const shape = shapes[i];
  20014. data.shapes.push(shape.uuid);
  20015. }
  20016. } else {
  20017. data.shapes.push(shapes.uuid);
  20018. }
  20019. return data;
  20020. }
  20021. class SphereGeometry extends BufferGeometry {
  20022. constructor(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) {
  20023. super();
  20024. this.type = 'SphereGeometry';
  20025. this.parameters = {
  20026. radius: radius,
  20027. widthSegments: widthSegments,
  20028. heightSegments: heightSegments,
  20029. phiStart: phiStart,
  20030. phiLength: phiLength,
  20031. thetaStart: thetaStart,
  20032. thetaLength: thetaLength
  20033. };
  20034. widthSegments = Math.max(3, Math.floor(widthSegments));
  20035. heightSegments = Math.max(2, Math.floor(heightSegments));
  20036. const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  20037. let index = 0;
  20038. const grid = [];
  20039. const vertex = new Vector3();
  20040. const normal = new Vector3(); // buffers
  20041. const indices = [];
  20042. const vertices = [];
  20043. const normals = [];
  20044. const uvs = []; // generate vertices, normals and uvs
  20045. for (let iy = 0; iy <= heightSegments; iy++) {
  20046. const verticesRow = [];
  20047. const v = iy / heightSegments; // special case for the poles
  20048. let uOffset = 0;
  20049. if (iy == 0 && thetaStart == 0) {
  20050. uOffset = 0.5 / widthSegments;
  20051. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  20052. uOffset = -0.5 / widthSegments;
  20053. }
  20054. for (let ix = 0; ix <= widthSegments; ix++) {
  20055. const u = ix / widthSegments; // vertex
  20056. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  20057. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  20058. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  20059. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20060. normal.copy(vertex).normalize();
  20061. normals.push(normal.x, normal.y, normal.z); // uv
  20062. uvs.push(u + uOffset, 1 - v);
  20063. verticesRow.push(index++);
  20064. }
  20065. grid.push(verticesRow);
  20066. } // indices
  20067. for (let iy = 0; iy < heightSegments; iy++) {
  20068. for (let ix = 0; ix < widthSegments; ix++) {
  20069. const a = grid[iy][ix + 1];
  20070. const b = grid[iy][ix];
  20071. const c = grid[iy + 1][ix];
  20072. const d = grid[iy + 1][ix + 1];
  20073. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  20074. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  20075. }
  20076. } // build geometry
  20077. this.setIndex(indices);
  20078. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20079. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20080. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20081. }
  20082. static fromJSON(data) {
  20083. return new SphereGeometry(data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  20084. }
  20085. }
  20086. class TetrahedronGeometry extends PolyhedronGeometry {
  20087. constructor(radius = 1, detail = 0) {
  20088. const vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  20089. const indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  20090. super(vertices, indices, radius, detail);
  20091. this.type = 'TetrahedronGeometry';
  20092. this.parameters = {
  20093. radius: radius,
  20094. detail: detail
  20095. };
  20096. }
  20097. static fromJSON(data) {
  20098. return new TetrahedronGeometry(data.radius, data.detail);
  20099. }
  20100. }
  20101. /**
  20102. * Text = 3D Text
  20103. *
  20104. * parameters = {
  20105. * font: <THREE.Font>, // font
  20106. *
  20107. * size: <float>, // size of the text
  20108. * height: <float>, // thickness to extrude text
  20109. * curveSegments: <int>, // number of points on the curves
  20110. *
  20111. * bevelEnabled: <bool>, // turn on bevel
  20112. * bevelThickness: <float>, // how deep into text bevel goes
  20113. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  20114. * bevelOffset: <float> // how far from text outline does bevel start
  20115. * }
  20116. */
  20117. class TextGeometry extends ExtrudeGeometry {
  20118. constructor(text, parameters = {}) {
  20119. const font = parameters.font;
  20120. if (!(font && font.isFont)) {
  20121. console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');
  20122. return new BufferGeometry();
  20123. }
  20124. const shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry API
  20125. parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults
  20126. if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;
  20127. if (parameters.bevelSize === undefined) parameters.bevelSize = 8;
  20128. if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;
  20129. super(shapes, parameters);
  20130. this.type = 'TextGeometry';
  20131. }
  20132. }
  20133. class TorusGeometry extends BufferGeometry {
  20134. constructor(radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) {
  20135. super();
  20136. this.type = 'TorusGeometry';
  20137. this.parameters = {
  20138. radius: radius,
  20139. tube: tube,
  20140. radialSegments: radialSegments,
  20141. tubularSegments: tubularSegments,
  20142. arc: arc
  20143. };
  20144. radialSegments = Math.floor(radialSegments);
  20145. tubularSegments = Math.floor(tubularSegments); // buffers
  20146. const indices = [];
  20147. const vertices = [];
  20148. const normals = [];
  20149. const uvs = []; // helper variables
  20150. const center = new Vector3();
  20151. const vertex = new Vector3();
  20152. const normal = new Vector3(); // generate vertices, normals and uvs
  20153. for (let j = 0; j <= radialSegments; j++) {
  20154. for (let i = 0; i <= tubularSegments; i++) {
  20155. const u = i / tubularSegments * arc;
  20156. const v = j / radialSegments * Math.PI * 2; // vertex
  20157. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  20158. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  20159. vertex.z = tube * Math.sin(v);
  20160. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20161. center.x = radius * Math.cos(u);
  20162. center.y = radius * Math.sin(u);
  20163. normal.subVectors(vertex, center).normalize();
  20164. normals.push(normal.x, normal.y, normal.z); // uv
  20165. uvs.push(i / tubularSegments);
  20166. uvs.push(j / radialSegments);
  20167. }
  20168. } // generate indices
  20169. for (let j = 1; j <= radialSegments; j++) {
  20170. for (let i = 1; i <= tubularSegments; i++) {
  20171. // indices
  20172. const a = (tubularSegments + 1) * j + i - 1;
  20173. const b = (tubularSegments + 1) * (j - 1) + i - 1;
  20174. const c = (tubularSegments + 1) * (j - 1) + i;
  20175. const d = (tubularSegments + 1) * j + i; // faces
  20176. indices.push(a, b, d);
  20177. indices.push(b, c, d);
  20178. }
  20179. } // build geometry
  20180. this.setIndex(indices);
  20181. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20182. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20183. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20184. }
  20185. static fromJSON(data) {
  20186. return new TorusGeometry(data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  20187. }
  20188. }
  20189. class TorusKnotGeometry extends BufferGeometry {
  20190. constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) {
  20191. super();
  20192. this.type = 'TorusKnotGeometry';
  20193. this.parameters = {
  20194. radius: radius,
  20195. tube: tube,
  20196. tubularSegments: tubularSegments,
  20197. radialSegments: radialSegments,
  20198. p: p,
  20199. q: q
  20200. };
  20201. tubularSegments = Math.floor(tubularSegments);
  20202. radialSegments = Math.floor(radialSegments); // buffers
  20203. const indices = [];
  20204. const vertices = [];
  20205. const normals = [];
  20206. const uvs = []; // helper variables
  20207. const vertex = new Vector3();
  20208. const normal = new Vector3();
  20209. const P1 = new Vector3();
  20210. const P2 = new Vector3();
  20211. const B = new Vector3();
  20212. const T = new Vector3();
  20213. const N = new Vector3(); // generate vertices, normals and uvs
  20214. for (let i = 0; i <= tubularSegments; ++i) {
  20215. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  20216. 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.
  20217. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  20218. calculatePositionOnCurve(u, p, q, radius, P1);
  20219. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  20220. T.subVectors(P2, P1);
  20221. N.addVectors(P2, P1);
  20222. B.crossVectors(T, N);
  20223. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  20224. B.normalize();
  20225. N.normalize();
  20226. for (let j = 0; j <= radialSegments; ++j) {
  20227. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  20228. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  20229. const v = j / radialSegments * Math.PI * 2;
  20230. const cx = -tube * Math.cos(v);
  20231. const cy = tube * Math.sin(v); // now calculate the final vertex position.
  20232. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  20233. vertex.x = P1.x + (cx * N.x + cy * B.x);
  20234. vertex.y = P1.y + (cx * N.y + cy * B.y);
  20235. vertex.z = P1.z + (cx * N.z + cy * B.z);
  20236. 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)
  20237. normal.subVectors(vertex, P1).normalize();
  20238. normals.push(normal.x, normal.y, normal.z); // uv
  20239. uvs.push(i / tubularSegments);
  20240. uvs.push(j / radialSegments);
  20241. }
  20242. } // generate indices
  20243. for (let j = 1; j <= tubularSegments; j++) {
  20244. for (let i = 1; i <= radialSegments; i++) {
  20245. // indices
  20246. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  20247. const b = (radialSegments + 1) * j + (i - 1);
  20248. const c = (radialSegments + 1) * j + i;
  20249. const d = (radialSegments + 1) * (j - 1) + i; // faces
  20250. indices.push(a, b, d);
  20251. indices.push(b, c, d);
  20252. }
  20253. } // build geometry
  20254. this.setIndex(indices);
  20255. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20256. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20257. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  20258. function calculatePositionOnCurve(u, p, q, radius, position) {
  20259. const cu = Math.cos(u);
  20260. const su = Math.sin(u);
  20261. const quOverP = q / p * u;
  20262. const cs = Math.cos(quOverP);
  20263. position.x = radius * (2 + cs) * 0.5 * cu;
  20264. position.y = radius * (2 + cs) * su * 0.5;
  20265. position.z = radius * Math.sin(quOverP) * 0.5;
  20266. }
  20267. }
  20268. static fromJSON(data) {
  20269. return new TorusKnotGeometry(data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  20270. }
  20271. }
  20272. class TubeGeometry extends BufferGeometry {
  20273. constructor(path, tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) {
  20274. super();
  20275. this.type = 'TubeGeometry';
  20276. this.parameters = {
  20277. path: path,
  20278. tubularSegments: tubularSegments,
  20279. radius: radius,
  20280. radialSegments: radialSegments,
  20281. closed: closed
  20282. };
  20283. const frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  20284. this.tangents = frames.tangents;
  20285. this.normals = frames.normals;
  20286. this.binormals = frames.binormals; // helper variables
  20287. const vertex = new Vector3();
  20288. const normal = new Vector3();
  20289. const uv = new Vector2();
  20290. let P = new Vector3(); // buffer
  20291. const vertices = [];
  20292. const normals = [];
  20293. const uvs = [];
  20294. const indices = []; // create buffer data
  20295. generateBufferData(); // build geometry
  20296. this.setIndex(indices);
  20297. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20298. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20299. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  20300. function generateBufferData() {
  20301. for (let i = 0; i < tubularSegments; i++) {
  20302. generateSegment(i);
  20303. } // if the geometry is not closed, generate the last row of vertices and normals
  20304. // at the regular position on the given path
  20305. //
  20306. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  20307. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  20308. // this makes it easy compute correct values for closed geometries
  20309. generateUVs(); // finally create faces
  20310. generateIndices();
  20311. }
  20312. function generateSegment(i) {
  20313. // we use getPointAt to sample evenly distributed points from the given path
  20314. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  20315. const N = frames.normals[i];
  20316. const B = frames.binormals[i]; // generate normals and vertices for the current segment
  20317. for (let j = 0; j <= radialSegments; j++) {
  20318. const v = j / radialSegments * Math.PI * 2;
  20319. const sin = Math.sin(v);
  20320. const cos = -Math.cos(v); // normal
  20321. normal.x = cos * N.x + sin * B.x;
  20322. normal.y = cos * N.y + sin * B.y;
  20323. normal.z = cos * N.z + sin * B.z;
  20324. normal.normalize();
  20325. normals.push(normal.x, normal.y, normal.z); // vertex
  20326. vertex.x = P.x + radius * normal.x;
  20327. vertex.y = P.y + radius * normal.y;
  20328. vertex.z = P.z + radius * normal.z;
  20329. vertices.push(vertex.x, vertex.y, vertex.z);
  20330. }
  20331. }
  20332. function generateIndices() {
  20333. for (let j = 1; j <= tubularSegments; j++) {
  20334. for (let i = 1; i <= radialSegments; i++) {
  20335. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  20336. const b = (radialSegments + 1) * j + (i - 1);
  20337. const c = (radialSegments + 1) * j + i;
  20338. const d = (radialSegments + 1) * (j - 1) + i; // faces
  20339. indices.push(a, b, d);
  20340. indices.push(b, c, d);
  20341. }
  20342. }
  20343. }
  20344. function generateUVs() {
  20345. for (let i = 0; i <= tubularSegments; i++) {
  20346. for (let j = 0; j <= radialSegments; j++) {
  20347. uv.x = i / tubularSegments;
  20348. uv.y = j / radialSegments;
  20349. uvs.push(uv.x, uv.y);
  20350. }
  20351. }
  20352. }
  20353. }
  20354. toJSON() {
  20355. const data = super.toJSON();
  20356. data.path = this.parameters.path.toJSON();
  20357. return data;
  20358. }
  20359. static fromJSON(data) {
  20360. // This only works for built-in curves (e.g. CatmullRomCurve3).
  20361. // User defined curves or instances of CurvePath will not be deserialized.
  20362. return new TubeGeometry(new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  20363. }
  20364. }
  20365. class WireframeGeometry extends BufferGeometry {
  20366. constructor(geometry) {
  20367. super();
  20368. this.type = 'WireframeGeometry';
  20369. if (geometry.isGeometry === true) {
  20370. console.error('THREE.WireframeGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  20371. return;
  20372. } // buffer
  20373. const vertices = [];
  20374. const edges = new Set(); // helper variables
  20375. const start = new Vector3();
  20376. const end = new Vector3();
  20377. if (geometry.index !== null) {
  20378. // indexed BufferGeometry
  20379. const position = geometry.attributes.position;
  20380. const indices = geometry.index;
  20381. let groups = geometry.groups;
  20382. if (groups.length === 0) {
  20383. groups = [{
  20384. start: 0,
  20385. count: indices.count,
  20386. materialIndex: 0
  20387. }];
  20388. } // create a data structure that contains all eges without duplicates
  20389. for (let o = 0, ol = groups.length; o < ol; ++o) {
  20390. const group = groups[o];
  20391. const groupStart = group.start;
  20392. const groupCount = group.count;
  20393. for (let i = groupStart, l = groupStart + groupCount; i < l; i += 3) {
  20394. for (let j = 0; j < 3; j++) {
  20395. const index1 = indices.getX(i + j);
  20396. const index2 = indices.getX(i + (j + 1) % 3);
  20397. start.fromBufferAttribute(position, index1);
  20398. end.fromBufferAttribute(position, index2);
  20399. if (isUniqueEdge(start, end, edges) === true) {
  20400. vertices.push(start.x, start.y, start.z);
  20401. vertices.push(end.x, end.y, end.z);
  20402. }
  20403. }
  20404. }
  20405. }
  20406. } else {
  20407. // non-indexed BufferGeometry
  20408. const position = geometry.attributes.position;
  20409. for (let i = 0, l = position.count / 3; i < l; i++) {
  20410. for (let j = 0; j < 3; j++) {
  20411. // three edges per triangle, an edge is represented as (index1, index2)
  20412. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  20413. const index1 = 3 * i + j;
  20414. const index2 = 3 * i + (j + 1) % 3;
  20415. start.fromBufferAttribute(position, index1);
  20416. end.fromBufferAttribute(position, index2);
  20417. if (isUniqueEdge(start, end, edges) === true) {
  20418. vertices.push(start.x, start.y, start.z);
  20419. vertices.push(end.x, end.y, end.z);
  20420. }
  20421. }
  20422. }
  20423. } // build geometry
  20424. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20425. }
  20426. }
  20427. function isUniqueEdge(start, end, edges) {
  20428. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  20429. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  20430. if (edges.has(hash1) === true || edges.has(hash2) === true) {
  20431. return false;
  20432. } else {
  20433. edges.add(hash1, hash2);
  20434. return true;
  20435. }
  20436. }
  20437. var Geometries = /*#__PURE__*/Object.freeze({
  20438. __proto__: null,
  20439. BoxGeometry: BoxGeometry,
  20440. BoxBufferGeometry: BoxGeometry,
  20441. CircleGeometry: CircleGeometry,
  20442. CircleBufferGeometry: CircleGeometry,
  20443. ConeGeometry: ConeGeometry,
  20444. ConeBufferGeometry: ConeGeometry,
  20445. CylinderGeometry: CylinderGeometry,
  20446. CylinderBufferGeometry: CylinderGeometry,
  20447. DodecahedronGeometry: DodecahedronGeometry,
  20448. DodecahedronBufferGeometry: DodecahedronGeometry,
  20449. EdgesGeometry: EdgesGeometry,
  20450. ExtrudeGeometry: ExtrudeGeometry,
  20451. ExtrudeBufferGeometry: ExtrudeGeometry,
  20452. IcosahedronGeometry: IcosahedronGeometry,
  20453. IcosahedronBufferGeometry: IcosahedronGeometry,
  20454. LatheGeometry: LatheGeometry,
  20455. LatheBufferGeometry: LatheGeometry,
  20456. OctahedronGeometry: OctahedronGeometry,
  20457. OctahedronBufferGeometry: OctahedronGeometry,
  20458. ParametricGeometry: ParametricGeometry,
  20459. ParametricBufferGeometry: ParametricGeometry,
  20460. PlaneGeometry: PlaneGeometry,
  20461. PlaneBufferGeometry: PlaneGeometry,
  20462. PolyhedronGeometry: PolyhedronGeometry,
  20463. PolyhedronBufferGeometry: PolyhedronGeometry,
  20464. RingGeometry: RingGeometry,
  20465. RingBufferGeometry: RingGeometry,
  20466. ShapeGeometry: ShapeGeometry,
  20467. ShapeBufferGeometry: ShapeGeometry,
  20468. SphereGeometry: SphereGeometry,
  20469. SphereBufferGeometry: SphereGeometry,
  20470. TetrahedronGeometry: TetrahedronGeometry,
  20471. TetrahedronBufferGeometry: TetrahedronGeometry,
  20472. TextGeometry: TextGeometry,
  20473. TextBufferGeometry: TextGeometry,
  20474. TorusGeometry: TorusGeometry,
  20475. TorusBufferGeometry: TorusGeometry,
  20476. TorusKnotGeometry: TorusKnotGeometry,
  20477. TorusKnotBufferGeometry: TorusKnotGeometry,
  20478. TubeGeometry: TubeGeometry,
  20479. TubeBufferGeometry: TubeGeometry,
  20480. WireframeGeometry: WireframeGeometry
  20481. });
  20482. /**
  20483. * parameters = {
  20484. * color: <THREE.Color>
  20485. * }
  20486. */
  20487. class ShadowMaterial extends Material {
  20488. constructor(parameters) {
  20489. super();
  20490. this.type = 'ShadowMaterial';
  20491. this.color = new Color(0x000000);
  20492. this.transparent = true;
  20493. this.setValues(parameters);
  20494. }
  20495. copy(source) {
  20496. super.copy(source);
  20497. this.color.copy(source.color);
  20498. return this;
  20499. }
  20500. }
  20501. ShadowMaterial.prototype.isShadowMaterial = true;
  20502. /**
  20503. * parameters = {
  20504. * color: <hex>,
  20505. * roughness: <float>,
  20506. * metalness: <float>,
  20507. * opacity: <float>,
  20508. *
  20509. * map: new THREE.Texture( <Image> ),
  20510. *
  20511. * lightMap: new THREE.Texture( <Image> ),
  20512. * lightMapIntensity: <float>
  20513. *
  20514. * aoMap: new THREE.Texture( <Image> ),
  20515. * aoMapIntensity: <float>
  20516. *
  20517. * emissive: <hex>,
  20518. * emissiveIntensity: <float>
  20519. * emissiveMap: new THREE.Texture( <Image> ),
  20520. *
  20521. * bumpMap: new THREE.Texture( <Image> ),
  20522. * bumpScale: <float>,
  20523. *
  20524. * normalMap: new THREE.Texture( <Image> ),
  20525. * normalMapType: THREE.TangentSpaceNormalMap,
  20526. * normalScale: <Vector2>,
  20527. *
  20528. * displacementMap: new THREE.Texture( <Image> ),
  20529. * displacementScale: <float>,
  20530. * displacementBias: <float>,
  20531. *
  20532. * roughnessMap: new THREE.Texture( <Image> ),
  20533. *
  20534. * metalnessMap: new THREE.Texture( <Image> ),
  20535. *
  20536. * alphaMap: new THREE.Texture( <Image> ),
  20537. *
  20538. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20539. * envMapIntensity: <float>
  20540. *
  20541. * refractionRatio: <float>,
  20542. *
  20543. * wireframe: <boolean>,
  20544. * wireframeLinewidth: <float>,
  20545. *
  20546. * flatShading: <bool>
  20547. * }
  20548. */
  20549. class MeshStandardMaterial extends Material {
  20550. constructor(parameters) {
  20551. super();
  20552. this.defines = {
  20553. 'STANDARD': ''
  20554. };
  20555. this.type = 'MeshStandardMaterial';
  20556. this.color = new Color(0xffffff); // diffuse
  20557. this.roughness = 1.0;
  20558. this.metalness = 0.0;
  20559. this.map = null;
  20560. this.lightMap = null;
  20561. this.lightMapIntensity = 1.0;
  20562. this.aoMap = null;
  20563. this.aoMapIntensity = 1.0;
  20564. this.emissive = new Color(0x000000);
  20565. this.emissiveIntensity = 1.0;
  20566. this.emissiveMap = null;
  20567. this.bumpMap = null;
  20568. this.bumpScale = 1;
  20569. this.normalMap = null;
  20570. this.normalMapType = TangentSpaceNormalMap;
  20571. this.normalScale = new Vector2(1, 1);
  20572. this.displacementMap = null;
  20573. this.displacementScale = 1;
  20574. this.displacementBias = 0;
  20575. this.roughnessMap = null;
  20576. this.metalnessMap = null;
  20577. this.alphaMap = null;
  20578. this.envMap = null;
  20579. this.envMapIntensity = 1.0;
  20580. this.refractionRatio = 0.98;
  20581. this.wireframe = false;
  20582. this.wireframeLinewidth = 1;
  20583. this.wireframeLinecap = 'round';
  20584. this.wireframeLinejoin = 'round';
  20585. this.flatShading = false;
  20586. this.setValues(parameters);
  20587. }
  20588. copy(source) {
  20589. super.copy(source);
  20590. this.defines = {
  20591. 'STANDARD': ''
  20592. };
  20593. this.color.copy(source.color);
  20594. this.roughness = source.roughness;
  20595. this.metalness = source.metalness;
  20596. this.map = source.map;
  20597. this.lightMap = source.lightMap;
  20598. this.lightMapIntensity = source.lightMapIntensity;
  20599. this.aoMap = source.aoMap;
  20600. this.aoMapIntensity = source.aoMapIntensity;
  20601. this.emissive.copy(source.emissive);
  20602. this.emissiveMap = source.emissiveMap;
  20603. this.emissiveIntensity = source.emissiveIntensity;
  20604. this.bumpMap = source.bumpMap;
  20605. this.bumpScale = source.bumpScale;
  20606. this.normalMap = source.normalMap;
  20607. this.normalMapType = source.normalMapType;
  20608. this.normalScale.copy(source.normalScale);
  20609. this.displacementMap = source.displacementMap;
  20610. this.displacementScale = source.displacementScale;
  20611. this.displacementBias = source.displacementBias;
  20612. this.roughnessMap = source.roughnessMap;
  20613. this.metalnessMap = source.metalnessMap;
  20614. this.alphaMap = source.alphaMap;
  20615. this.envMap = source.envMap;
  20616. this.envMapIntensity = source.envMapIntensity;
  20617. this.refractionRatio = source.refractionRatio;
  20618. this.wireframe = source.wireframe;
  20619. this.wireframeLinewidth = source.wireframeLinewidth;
  20620. this.wireframeLinecap = source.wireframeLinecap;
  20621. this.wireframeLinejoin = source.wireframeLinejoin;
  20622. this.flatShading = source.flatShading;
  20623. return this;
  20624. }
  20625. }
  20626. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  20627. /**
  20628. * parameters = {
  20629. * clearcoat: <float>,
  20630. * clearcoatMap: new THREE.Texture( <Image> ),
  20631. * clearcoatRoughness: <float>,
  20632. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  20633. * clearcoatNormalScale: <Vector2>,
  20634. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  20635. *
  20636. * ior: <float>,
  20637. * reflectivity: <float>,
  20638. *
  20639. * sheenTint: <Color>,
  20640. *
  20641. * transmission: <float>,
  20642. * transmissionMap: new THREE.Texture( <Image> ),
  20643. *
  20644. * thickness: <float>,
  20645. * thicknessMap: new THREE.Texture( <Image> ),
  20646. * attenuationDistance: <float>,
  20647. * attenuationTint: <Color>,
  20648. *
  20649. * specularIntensity: <float>,
  20650. * specularIntensityhMap: new THREE.Texture( <Image> ),
  20651. * specularTint: <Color>,
  20652. * specularTintMap: new THREE.Texture( <Image> )
  20653. * }
  20654. */
  20655. class MeshPhysicalMaterial extends MeshStandardMaterial {
  20656. constructor(parameters) {
  20657. super();
  20658. this.defines = {
  20659. 'STANDARD': '',
  20660. 'PHYSICAL': ''
  20661. };
  20662. this.type = 'MeshPhysicalMaterial';
  20663. this.clearcoatMap = null;
  20664. this.clearcoatRoughness = 0.0;
  20665. this.clearcoatRoughnessMap = null;
  20666. this.clearcoatNormalScale = new Vector2(1, 1);
  20667. this.clearcoatNormalMap = null;
  20668. this.ior = 1.5;
  20669. Object.defineProperty(this, 'reflectivity', {
  20670. get: function () {
  20671. return clamp(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1);
  20672. },
  20673. set: function (reflectivity) {
  20674. this.ior = (1 + 0.4 * reflectivity) / (1 - 0.4 * reflectivity);
  20675. }
  20676. });
  20677. this.sheenTint = new Color(0x000000);
  20678. this.transmission = 0.0;
  20679. this.transmissionMap = null;
  20680. this.thickness = 0.01;
  20681. this.thicknessMap = null;
  20682. this.attenuationDistance = 0.0;
  20683. this.attenuationTint = new Color(1, 1, 1);
  20684. this.specularIntensity = 1.0;
  20685. this.specularIntensityMap = null;
  20686. this.specularTint = new Color(1, 1, 1);
  20687. this.specularTintMap = null;
  20688. this._clearcoat = 0;
  20689. this._transmission = 0;
  20690. this.setValues(parameters);
  20691. }
  20692. get clearcoat() {
  20693. return this._clearcoat;
  20694. }
  20695. set clearcoat(value) {
  20696. if (this._clearcoat > 0 !== value > 0) {
  20697. this.version++;
  20698. }
  20699. this._clearcoat = value;
  20700. }
  20701. get transmission() {
  20702. return this._transmission;
  20703. }
  20704. set transmission(value) {
  20705. if (this._transmission > 0 !== value > 0) {
  20706. this.version++;
  20707. }
  20708. this._transmission = value;
  20709. }
  20710. copy(source) {
  20711. super.copy(source);
  20712. this.defines = {
  20713. 'STANDARD': '',
  20714. 'PHYSICAL': ''
  20715. };
  20716. this.clearcoat = source.clearcoat;
  20717. this.clearcoatMap = source.clearcoatMap;
  20718. this.clearcoatRoughness = source.clearcoatRoughness;
  20719. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  20720. this.clearcoatNormalMap = source.clearcoatNormalMap;
  20721. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  20722. this.ior = source.ior;
  20723. this.sheenTint.copy(source.sheenTint);
  20724. this.transmission = source.transmission;
  20725. this.transmissionMap = source.transmissionMap;
  20726. this.thickness = source.thickness;
  20727. this.thicknessMap = source.thicknessMap;
  20728. this.attenuationDistance = source.attenuationDistance;
  20729. this.attenuationTint.copy(source.attenuationTint);
  20730. this.specularIntensity = source.specularIntensity;
  20731. this.specularIntensityMap = source.specularIntensityMap;
  20732. this.specularTint.copy(source.specularTint);
  20733. this.specularTintMap = source.specularTintMap;
  20734. return this;
  20735. }
  20736. }
  20737. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  20738. /**
  20739. * parameters = {
  20740. * color: <hex>,
  20741. * specular: <hex>,
  20742. * shininess: <float>,
  20743. * opacity: <float>,
  20744. *
  20745. * map: new THREE.Texture( <Image> ),
  20746. *
  20747. * lightMap: new THREE.Texture( <Image> ),
  20748. * lightMapIntensity: <float>
  20749. *
  20750. * aoMap: new THREE.Texture( <Image> ),
  20751. * aoMapIntensity: <float>
  20752. *
  20753. * emissive: <hex>,
  20754. * emissiveIntensity: <float>
  20755. * emissiveMap: new THREE.Texture( <Image> ),
  20756. *
  20757. * bumpMap: new THREE.Texture( <Image> ),
  20758. * bumpScale: <float>,
  20759. *
  20760. * normalMap: new THREE.Texture( <Image> ),
  20761. * normalMapType: THREE.TangentSpaceNormalMap,
  20762. * normalScale: <Vector2>,
  20763. *
  20764. * displacementMap: new THREE.Texture( <Image> ),
  20765. * displacementScale: <float>,
  20766. * displacementBias: <float>,
  20767. *
  20768. * specularMap: new THREE.Texture( <Image> ),
  20769. *
  20770. * alphaMap: new THREE.Texture( <Image> ),
  20771. *
  20772. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20773. * combine: THREE.MultiplyOperation,
  20774. * reflectivity: <float>,
  20775. * refractionRatio: <float>,
  20776. *
  20777. * wireframe: <boolean>,
  20778. * wireframeLinewidth: <float>,
  20779. *
  20780. * flatShading: <bool>
  20781. * }
  20782. */
  20783. class MeshPhongMaterial extends Material {
  20784. constructor(parameters) {
  20785. super();
  20786. this.type = 'MeshPhongMaterial';
  20787. this.color = new Color(0xffffff); // diffuse
  20788. this.specular = new Color(0x111111);
  20789. this.shininess = 30;
  20790. this.map = null;
  20791. this.lightMap = null;
  20792. this.lightMapIntensity = 1.0;
  20793. this.aoMap = null;
  20794. this.aoMapIntensity = 1.0;
  20795. this.emissive = new Color(0x000000);
  20796. this.emissiveIntensity = 1.0;
  20797. this.emissiveMap = null;
  20798. this.bumpMap = null;
  20799. this.bumpScale = 1;
  20800. this.normalMap = null;
  20801. this.normalMapType = TangentSpaceNormalMap;
  20802. this.normalScale = new Vector2(1, 1);
  20803. this.displacementMap = null;
  20804. this.displacementScale = 1;
  20805. this.displacementBias = 0;
  20806. this.specularMap = null;
  20807. this.alphaMap = null;
  20808. this.envMap = null;
  20809. this.combine = MultiplyOperation;
  20810. this.reflectivity = 1;
  20811. this.refractionRatio = 0.98;
  20812. this.wireframe = false;
  20813. this.wireframeLinewidth = 1;
  20814. this.wireframeLinecap = 'round';
  20815. this.wireframeLinejoin = 'round';
  20816. this.flatShading = false;
  20817. this.setValues(parameters);
  20818. }
  20819. copy(source) {
  20820. super.copy(source);
  20821. this.color.copy(source.color);
  20822. this.specular.copy(source.specular);
  20823. this.shininess = source.shininess;
  20824. this.map = source.map;
  20825. this.lightMap = source.lightMap;
  20826. this.lightMapIntensity = source.lightMapIntensity;
  20827. this.aoMap = source.aoMap;
  20828. this.aoMapIntensity = source.aoMapIntensity;
  20829. this.emissive.copy(source.emissive);
  20830. this.emissiveMap = source.emissiveMap;
  20831. this.emissiveIntensity = source.emissiveIntensity;
  20832. this.bumpMap = source.bumpMap;
  20833. this.bumpScale = source.bumpScale;
  20834. this.normalMap = source.normalMap;
  20835. this.normalMapType = source.normalMapType;
  20836. this.normalScale.copy(source.normalScale);
  20837. this.displacementMap = source.displacementMap;
  20838. this.displacementScale = source.displacementScale;
  20839. this.displacementBias = source.displacementBias;
  20840. this.specularMap = source.specularMap;
  20841. this.alphaMap = source.alphaMap;
  20842. this.envMap = source.envMap;
  20843. this.combine = source.combine;
  20844. this.reflectivity = source.reflectivity;
  20845. this.refractionRatio = source.refractionRatio;
  20846. this.wireframe = source.wireframe;
  20847. this.wireframeLinewidth = source.wireframeLinewidth;
  20848. this.wireframeLinecap = source.wireframeLinecap;
  20849. this.wireframeLinejoin = source.wireframeLinejoin;
  20850. this.flatShading = source.flatShading;
  20851. return this;
  20852. }
  20853. }
  20854. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  20855. /**
  20856. * parameters = {
  20857. * color: <hex>,
  20858. *
  20859. * map: new THREE.Texture( <Image> ),
  20860. * gradientMap: new THREE.Texture( <Image> ),
  20861. *
  20862. * lightMap: new THREE.Texture( <Image> ),
  20863. * lightMapIntensity: <float>
  20864. *
  20865. * aoMap: new THREE.Texture( <Image> ),
  20866. * aoMapIntensity: <float>
  20867. *
  20868. * emissive: <hex>,
  20869. * emissiveIntensity: <float>
  20870. * emissiveMap: new THREE.Texture( <Image> ),
  20871. *
  20872. * bumpMap: new THREE.Texture( <Image> ),
  20873. * bumpScale: <float>,
  20874. *
  20875. * normalMap: new THREE.Texture( <Image> ),
  20876. * normalMapType: THREE.TangentSpaceNormalMap,
  20877. * normalScale: <Vector2>,
  20878. *
  20879. * displacementMap: new THREE.Texture( <Image> ),
  20880. * displacementScale: <float>,
  20881. * displacementBias: <float>,
  20882. *
  20883. * alphaMap: new THREE.Texture( <Image> ),
  20884. *
  20885. * wireframe: <boolean>,
  20886. * wireframeLinewidth: <float>,
  20887. *
  20888. * }
  20889. */
  20890. class MeshToonMaterial extends Material {
  20891. constructor(parameters) {
  20892. super();
  20893. this.defines = {
  20894. 'TOON': ''
  20895. };
  20896. this.type = 'MeshToonMaterial';
  20897. this.color = new Color(0xffffff);
  20898. this.map = null;
  20899. this.gradientMap = null;
  20900. this.lightMap = null;
  20901. this.lightMapIntensity = 1.0;
  20902. this.aoMap = null;
  20903. this.aoMapIntensity = 1.0;
  20904. this.emissive = new Color(0x000000);
  20905. this.emissiveIntensity = 1.0;
  20906. this.emissiveMap = null;
  20907. this.bumpMap = null;
  20908. this.bumpScale = 1;
  20909. this.normalMap = null;
  20910. this.normalMapType = TangentSpaceNormalMap;
  20911. this.normalScale = new Vector2(1, 1);
  20912. this.displacementMap = null;
  20913. this.displacementScale = 1;
  20914. this.displacementBias = 0;
  20915. this.alphaMap = null;
  20916. this.wireframe = false;
  20917. this.wireframeLinewidth = 1;
  20918. this.wireframeLinecap = 'round';
  20919. this.wireframeLinejoin = 'round';
  20920. this.setValues(parameters);
  20921. }
  20922. copy(source) {
  20923. super.copy(source);
  20924. this.color.copy(source.color);
  20925. this.map = source.map;
  20926. this.gradientMap = source.gradientMap;
  20927. this.lightMap = source.lightMap;
  20928. this.lightMapIntensity = source.lightMapIntensity;
  20929. this.aoMap = source.aoMap;
  20930. this.aoMapIntensity = source.aoMapIntensity;
  20931. this.emissive.copy(source.emissive);
  20932. this.emissiveMap = source.emissiveMap;
  20933. this.emissiveIntensity = source.emissiveIntensity;
  20934. this.bumpMap = source.bumpMap;
  20935. this.bumpScale = source.bumpScale;
  20936. this.normalMap = source.normalMap;
  20937. this.normalMapType = source.normalMapType;
  20938. this.normalScale.copy(source.normalScale);
  20939. this.displacementMap = source.displacementMap;
  20940. this.displacementScale = source.displacementScale;
  20941. this.displacementBias = source.displacementBias;
  20942. this.alphaMap = source.alphaMap;
  20943. this.wireframe = source.wireframe;
  20944. this.wireframeLinewidth = source.wireframeLinewidth;
  20945. this.wireframeLinecap = source.wireframeLinecap;
  20946. this.wireframeLinejoin = source.wireframeLinejoin;
  20947. return this;
  20948. }
  20949. }
  20950. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  20951. /**
  20952. * parameters = {
  20953. * opacity: <float>,
  20954. *
  20955. * bumpMap: new THREE.Texture( <Image> ),
  20956. * bumpScale: <float>,
  20957. *
  20958. * normalMap: new THREE.Texture( <Image> ),
  20959. * normalMapType: THREE.TangentSpaceNormalMap,
  20960. * normalScale: <Vector2>,
  20961. *
  20962. * displacementMap: new THREE.Texture( <Image> ),
  20963. * displacementScale: <float>,
  20964. * displacementBias: <float>,
  20965. *
  20966. * wireframe: <boolean>,
  20967. * wireframeLinewidth: <float>
  20968. *
  20969. * flatShading: <bool>
  20970. * }
  20971. */
  20972. class MeshNormalMaterial extends Material {
  20973. constructor(parameters) {
  20974. super();
  20975. this.type = 'MeshNormalMaterial';
  20976. this.bumpMap = null;
  20977. this.bumpScale = 1;
  20978. this.normalMap = null;
  20979. this.normalMapType = TangentSpaceNormalMap;
  20980. this.normalScale = new Vector2(1, 1);
  20981. this.displacementMap = null;
  20982. this.displacementScale = 1;
  20983. this.displacementBias = 0;
  20984. this.wireframe = false;
  20985. this.wireframeLinewidth = 1;
  20986. this.fog = false;
  20987. this.flatShading = false;
  20988. this.setValues(parameters);
  20989. }
  20990. copy(source) {
  20991. super.copy(source);
  20992. this.bumpMap = source.bumpMap;
  20993. this.bumpScale = source.bumpScale;
  20994. this.normalMap = source.normalMap;
  20995. this.normalMapType = source.normalMapType;
  20996. this.normalScale.copy(source.normalScale);
  20997. this.displacementMap = source.displacementMap;
  20998. this.displacementScale = source.displacementScale;
  20999. this.displacementBias = source.displacementBias;
  21000. this.wireframe = source.wireframe;
  21001. this.wireframeLinewidth = source.wireframeLinewidth;
  21002. this.flatShading = source.flatShading;
  21003. return this;
  21004. }
  21005. }
  21006. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  21007. /**
  21008. * parameters = {
  21009. * color: <hex>,
  21010. * opacity: <float>,
  21011. *
  21012. * map: new THREE.Texture( <Image> ),
  21013. *
  21014. * lightMap: new THREE.Texture( <Image> ),
  21015. * lightMapIntensity: <float>
  21016. *
  21017. * aoMap: new THREE.Texture( <Image> ),
  21018. * aoMapIntensity: <float>
  21019. *
  21020. * emissive: <hex>,
  21021. * emissiveIntensity: <float>
  21022. * emissiveMap: new THREE.Texture( <Image> ),
  21023. *
  21024. * specularMap: new THREE.Texture( <Image> ),
  21025. *
  21026. * alphaMap: new THREE.Texture( <Image> ),
  21027. *
  21028. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21029. * combine: THREE.Multiply,
  21030. * reflectivity: <float>,
  21031. * refractionRatio: <float>,
  21032. *
  21033. * wireframe: <boolean>,
  21034. * wireframeLinewidth: <float>,
  21035. *
  21036. * }
  21037. */
  21038. class MeshLambertMaterial extends Material {
  21039. constructor(parameters) {
  21040. super();
  21041. this.type = 'MeshLambertMaterial';
  21042. this.color = new Color(0xffffff); // diffuse
  21043. this.map = null;
  21044. this.lightMap = null;
  21045. this.lightMapIntensity = 1.0;
  21046. this.aoMap = null;
  21047. this.aoMapIntensity = 1.0;
  21048. this.emissive = new Color(0x000000);
  21049. this.emissiveIntensity = 1.0;
  21050. this.emissiveMap = null;
  21051. this.specularMap = null;
  21052. this.alphaMap = null;
  21053. this.envMap = null;
  21054. this.combine = MultiplyOperation;
  21055. this.reflectivity = 1;
  21056. this.refractionRatio = 0.98;
  21057. this.wireframe = false;
  21058. this.wireframeLinewidth = 1;
  21059. this.wireframeLinecap = 'round';
  21060. this.wireframeLinejoin = 'round';
  21061. this.setValues(parameters);
  21062. }
  21063. copy(source) {
  21064. super.copy(source);
  21065. this.color.copy(source.color);
  21066. this.map = source.map;
  21067. this.lightMap = source.lightMap;
  21068. this.lightMapIntensity = source.lightMapIntensity;
  21069. this.aoMap = source.aoMap;
  21070. this.aoMapIntensity = source.aoMapIntensity;
  21071. this.emissive.copy(source.emissive);
  21072. this.emissiveMap = source.emissiveMap;
  21073. this.emissiveIntensity = source.emissiveIntensity;
  21074. this.specularMap = source.specularMap;
  21075. this.alphaMap = source.alphaMap;
  21076. this.envMap = source.envMap;
  21077. this.combine = source.combine;
  21078. this.reflectivity = source.reflectivity;
  21079. this.refractionRatio = source.refractionRatio;
  21080. this.wireframe = source.wireframe;
  21081. this.wireframeLinewidth = source.wireframeLinewidth;
  21082. this.wireframeLinecap = source.wireframeLinecap;
  21083. this.wireframeLinejoin = source.wireframeLinejoin;
  21084. return this;
  21085. }
  21086. }
  21087. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  21088. /**
  21089. * parameters = {
  21090. * color: <hex>,
  21091. * opacity: <float>,
  21092. *
  21093. * matcap: new THREE.Texture( <Image> ),
  21094. *
  21095. * map: new THREE.Texture( <Image> ),
  21096. *
  21097. * bumpMap: new THREE.Texture( <Image> ),
  21098. * bumpScale: <float>,
  21099. *
  21100. * normalMap: new THREE.Texture( <Image> ),
  21101. * normalMapType: THREE.TangentSpaceNormalMap,
  21102. * normalScale: <Vector2>,
  21103. *
  21104. * displacementMap: new THREE.Texture( <Image> ),
  21105. * displacementScale: <float>,
  21106. * displacementBias: <float>,
  21107. *
  21108. * alphaMap: new THREE.Texture( <Image> ),
  21109. *
  21110. * flatShading: <bool>
  21111. * }
  21112. */
  21113. class MeshMatcapMaterial extends Material {
  21114. constructor(parameters) {
  21115. super();
  21116. this.defines = {
  21117. 'MATCAP': ''
  21118. };
  21119. this.type = 'MeshMatcapMaterial';
  21120. this.color = new Color(0xffffff); // diffuse
  21121. this.matcap = null;
  21122. this.map = null;
  21123. this.bumpMap = null;
  21124. this.bumpScale = 1;
  21125. this.normalMap = null;
  21126. this.normalMapType = TangentSpaceNormalMap;
  21127. this.normalScale = new Vector2(1, 1);
  21128. this.displacementMap = null;
  21129. this.displacementScale = 1;
  21130. this.displacementBias = 0;
  21131. this.alphaMap = null;
  21132. this.flatShading = false;
  21133. this.setValues(parameters);
  21134. }
  21135. copy(source) {
  21136. super.copy(source);
  21137. this.defines = {
  21138. 'MATCAP': ''
  21139. };
  21140. this.color.copy(source.color);
  21141. this.matcap = source.matcap;
  21142. this.map = source.map;
  21143. this.bumpMap = source.bumpMap;
  21144. this.bumpScale = source.bumpScale;
  21145. this.normalMap = source.normalMap;
  21146. this.normalMapType = source.normalMapType;
  21147. this.normalScale.copy(source.normalScale);
  21148. this.displacementMap = source.displacementMap;
  21149. this.displacementScale = source.displacementScale;
  21150. this.displacementBias = source.displacementBias;
  21151. this.alphaMap = source.alphaMap;
  21152. this.flatShading = source.flatShading;
  21153. return this;
  21154. }
  21155. }
  21156. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  21157. /**
  21158. * parameters = {
  21159. * color: <hex>,
  21160. * opacity: <float>,
  21161. *
  21162. * linewidth: <float>,
  21163. *
  21164. * scale: <float>,
  21165. * dashSize: <float>,
  21166. * gapSize: <float>
  21167. * }
  21168. */
  21169. class LineDashedMaterial extends LineBasicMaterial {
  21170. constructor(parameters) {
  21171. super();
  21172. this.type = 'LineDashedMaterial';
  21173. this.scale = 1;
  21174. this.dashSize = 3;
  21175. this.gapSize = 1;
  21176. this.setValues(parameters);
  21177. }
  21178. copy(source) {
  21179. super.copy(source);
  21180. this.scale = source.scale;
  21181. this.dashSize = source.dashSize;
  21182. this.gapSize = source.gapSize;
  21183. return this;
  21184. }
  21185. }
  21186. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  21187. var Materials = /*#__PURE__*/Object.freeze({
  21188. __proto__: null,
  21189. ShadowMaterial: ShadowMaterial,
  21190. SpriteMaterial: SpriteMaterial,
  21191. RawShaderMaterial: RawShaderMaterial,
  21192. ShaderMaterial: ShaderMaterial,
  21193. PointsMaterial: PointsMaterial,
  21194. MeshPhysicalMaterial: MeshPhysicalMaterial,
  21195. MeshStandardMaterial: MeshStandardMaterial,
  21196. MeshPhongMaterial: MeshPhongMaterial,
  21197. MeshToonMaterial: MeshToonMaterial,
  21198. MeshNormalMaterial: MeshNormalMaterial,
  21199. MeshLambertMaterial: MeshLambertMaterial,
  21200. MeshDepthMaterial: MeshDepthMaterial,
  21201. MeshDistanceMaterial: MeshDistanceMaterial,
  21202. MeshBasicMaterial: MeshBasicMaterial,
  21203. MeshMatcapMaterial: MeshMatcapMaterial,
  21204. LineDashedMaterial: LineDashedMaterial,
  21205. LineBasicMaterial: LineBasicMaterial,
  21206. Material: Material
  21207. });
  21208. const AnimationUtils = {
  21209. // same as Array.prototype.slice, but also works on typed arrays
  21210. arraySlice: function (array, from, to) {
  21211. if (AnimationUtils.isTypedArray(array)) {
  21212. // in ios9 array.subarray(from, undefined) will return empty array
  21213. // but array.subarray(from) or array.subarray(from, len) is correct
  21214. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  21215. }
  21216. return array.slice(from, to);
  21217. },
  21218. // converts an array to a specific type
  21219. convertArray: function (array, type, forceClone) {
  21220. if (!array || // let 'undefined' and 'null' pass
  21221. !forceClone && array.constructor === type) return array;
  21222. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  21223. return new type(array); // create typed array
  21224. }
  21225. return Array.prototype.slice.call(array); // create Array
  21226. },
  21227. isTypedArray: function (object) {
  21228. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  21229. },
  21230. // returns an array by which times and values can be sorted
  21231. getKeyframeOrder: function (times) {
  21232. function compareTime(i, j) {
  21233. return times[i] - times[j];
  21234. }
  21235. const n = times.length;
  21236. const result = new Array(n);
  21237. for (let i = 0; i !== n; ++i) result[i] = i;
  21238. result.sort(compareTime);
  21239. return result;
  21240. },
  21241. // uses the array previously returned by 'getKeyframeOrder' to sort data
  21242. sortedArray: function (values, stride, order) {
  21243. const nValues = values.length;
  21244. const result = new values.constructor(nValues);
  21245. for (let i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  21246. const srcOffset = order[i] * stride;
  21247. for (let j = 0; j !== stride; ++j) {
  21248. result[dstOffset++] = values[srcOffset + j];
  21249. }
  21250. }
  21251. return result;
  21252. },
  21253. // function for parsing AOS keyframe formats
  21254. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  21255. let i = 1,
  21256. key = jsonKeys[0];
  21257. while (key !== undefined && key[valuePropertyName] === undefined) {
  21258. key = jsonKeys[i++];
  21259. }
  21260. if (key === undefined) return; // no data
  21261. let value = key[valuePropertyName];
  21262. if (value === undefined) return; // no data
  21263. if (Array.isArray(value)) {
  21264. do {
  21265. value = key[valuePropertyName];
  21266. if (value !== undefined) {
  21267. times.push(key.time);
  21268. values.push.apply(values, value); // push all elements
  21269. }
  21270. key = jsonKeys[i++];
  21271. } while (key !== undefined);
  21272. } else if (value.toArray !== undefined) {
  21273. // ...assume THREE.Math-ish
  21274. do {
  21275. value = key[valuePropertyName];
  21276. if (value !== undefined) {
  21277. times.push(key.time);
  21278. value.toArray(values, values.length);
  21279. }
  21280. key = jsonKeys[i++];
  21281. } while (key !== undefined);
  21282. } else {
  21283. // otherwise push as-is
  21284. do {
  21285. value = key[valuePropertyName];
  21286. if (value !== undefined) {
  21287. times.push(key.time);
  21288. values.push(value);
  21289. }
  21290. key = jsonKeys[i++];
  21291. } while (key !== undefined);
  21292. }
  21293. },
  21294. subclip: function (sourceClip, name, startFrame, endFrame, fps = 30) {
  21295. const clip = sourceClip.clone();
  21296. clip.name = name;
  21297. const tracks = [];
  21298. for (let i = 0; i < clip.tracks.length; ++i) {
  21299. const track = clip.tracks[i];
  21300. const valueSize = track.getValueSize();
  21301. const times = [];
  21302. const values = [];
  21303. for (let j = 0; j < track.times.length; ++j) {
  21304. const frame = track.times[j] * fps;
  21305. if (frame < startFrame || frame >= endFrame) continue;
  21306. times.push(track.times[j]);
  21307. for (let k = 0; k < valueSize; ++k) {
  21308. values.push(track.values[j * valueSize + k]);
  21309. }
  21310. }
  21311. if (times.length === 0) continue;
  21312. track.times = AnimationUtils.convertArray(times, track.times.constructor);
  21313. track.values = AnimationUtils.convertArray(values, track.values.constructor);
  21314. tracks.push(track);
  21315. }
  21316. clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
  21317. let minStartTime = Infinity;
  21318. for (let i = 0; i < clip.tracks.length; ++i) {
  21319. if (minStartTime > clip.tracks[i].times[0]) {
  21320. minStartTime = clip.tracks[i].times[0];
  21321. }
  21322. } // shift all tracks such that clip begins at t=0
  21323. for (let i = 0; i < clip.tracks.length; ++i) {
  21324. clip.tracks[i].shift(-1 * minStartTime);
  21325. }
  21326. clip.resetDuration();
  21327. return clip;
  21328. },
  21329. makeClipAdditive: function (targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) {
  21330. if (fps <= 0) fps = 30;
  21331. const numTracks = referenceClip.tracks.length;
  21332. const referenceTime = referenceFrame / fps; // Make each track's values relative to the values at the reference frame
  21333. for (let i = 0; i < numTracks; ++i) {
  21334. const referenceTrack = referenceClip.tracks[i];
  21335. const referenceTrackType = referenceTrack.ValueTypeName; // Skip this track if it's non-numeric
  21336. if (referenceTrackType === 'bool' || referenceTrackType === 'string') continue; // Find the track in the target clip whose name and type matches the reference track
  21337. const targetTrack = targetClip.tracks.find(function (track) {
  21338. return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
  21339. });
  21340. if (targetTrack === undefined) continue;
  21341. let referenceOffset = 0;
  21342. const referenceValueSize = referenceTrack.getValueSize();
  21343. if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  21344. referenceOffset = referenceValueSize / 3;
  21345. }
  21346. let targetOffset = 0;
  21347. const targetValueSize = targetTrack.getValueSize();
  21348. if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  21349. targetOffset = targetValueSize / 3;
  21350. }
  21351. const lastIndex = referenceTrack.times.length - 1;
  21352. let referenceValue; // Find the value to subtract out of the track
  21353. if (referenceTime <= referenceTrack.times[0]) {
  21354. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  21355. const startIndex = referenceOffset;
  21356. const endIndex = referenceValueSize - referenceOffset;
  21357. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  21358. } else if (referenceTime >= referenceTrack.times[lastIndex]) {
  21359. // Reference frame is after the last keyframe, so just use the last keyframe
  21360. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  21361. const endIndex = startIndex + referenceValueSize - referenceOffset;
  21362. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  21363. } else {
  21364. // Interpolate to the reference value
  21365. const interpolant = referenceTrack.createInterpolant();
  21366. const startIndex = referenceOffset;
  21367. const endIndex = referenceValueSize - referenceOffset;
  21368. interpolant.evaluate(referenceTime);
  21369. referenceValue = AnimationUtils.arraySlice(interpolant.resultBuffer, startIndex, endIndex);
  21370. } // Conjugate the quaternion
  21371. if (referenceTrackType === 'quaternion') {
  21372. const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
  21373. referenceQuat.toArray(referenceValue);
  21374. } // Subtract the reference value from all of the track values
  21375. const numTimes = targetTrack.times.length;
  21376. for (let j = 0; j < numTimes; ++j) {
  21377. const valueStart = j * targetValueSize + targetOffset;
  21378. if (referenceTrackType === 'quaternion') {
  21379. // Multiply the conjugate for quaternion track types
  21380. Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
  21381. } else {
  21382. const valueEnd = targetValueSize - targetOffset * 2; // Subtract each value for all other numeric track types
  21383. for (let k = 0; k < valueEnd; ++k) {
  21384. targetTrack.values[valueStart + k] -= referenceValue[k];
  21385. }
  21386. }
  21387. }
  21388. }
  21389. targetClip.blendMode = AdditiveAnimationBlendMode;
  21390. return targetClip;
  21391. }
  21392. };
  21393. /**
  21394. * Abstract base class of interpolants over parametric samples.
  21395. *
  21396. * The parameter domain is one dimensional, typically the time or a path
  21397. * along a curve defined by the data.
  21398. *
  21399. * The sample values can have any dimensionality and derived classes may
  21400. * apply special interpretations to the data.
  21401. *
  21402. * This class provides the interval seek in a Template Method, deferring
  21403. * the actual interpolation to derived classes.
  21404. *
  21405. * Time complexity is O(1) for linear access crossing at most two points
  21406. * and O(log N) for random access, where N is the number of positions.
  21407. *
  21408. * References:
  21409. *
  21410. * http://www.oodesign.com/template-method-pattern.html
  21411. *
  21412. */
  21413. class Interpolant {
  21414. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21415. this.parameterPositions = parameterPositions;
  21416. this._cachedIndex = 0;
  21417. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  21418. this.sampleValues = sampleValues;
  21419. this.valueSize = sampleSize;
  21420. this.settings = null;
  21421. this.DefaultSettings_ = {};
  21422. }
  21423. evaluate(t) {
  21424. const pp = this.parameterPositions;
  21425. let i1 = this._cachedIndex,
  21426. t1 = pp[i1],
  21427. t0 = pp[i1 - 1];
  21428. validate_interval: {
  21429. seek: {
  21430. let right;
  21431. linear_scan: {
  21432. //- See http://jsperf.com/comparison-to-undefined/3
  21433. //- slower code:
  21434. //-
  21435. //- if ( t >= t1 || t1 === undefined ) {
  21436. forward_scan: if (!(t < t1)) {
  21437. for (let giveUpAt = i1 + 2;;) {
  21438. if (t1 === undefined) {
  21439. if (t < t0) break forward_scan; // after end
  21440. i1 = pp.length;
  21441. this._cachedIndex = i1;
  21442. return this.afterEnd_(i1 - 1, t, t0);
  21443. }
  21444. if (i1 === giveUpAt) break; // this loop
  21445. t0 = t1;
  21446. t1 = pp[++i1];
  21447. if (t < t1) {
  21448. // we have arrived at the sought interval
  21449. break seek;
  21450. }
  21451. } // prepare binary search on the right side of the index
  21452. right = pp.length;
  21453. break linear_scan;
  21454. } //- slower code:
  21455. //- if ( t < t0 || t0 === undefined ) {
  21456. if (!(t >= t0)) {
  21457. // looping?
  21458. const t1global = pp[1];
  21459. if (t < t1global) {
  21460. i1 = 2; // + 1, using the scan for the details
  21461. t0 = t1global;
  21462. } // linear reverse scan
  21463. for (let giveUpAt = i1 - 2;;) {
  21464. if (t0 === undefined) {
  21465. // before start
  21466. this._cachedIndex = 0;
  21467. return this.beforeStart_(0, t, t1);
  21468. }
  21469. if (i1 === giveUpAt) break; // this loop
  21470. t1 = t0;
  21471. t0 = pp[--i1 - 1];
  21472. if (t >= t0) {
  21473. // we have arrived at the sought interval
  21474. break seek;
  21475. }
  21476. } // prepare binary search on the left side of the index
  21477. right = i1;
  21478. i1 = 0;
  21479. break linear_scan;
  21480. } // the interval is valid
  21481. break validate_interval;
  21482. } // linear scan
  21483. // binary search
  21484. while (i1 < right) {
  21485. const mid = i1 + right >>> 1;
  21486. if (t < pp[mid]) {
  21487. right = mid;
  21488. } else {
  21489. i1 = mid + 1;
  21490. }
  21491. }
  21492. t1 = pp[i1];
  21493. t0 = pp[i1 - 1]; // check boundary cases, again
  21494. if (t0 === undefined) {
  21495. this._cachedIndex = 0;
  21496. return this.beforeStart_(0, t, t1);
  21497. }
  21498. if (t1 === undefined) {
  21499. i1 = pp.length;
  21500. this._cachedIndex = i1;
  21501. return this.afterEnd_(i1 - 1, t0, t);
  21502. }
  21503. } // seek
  21504. this._cachedIndex = i1;
  21505. this.intervalChanged_(i1, t0, t1);
  21506. } // validate_interval
  21507. return this.interpolate_(i1, t0, t, t1);
  21508. }
  21509. getSettings_() {
  21510. return this.settings || this.DefaultSettings_;
  21511. }
  21512. copySampleValue_(index) {
  21513. // copies a sample value to the result buffer
  21514. const result = this.resultBuffer,
  21515. values = this.sampleValues,
  21516. stride = this.valueSize,
  21517. offset = index * stride;
  21518. for (let i = 0; i !== stride; ++i) {
  21519. result[i] = values[offset + i];
  21520. }
  21521. return result;
  21522. } // Template methods for derived classes:
  21523. interpolate_() {
  21524. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  21525. }
  21526. intervalChanged_() {// empty
  21527. }
  21528. } // ALIAS DEFINITIONS
  21529. Interpolant.prototype.beforeStart_ = Interpolant.prototype.copySampleValue_;
  21530. Interpolant.prototype.afterEnd_ = Interpolant.prototype.copySampleValue_;
  21531. /**
  21532. * Fast and simple cubic spline interpolant.
  21533. *
  21534. * It was derived from a Hermitian construction setting the first derivative
  21535. * at each sample position to the linear slope between neighboring positions
  21536. * over their parameter interval.
  21537. */
  21538. class CubicInterpolant extends Interpolant {
  21539. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21540. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  21541. this._weightPrev = -0;
  21542. this._offsetPrev = -0;
  21543. this._weightNext = -0;
  21544. this._offsetNext = -0;
  21545. this.DefaultSettings_ = {
  21546. endingStart: ZeroCurvatureEnding,
  21547. endingEnd: ZeroCurvatureEnding
  21548. };
  21549. }
  21550. intervalChanged_(i1, t0, t1) {
  21551. const pp = this.parameterPositions;
  21552. let iPrev = i1 - 2,
  21553. iNext = i1 + 1,
  21554. tPrev = pp[iPrev],
  21555. tNext = pp[iNext];
  21556. if (tPrev === undefined) {
  21557. switch (this.getSettings_().endingStart) {
  21558. case ZeroSlopeEnding:
  21559. // f'(t0) = 0
  21560. iPrev = i1;
  21561. tPrev = 2 * t0 - t1;
  21562. break;
  21563. case WrapAroundEnding:
  21564. // use the other end of the curve
  21565. iPrev = pp.length - 2;
  21566. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  21567. break;
  21568. default:
  21569. // ZeroCurvatureEnding
  21570. // f''(t0) = 0 a.k.a. Natural Spline
  21571. iPrev = i1;
  21572. tPrev = t1;
  21573. }
  21574. }
  21575. if (tNext === undefined) {
  21576. switch (this.getSettings_().endingEnd) {
  21577. case ZeroSlopeEnding:
  21578. // f'(tN) = 0
  21579. iNext = i1;
  21580. tNext = 2 * t1 - t0;
  21581. break;
  21582. case WrapAroundEnding:
  21583. // use the other end of the curve
  21584. iNext = 1;
  21585. tNext = t1 + pp[1] - pp[0];
  21586. break;
  21587. default:
  21588. // ZeroCurvatureEnding
  21589. // f''(tN) = 0, a.k.a. Natural Spline
  21590. iNext = i1 - 1;
  21591. tNext = t0;
  21592. }
  21593. }
  21594. const halfDt = (t1 - t0) * 0.5,
  21595. stride = this.valueSize;
  21596. this._weightPrev = halfDt / (t0 - tPrev);
  21597. this._weightNext = halfDt / (tNext - t1);
  21598. this._offsetPrev = iPrev * stride;
  21599. this._offsetNext = iNext * stride;
  21600. }
  21601. interpolate_(i1, t0, t, t1) {
  21602. const result = this.resultBuffer,
  21603. values = this.sampleValues,
  21604. stride = this.valueSize,
  21605. o1 = i1 * stride,
  21606. o0 = o1 - stride,
  21607. oP = this._offsetPrev,
  21608. oN = this._offsetNext,
  21609. wP = this._weightPrev,
  21610. wN = this._weightNext,
  21611. p = (t - t0) / (t1 - t0),
  21612. pp = p * p,
  21613. ppp = pp * p; // evaluate polynomials
  21614. const sP = -wP * ppp + 2 * wP * pp - wP * p;
  21615. const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  21616. const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  21617. const sN = wN * ppp - wN * pp; // combine data linearly
  21618. for (let i = 0; i !== stride; ++i) {
  21619. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  21620. }
  21621. return result;
  21622. }
  21623. }
  21624. class LinearInterpolant extends Interpolant {
  21625. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21626. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  21627. }
  21628. interpolate_(i1, t0, t, t1) {
  21629. const result = this.resultBuffer,
  21630. values = this.sampleValues,
  21631. stride = this.valueSize,
  21632. offset1 = i1 * stride,
  21633. offset0 = offset1 - stride,
  21634. weight1 = (t - t0) / (t1 - t0),
  21635. weight0 = 1 - weight1;
  21636. for (let i = 0; i !== stride; ++i) {
  21637. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  21638. }
  21639. return result;
  21640. }
  21641. }
  21642. /**
  21643. *
  21644. * Interpolant that evaluates to the sample value at the position preceeding
  21645. * the parameter.
  21646. */
  21647. class DiscreteInterpolant extends Interpolant {
  21648. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21649. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  21650. }
  21651. interpolate_(i1
  21652. /*, t0, t, t1 */
  21653. ) {
  21654. return this.copySampleValue_(i1 - 1);
  21655. }
  21656. }
  21657. class KeyframeTrack {
  21658. constructor(name, times, values, interpolation) {
  21659. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  21660. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  21661. this.name = name;
  21662. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  21663. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  21664. this.setInterpolation(interpolation || this.DefaultInterpolation);
  21665. } // Serialization (in static context, because of constructor invocation
  21666. // and automatic invocation of .toJSON):
  21667. static toJSON(track) {
  21668. const trackType = track.constructor;
  21669. let json; // derived classes can define a static toJSON method
  21670. if (trackType.toJSON !== this.toJSON) {
  21671. json = trackType.toJSON(track);
  21672. } else {
  21673. // by default, we assume the data can be serialized as-is
  21674. json = {
  21675. 'name': track.name,
  21676. 'times': AnimationUtils.convertArray(track.times, Array),
  21677. 'values': AnimationUtils.convertArray(track.values, Array)
  21678. };
  21679. const interpolation = track.getInterpolation();
  21680. if (interpolation !== track.DefaultInterpolation) {
  21681. json.interpolation = interpolation;
  21682. }
  21683. }
  21684. json.type = track.ValueTypeName; // mandatory
  21685. return json;
  21686. }
  21687. InterpolantFactoryMethodDiscrete(result) {
  21688. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  21689. }
  21690. InterpolantFactoryMethodLinear(result) {
  21691. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  21692. }
  21693. InterpolantFactoryMethodSmooth(result) {
  21694. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  21695. }
  21696. setInterpolation(interpolation) {
  21697. let factoryMethod;
  21698. switch (interpolation) {
  21699. case InterpolateDiscrete:
  21700. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  21701. break;
  21702. case InterpolateLinear:
  21703. factoryMethod = this.InterpolantFactoryMethodLinear;
  21704. break;
  21705. case InterpolateSmooth:
  21706. factoryMethod = this.InterpolantFactoryMethodSmooth;
  21707. break;
  21708. }
  21709. if (factoryMethod === undefined) {
  21710. const message = 'unsupported interpolation for ' + this.ValueTypeName + ' keyframe track named ' + this.name;
  21711. if (this.createInterpolant === undefined) {
  21712. // fall back to default, unless the default itself is messed up
  21713. if (interpolation !== this.DefaultInterpolation) {
  21714. this.setInterpolation(this.DefaultInterpolation);
  21715. } else {
  21716. throw new Error(message); // fatal, in this case
  21717. }
  21718. }
  21719. console.warn('THREE.KeyframeTrack:', message);
  21720. return this;
  21721. }
  21722. this.createInterpolant = factoryMethod;
  21723. return this;
  21724. }
  21725. getInterpolation() {
  21726. switch (this.createInterpolant) {
  21727. case this.InterpolantFactoryMethodDiscrete:
  21728. return InterpolateDiscrete;
  21729. case this.InterpolantFactoryMethodLinear:
  21730. return InterpolateLinear;
  21731. case this.InterpolantFactoryMethodSmooth:
  21732. return InterpolateSmooth;
  21733. }
  21734. }
  21735. getValueSize() {
  21736. return this.values.length / this.times.length;
  21737. } // move all keyframes either forwards or backwards in time
  21738. shift(timeOffset) {
  21739. if (timeOffset !== 0.0) {
  21740. const times = this.times;
  21741. for (let i = 0, n = times.length; i !== n; ++i) {
  21742. times[i] += timeOffset;
  21743. }
  21744. }
  21745. return this;
  21746. } // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  21747. scale(timeScale) {
  21748. if (timeScale !== 1.0) {
  21749. const times = this.times;
  21750. for (let i = 0, n = times.length; i !== n; ++i) {
  21751. times[i] *= timeScale;
  21752. }
  21753. }
  21754. return this;
  21755. } // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  21756. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  21757. trim(startTime, endTime) {
  21758. const times = this.times,
  21759. nKeys = times.length;
  21760. let from = 0,
  21761. to = nKeys - 1;
  21762. while (from !== nKeys && times[from] < startTime) {
  21763. ++from;
  21764. }
  21765. while (to !== -1 && times[to] > endTime) {
  21766. --to;
  21767. }
  21768. ++to; // inclusive -> exclusive bound
  21769. if (from !== 0 || to !== nKeys) {
  21770. // empty tracks are forbidden, so keep at least one keyframe
  21771. if (from >= to) {
  21772. to = Math.max(to, 1);
  21773. from = to - 1;
  21774. }
  21775. const stride = this.getValueSize();
  21776. this.times = AnimationUtils.arraySlice(times, from, to);
  21777. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  21778. }
  21779. return this;
  21780. } // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  21781. validate() {
  21782. let valid = true;
  21783. const valueSize = this.getValueSize();
  21784. if (valueSize - Math.floor(valueSize) !== 0) {
  21785. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  21786. valid = false;
  21787. }
  21788. const times = this.times,
  21789. values = this.values,
  21790. nKeys = times.length;
  21791. if (nKeys === 0) {
  21792. console.error('THREE.KeyframeTrack: Track is empty.', this);
  21793. valid = false;
  21794. }
  21795. let prevTime = null;
  21796. for (let i = 0; i !== nKeys; i++) {
  21797. const currTime = times[i];
  21798. if (typeof currTime === 'number' && isNaN(currTime)) {
  21799. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  21800. valid = false;
  21801. break;
  21802. }
  21803. if (prevTime !== null && prevTime > currTime) {
  21804. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  21805. valid = false;
  21806. break;
  21807. }
  21808. prevTime = currTime;
  21809. }
  21810. if (values !== undefined) {
  21811. if (AnimationUtils.isTypedArray(values)) {
  21812. for (let i = 0, n = values.length; i !== n; ++i) {
  21813. const value = values[i];
  21814. if (isNaN(value)) {
  21815. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  21816. valid = false;
  21817. break;
  21818. }
  21819. }
  21820. }
  21821. }
  21822. return valid;
  21823. } // removes equivalent sequential keys as common in morph target sequences
  21824. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  21825. optimize() {
  21826. // times or values may be shared with other tracks, so overwriting is unsafe
  21827. const times = AnimationUtils.arraySlice(this.times),
  21828. values = AnimationUtils.arraySlice(this.values),
  21829. stride = this.getValueSize(),
  21830. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  21831. lastIndex = times.length - 1;
  21832. let writeIndex = 1;
  21833. for (let i = 1; i < lastIndex; ++i) {
  21834. let keep = false;
  21835. const time = times[i];
  21836. const timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  21837. if (time !== timeNext && (i !== 1 || time !== times[0])) {
  21838. if (!smoothInterpolation) {
  21839. // remove unnecessary keyframes same as their neighbors
  21840. const offset = i * stride,
  21841. offsetP = offset - stride,
  21842. offsetN = offset + stride;
  21843. for (let j = 0; j !== stride; ++j) {
  21844. const value = values[offset + j];
  21845. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  21846. keep = true;
  21847. break;
  21848. }
  21849. }
  21850. } else {
  21851. keep = true;
  21852. }
  21853. } // in-place compaction
  21854. if (keep) {
  21855. if (i !== writeIndex) {
  21856. times[writeIndex] = times[i];
  21857. const readOffset = i * stride,
  21858. writeOffset = writeIndex * stride;
  21859. for (let j = 0; j !== stride; ++j) {
  21860. values[writeOffset + j] = values[readOffset + j];
  21861. }
  21862. }
  21863. ++writeIndex;
  21864. }
  21865. } // flush last keyframe (compaction looks ahead)
  21866. if (lastIndex > 0) {
  21867. times[writeIndex] = times[lastIndex];
  21868. for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  21869. values[writeOffset + j] = values[readOffset + j];
  21870. }
  21871. ++writeIndex;
  21872. }
  21873. if (writeIndex !== times.length) {
  21874. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  21875. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  21876. } else {
  21877. this.times = times;
  21878. this.values = values;
  21879. }
  21880. return this;
  21881. }
  21882. clone() {
  21883. const times = AnimationUtils.arraySlice(this.times, 0);
  21884. const values = AnimationUtils.arraySlice(this.values, 0);
  21885. const TypedKeyframeTrack = this.constructor;
  21886. const track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  21887. track.createInterpolant = this.createInterpolant;
  21888. return track;
  21889. }
  21890. }
  21891. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  21892. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  21893. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  21894. /**
  21895. * A Track of Boolean keyframe values.
  21896. */
  21897. class BooleanKeyframeTrack extends KeyframeTrack {}
  21898. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  21899. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  21900. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  21901. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  21902. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; // Note: Actually this track could have a optimized / compressed
  21903. /**
  21904. * A Track of keyframe values that represent color.
  21905. */
  21906. class ColorKeyframeTrack extends KeyframeTrack {}
  21907. ColorKeyframeTrack.prototype.ValueTypeName = 'color'; // ValueBufferType is inherited
  21908. /**
  21909. * A Track of numeric keyframe values.
  21910. */
  21911. class NumberKeyframeTrack extends KeyframeTrack {}
  21912. NumberKeyframeTrack.prototype.ValueTypeName = 'number'; // ValueBufferType is inherited
  21913. /**
  21914. * Spherical linear unit quaternion interpolant.
  21915. */
  21916. class QuaternionLinearInterpolant extends Interpolant {
  21917. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21918. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  21919. }
  21920. interpolate_(i1, t0, t, t1) {
  21921. const result = this.resultBuffer,
  21922. values = this.sampleValues,
  21923. stride = this.valueSize,
  21924. alpha = (t - t0) / (t1 - t0);
  21925. let offset = i1 * stride;
  21926. for (let end = offset + stride; offset !== end; offset += 4) {
  21927. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  21928. }
  21929. return result;
  21930. }
  21931. }
  21932. /**
  21933. * A Track of quaternion keyframe values.
  21934. */
  21935. class QuaternionKeyframeTrack extends KeyframeTrack {
  21936. InterpolantFactoryMethodLinear(result) {
  21937. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  21938. }
  21939. }
  21940. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion'; // ValueBufferType is inherited
  21941. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  21942. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  21943. /**
  21944. * A Track that interpolates Strings
  21945. */
  21946. class StringKeyframeTrack extends KeyframeTrack {}
  21947. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  21948. StringKeyframeTrack.prototype.ValueBufferType = Array;
  21949. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  21950. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  21951. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  21952. /**
  21953. * A Track of vectored keyframe values.
  21954. */
  21955. class VectorKeyframeTrack extends KeyframeTrack {}
  21956. VectorKeyframeTrack.prototype.ValueTypeName = 'vector'; // ValueBufferType is inherited
  21957. class AnimationClip {
  21958. constructor(name, duration = -1, tracks, blendMode = NormalAnimationBlendMode) {
  21959. this.name = name;
  21960. this.tracks = tracks;
  21961. this.duration = duration;
  21962. this.blendMode = blendMode;
  21963. this.uuid = generateUUID(); // this means it should figure out its duration by scanning the tracks
  21964. if (this.duration < 0) {
  21965. this.resetDuration();
  21966. }
  21967. }
  21968. static parse(json) {
  21969. const tracks = [],
  21970. jsonTracks = json.tracks,
  21971. frameTime = 1.0 / (json.fps || 1.0);
  21972. for (let i = 0, n = jsonTracks.length; i !== n; ++i) {
  21973. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  21974. }
  21975. const clip = new this(json.name, json.duration, tracks, json.blendMode);
  21976. clip.uuid = json.uuid;
  21977. return clip;
  21978. }
  21979. static toJSON(clip) {
  21980. const tracks = [],
  21981. clipTracks = clip.tracks;
  21982. const json = {
  21983. 'name': clip.name,
  21984. 'duration': clip.duration,
  21985. 'tracks': tracks,
  21986. 'uuid': clip.uuid,
  21987. 'blendMode': clip.blendMode
  21988. };
  21989. for (let i = 0, n = clipTracks.length; i !== n; ++i) {
  21990. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  21991. }
  21992. return json;
  21993. }
  21994. static CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) {
  21995. const numMorphTargets = morphTargetSequence.length;
  21996. const tracks = [];
  21997. for (let i = 0; i < numMorphTargets; i++) {
  21998. let times = [];
  21999. let values = [];
  22000. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  22001. values.push(0, 1, 0);
  22002. const order = AnimationUtils.getKeyframeOrder(times);
  22003. times = AnimationUtils.sortedArray(times, 1, order);
  22004. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  22005. // last frame as well for perfect loop.
  22006. if (!noLoop && times[0] === 0) {
  22007. times.push(numMorphTargets);
  22008. values.push(values[0]);
  22009. }
  22010. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  22011. }
  22012. return new this(name, -1, tracks);
  22013. }
  22014. static findByName(objectOrClipArray, name) {
  22015. let clipArray = objectOrClipArray;
  22016. if (!Array.isArray(objectOrClipArray)) {
  22017. const o = objectOrClipArray;
  22018. clipArray = o.geometry && o.geometry.animations || o.animations;
  22019. }
  22020. for (let i = 0; i < clipArray.length; i++) {
  22021. if (clipArray[i].name === name) {
  22022. return clipArray[i];
  22023. }
  22024. }
  22025. return null;
  22026. }
  22027. static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {
  22028. const animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  22029. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  22030. const pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  22031. // patterns like Walk_001, Walk_002, Run_001, Run_002
  22032. for (let i = 0, il = morphTargets.length; i < il; i++) {
  22033. const morphTarget = morphTargets[i];
  22034. const parts = morphTarget.name.match(pattern);
  22035. if (parts && parts.length > 1) {
  22036. const name = parts[1];
  22037. let animationMorphTargets = animationToMorphTargets[name];
  22038. if (!animationMorphTargets) {
  22039. animationToMorphTargets[name] = animationMorphTargets = [];
  22040. }
  22041. animationMorphTargets.push(morphTarget);
  22042. }
  22043. }
  22044. const clips = [];
  22045. for (const name in animationToMorphTargets) {
  22046. clips.push(this.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  22047. }
  22048. return clips;
  22049. } // parse the animation.hierarchy format
  22050. static parseAnimation(animation, bones) {
  22051. if (!animation) {
  22052. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  22053. return null;
  22054. }
  22055. const addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  22056. // only return track if there are actually keys.
  22057. if (animationKeys.length !== 0) {
  22058. const times = [];
  22059. const values = [];
  22060. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  22061. if (times.length !== 0) {
  22062. destTracks.push(new trackType(trackName, times, values));
  22063. }
  22064. }
  22065. };
  22066. const tracks = [];
  22067. const clipName = animation.name || 'default';
  22068. const fps = animation.fps || 30;
  22069. const blendMode = animation.blendMode; // automatic length determination in AnimationClip.
  22070. let duration = animation.length || -1;
  22071. const hierarchyTracks = animation.hierarchy || [];
  22072. for (let h = 0; h < hierarchyTracks.length; h++) {
  22073. const animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  22074. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  22075. if (animationKeys[0].morphTargets) {
  22076. // figure out all morph targets used in this track
  22077. const morphTargetNames = {};
  22078. let k;
  22079. for (k = 0; k < animationKeys.length; k++) {
  22080. if (animationKeys[k].morphTargets) {
  22081. for (let m = 0; m < animationKeys[k].morphTargets.length; m++) {
  22082. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  22083. }
  22084. }
  22085. } // create a track for each morph target with all zero
  22086. // morphTargetInfluences except for the keys in which
  22087. // the morphTarget is named.
  22088. for (const morphTargetName in morphTargetNames) {
  22089. const times = [];
  22090. const values = [];
  22091. for (let m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  22092. const animationKey = animationKeys[k];
  22093. times.push(animationKey.time);
  22094. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  22095. }
  22096. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  22097. }
  22098. duration = morphTargetNames.length * (fps || 1.0);
  22099. } else {
  22100. // ...assume skeletal animation
  22101. const boneName = '.bones[' + bones[h].name + ']';
  22102. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  22103. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  22104. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  22105. }
  22106. }
  22107. if (tracks.length === 0) {
  22108. return null;
  22109. }
  22110. const clip = new this(clipName, duration, tracks, blendMode);
  22111. return clip;
  22112. }
  22113. resetDuration() {
  22114. const tracks = this.tracks;
  22115. let duration = 0;
  22116. for (let i = 0, n = tracks.length; i !== n; ++i) {
  22117. const track = this.tracks[i];
  22118. duration = Math.max(duration, track.times[track.times.length - 1]);
  22119. }
  22120. this.duration = duration;
  22121. return this;
  22122. }
  22123. trim() {
  22124. for (let i = 0; i < this.tracks.length; i++) {
  22125. this.tracks[i].trim(0, this.duration);
  22126. }
  22127. return this;
  22128. }
  22129. validate() {
  22130. let valid = true;
  22131. for (let i = 0; i < this.tracks.length; i++) {
  22132. valid = valid && this.tracks[i].validate();
  22133. }
  22134. return valid;
  22135. }
  22136. optimize() {
  22137. for (let i = 0; i < this.tracks.length; i++) {
  22138. this.tracks[i].optimize();
  22139. }
  22140. return this;
  22141. }
  22142. clone() {
  22143. const tracks = [];
  22144. for (let i = 0; i < this.tracks.length; i++) {
  22145. tracks.push(this.tracks[i].clone());
  22146. }
  22147. return new this.constructor(this.name, this.duration, tracks, this.blendMode);
  22148. }
  22149. toJSON() {
  22150. return this.constructor.toJSON(this);
  22151. }
  22152. }
  22153. function getTrackTypeForValueTypeName(typeName) {
  22154. switch (typeName.toLowerCase()) {
  22155. case 'scalar':
  22156. case 'double':
  22157. case 'float':
  22158. case 'number':
  22159. case 'integer':
  22160. return NumberKeyframeTrack;
  22161. case 'vector':
  22162. case 'vector2':
  22163. case 'vector3':
  22164. case 'vector4':
  22165. return VectorKeyframeTrack;
  22166. case 'color':
  22167. return ColorKeyframeTrack;
  22168. case 'quaternion':
  22169. return QuaternionKeyframeTrack;
  22170. case 'bool':
  22171. case 'boolean':
  22172. return BooleanKeyframeTrack;
  22173. case 'string':
  22174. return StringKeyframeTrack;
  22175. }
  22176. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  22177. }
  22178. function parseKeyframeTrack(json) {
  22179. if (json.type === undefined) {
  22180. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  22181. }
  22182. const trackType = getTrackTypeForValueTypeName(json.type);
  22183. if (json.times === undefined) {
  22184. const times = [],
  22185. values = [];
  22186. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  22187. json.times = times;
  22188. json.values = values;
  22189. } // derived classes can define a static parse method
  22190. if (trackType.parse !== undefined) {
  22191. return trackType.parse(json);
  22192. } else {
  22193. // by default, we assume a constructor compatible with the base
  22194. return new trackType(json.name, json.times, json.values, json.interpolation);
  22195. }
  22196. }
  22197. const Cache = {
  22198. enabled: false,
  22199. files: {},
  22200. add: function (key, file) {
  22201. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  22202. this.files[key] = file;
  22203. },
  22204. get: function (key) {
  22205. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  22206. return this.files[key];
  22207. },
  22208. remove: function (key) {
  22209. delete this.files[key];
  22210. },
  22211. clear: function () {
  22212. this.files = {};
  22213. }
  22214. };
  22215. class LoadingManager {
  22216. constructor(onLoad, onProgress, onError) {
  22217. const scope = this;
  22218. let isLoading = false;
  22219. let itemsLoaded = 0;
  22220. let itemsTotal = 0;
  22221. let urlModifier = undefined;
  22222. const handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  22223. // in the constructor
  22224. this.onStart = undefined;
  22225. this.onLoad = onLoad;
  22226. this.onProgress = onProgress;
  22227. this.onError = onError;
  22228. this.itemStart = function (url) {
  22229. itemsTotal++;
  22230. if (isLoading === false) {
  22231. if (scope.onStart !== undefined) {
  22232. scope.onStart(url, itemsLoaded, itemsTotal);
  22233. }
  22234. }
  22235. isLoading = true;
  22236. };
  22237. this.itemEnd = function (url) {
  22238. itemsLoaded++;
  22239. if (scope.onProgress !== undefined) {
  22240. scope.onProgress(url, itemsLoaded, itemsTotal);
  22241. }
  22242. if (itemsLoaded === itemsTotal) {
  22243. isLoading = false;
  22244. if (scope.onLoad !== undefined) {
  22245. scope.onLoad();
  22246. }
  22247. }
  22248. };
  22249. this.itemError = function (url) {
  22250. if (scope.onError !== undefined) {
  22251. scope.onError(url);
  22252. }
  22253. };
  22254. this.resolveURL = function (url) {
  22255. if (urlModifier) {
  22256. return urlModifier(url);
  22257. }
  22258. return url;
  22259. };
  22260. this.setURLModifier = function (transform) {
  22261. urlModifier = transform;
  22262. return this;
  22263. };
  22264. this.addHandler = function (regex, loader) {
  22265. handlers.push(regex, loader);
  22266. return this;
  22267. };
  22268. this.removeHandler = function (regex) {
  22269. const index = handlers.indexOf(regex);
  22270. if (index !== -1) {
  22271. handlers.splice(index, 2);
  22272. }
  22273. return this;
  22274. };
  22275. this.getHandler = function (file) {
  22276. for (let i = 0, l = handlers.length; i < l; i += 2) {
  22277. const regex = handlers[i];
  22278. const loader = handlers[i + 1];
  22279. if (regex.global) regex.lastIndex = 0; // see #17920
  22280. if (regex.test(file)) {
  22281. return loader;
  22282. }
  22283. }
  22284. return null;
  22285. };
  22286. }
  22287. }
  22288. const DefaultLoadingManager = new LoadingManager();
  22289. class Loader {
  22290. constructor(manager) {
  22291. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  22292. this.crossOrigin = 'anonymous';
  22293. this.withCredentials = false;
  22294. this.path = '';
  22295. this.resourcePath = '';
  22296. this.requestHeader = {};
  22297. }
  22298. load() {}
  22299. loadAsync(url, onProgress) {
  22300. const scope = this;
  22301. return new Promise(function (resolve, reject) {
  22302. scope.load(url, resolve, onProgress, reject);
  22303. });
  22304. }
  22305. parse() {}
  22306. setCrossOrigin(crossOrigin) {
  22307. this.crossOrigin = crossOrigin;
  22308. return this;
  22309. }
  22310. setWithCredentials(value) {
  22311. this.withCredentials = value;
  22312. return this;
  22313. }
  22314. setPath(path) {
  22315. this.path = path;
  22316. return this;
  22317. }
  22318. setResourcePath(resourcePath) {
  22319. this.resourcePath = resourcePath;
  22320. return this;
  22321. }
  22322. setRequestHeader(requestHeader) {
  22323. this.requestHeader = requestHeader;
  22324. return this;
  22325. }
  22326. }
  22327. const loading = {};
  22328. class FileLoader extends Loader {
  22329. constructor(manager) {
  22330. super(manager);
  22331. }
  22332. load(url, onLoad, onProgress, onError) {
  22333. if (url === undefined) url = '';
  22334. if (this.path !== undefined) url = this.path + url;
  22335. url = this.manager.resolveURL(url);
  22336. const scope = this;
  22337. const cached = Cache.get(url);
  22338. if (cached !== undefined) {
  22339. scope.manager.itemStart(url);
  22340. setTimeout(function () {
  22341. if (onLoad) onLoad(cached);
  22342. scope.manager.itemEnd(url);
  22343. }, 0);
  22344. return cached;
  22345. } // Check if request is duplicate
  22346. if (loading[url] !== undefined) {
  22347. loading[url].push({
  22348. onLoad: onLoad,
  22349. onProgress: onProgress,
  22350. onError: onError
  22351. });
  22352. return;
  22353. } // Check for data: URI
  22354. const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  22355. const dataUriRegexResult = url.match(dataUriRegex);
  22356. let request; // Safari can not handle Data URIs through XMLHttpRequest so process manually
  22357. if (dataUriRegexResult) {
  22358. const mimeType = dataUriRegexResult[1];
  22359. const isBase64 = !!dataUriRegexResult[2];
  22360. let data = dataUriRegexResult[3];
  22361. data = decodeURIComponent(data);
  22362. if (isBase64) data = atob(data);
  22363. try {
  22364. let response;
  22365. const responseType = (this.responseType || '').toLowerCase();
  22366. switch (responseType) {
  22367. case 'arraybuffer':
  22368. case 'blob':
  22369. const view = new Uint8Array(data.length);
  22370. for (let i = 0; i < data.length; i++) {
  22371. view[i] = data.charCodeAt(i);
  22372. }
  22373. if (responseType === 'blob') {
  22374. response = new Blob([view.buffer], {
  22375. type: mimeType
  22376. });
  22377. } else {
  22378. response = view.buffer;
  22379. }
  22380. break;
  22381. case 'document':
  22382. const parser = new DOMParser();
  22383. response = parser.parseFromString(data, mimeType);
  22384. break;
  22385. case 'json':
  22386. response = JSON.parse(data);
  22387. break;
  22388. default:
  22389. // 'text' or other
  22390. response = data;
  22391. break;
  22392. } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22393. setTimeout(function () {
  22394. if (onLoad) onLoad(response);
  22395. scope.manager.itemEnd(url);
  22396. }, 0);
  22397. } catch (error) {
  22398. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22399. setTimeout(function () {
  22400. if (onError) onError(error);
  22401. scope.manager.itemError(url);
  22402. scope.manager.itemEnd(url);
  22403. }, 0);
  22404. }
  22405. } else {
  22406. // Initialise array for duplicate requests
  22407. loading[url] = [];
  22408. loading[url].push({
  22409. onLoad: onLoad,
  22410. onProgress: onProgress,
  22411. onError: onError
  22412. });
  22413. request = new XMLHttpRequest();
  22414. request.open('GET', url, true);
  22415. request.addEventListener('load', function (event) {
  22416. const response = this.response;
  22417. const callbacks = loading[url];
  22418. delete loading[url];
  22419. if (this.status === 200 || this.status === 0) {
  22420. // Some browsers return HTTP Status 0 when using non-http protocol
  22421. // e.g. 'file://' or 'data://'. Handle as success.
  22422. 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
  22423. // error response bodies as proper responses to requests.
  22424. Cache.add(url, response);
  22425. for (let i = 0, il = callbacks.length; i < il; i++) {
  22426. const callback = callbacks[i];
  22427. if (callback.onLoad) callback.onLoad(response);
  22428. }
  22429. scope.manager.itemEnd(url);
  22430. } else {
  22431. for (let i = 0, il = callbacks.length; i < il; i++) {
  22432. const callback = callbacks[i];
  22433. if (callback.onError) callback.onError(event);
  22434. }
  22435. scope.manager.itemError(url);
  22436. scope.manager.itemEnd(url);
  22437. }
  22438. }, false);
  22439. request.addEventListener('progress', function (event) {
  22440. const callbacks = loading[url];
  22441. for (let i = 0, il = callbacks.length; i < il; i++) {
  22442. const callback = callbacks[i];
  22443. if (callback.onProgress) callback.onProgress(event);
  22444. }
  22445. }, false);
  22446. request.addEventListener('error', function (event) {
  22447. const callbacks = loading[url];
  22448. delete loading[url];
  22449. for (let i = 0, il = callbacks.length; i < il; i++) {
  22450. const callback = callbacks[i];
  22451. if (callback.onError) callback.onError(event);
  22452. }
  22453. scope.manager.itemError(url);
  22454. scope.manager.itemEnd(url);
  22455. }, false);
  22456. request.addEventListener('abort', function (event) {
  22457. const callbacks = loading[url];
  22458. delete loading[url];
  22459. for (let i = 0, il = callbacks.length; i < il; i++) {
  22460. const callback = callbacks[i];
  22461. if (callback.onError) callback.onError(event);
  22462. }
  22463. scope.manager.itemError(url);
  22464. scope.manager.itemEnd(url);
  22465. }, false);
  22466. if (this.responseType !== undefined) request.responseType = this.responseType;
  22467. if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
  22468. if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
  22469. for (const header in this.requestHeader) {
  22470. request.setRequestHeader(header, this.requestHeader[header]);
  22471. }
  22472. request.send(null);
  22473. }
  22474. scope.manager.itemStart(url);
  22475. return request;
  22476. }
  22477. setResponseType(value) {
  22478. this.responseType = value;
  22479. return this;
  22480. }
  22481. setMimeType(value) {
  22482. this.mimeType = value;
  22483. return this;
  22484. }
  22485. }
  22486. class AnimationLoader extends Loader {
  22487. constructor(manager) {
  22488. super(manager);
  22489. }
  22490. load(url, onLoad, onProgress, onError) {
  22491. const scope = this;
  22492. const loader = new FileLoader(this.manager);
  22493. loader.setPath(this.path);
  22494. loader.setRequestHeader(this.requestHeader);
  22495. loader.setWithCredentials(this.withCredentials);
  22496. loader.load(url, function (text) {
  22497. try {
  22498. onLoad(scope.parse(JSON.parse(text)));
  22499. } catch (e) {
  22500. if (onError) {
  22501. onError(e);
  22502. } else {
  22503. console.error(e);
  22504. }
  22505. scope.manager.itemError(url);
  22506. }
  22507. }, onProgress, onError);
  22508. }
  22509. parse(json) {
  22510. const animations = [];
  22511. for (let i = 0; i < json.length; i++) {
  22512. const clip = AnimationClip.parse(json[i]);
  22513. animations.push(clip);
  22514. }
  22515. return animations;
  22516. }
  22517. }
  22518. /**
  22519. * Abstract Base class to block based textures loader (dds, pvr, ...)
  22520. *
  22521. * Sub classes have to implement the parse() method which will be used in load().
  22522. */
  22523. class CompressedTextureLoader extends Loader {
  22524. constructor(manager) {
  22525. super(manager);
  22526. }
  22527. load(url, onLoad, onProgress, onError) {
  22528. const scope = this;
  22529. const images = [];
  22530. const texture = new CompressedTexture();
  22531. const loader = new FileLoader(this.manager);
  22532. loader.setPath(this.path);
  22533. loader.setResponseType('arraybuffer');
  22534. loader.setRequestHeader(this.requestHeader);
  22535. loader.setWithCredentials(scope.withCredentials);
  22536. let loaded = 0;
  22537. function loadTexture(i) {
  22538. loader.load(url[i], function (buffer) {
  22539. const texDatas = scope.parse(buffer, true);
  22540. images[i] = {
  22541. width: texDatas.width,
  22542. height: texDatas.height,
  22543. format: texDatas.format,
  22544. mipmaps: texDatas.mipmaps
  22545. };
  22546. loaded += 1;
  22547. if (loaded === 6) {
  22548. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  22549. texture.image = images;
  22550. texture.format = texDatas.format;
  22551. texture.needsUpdate = true;
  22552. if (onLoad) onLoad(texture);
  22553. }
  22554. }, onProgress, onError);
  22555. }
  22556. if (Array.isArray(url)) {
  22557. for (let i = 0, il = url.length; i < il; ++i) {
  22558. loadTexture(i);
  22559. }
  22560. } else {
  22561. // compressed cubemap texture stored in a single DDS file
  22562. loader.load(url, function (buffer) {
  22563. const texDatas = scope.parse(buffer, true);
  22564. if (texDatas.isCubemap) {
  22565. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  22566. for (let f = 0; f < faces; f++) {
  22567. images[f] = {
  22568. mipmaps: []
  22569. };
  22570. for (let i = 0; i < texDatas.mipmapCount; i++) {
  22571. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  22572. images[f].format = texDatas.format;
  22573. images[f].width = texDatas.width;
  22574. images[f].height = texDatas.height;
  22575. }
  22576. }
  22577. texture.image = images;
  22578. } else {
  22579. texture.image.width = texDatas.width;
  22580. texture.image.height = texDatas.height;
  22581. texture.mipmaps = texDatas.mipmaps;
  22582. }
  22583. if (texDatas.mipmapCount === 1) {
  22584. texture.minFilter = LinearFilter;
  22585. }
  22586. texture.format = texDatas.format;
  22587. texture.needsUpdate = true;
  22588. if (onLoad) onLoad(texture);
  22589. }, onProgress, onError);
  22590. }
  22591. return texture;
  22592. }
  22593. }
  22594. class ImageLoader extends Loader {
  22595. constructor(manager) {
  22596. super(manager);
  22597. }
  22598. load(url, onLoad, onProgress, onError) {
  22599. if (this.path !== undefined) url = this.path + url;
  22600. url = this.manager.resolveURL(url);
  22601. const scope = this;
  22602. const cached = Cache.get(url);
  22603. if (cached !== undefined) {
  22604. scope.manager.itemStart(url);
  22605. setTimeout(function () {
  22606. if (onLoad) onLoad(cached);
  22607. scope.manager.itemEnd(url);
  22608. }, 0);
  22609. return cached;
  22610. }
  22611. const image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
  22612. function onImageLoad() {
  22613. image.removeEventListener('load', onImageLoad, false);
  22614. image.removeEventListener('error', onImageError, false);
  22615. Cache.add(url, this);
  22616. if (onLoad) onLoad(this);
  22617. scope.manager.itemEnd(url);
  22618. }
  22619. function onImageError(event) {
  22620. image.removeEventListener('load', onImageLoad, false);
  22621. image.removeEventListener('error', onImageError, false);
  22622. if (onError) onError(event);
  22623. scope.manager.itemError(url);
  22624. scope.manager.itemEnd(url);
  22625. }
  22626. image.addEventListener('load', onImageLoad, false);
  22627. image.addEventListener('error', onImageError, false);
  22628. if (url.substr(0, 5) !== 'data:') {
  22629. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  22630. }
  22631. scope.manager.itemStart(url);
  22632. image.src = url;
  22633. return image;
  22634. }
  22635. }
  22636. class CubeTextureLoader extends Loader {
  22637. constructor(manager) {
  22638. super(manager);
  22639. }
  22640. load(urls, onLoad, onProgress, onError) {
  22641. const texture = new CubeTexture();
  22642. const loader = new ImageLoader(this.manager);
  22643. loader.setCrossOrigin(this.crossOrigin);
  22644. loader.setPath(this.path);
  22645. let loaded = 0;
  22646. function loadTexture(i) {
  22647. loader.load(urls[i], function (image) {
  22648. texture.images[i] = image;
  22649. loaded++;
  22650. if (loaded === 6) {
  22651. texture.needsUpdate = true;
  22652. if (onLoad) onLoad(texture);
  22653. }
  22654. }, undefined, onError);
  22655. }
  22656. for (let i = 0; i < urls.length; ++i) {
  22657. loadTexture(i);
  22658. }
  22659. return texture;
  22660. }
  22661. }
  22662. /**
  22663. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  22664. *
  22665. * Sub classes have to implement the parse() method which will be used in load().
  22666. */
  22667. class DataTextureLoader extends Loader {
  22668. constructor(manager) {
  22669. super(manager);
  22670. }
  22671. load(url, onLoad, onProgress, onError) {
  22672. const scope = this;
  22673. const texture = new DataTexture();
  22674. const loader = new FileLoader(this.manager);
  22675. loader.setResponseType('arraybuffer');
  22676. loader.setRequestHeader(this.requestHeader);
  22677. loader.setPath(this.path);
  22678. loader.setWithCredentials(scope.withCredentials);
  22679. loader.load(url, function (buffer) {
  22680. const texData = scope.parse(buffer);
  22681. if (!texData) return;
  22682. if (texData.image !== undefined) {
  22683. texture.image = texData.image;
  22684. } else if (texData.data !== undefined) {
  22685. texture.image.width = texData.width;
  22686. texture.image.height = texData.height;
  22687. texture.image.data = texData.data;
  22688. }
  22689. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  22690. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  22691. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  22692. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  22693. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  22694. if (texData.encoding !== undefined) {
  22695. texture.encoding = texData.encoding;
  22696. }
  22697. if (texData.flipY !== undefined) {
  22698. texture.flipY = texData.flipY;
  22699. }
  22700. if (texData.format !== undefined) {
  22701. texture.format = texData.format;
  22702. }
  22703. if (texData.type !== undefined) {
  22704. texture.type = texData.type;
  22705. }
  22706. if (texData.mipmaps !== undefined) {
  22707. texture.mipmaps = texData.mipmaps;
  22708. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  22709. }
  22710. if (texData.mipmapCount === 1) {
  22711. texture.minFilter = LinearFilter;
  22712. }
  22713. if (texData.generateMipmaps !== undefined) {
  22714. texture.generateMipmaps = texData.generateMipmaps;
  22715. }
  22716. texture.needsUpdate = true;
  22717. if (onLoad) onLoad(texture, texData);
  22718. }, onProgress, onError);
  22719. return texture;
  22720. }
  22721. }
  22722. class TextureLoader extends Loader {
  22723. constructor(manager) {
  22724. super(manager);
  22725. }
  22726. load(url, onLoad, onProgress, onError) {
  22727. const texture = new Texture();
  22728. const loader = new ImageLoader(this.manager);
  22729. loader.setCrossOrigin(this.crossOrigin);
  22730. loader.setPath(this.path);
  22731. loader.load(url, function (image) {
  22732. texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  22733. const isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;
  22734. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  22735. texture.needsUpdate = true;
  22736. if (onLoad !== undefined) {
  22737. onLoad(texture);
  22738. }
  22739. }, onProgress, onError);
  22740. return texture;
  22741. }
  22742. }
  22743. /**************************************************************
  22744. * Curved Path - a curve path is simply a array of connected
  22745. * curves, but retains the api of a curve
  22746. **************************************************************/
  22747. class CurvePath extends Curve {
  22748. constructor() {
  22749. super();
  22750. this.type = 'CurvePath';
  22751. this.curves = [];
  22752. this.autoClose = false; // Automatically closes the path
  22753. }
  22754. add(curve) {
  22755. this.curves.push(curve);
  22756. }
  22757. closePath() {
  22758. // Add a line curve if start and end of lines are not connected
  22759. const startPoint = this.curves[0].getPoint(0);
  22760. const endPoint = this.curves[this.curves.length - 1].getPoint(1);
  22761. if (!startPoint.equals(endPoint)) {
  22762. this.curves.push(new LineCurve(endPoint, startPoint));
  22763. }
  22764. } // To get accurate point with reference to
  22765. // entire path distance at time t,
  22766. // following has to be done:
  22767. // 1. Length of each sub path have to be known
  22768. // 2. Locate and identify type of curve
  22769. // 3. Get t for the curve
  22770. // 4. Return curve.getPointAt(t')
  22771. getPoint(t) {
  22772. const d = t * this.getLength();
  22773. const curveLengths = this.getCurveLengths();
  22774. let i = 0; // To think about boundaries points.
  22775. while (i < curveLengths.length) {
  22776. if (curveLengths[i] >= d) {
  22777. const diff = curveLengths[i] - d;
  22778. const curve = this.curves[i];
  22779. const segmentLength = curve.getLength();
  22780. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  22781. return curve.getPointAt(u);
  22782. }
  22783. i++;
  22784. }
  22785. return null; // loop where sum != 0, sum > d , sum+1 <d
  22786. } // We cannot use the default THREE.Curve getPoint() with getLength() because in
  22787. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  22788. // getPoint() depends on getLength
  22789. getLength() {
  22790. const lens = this.getCurveLengths();
  22791. return lens[lens.length - 1];
  22792. } // cacheLengths must be recalculated.
  22793. updateArcLengths() {
  22794. this.needsUpdate = true;
  22795. this.cacheLengths = null;
  22796. this.getCurveLengths();
  22797. } // Compute lengths and cache them
  22798. // We cannot overwrite getLengths() because UtoT mapping uses it.
  22799. getCurveLengths() {
  22800. // We use cache values if curves and cache array are same length
  22801. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  22802. return this.cacheLengths;
  22803. } // Get length of sub-curve
  22804. // Push sums into cached array
  22805. const lengths = [];
  22806. let sums = 0;
  22807. for (let i = 0, l = this.curves.length; i < l; i++) {
  22808. sums += this.curves[i].getLength();
  22809. lengths.push(sums);
  22810. }
  22811. this.cacheLengths = lengths;
  22812. return lengths;
  22813. }
  22814. getSpacedPoints(divisions = 40) {
  22815. const points = [];
  22816. for (let i = 0; i <= divisions; i++) {
  22817. points.push(this.getPoint(i / divisions));
  22818. }
  22819. if (this.autoClose) {
  22820. points.push(points[0]);
  22821. }
  22822. return points;
  22823. }
  22824. getPoints(divisions = 12) {
  22825. const points = [];
  22826. let last;
  22827. for (let i = 0, curves = this.curves; i < curves.length; i++) {
  22828. const curve = curves[i];
  22829. const resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  22830. const pts = curve.getPoints(resolution);
  22831. for (let j = 0; j < pts.length; j++) {
  22832. const point = pts[j];
  22833. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  22834. points.push(point);
  22835. last = point;
  22836. }
  22837. }
  22838. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  22839. points.push(points[0]);
  22840. }
  22841. return points;
  22842. }
  22843. copy(source) {
  22844. super.copy(source);
  22845. this.curves = [];
  22846. for (let i = 0, l = source.curves.length; i < l; i++) {
  22847. const curve = source.curves[i];
  22848. this.curves.push(curve.clone());
  22849. }
  22850. this.autoClose = source.autoClose;
  22851. return this;
  22852. }
  22853. toJSON() {
  22854. const data = super.toJSON();
  22855. data.autoClose = this.autoClose;
  22856. data.curves = [];
  22857. for (let i = 0, l = this.curves.length; i < l; i++) {
  22858. const curve = this.curves[i];
  22859. data.curves.push(curve.toJSON());
  22860. }
  22861. return data;
  22862. }
  22863. fromJSON(json) {
  22864. super.fromJSON(json);
  22865. this.autoClose = json.autoClose;
  22866. this.curves = [];
  22867. for (let i = 0, l = json.curves.length; i < l; i++) {
  22868. const curve = json.curves[i];
  22869. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  22870. }
  22871. return this;
  22872. }
  22873. }
  22874. class Path extends CurvePath {
  22875. constructor(points) {
  22876. super();
  22877. this.type = 'Path';
  22878. this.currentPoint = new Vector2();
  22879. if (points) {
  22880. this.setFromPoints(points);
  22881. }
  22882. }
  22883. setFromPoints(points) {
  22884. this.moveTo(points[0].x, points[0].y);
  22885. for (let i = 1, l = points.length; i < l; i++) {
  22886. this.lineTo(points[i].x, points[i].y);
  22887. }
  22888. return this;
  22889. }
  22890. moveTo(x, y) {
  22891. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  22892. return this;
  22893. }
  22894. lineTo(x, y) {
  22895. const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  22896. this.curves.push(curve);
  22897. this.currentPoint.set(x, y);
  22898. return this;
  22899. }
  22900. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  22901. const curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  22902. this.curves.push(curve);
  22903. this.currentPoint.set(aX, aY);
  22904. return this;
  22905. }
  22906. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  22907. const curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  22908. this.curves.push(curve);
  22909. this.currentPoint.set(aX, aY);
  22910. return this;
  22911. }
  22912. splineThru(pts
  22913. /*Array of Vector*/
  22914. ) {
  22915. const npts = [this.currentPoint.clone()].concat(pts);
  22916. const curve = new SplineCurve(npts);
  22917. this.curves.push(curve);
  22918. this.currentPoint.copy(pts[pts.length - 1]);
  22919. return this;
  22920. }
  22921. arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  22922. const x0 = this.currentPoint.x;
  22923. const y0 = this.currentPoint.y;
  22924. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  22925. return this;
  22926. }
  22927. absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  22928. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  22929. return this;
  22930. }
  22931. ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  22932. const x0 = this.currentPoint.x;
  22933. const y0 = this.currentPoint.y;
  22934. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  22935. return this;
  22936. }
  22937. absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  22938. const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  22939. if (this.curves.length > 0) {
  22940. // if a previous curve is present, attempt to join
  22941. const firstPoint = curve.getPoint(0);
  22942. if (!firstPoint.equals(this.currentPoint)) {
  22943. this.lineTo(firstPoint.x, firstPoint.y);
  22944. }
  22945. }
  22946. this.curves.push(curve);
  22947. const lastPoint = curve.getPoint(1);
  22948. this.currentPoint.copy(lastPoint);
  22949. return this;
  22950. }
  22951. copy(source) {
  22952. super.copy(source);
  22953. this.currentPoint.copy(source.currentPoint);
  22954. return this;
  22955. }
  22956. toJSON() {
  22957. const data = super.toJSON();
  22958. data.currentPoint = this.currentPoint.toArray();
  22959. return data;
  22960. }
  22961. fromJSON(json) {
  22962. super.fromJSON(json);
  22963. this.currentPoint.fromArray(json.currentPoint);
  22964. return this;
  22965. }
  22966. }
  22967. class Shape extends Path {
  22968. constructor(points) {
  22969. super(points);
  22970. this.uuid = generateUUID();
  22971. this.type = 'Shape';
  22972. this.holes = [];
  22973. }
  22974. getPointsHoles(divisions) {
  22975. const holesPts = [];
  22976. for (let i = 0, l = this.holes.length; i < l; i++) {
  22977. holesPts[i] = this.holes[i].getPoints(divisions);
  22978. }
  22979. return holesPts;
  22980. } // get points of shape and holes (keypoints based on segments parameter)
  22981. extractPoints(divisions) {
  22982. return {
  22983. shape: this.getPoints(divisions),
  22984. holes: this.getPointsHoles(divisions)
  22985. };
  22986. }
  22987. copy(source) {
  22988. super.copy(source);
  22989. this.holes = [];
  22990. for (let i = 0, l = source.holes.length; i < l; i++) {
  22991. const hole = source.holes[i];
  22992. this.holes.push(hole.clone());
  22993. }
  22994. return this;
  22995. }
  22996. toJSON() {
  22997. const data = super.toJSON();
  22998. data.uuid = this.uuid;
  22999. data.holes = [];
  23000. for (let i = 0, l = this.holes.length; i < l; i++) {
  23001. const hole = this.holes[i];
  23002. data.holes.push(hole.toJSON());
  23003. }
  23004. return data;
  23005. }
  23006. fromJSON(json) {
  23007. super.fromJSON(json);
  23008. this.uuid = json.uuid;
  23009. this.holes = [];
  23010. for (let i = 0, l = json.holes.length; i < l; i++) {
  23011. const hole = json.holes[i];
  23012. this.holes.push(new Path().fromJSON(hole));
  23013. }
  23014. return this;
  23015. }
  23016. }
  23017. class Light extends Object3D {
  23018. constructor(color, intensity = 1) {
  23019. super();
  23020. this.type = 'Light';
  23021. this.color = new Color(color);
  23022. this.intensity = intensity;
  23023. }
  23024. dispose() {// Empty here in base class; some subclasses override.
  23025. }
  23026. copy(source) {
  23027. super.copy(source);
  23028. this.color.copy(source.color);
  23029. this.intensity = source.intensity;
  23030. return this;
  23031. }
  23032. toJSON(meta) {
  23033. const data = super.toJSON(meta);
  23034. data.object.color = this.color.getHex();
  23035. data.object.intensity = this.intensity;
  23036. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  23037. if (this.distance !== undefined) data.object.distance = this.distance;
  23038. if (this.angle !== undefined) data.object.angle = this.angle;
  23039. if (this.decay !== undefined) data.object.decay = this.decay;
  23040. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  23041. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  23042. return data;
  23043. }
  23044. }
  23045. Light.prototype.isLight = true;
  23046. class HemisphereLight extends Light {
  23047. constructor(skyColor, groundColor, intensity) {
  23048. super(skyColor, intensity);
  23049. this.type = 'HemisphereLight';
  23050. this.position.copy(Object3D.DefaultUp);
  23051. this.updateMatrix();
  23052. this.groundColor = new Color(groundColor);
  23053. }
  23054. copy(source) {
  23055. Light.prototype.copy.call(this, source);
  23056. this.groundColor.copy(source.groundColor);
  23057. return this;
  23058. }
  23059. }
  23060. HemisphereLight.prototype.isHemisphereLight = true;
  23061. const _projScreenMatrix$1 = /*@__PURE__*/new Matrix4();
  23062. const _lightPositionWorld$1 = /*@__PURE__*/new Vector3();
  23063. const _lookTarget$1 = /*@__PURE__*/new Vector3();
  23064. class LightShadow {
  23065. constructor(camera) {
  23066. this.camera = camera;
  23067. this.bias = 0;
  23068. this.normalBias = 0;
  23069. this.radius = 1;
  23070. this.blurSamples = 8;
  23071. this.mapSize = new Vector2(512, 512);
  23072. this.map = null;
  23073. this.mapPass = null;
  23074. this.matrix = new Matrix4();
  23075. this.autoUpdate = true;
  23076. this.needsUpdate = false;
  23077. this._frustum = new Frustum();
  23078. this._frameExtents = new Vector2(1, 1);
  23079. this._viewportCount = 1;
  23080. this._viewports = [new Vector4(0, 0, 1, 1)];
  23081. }
  23082. getViewportCount() {
  23083. return this._viewportCount;
  23084. }
  23085. getFrustum() {
  23086. return this._frustum;
  23087. }
  23088. updateMatrices(light) {
  23089. const shadowCamera = this.camera;
  23090. const shadowMatrix = this.matrix;
  23091. _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld);
  23092. shadowCamera.position.copy(_lightPositionWorld$1);
  23093. _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld);
  23094. shadowCamera.lookAt(_lookTarget$1);
  23095. shadowCamera.updateMatrixWorld();
  23096. _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  23097. this._frustum.setFromProjectionMatrix(_projScreenMatrix$1);
  23098. 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);
  23099. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  23100. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  23101. }
  23102. getViewport(viewportIndex) {
  23103. return this._viewports[viewportIndex];
  23104. }
  23105. getFrameExtents() {
  23106. return this._frameExtents;
  23107. }
  23108. dispose() {
  23109. if (this.map) {
  23110. this.map.dispose();
  23111. }
  23112. if (this.mapPass) {
  23113. this.mapPass.dispose();
  23114. }
  23115. }
  23116. copy(source) {
  23117. this.camera = source.camera.clone();
  23118. this.bias = source.bias;
  23119. this.radius = source.radius;
  23120. this.mapSize.copy(source.mapSize);
  23121. return this;
  23122. }
  23123. clone() {
  23124. return new this.constructor().copy(this);
  23125. }
  23126. toJSON() {
  23127. const object = {};
  23128. if (this.bias !== 0) object.bias = this.bias;
  23129. if (this.normalBias !== 0) object.normalBias = this.normalBias;
  23130. if (this.radius !== 1) object.radius = this.radius;
  23131. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  23132. object.camera = this.camera.toJSON(false).object;
  23133. delete object.camera.matrix;
  23134. return object;
  23135. }
  23136. }
  23137. class SpotLightShadow extends LightShadow {
  23138. constructor() {
  23139. super(new PerspectiveCamera(50, 1, 0.5, 500));
  23140. this.focus = 1;
  23141. }
  23142. updateMatrices(light) {
  23143. const camera = this.camera;
  23144. const fov = RAD2DEG * 2 * light.angle * this.focus;
  23145. const aspect = this.mapSize.width / this.mapSize.height;
  23146. const far = light.distance || camera.far;
  23147. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  23148. camera.fov = fov;
  23149. camera.aspect = aspect;
  23150. camera.far = far;
  23151. camera.updateProjectionMatrix();
  23152. }
  23153. super.updateMatrices(light);
  23154. }
  23155. copy(source) {
  23156. super.copy(source);
  23157. this.focus = source.focus;
  23158. return this;
  23159. }
  23160. }
  23161. SpotLightShadow.prototype.isSpotLightShadow = true;
  23162. class SpotLight extends Light {
  23163. constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1) {
  23164. super(color, intensity);
  23165. this.type = 'SpotLight';
  23166. this.position.copy(Object3D.DefaultUp);
  23167. this.updateMatrix();
  23168. this.target = new Object3D();
  23169. this.distance = distance;
  23170. this.angle = angle;
  23171. this.penumbra = penumbra;
  23172. this.decay = decay; // for physically correct lights, should be 2.
  23173. this.shadow = new SpotLightShadow();
  23174. }
  23175. get power() {
  23176. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23177. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  23178. return this.intensity * Math.PI;
  23179. }
  23180. set power(power) {
  23181. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23182. this.intensity = power / Math.PI;
  23183. }
  23184. dispose() {
  23185. this.shadow.dispose();
  23186. }
  23187. copy(source) {
  23188. super.copy(source);
  23189. this.distance = source.distance;
  23190. this.angle = source.angle;
  23191. this.penumbra = source.penumbra;
  23192. this.decay = source.decay;
  23193. this.target = source.target.clone();
  23194. this.shadow = source.shadow.clone();
  23195. return this;
  23196. }
  23197. }
  23198. SpotLight.prototype.isSpotLight = true;
  23199. const _projScreenMatrix = /*@__PURE__*/new Matrix4();
  23200. const _lightPositionWorld = /*@__PURE__*/new Vector3();
  23201. const _lookTarget = /*@__PURE__*/new Vector3();
  23202. class PointLightShadow extends LightShadow {
  23203. constructor() {
  23204. super(new PerspectiveCamera(90, 1, 0.5, 500));
  23205. this._frameExtents = new Vector2(4, 2);
  23206. this._viewportCount = 6;
  23207. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  23208. // following orientation:
  23209. //
  23210. // xzXZ
  23211. // y Y
  23212. //
  23213. // X - Positive x direction
  23214. // x - Negative x direction
  23215. // Y - Positive y direction
  23216. // y - Negative y direction
  23217. // Z - Positive z direction
  23218. // z - Negative z direction
  23219. // positive X
  23220. new Vector4(2, 1, 1, 1), // negative X
  23221. new Vector4(0, 1, 1, 1), // positive Z
  23222. new Vector4(3, 1, 1, 1), // negative Z
  23223. new Vector4(1, 1, 1, 1), // positive Y
  23224. new Vector4(3, 0, 1, 1), // negative Y
  23225. new Vector4(1, 0, 1, 1)];
  23226. 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)];
  23227. 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)];
  23228. }
  23229. updateMatrices(light, viewportIndex = 0) {
  23230. const camera = this.camera;
  23231. const shadowMatrix = this.matrix;
  23232. const far = light.distance || camera.far;
  23233. if (far !== camera.far) {
  23234. camera.far = far;
  23235. camera.updateProjectionMatrix();
  23236. }
  23237. _lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23238. camera.position.copy(_lightPositionWorld);
  23239. _lookTarget.copy(camera.position);
  23240. _lookTarget.add(this._cubeDirections[viewportIndex]);
  23241. camera.up.copy(this._cubeUps[viewportIndex]);
  23242. camera.lookAt(_lookTarget);
  23243. camera.updateMatrixWorld();
  23244. shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z);
  23245. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  23246. this._frustum.setFromProjectionMatrix(_projScreenMatrix);
  23247. }
  23248. }
  23249. PointLightShadow.prototype.isPointLightShadow = true;
  23250. class PointLight extends Light {
  23251. constructor(color, intensity, distance = 0, decay = 1) {
  23252. super(color, intensity);
  23253. this.type = 'PointLight';
  23254. this.distance = distance;
  23255. this.decay = decay; // for physically correct lights, should be 2.
  23256. this.shadow = new PointLightShadow();
  23257. }
  23258. get power() {
  23259. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23260. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  23261. return this.intensity * 4 * Math.PI;
  23262. }
  23263. set power(power) {
  23264. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23265. this.intensity = power / (4 * Math.PI);
  23266. }
  23267. dispose() {
  23268. this.shadow.dispose();
  23269. }
  23270. copy(source) {
  23271. super.copy(source);
  23272. this.distance = source.distance;
  23273. this.decay = source.decay;
  23274. this.shadow = source.shadow.clone();
  23275. return this;
  23276. }
  23277. }
  23278. PointLight.prototype.isPointLight = true;
  23279. class DirectionalLightShadow extends LightShadow {
  23280. constructor() {
  23281. super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  23282. }
  23283. }
  23284. DirectionalLightShadow.prototype.isDirectionalLightShadow = true;
  23285. class DirectionalLight extends Light {
  23286. constructor(color, intensity) {
  23287. super(color, intensity);
  23288. this.type = 'DirectionalLight';
  23289. this.position.copy(Object3D.DefaultUp);
  23290. this.updateMatrix();
  23291. this.target = new Object3D();
  23292. this.shadow = new DirectionalLightShadow();
  23293. }
  23294. dispose() {
  23295. this.shadow.dispose();
  23296. }
  23297. copy(source) {
  23298. super.copy(source);
  23299. this.target = source.target.clone();
  23300. this.shadow = source.shadow.clone();
  23301. return this;
  23302. }
  23303. }
  23304. DirectionalLight.prototype.isDirectionalLight = true;
  23305. class AmbientLight extends Light {
  23306. constructor(color, intensity) {
  23307. super(color, intensity);
  23308. this.type = 'AmbientLight';
  23309. }
  23310. }
  23311. AmbientLight.prototype.isAmbientLight = true;
  23312. class RectAreaLight extends Light {
  23313. constructor(color, intensity, width = 10, height = 10) {
  23314. super(color, intensity);
  23315. this.type = 'RectAreaLight';
  23316. this.width = width;
  23317. this.height = height;
  23318. }
  23319. get power() {
  23320. // compute the light's luminous power (in lumens) from its intensity (in nits)
  23321. return this.intensity * this.width * this.height * Math.PI;
  23322. }
  23323. set power(power) {
  23324. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  23325. this.intensity = power / (this.width * this.height * Math.PI);
  23326. }
  23327. copy(source) {
  23328. super.copy(source);
  23329. this.width = source.width;
  23330. this.height = source.height;
  23331. return this;
  23332. }
  23333. toJSON(meta) {
  23334. const data = super.toJSON(meta);
  23335. data.object.width = this.width;
  23336. data.object.height = this.height;
  23337. return data;
  23338. }
  23339. }
  23340. RectAreaLight.prototype.isRectAreaLight = true;
  23341. /**
  23342. * Primary reference:
  23343. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23344. *
  23345. * Secondary reference:
  23346. * https://www.ppsloan.org/publications/StupidSH36.pdf
  23347. */
  23348. // 3-band SH defined by 9 coefficients
  23349. class SphericalHarmonics3 {
  23350. constructor() {
  23351. this.coefficients = [];
  23352. for (let i = 0; i < 9; i++) {
  23353. this.coefficients.push(new Vector3());
  23354. }
  23355. }
  23356. set(coefficients) {
  23357. for (let i = 0; i < 9; i++) {
  23358. this.coefficients[i].copy(coefficients[i]);
  23359. }
  23360. return this;
  23361. }
  23362. zero() {
  23363. for (let i = 0; i < 9; i++) {
  23364. this.coefficients[i].set(0, 0, 0);
  23365. }
  23366. return this;
  23367. } // get the radiance in the direction of the normal
  23368. // target is a Vector3
  23369. getAt(normal, target) {
  23370. // normal is assumed to be unit length
  23371. const x = normal.x,
  23372. y = normal.y,
  23373. z = normal.z;
  23374. const coeff = this.coefficients; // band 0
  23375. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  23376. target.addScaledVector(coeff[1], 0.488603 * y);
  23377. target.addScaledVector(coeff[2], 0.488603 * z);
  23378. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  23379. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  23380. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  23381. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  23382. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  23383. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  23384. return target;
  23385. } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  23386. // target is a Vector3
  23387. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23388. getIrradianceAt(normal, target) {
  23389. // normal is assumed to be unit length
  23390. const x = normal.x,
  23391. y = normal.y,
  23392. z = normal.z;
  23393. const coeff = this.coefficients; // band 0
  23394. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  23395. // band 1
  23396. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  23397. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  23398. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  23399. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  23400. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  23401. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  23402. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  23403. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  23404. return target;
  23405. }
  23406. add(sh) {
  23407. for (let i = 0; i < 9; i++) {
  23408. this.coefficients[i].add(sh.coefficients[i]);
  23409. }
  23410. return this;
  23411. }
  23412. addScaledSH(sh, s) {
  23413. for (let i = 0; i < 9; i++) {
  23414. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  23415. }
  23416. return this;
  23417. }
  23418. scale(s) {
  23419. for (let i = 0; i < 9; i++) {
  23420. this.coefficients[i].multiplyScalar(s);
  23421. }
  23422. return this;
  23423. }
  23424. lerp(sh, alpha) {
  23425. for (let i = 0; i < 9; i++) {
  23426. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  23427. }
  23428. return this;
  23429. }
  23430. equals(sh) {
  23431. for (let i = 0; i < 9; i++) {
  23432. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  23433. return false;
  23434. }
  23435. }
  23436. return true;
  23437. }
  23438. copy(sh) {
  23439. return this.set(sh.coefficients);
  23440. }
  23441. clone() {
  23442. return new this.constructor().copy(this);
  23443. }
  23444. fromArray(array, offset = 0) {
  23445. const coefficients = this.coefficients;
  23446. for (let i = 0; i < 9; i++) {
  23447. coefficients[i].fromArray(array, offset + i * 3);
  23448. }
  23449. return this;
  23450. }
  23451. toArray(array = [], offset = 0) {
  23452. const coefficients = this.coefficients;
  23453. for (let i = 0; i < 9; i++) {
  23454. coefficients[i].toArray(array, offset + i * 3);
  23455. }
  23456. return array;
  23457. } // evaluate the basis functions
  23458. // shBasis is an Array[ 9 ]
  23459. static getBasisAt(normal, shBasis) {
  23460. // normal is assumed to be unit length
  23461. const x = normal.x,
  23462. y = normal.y,
  23463. z = normal.z; // band 0
  23464. shBasis[0] = 0.282095; // band 1
  23465. shBasis[1] = 0.488603 * y;
  23466. shBasis[2] = 0.488603 * z;
  23467. shBasis[3] = 0.488603 * x; // band 2
  23468. shBasis[4] = 1.092548 * x * y;
  23469. shBasis[5] = 1.092548 * y * z;
  23470. shBasis[6] = 0.315392 * (3 * z * z - 1);
  23471. shBasis[7] = 1.092548 * x * z;
  23472. shBasis[8] = 0.546274 * (x * x - y * y);
  23473. }
  23474. }
  23475. SphericalHarmonics3.prototype.isSphericalHarmonics3 = true;
  23476. class LightProbe extends Light {
  23477. constructor(sh = new SphericalHarmonics3(), intensity = 1) {
  23478. super(undefined, intensity);
  23479. this.sh = sh;
  23480. }
  23481. copy(source) {
  23482. super.copy(source);
  23483. this.sh.copy(source.sh);
  23484. return this;
  23485. }
  23486. fromJSON(json) {
  23487. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  23488. this.sh.fromArray(json.sh);
  23489. return this;
  23490. }
  23491. toJSON(meta) {
  23492. const data = super.toJSON(meta);
  23493. data.object.sh = this.sh.toArray();
  23494. return data;
  23495. }
  23496. }
  23497. LightProbe.prototype.isLightProbe = true;
  23498. class MaterialLoader extends Loader {
  23499. constructor(manager) {
  23500. super(manager);
  23501. this.textures = {};
  23502. }
  23503. load(url, onLoad, onProgress, onError) {
  23504. const scope = this;
  23505. const loader = new FileLoader(scope.manager);
  23506. loader.setPath(scope.path);
  23507. loader.setRequestHeader(scope.requestHeader);
  23508. loader.setWithCredentials(scope.withCredentials);
  23509. loader.load(url, function (text) {
  23510. try {
  23511. onLoad(scope.parse(JSON.parse(text)));
  23512. } catch (e) {
  23513. if (onError) {
  23514. onError(e);
  23515. } else {
  23516. console.error(e);
  23517. }
  23518. scope.manager.itemError(url);
  23519. }
  23520. }, onProgress, onError);
  23521. }
  23522. parse(json) {
  23523. const textures = this.textures;
  23524. function getTexture(name) {
  23525. if (textures[name] === undefined) {
  23526. console.warn('THREE.MaterialLoader: Undefined texture', name);
  23527. }
  23528. return textures[name];
  23529. }
  23530. const material = new Materials[json.type]();
  23531. if (json.uuid !== undefined) material.uuid = json.uuid;
  23532. if (json.name !== undefined) material.name = json.name;
  23533. if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
  23534. if (json.roughness !== undefined) material.roughness = json.roughness;
  23535. if (json.metalness !== undefined) material.metalness = json.metalness;
  23536. if (json.sheenTint !== undefined) material.sheenTint = new Color().setHex(json.sheenTint);
  23537. if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
  23538. if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
  23539. if (json.specularIntensity !== undefined) material.specularIntensity = json.specularIntensity;
  23540. if (json.specularTint !== undefined && material.specularTint !== undefined) material.specularTint.setHex(json.specularTint);
  23541. if (json.shininess !== undefined) material.shininess = json.shininess;
  23542. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  23543. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  23544. if (json.transmission !== undefined) material.transmission = json.transmission;
  23545. if (json.thickness !== undefined) material.thickness = json.thickness;
  23546. if (json.attenuationDistance !== undefined) material.attenuationDistance = json.attenuationDistance;
  23547. if (json.attenuationTint !== undefined && material.attenuationTint !== undefined) material.attenuationTint.setHex(json.attenuationTint);
  23548. if (json.fog !== undefined) material.fog = json.fog;
  23549. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  23550. if (json.blending !== undefined) material.blending = json.blending;
  23551. if (json.combine !== undefined) material.combine = json.combine;
  23552. if (json.side !== undefined) material.side = json.side;
  23553. if (json.shadowSide !== undefined) material.shadowSide = json.shadowSide;
  23554. if (json.opacity !== undefined) material.opacity = json.opacity;
  23555. if (json.format !== undefined) material.format = json.format;
  23556. if (json.transparent !== undefined) material.transparent = json.transparent;
  23557. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  23558. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  23559. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  23560. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  23561. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  23562. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  23563. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  23564. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  23565. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  23566. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  23567. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  23568. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  23569. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  23570. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  23571. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  23572. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  23573. if (json.rotation !== undefined) material.rotation = json.rotation;
  23574. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  23575. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  23576. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  23577. if (json.scale !== undefined) material.scale = json.scale;
  23578. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  23579. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  23580. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  23581. if (json.dithering !== undefined) material.dithering = json.dithering;
  23582. if (json.alphaToCoverage !== undefined) material.alphaToCoverage = json.alphaToCoverage;
  23583. if (json.premultipliedAlpha !== undefined) material.premultipliedAlpha = json.premultipliedAlpha;
  23584. if (json.visible !== undefined) material.visible = json.visible;
  23585. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  23586. if (json.userData !== undefined) material.userData = json.userData;
  23587. if (json.vertexColors !== undefined) {
  23588. if (typeof json.vertexColors === 'number') {
  23589. material.vertexColors = json.vertexColors > 0 ? true : false;
  23590. } else {
  23591. material.vertexColors = json.vertexColors;
  23592. }
  23593. } // Shader Material
  23594. if (json.uniforms !== undefined) {
  23595. for (const name in json.uniforms) {
  23596. const uniform = json.uniforms[name];
  23597. material.uniforms[name] = {};
  23598. switch (uniform.type) {
  23599. case 't':
  23600. material.uniforms[name].value = getTexture(uniform.value);
  23601. break;
  23602. case 'c':
  23603. material.uniforms[name].value = new Color().setHex(uniform.value);
  23604. break;
  23605. case 'v2':
  23606. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  23607. break;
  23608. case 'v3':
  23609. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  23610. break;
  23611. case 'v4':
  23612. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  23613. break;
  23614. case 'm3':
  23615. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  23616. break;
  23617. case 'm4':
  23618. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  23619. break;
  23620. default:
  23621. material.uniforms[name].value = uniform.value;
  23622. }
  23623. }
  23624. }
  23625. if (json.defines !== undefined) material.defines = json.defines;
  23626. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  23627. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  23628. if (json.extensions !== undefined) {
  23629. for (const key in json.extensions) {
  23630. material.extensions[key] = json.extensions[key];
  23631. }
  23632. } // Deprecated
  23633. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  23634. // for PointsMaterial
  23635. if (json.size !== undefined) material.size = json.size;
  23636. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  23637. if (json.map !== undefined) material.map = getTexture(json.map);
  23638. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  23639. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  23640. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  23641. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  23642. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  23643. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  23644. if (json.normalScale !== undefined) {
  23645. let normalScale = json.normalScale;
  23646. if (Array.isArray(normalScale) === false) {
  23647. // Blender exporter used to export a scalar. See #7459
  23648. normalScale = [normalScale, normalScale];
  23649. }
  23650. material.normalScale = new Vector2().fromArray(normalScale);
  23651. }
  23652. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  23653. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  23654. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  23655. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  23656. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  23657. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  23658. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  23659. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  23660. if (json.specularIntensityMap !== undefined) material.specularIntensityMap = getTexture(json.specularIntensityMap);
  23661. if (json.specularTintMap !== undefined) material.specularTintMap = getTexture(json.specularTintMap);
  23662. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  23663. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  23664. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  23665. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  23666. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  23667. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  23668. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  23669. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  23670. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  23671. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  23672. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  23673. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  23674. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  23675. if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
  23676. if (json.thicknessMap !== undefined) material.thicknessMap = getTexture(json.thicknessMap);
  23677. return material;
  23678. }
  23679. setTextures(value) {
  23680. this.textures = value;
  23681. return this;
  23682. }
  23683. }
  23684. class LoaderUtils {
  23685. static decodeText(array) {
  23686. if (typeof TextDecoder !== 'undefined') {
  23687. return new TextDecoder().decode(array);
  23688. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  23689. // throws a "maximum call stack size exceeded" error for large arrays.
  23690. let s = '';
  23691. for (let i = 0, il = array.length; i < il; i++) {
  23692. // Implicitly assumes little-endian.
  23693. s += String.fromCharCode(array[i]);
  23694. }
  23695. try {
  23696. // merges multi-byte utf-8 characters.
  23697. return decodeURIComponent(escape(s));
  23698. } catch (e) {
  23699. // see #16358
  23700. return s;
  23701. }
  23702. }
  23703. static extractUrlBase(url) {
  23704. const index = url.lastIndexOf('/');
  23705. if (index === -1) return './';
  23706. return url.substr(0, index + 1);
  23707. }
  23708. }
  23709. class InstancedBufferGeometry extends BufferGeometry {
  23710. constructor() {
  23711. super();
  23712. this.type = 'InstancedBufferGeometry';
  23713. this.instanceCount = Infinity;
  23714. }
  23715. copy(source) {
  23716. super.copy(source);
  23717. this.instanceCount = source.instanceCount;
  23718. return this;
  23719. }
  23720. clone() {
  23721. return new this.constructor().copy(this);
  23722. }
  23723. toJSON() {
  23724. const data = super.toJSON(this);
  23725. data.instanceCount = this.instanceCount;
  23726. data.isInstancedBufferGeometry = true;
  23727. return data;
  23728. }
  23729. }
  23730. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  23731. class BufferGeometryLoader extends Loader {
  23732. constructor(manager) {
  23733. super(manager);
  23734. }
  23735. load(url, onLoad, onProgress, onError) {
  23736. const scope = this;
  23737. const loader = new FileLoader(scope.manager);
  23738. loader.setPath(scope.path);
  23739. loader.setRequestHeader(scope.requestHeader);
  23740. loader.setWithCredentials(scope.withCredentials);
  23741. loader.load(url, function (text) {
  23742. try {
  23743. onLoad(scope.parse(JSON.parse(text)));
  23744. } catch (e) {
  23745. if (onError) {
  23746. onError(e);
  23747. } else {
  23748. console.error(e);
  23749. }
  23750. scope.manager.itemError(url);
  23751. }
  23752. }, onProgress, onError);
  23753. }
  23754. parse(json) {
  23755. const interleavedBufferMap = {};
  23756. const arrayBufferMap = {};
  23757. function getInterleavedBuffer(json, uuid) {
  23758. if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
  23759. const interleavedBuffers = json.interleavedBuffers;
  23760. const interleavedBuffer = interleavedBuffers[uuid];
  23761. const buffer = getArrayBuffer(json, interleavedBuffer.buffer);
  23762. const array = getTypedArray(interleavedBuffer.type, buffer);
  23763. const ib = new InterleavedBuffer(array, interleavedBuffer.stride);
  23764. ib.uuid = interleavedBuffer.uuid;
  23765. interleavedBufferMap[uuid] = ib;
  23766. return ib;
  23767. }
  23768. function getArrayBuffer(json, uuid) {
  23769. if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
  23770. const arrayBuffers = json.arrayBuffers;
  23771. const arrayBuffer = arrayBuffers[uuid];
  23772. const ab = new Uint32Array(arrayBuffer).buffer;
  23773. arrayBufferMap[uuid] = ab;
  23774. return ab;
  23775. }
  23776. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  23777. const index = json.data.index;
  23778. if (index !== undefined) {
  23779. const typedArray = getTypedArray(index.type, index.array);
  23780. geometry.setIndex(new BufferAttribute(typedArray, 1));
  23781. }
  23782. const attributes = json.data.attributes;
  23783. for (const key in attributes) {
  23784. const attribute = attributes[key];
  23785. let bufferAttribute;
  23786. if (attribute.isInterleavedBufferAttribute) {
  23787. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  23788. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  23789. } else {
  23790. const typedArray = getTypedArray(attribute.type, attribute.array);
  23791. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  23792. bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  23793. }
  23794. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  23795. if (attribute.usage !== undefined) bufferAttribute.setUsage(attribute.usage);
  23796. if (attribute.updateRange !== undefined) {
  23797. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  23798. bufferAttribute.updateRange.count = attribute.updateRange.count;
  23799. }
  23800. geometry.setAttribute(key, bufferAttribute);
  23801. }
  23802. const morphAttributes = json.data.morphAttributes;
  23803. if (morphAttributes) {
  23804. for (const key in morphAttributes) {
  23805. const attributeArray = morphAttributes[key];
  23806. const array = [];
  23807. for (let i = 0, il = attributeArray.length; i < il; i++) {
  23808. const attribute = attributeArray[i];
  23809. let bufferAttribute;
  23810. if (attribute.isInterleavedBufferAttribute) {
  23811. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  23812. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  23813. } else {
  23814. const typedArray = getTypedArray(attribute.type, attribute.array);
  23815. bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  23816. }
  23817. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  23818. array.push(bufferAttribute);
  23819. }
  23820. geometry.morphAttributes[key] = array;
  23821. }
  23822. }
  23823. const morphTargetsRelative = json.data.morphTargetsRelative;
  23824. if (morphTargetsRelative) {
  23825. geometry.morphTargetsRelative = true;
  23826. }
  23827. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  23828. if (groups !== undefined) {
  23829. for (let i = 0, n = groups.length; i !== n; ++i) {
  23830. const group = groups[i];
  23831. geometry.addGroup(group.start, group.count, group.materialIndex);
  23832. }
  23833. }
  23834. const boundingSphere = json.data.boundingSphere;
  23835. if (boundingSphere !== undefined) {
  23836. const center = new Vector3();
  23837. if (boundingSphere.center !== undefined) {
  23838. center.fromArray(boundingSphere.center);
  23839. }
  23840. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  23841. }
  23842. if (json.name) geometry.name = json.name;
  23843. if (json.userData) geometry.userData = json.userData;
  23844. return geometry;
  23845. }
  23846. }
  23847. class ObjectLoader extends Loader {
  23848. constructor(manager) {
  23849. super(manager);
  23850. }
  23851. load(url, onLoad, onProgress, onError) {
  23852. const scope = this;
  23853. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  23854. this.resourcePath = this.resourcePath || path;
  23855. const loader = new FileLoader(this.manager);
  23856. loader.setPath(this.path);
  23857. loader.setRequestHeader(this.requestHeader);
  23858. loader.setWithCredentials(this.withCredentials);
  23859. loader.load(url, function (text) {
  23860. let json = null;
  23861. try {
  23862. json = JSON.parse(text);
  23863. } catch (error) {
  23864. if (onError !== undefined) onError(error);
  23865. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  23866. return;
  23867. }
  23868. const metadata = json.metadata;
  23869. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  23870. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  23871. return;
  23872. }
  23873. scope.parse(json, onLoad);
  23874. }, onProgress, onError);
  23875. }
  23876. async loadAsync(url, onProgress) {
  23877. const scope = this;
  23878. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  23879. this.resourcePath = this.resourcePath || path;
  23880. const loader = new FileLoader(this.manager);
  23881. loader.setPath(this.path);
  23882. loader.setRequestHeader(this.requestHeader);
  23883. loader.setWithCredentials(this.withCredentials);
  23884. const text = await loader.loadAsync(url, onProgress);
  23885. const json = JSON.parse(text);
  23886. const metadata = json.metadata;
  23887. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  23888. throw new Error('THREE.ObjectLoader: Can\'t load ' + url);
  23889. }
  23890. return await scope.parseAsync(json);
  23891. }
  23892. parse(json, onLoad) {
  23893. const animations = this.parseAnimations(json.animations);
  23894. const shapes = this.parseShapes(json.shapes);
  23895. const geometries = this.parseGeometries(json.geometries, shapes);
  23896. const images = this.parseImages(json.images, function () {
  23897. if (onLoad !== undefined) onLoad(object);
  23898. });
  23899. const textures = this.parseTextures(json.textures, images);
  23900. const materials = this.parseMaterials(json.materials, textures);
  23901. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  23902. const skeletons = this.parseSkeletons(json.skeletons, object);
  23903. this.bindSkeletons(object, skeletons); //
  23904. if (onLoad !== undefined) {
  23905. let hasImages = false;
  23906. for (const uuid in images) {
  23907. if (images[uuid] instanceof HTMLImageElement) {
  23908. hasImages = true;
  23909. break;
  23910. }
  23911. }
  23912. if (hasImages === false) onLoad(object);
  23913. }
  23914. return object;
  23915. }
  23916. async parseAsync(json) {
  23917. const animations = this.parseAnimations(json.animations);
  23918. const shapes = this.parseShapes(json.shapes);
  23919. const geometries = this.parseGeometries(json.geometries, shapes);
  23920. const images = await this.parseImagesAsync(json.images);
  23921. const textures = this.parseTextures(json.textures, images);
  23922. const materials = this.parseMaterials(json.materials, textures);
  23923. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  23924. const skeletons = this.parseSkeletons(json.skeletons, object);
  23925. this.bindSkeletons(object, skeletons);
  23926. return object;
  23927. }
  23928. parseShapes(json) {
  23929. const shapes = {};
  23930. if (json !== undefined) {
  23931. for (let i = 0, l = json.length; i < l; i++) {
  23932. const shape = new Shape().fromJSON(json[i]);
  23933. shapes[shape.uuid] = shape;
  23934. }
  23935. }
  23936. return shapes;
  23937. }
  23938. parseSkeletons(json, object) {
  23939. const skeletons = {};
  23940. const bones = {}; // generate bone lookup table
  23941. object.traverse(function (child) {
  23942. if (child.isBone) bones[child.uuid] = child;
  23943. }); // create skeletons
  23944. if (json !== undefined) {
  23945. for (let i = 0, l = json.length; i < l; i++) {
  23946. const skeleton = new Skeleton().fromJSON(json[i], bones);
  23947. skeletons[skeleton.uuid] = skeleton;
  23948. }
  23949. }
  23950. return skeletons;
  23951. }
  23952. parseGeometries(json, shapes) {
  23953. const geometries = {};
  23954. if (json !== undefined) {
  23955. const bufferGeometryLoader = new BufferGeometryLoader();
  23956. for (let i = 0, l = json.length; i < l; i++) {
  23957. let geometry;
  23958. const data = json[i];
  23959. switch (data.type) {
  23960. case 'BufferGeometry':
  23961. case 'InstancedBufferGeometry':
  23962. geometry = bufferGeometryLoader.parse(data);
  23963. break;
  23964. case 'Geometry':
  23965. console.error('THREE.ObjectLoader: The legacy Geometry type is no longer supported.');
  23966. break;
  23967. default:
  23968. if (data.type in Geometries) {
  23969. geometry = Geometries[data.type].fromJSON(data, shapes);
  23970. } else {
  23971. console.warn(`THREE.ObjectLoader: Unsupported geometry type "${data.type}"`);
  23972. }
  23973. }
  23974. geometry.uuid = data.uuid;
  23975. if (data.name !== undefined) geometry.name = data.name;
  23976. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  23977. geometries[data.uuid] = geometry;
  23978. }
  23979. }
  23980. return geometries;
  23981. }
  23982. parseMaterials(json, textures) {
  23983. const cache = {}; // MultiMaterial
  23984. const materials = {};
  23985. if (json !== undefined) {
  23986. const loader = new MaterialLoader();
  23987. loader.setTextures(textures);
  23988. for (let i = 0, l = json.length; i < l; i++) {
  23989. const data = json[i];
  23990. if (data.type === 'MultiMaterial') {
  23991. // Deprecated
  23992. const array = [];
  23993. for (let j = 0; j < data.materials.length; j++) {
  23994. const material = data.materials[j];
  23995. if (cache[material.uuid] === undefined) {
  23996. cache[material.uuid] = loader.parse(material);
  23997. }
  23998. array.push(cache[material.uuid]);
  23999. }
  24000. materials[data.uuid] = array;
  24001. } else {
  24002. if (cache[data.uuid] === undefined) {
  24003. cache[data.uuid] = loader.parse(data);
  24004. }
  24005. materials[data.uuid] = cache[data.uuid];
  24006. }
  24007. }
  24008. }
  24009. return materials;
  24010. }
  24011. parseAnimations(json) {
  24012. const animations = {};
  24013. if (json !== undefined) {
  24014. for (let i = 0; i < json.length; i++) {
  24015. const data = json[i];
  24016. const clip = AnimationClip.parse(data);
  24017. animations[clip.uuid] = clip;
  24018. }
  24019. }
  24020. return animations;
  24021. }
  24022. parseImages(json, onLoad) {
  24023. const scope = this;
  24024. const images = {};
  24025. let loader;
  24026. function loadImage(url) {
  24027. scope.manager.itemStart(url);
  24028. return loader.load(url, function () {
  24029. scope.manager.itemEnd(url);
  24030. }, undefined, function () {
  24031. scope.manager.itemError(url);
  24032. scope.manager.itemEnd(url);
  24033. });
  24034. }
  24035. function deserializeImage(image) {
  24036. if (typeof image === 'string') {
  24037. const url = image;
  24038. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  24039. return loadImage(path);
  24040. } else {
  24041. if (image.data) {
  24042. return {
  24043. data: getTypedArray(image.type, image.data),
  24044. width: image.width,
  24045. height: image.height
  24046. };
  24047. } else {
  24048. return null;
  24049. }
  24050. }
  24051. }
  24052. if (json !== undefined && json.length > 0) {
  24053. const manager = new LoadingManager(onLoad);
  24054. loader = new ImageLoader(manager);
  24055. loader.setCrossOrigin(this.crossOrigin);
  24056. for (let i = 0, il = json.length; i < il; i++) {
  24057. const image = json[i];
  24058. const url = image.url;
  24059. if (Array.isArray(url)) {
  24060. // load array of images e.g CubeTexture
  24061. images[image.uuid] = [];
  24062. for (let j = 0, jl = url.length; j < jl; j++) {
  24063. const currentUrl = url[j];
  24064. const deserializedImage = deserializeImage(currentUrl);
  24065. if (deserializedImage !== null) {
  24066. if (deserializedImage instanceof HTMLImageElement) {
  24067. images[image.uuid].push(deserializedImage);
  24068. } else {
  24069. // special case: handle array of data textures for cube textures
  24070. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  24071. }
  24072. }
  24073. }
  24074. } else {
  24075. // load single image
  24076. const deserializedImage = deserializeImage(image.url);
  24077. if (deserializedImage !== null) {
  24078. images[image.uuid] = deserializedImage;
  24079. }
  24080. }
  24081. }
  24082. }
  24083. return images;
  24084. }
  24085. async parseImagesAsync(json) {
  24086. const scope = this;
  24087. const images = {};
  24088. let loader;
  24089. async function deserializeImage(image) {
  24090. if (typeof image === 'string') {
  24091. const url = image;
  24092. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  24093. return await loader.loadAsync(path);
  24094. } else {
  24095. if (image.data) {
  24096. return {
  24097. data: getTypedArray(image.type, image.data),
  24098. width: image.width,
  24099. height: image.height
  24100. };
  24101. } else {
  24102. return null;
  24103. }
  24104. }
  24105. }
  24106. if (json !== undefined && json.length > 0) {
  24107. loader = new ImageLoader(this.manager);
  24108. loader.setCrossOrigin(this.crossOrigin);
  24109. for (let i = 0, il = json.length; i < il; i++) {
  24110. const image = json[i];
  24111. const url = image.url;
  24112. if (Array.isArray(url)) {
  24113. // load array of images e.g CubeTexture
  24114. images[image.uuid] = [];
  24115. for (let j = 0, jl = url.length; j < jl; j++) {
  24116. const currentUrl = url[j];
  24117. const deserializedImage = await deserializeImage(currentUrl);
  24118. if (deserializedImage !== null) {
  24119. if (deserializedImage instanceof HTMLImageElement) {
  24120. images[image.uuid].push(deserializedImage);
  24121. } else {
  24122. // special case: handle array of data textures for cube textures
  24123. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  24124. }
  24125. }
  24126. }
  24127. } else {
  24128. // load single image
  24129. const deserializedImage = await deserializeImage(image.url);
  24130. if (deserializedImage !== null) {
  24131. images[image.uuid] = deserializedImage;
  24132. }
  24133. }
  24134. }
  24135. }
  24136. return images;
  24137. }
  24138. parseTextures(json, images) {
  24139. function parseConstant(value, type) {
  24140. if (typeof value === 'number') return value;
  24141. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  24142. return type[value];
  24143. }
  24144. const textures = {};
  24145. if (json !== undefined) {
  24146. for (let i = 0, l = json.length; i < l; i++) {
  24147. const data = json[i];
  24148. if (data.image === undefined) {
  24149. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  24150. }
  24151. if (images[data.image] === undefined) {
  24152. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  24153. }
  24154. let texture;
  24155. const image = images[data.image];
  24156. if (Array.isArray(image)) {
  24157. texture = new CubeTexture(image);
  24158. if (image.length === 6) texture.needsUpdate = true;
  24159. } else {
  24160. if (image && image.data) {
  24161. texture = new DataTexture(image.data, image.width, image.height);
  24162. } else {
  24163. texture = new Texture(image);
  24164. }
  24165. if (image) texture.needsUpdate = true; // textures can have undefined image data
  24166. }
  24167. texture.uuid = data.uuid;
  24168. if (data.name !== undefined) texture.name = data.name;
  24169. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  24170. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  24171. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  24172. if (data.center !== undefined) texture.center.fromArray(data.center);
  24173. if (data.rotation !== undefined) texture.rotation = data.rotation;
  24174. if (data.wrap !== undefined) {
  24175. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  24176. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  24177. }
  24178. if (data.format !== undefined) texture.format = data.format;
  24179. if (data.type !== undefined) texture.type = data.type;
  24180. if (data.encoding !== undefined) texture.encoding = data.encoding;
  24181. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  24182. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  24183. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  24184. if (data.flipY !== undefined) texture.flipY = data.flipY;
  24185. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  24186. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  24187. textures[data.uuid] = texture;
  24188. }
  24189. }
  24190. return textures;
  24191. }
  24192. parseObject(data, geometries, materials, textures, animations) {
  24193. let object;
  24194. function getGeometry(name) {
  24195. if (geometries[name] === undefined) {
  24196. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  24197. }
  24198. return geometries[name];
  24199. }
  24200. function getMaterial(name) {
  24201. if (name === undefined) return undefined;
  24202. if (Array.isArray(name)) {
  24203. const array = [];
  24204. for (let i = 0, l = name.length; i < l; i++) {
  24205. const uuid = name[i];
  24206. if (materials[uuid] === undefined) {
  24207. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  24208. }
  24209. array.push(materials[uuid]);
  24210. }
  24211. return array;
  24212. }
  24213. if (materials[name] === undefined) {
  24214. console.warn('THREE.ObjectLoader: Undefined material', name);
  24215. }
  24216. return materials[name];
  24217. }
  24218. function getTexture(uuid) {
  24219. if (textures[uuid] === undefined) {
  24220. console.warn('THREE.ObjectLoader: Undefined texture', uuid);
  24221. }
  24222. return textures[uuid];
  24223. }
  24224. let geometry, material;
  24225. switch (data.type) {
  24226. case 'Scene':
  24227. object = new Scene();
  24228. if (data.background !== undefined) {
  24229. if (Number.isInteger(data.background)) {
  24230. object.background = new Color(data.background);
  24231. } else {
  24232. object.background = getTexture(data.background);
  24233. }
  24234. }
  24235. if (data.environment !== undefined) {
  24236. object.environment = getTexture(data.environment);
  24237. }
  24238. if (data.fog !== undefined) {
  24239. if (data.fog.type === 'Fog') {
  24240. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  24241. } else if (data.fog.type === 'FogExp2') {
  24242. object.fog = new FogExp2(data.fog.color, data.fog.density);
  24243. }
  24244. }
  24245. break;
  24246. case 'PerspectiveCamera':
  24247. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  24248. if (data.focus !== undefined) object.focus = data.focus;
  24249. if (data.zoom !== undefined) object.zoom = data.zoom;
  24250. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  24251. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  24252. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24253. break;
  24254. case 'OrthographicCamera':
  24255. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  24256. if (data.zoom !== undefined) object.zoom = data.zoom;
  24257. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24258. break;
  24259. case 'AmbientLight':
  24260. object = new AmbientLight(data.color, data.intensity);
  24261. break;
  24262. case 'DirectionalLight':
  24263. object = new DirectionalLight(data.color, data.intensity);
  24264. break;
  24265. case 'PointLight':
  24266. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  24267. break;
  24268. case 'RectAreaLight':
  24269. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  24270. break;
  24271. case 'SpotLight':
  24272. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  24273. break;
  24274. case 'HemisphereLight':
  24275. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  24276. break;
  24277. case 'LightProbe':
  24278. object = new LightProbe().fromJSON(data);
  24279. break;
  24280. case 'SkinnedMesh':
  24281. geometry = getGeometry(data.geometry);
  24282. material = getMaterial(data.material);
  24283. object = new SkinnedMesh(geometry, material);
  24284. if (data.bindMode !== undefined) object.bindMode = data.bindMode;
  24285. if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
  24286. if (data.skeleton !== undefined) object.skeleton = data.skeleton;
  24287. break;
  24288. case 'Mesh':
  24289. geometry = getGeometry(data.geometry);
  24290. material = getMaterial(data.material);
  24291. object = new Mesh(geometry, material);
  24292. break;
  24293. case 'InstancedMesh':
  24294. geometry = getGeometry(data.geometry);
  24295. material = getMaterial(data.material);
  24296. const count = data.count;
  24297. const instanceMatrix = data.instanceMatrix;
  24298. const instanceColor = data.instanceColor;
  24299. object = new InstancedMesh(geometry, material, count);
  24300. object.instanceMatrix = new InstancedBufferAttribute(new Float32Array(instanceMatrix.array), 16);
  24301. if (instanceColor !== undefined) object.instanceColor = new InstancedBufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize);
  24302. break;
  24303. case 'LOD':
  24304. object = new LOD();
  24305. break;
  24306. case 'Line':
  24307. object = new Line(getGeometry(data.geometry), getMaterial(data.material));
  24308. break;
  24309. case 'LineLoop':
  24310. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  24311. break;
  24312. case 'LineSegments':
  24313. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  24314. break;
  24315. case 'PointCloud':
  24316. case 'Points':
  24317. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  24318. break;
  24319. case 'Sprite':
  24320. object = new Sprite(getMaterial(data.material));
  24321. break;
  24322. case 'Group':
  24323. object = new Group();
  24324. break;
  24325. case 'Bone':
  24326. object = new Bone();
  24327. break;
  24328. default:
  24329. object = new Object3D();
  24330. }
  24331. object.uuid = data.uuid;
  24332. if (data.name !== undefined) object.name = data.name;
  24333. if (data.matrix !== undefined) {
  24334. object.matrix.fromArray(data.matrix);
  24335. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  24336. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  24337. } else {
  24338. if (data.position !== undefined) object.position.fromArray(data.position);
  24339. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  24340. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  24341. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  24342. }
  24343. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  24344. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  24345. if (data.shadow) {
  24346. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  24347. if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
  24348. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  24349. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  24350. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  24351. }
  24352. if (data.visible !== undefined) object.visible = data.visible;
  24353. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  24354. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  24355. if (data.userData !== undefined) object.userData = data.userData;
  24356. if (data.layers !== undefined) object.layers.mask = data.layers;
  24357. if (data.children !== undefined) {
  24358. const children = data.children;
  24359. for (let i = 0; i < children.length; i++) {
  24360. object.add(this.parseObject(children[i], geometries, materials, textures, animations));
  24361. }
  24362. }
  24363. if (data.animations !== undefined) {
  24364. const objectAnimations = data.animations;
  24365. for (let i = 0; i < objectAnimations.length; i++) {
  24366. const uuid = objectAnimations[i];
  24367. object.animations.push(animations[uuid]);
  24368. }
  24369. }
  24370. if (data.type === 'LOD') {
  24371. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  24372. const levels = data.levels;
  24373. for (let l = 0; l < levels.length; l++) {
  24374. const level = levels[l];
  24375. const child = object.getObjectByProperty('uuid', level.object);
  24376. if (child !== undefined) {
  24377. object.addLevel(child, level.distance);
  24378. }
  24379. }
  24380. }
  24381. return object;
  24382. }
  24383. bindSkeletons(object, skeletons) {
  24384. if (Object.keys(skeletons).length === 0) return;
  24385. object.traverse(function (child) {
  24386. if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
  24387. const skeleton = skeletons[child.skeleton];
  24388. if (skeleton === undefined) {
  24389. console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
  24390. } else {
  24391. child.bind(skeleton, child.bindMatrix);
  24392. }
  24393. }
  24394. });
  24395. }
  24396. /* DEPRECATED */
  24397. setTexturePath(value) {
  24398. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  24399. return this.setResourcePath(value);
  24400. }
  24401. }
  24402. const TEXTURE_MAPPING = {
  24403. UVMapping: UVMapping,
  24404. CubeReflectionMapping: CubeReflectionMapping,
  24405. CubeRefractionMapping: CubeRefractionMapping,
  24406. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  24407. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  24408. CubeUVReflectionMapping: CubeUVReflectionMapping,
  24409. CubeUVRefractionMapping: CubeUVRefractionMapping
  24410. };
  24411. const TEXTURE_WRAPPING = {
  24412. RepeatWrapping: RepeatWrapping,
  24413. ClampToEdgeWrapping: ClampToEdgeWrapping,
  24414. MirroredRepeatWrapping: MirroredRepeatWrapping
  24415. };
  24416. const TEXTURE_FILTER = {
  24417. NearestFilter: NearestFilter,
  24418. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  24419. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  24420. LinearFilter: LinearFilter,
  24421. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  24422. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  24423. };
  24424. class ImageBitmapLoader extends Loader {
  24425. constructor(manager) {
  24426. super(manager);
  24427. if (typeof createImageBitmap === 'undefined') {
  24428. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  24429. }
  24430. if (typeof fetch === 'undefined') {
  24431. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  24432. }
  24433. this.options = {
  24434. premultiplyAlpha: 'none'
  24435. };
  24436. }
  24437. setOptions(options) {
  24438. this.options = options;
  24439. return this;
  24440. }
  24441. load(url, onLoad, onProgress, onError) {
  24442. if (url === undefined) url = '';
  24443. if (this.path !== undefined) url = this.path + url;
  24444. url = this.manager.resolveURL(url);
  24445. const scope = this;
  24446. const cached = Cache.get(url);
  24447. if (cached !== undefined) {
  24448. scope.manager.itemStart(url);
  24449. setTimeout(function () {
  24450. if (onLoad) onLoad(cached);
  24451. scope.manager.itemEnd(url);
  24452. }, 0);
  24453. return cached;
  24454. }
  24455. const fetchOptions = {};
  24456. fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
  24457. fetchOptions.headers = this.requestHeader;
  24458. fetch(url, fetchOptions).then(function (res) {
  24459. return res.blob();
  24460. }).then(function (blob) {
  24461. return createImageBitmap(blob, Object.assign(scope.options, {
  24462. colorSpaceConversion: 'none'
  24463. }));
  24464. }).then(function (imageBitmap) {
  24465. Cache.add(url, imageBitmap);
  24466. if (onLoad) onLoad(imageBitmap);
  24467. scope.manager.itemEnd(url);
  24468. }).catch(function (e) {
  24469. if (onError) onError(e);
  24470. scope.manager.itemError(url);
  24471. scope.manager.itemEnd(url);
  24472. });
  24473. scope.manager.itemStart(url);
  24474. }
  24475. }
  24476. ImageBitmapLoader.prototype.isImageBitmapLoader = true;
  24477. class ShapePath {
  24478. constructor() {
  24479. this.type = 'ShapePath';
  24480. this.color = new Color();
  24481. this.subPaths = [];
  24482. this.currentPath = null;
  24483. }
  24484. moveTo(x, y) {
  24485. this.currentPath = new Path();
  24486. this.subPaths.push(this.currentPath);
  24487. this.currentPath.moveTo(x, y);
  24488. return this;
  24489. }
  24490. lineTo(x, y) {
  24491. this.currentPath.lineTo(x, y);
  24492. return this;
  24493. }
  24494. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  24495. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  24496. return this;
  24497. }
  24498. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  24499. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  24500. return this;
  24501. }
  24502. splineThru(pts) {
  24503. this.currentPath.splineThru(pts);
  24504. return this;
  24505. }
  24506. toShapes(isCCW, noHoles) {
  24507. function toShapesNoHoles(inSubpaths) {
  24508. const shapes = [];
  24509. for (let i = 0, l = inSubpaths.length; i < l; i++) {
  24510. const tmpPath = inSubpaths[i];
  24511. const tmpShape = new Shape();
  24512. tmpShape.curves = tmpPath.curves;
  24513. shapes.push(tmpShape);
  24514. }
  24515. return shapes;
  24516. }
  24517. function isPointInsidePolygon(inPt, inPolygon) {
  24518. const polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  24519. // toggling of inside/outside at every single! intersection point of an edge
  24520. // with the horizontal line through inPt, left of inPt
  24521. // not counting lowerY endpoints of edges and whole edges on that line
  24522. let inside = false;
  24523. for (let p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  24524. let edgeLowPt = inPolygon[p];
  24525. let edgeHighPt = inPolygon[q];
  24526. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  24527. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  24528. if (Math.abs(edgeDy) > Number.EPSILON) {
  24529. // not parallel
  24530. if (edgeDy < 0) {
  24531. edgeLowPt = inPolygon[q];
  24532. edgeDx = -edgeDx;
  24533. edgeHighPt = inPolygon[p];
  24534. edgeDy = -edgeDy;
  24535. }
  24536. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  24537. if (inPt.y === edgeLowPt.y) {
  24538. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  24539. // continue; // no intersection or edgeLowPt => doesn't count !!!
  24540. } else {
  24541. const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  24542. if (perpEdge === 0) return true; // inPt is on contour ?
  24543. if (perpEdge < 0) continue;
  24544. inside = !inside; // true intersection left of inPt
  24545. }
  24546. } else {
  24547. // parallel or collinear
  24548. if (inPt.y !== edgeLowPt.y) continue; // parallel
  24549. // edge lies on the same horizontal line as inPt
  24550. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  24551. // continue;
  24552. }
  24553. }
  24554. return inside;
  24555. }
  24556. const isClockWise = ShapeUtils.isClockWise;
  24557. const subPaths = this.subPaths;
  24558. if (subPaths.length === 0) return [];
  24559. if (noHoles === true) return toShapesNoHoles(subPaths);
  24560. let solid, tmpPath, tmpShape;
  24561. const shapes = [];
  24562. if (subPaths.length === 1) {
  24563. tmpPath = subPaths[0];
  24564. tmpShape = new Shape();
  24565. tmpShape.curves = tmpPath.curves;
  24566. shapes.push(tmpShape);
  24567. return shapes;
  24568. }
  24569. let holesFirst = !isClockWise(subPaths[0].getPoints());
  24570. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  24571. const betterShapeHoles = [];
  24572. const newShapes = [];
  24573. let newShapeHoles = [];
  24574. let mainIdx = 0;
  24575. let tmpPoints;
  24576. newShapes[mainIdx] = undefined;
  24577. newShapeHoles[mainIdx] = [];
  24578. for (let i = 0, l = subPaths.length; i < l; i++) {
  24579. tmpPath = subPaths[i];
  24580. tmpPoints = tmpPath.getPoints();
  24581. solid = isClockWise(tmpPoints);
  24582. solid = isCCW ? !solid : solid;
  24583. if (solid) {
  24584. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  24585. newShapes[mainIdx] = {
  24586. s: new Shape(),
  24587. p: tmpPoints
  24588. };
  24589. newShapes[mainIdx].s.curves = tmpPath.curves;
  24590. if (holesFirst) mainIdx++;
  24591. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  24592. } else {
  24593. newShapeHoles[mainIdx].push({
  24594. h: tmpPath,
  24595. p: tmpPoints[0]
  24596. }); //console.log('ccw', i);
  24597. }
  24598. } // only Holes? -> probably all Shapes with wrong orientation
  24599. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  24600. if (newShapes.length > 1) {
  24601. let ambiguous = false;
  24602. const toChange = [];
  24603. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  24604. betterShapeHoles[sIdx] = [];
  24605. }
  24606. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  24607. const sho = newShapeHoles[sIdx];
  24608. for (let hIdx = 0; hIdx < sho.length; hIdx++) {
  24609. const ho = sho[hIdx];
  24610. let hole_unassigned = true;
  24611. for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  24612. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  24613. if (sIdx !== s2Idx) toChange.push({
  24614. froms: sIdx,
  24615. tos: s2Idx,
  24616. hole: hIdx
  24617. });
  24618. if (hole_unassigned) {
  24619. hole_unassigned = false;
  24620. betterShapeHoles[s2Idx].push(ho);
  24621. } else {
  24622. ambiguous = true;
  24623. }
  24624. }
  24625. }
  24626. if (hole_unassigned) {
  24627. betterShapeHoles[sIdx].push(ho);
  24628. }
  24629. }
  24630. } // console.log("ambiguous: ", ambiguous);
  24631. if (toChange.length > 0) {
  24632. // console.log("to change: ", toChange);
  24633. if (!ambiguous) newShapeHoles = betterShapeHoles;
  24634. }
  24635. }
  24636. let tmpHoles;
  24637. for (let i = 0, il = newShapes.length; i < il; i++) {
  24638. tmpShape = newShapes[i].s;
  24639. shapes.push(tmpShape);
  24640. tmpHoles = newShapeHoles[i];
  24641. for (let j = 0, jl = tmpHoles.length; j < jl; j++) {
  24642. tmpShape.holes.push(tmpHoles[j].h);
  24643. }
  24644. } //console.log("shape", shapes);
  24645. return shapes;
  24646. }
  24647. }
  24648. class Font {
  24649. constructor(data) {
  24650. this.type = 'Font';
  24651. this.data = data;
  24652. }
  24653. generateShapes(text, size = 100) {
  24654. const shapes = [];
  24655. const paths = createPaths(text, size, this.data);
  24656. for (let p = 0, pl = paths.length; p < pl; p++) {
  24657. Array.prototype.push.apply(shapes, paths[p].toShapes());
  24658. }
  24659. return shapes;
  24660. }
  24661. }
  24662. function createPaths(text, size, data) {
  24663. const chars = Array.from(text);
  24664. const scale = size / data.resolution;
  24665. const line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
  24666. const paths = [];
  24667. let offsetX = 0,
  24668. offsetY = 0;
  24669. for (let i = 0; i < chars.length; i++) {
  24670. const char = chars[i];
  24671. if (char === '\n') {
  24672. offsetX = 0;
  24673. offsetY -= line_height;
  24674. } else {
  24675. const ret = createPath(char, scale, offsetX, offsetY, data);
  24676. offsetX += ret.offsetX;
  24677. paths.push(ret.path);
  24678. }
  24679. }
  24680. return paths;
  24681. }
  24682. function createPath(char, scale, offsetX, offsetY, data) {
  24683. const glyph = data.glyphs[char] || data.glyphs['?'];
  24684. if (!glyph) {
  24685. console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
  24686. return;
  24687. }
  24688. const path = new ShapePath();
  24689. let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  24690. if (glyph.o) {
  24691. const outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
  24692. for (let i = 0, l = outline.length; i < l;) {
  24693. const action = outline[i++];
  24694. switch (action) {
  24695. case 'm':
  24696. // moveTo
  24697. x = outline[i++] * scale + offsetX;
  24698. y = outline[i++] * scale + offsetY;
  24699. path.moveTo(x, y);
  24700. break;
  24701. case 'l':
  24702. // lineTo
  24703. x = outline[i++] * scale + offsetX;
  24704. y = outline[i++] * scale + offsetY;
  24705. path.lineTo(x, y);
  24706. break;
  24707. case 'q':
  24708. // quadraticCurveTo
  24709. cpx = outline[i++] * scale + offsetX;
  24710. cpy = outline[i++] * scale + offsetY;
  24711. cpx1 = outline[i++] * scale + offsetX;
  24712. cpy1 = outline[i++] * scale + offsetY;
  24713. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  24714. break;
  24715. case 'b':
  24716. // bezierCurveTo
  24717. cpx = outline[i++] * scale + offsetX;
  24718. cpy = outline[i++] * scale + offsetY;
  24719. cpx1 = outline[i++] * scale + offsetX;
  24720. cpy1 = outline[i++] * scale + offsetY;
  24721. cpx2 = outline[i++] * scale + offsetX;
  24722. cpy2 = outline[i++] * scale + offsetY;
  24723. path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
  24724. break;
  24725. }
  24726. }
  24727. }
  24728. return {
  24729. offsetX: glyph.ha * scale,
  24730. path: path
  24731. };
  24732. }
  24733. Font.prototype.isFont = true;
  24734. class FontLoader extends Loader {
  24735. constructor(manager) {
  24736. super(manager);
  24737. }
  24738. load(url, onLoad, onProgress, onError) {
  24739. const scope = this;
  24740. const loader = new FileLoader(this.manager);
  24741. loader.setPath(this.path);
  24742. loader.setRequestHeader(this.requestHeader);
  24743. loader.setWithCredentials(scope.withCredentials);
  24744. loader.load(url, function (text) {
  24745. let json;
  24746. try {
  24747. json = JSON.parse(text);
  24748. } catch (e) {
  24749. console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
  24750. json = JSON.parse(text.substring(65, text.length - 2));
  24751. }
  24752. const font = scope.parse(json);
  24753. if (onLoad) onLoad(font);
  24754. }, onProgress, onError);
  24755. }
  24756. parse(json) {
  24757. return new Font(json);
  24758. }
  24759. }
  24760. let _context;
  24761. const AudioContext = {
  24762. getContext: function () {
  24763. if (_context === undefined) {
  24764. _context = new (window.AudioContext || window.webkitAudioContext)();
  24765. }
  24766. return _context;
  24767. },
  24768. setContext: function (value) {
  24769. _context = value;
  24770. }
  24771. };
  24772. class AudioLoader extends Loader {
  24773. constructor(manager) {
  24774. super(manager);
  24775. }
  24776. load(url, onLoad, onProgress, onError) {
  24777. const scope = this;
  24778. const loader = new FileLoader(this.manager);
  24779. loader.setResponseType('arraybuffer');
  24780. loader.setPath(this.path);
  24781. loader.setRequestHeader(this.requestHeader);
  24782. loader.setWithCredentials(this.withCredentials);
  24783. loader.load(url, function (buffer) {
  24784. try {
  24785. // Create a copy of the buffer. The `decodeAudioData` method
  24786. // detaches the buffer when complete, preventing reuse.
  24787. const bufferCopy = buffer.slice(0);
  24788. const context = AudioContext.getContext();
  24789. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  24790. onLoad(audioBuffer);
  24791. });
  24792. } catch (e) {
  24793. if (onError) {
  24794. onError(e);
  24795. } else {
  24796. console.error(e);
  24797. }
  24798. scope.manager.itemError(url);
  24799. }
  24800. }, onProgress, onError);
  24801. }
  24802. }
  24803. class HemisphereLightProbe extends LightProbe {
  24804. constructor(skyColor, groundColor, intensity = 1) {
  24805. super(undefined, intensity);
  24806. const color1 = new Color().set(skyColor);
  24807. const color2 = new Color().set(groundColor);
  24808. const sky = new Vector3(color1.r, color1.g, color1.b);
  24809. const ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  24810. const c0 = Math.sqrt(Math.PI);
  24811. const c1 = c0 * Math.sqrt(0.75);
  24812. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  24813. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  24814. }
  24815. }
  24816. HemisphereLightProbe.prototype.isHemisphereLightProbe = true;
  24817. class AmbientLightProbe extends LightProbe {
  24818. constructor(color, intensity = 1) {
  24819. super(undefined, intensity);
  24820. const color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  24821. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  24822. }
  24823. }
  24824. AmbientLightProbe.prototype.isAmbientLightProbe = true;
  24825. const _eyeRight = /*@__PURE__*/new Matrix4();
  24826. const _eyeLeft = /*@__PURE__*/new Matrix4();
  24827. class StereoCamera {
  24828. constructor() {
  24829. this.type = 'StereoCamera';
  24830. this.aspect = 1;
  24831. this.eyeSep = 0.064;
  24832. this.cameraL = new PerspectiveCamera();
  24833. this.cameraL.layers.enable(1);
  24834. this.cameraL.matrixAutoUpdate = false;
  24835. this.cameraR = new PerspectiveCamera();
  24836. this.cameraR.layers.enable(2);
  24837. this.cameraR.matrixAutoUpdate = false;
  24838. this._cache = {
  24839. focus: null,
  24840. fov: null,
  24841. aspect: null,
  24842. near: null,
  24843. far: null,
  24844. zoom: null,
  24845. eyeSep: null
  24846. };
  24847. }
  24848. update(camera) {
  24849. const cache = this._cache;
  24850. 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;
  24851. if (needsUpdate) {
  24852. cache.focus = camera.focus;
  24853. cache.fov = camera.fov;
  24854. cache.aspect = camera.aspect * this.aspect;
  24855. cache.near = camera.near;
  24856. cache.far = camera.far;
  24857. cache.zoom = camera.zoom;
  24858. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  24859. // http://paulbourke.net/stereographics/stereorender/
  24860. const projectionMatrix = camera.projectionMatrix.clone();
  24861. const eyeSepHalf = cache.eyeSep / 2;
  24862. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  24863. const ymax = cache.near * Math.tan(DEG2RAD * cache.fov * 0.5) / cache.zoom;
  24864. let xmin, xmax; // translate xOffset
  24865. _eyeLeft.elements[12] = -eyeSepHalf;
  24866. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  24867. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  24868. xmax = ymax * cache.aspect + eyeSepOnProjection;
  24869. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  24870. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  24871. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  24872. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  24873. xmax = ymax * cache.aspect - eyeSepOnProjection;
  24874. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  24875. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  24876. this.cameraR.projectionMatrix.copy(projectionMatrix);
  24877. }
  24878. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  24879. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  24880. }
  24881. }
  24882. class Clock {
  24883. constructor(autoStart = true) {
  24884. this.autoStart = autoStart;
  24885. this.startTime = 0;
  24886. this.oldTime = 0;
  24887. this.elapsedTime = 0;
  24888. this.running = false;
  24889. }
  24890. start() {
  24891. this.startTime = now();
  24892. this.oldTime = this.startTime;
  24893. this.elapsedTime = 0;
  24894. this.running = true;
  24895. }
  24896. stop() {
  24897. this.getElapsedTime();
  24898. this.running = false;
  24899. this.autoStart = false;
  24900. }
  24901. getElapsedTime() {
  24902. this.getDelta();
  24903. return this.elapsedTime;
  24904. }
  24905. getDelta() {
  24906. let diff = 0;
  24907. if (this.autoStart && !this.running) {
  24908. this.start();
  24909. return 0;
  24910. }
  24911. if (this.running) {
  24912. const newTime = now();
  24913. diff = (newTime - this.oldTime) / 1000;
  24914. this.oldTime = newTime;
  24915. this.elapsedTime += diff;
  24916. }
  24917. return diff;
  24918. }
  24919. }
  24920. function now() {
  24921. return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  24922. }
  24923. const _position$1 = /*@__PURE__*/new Vector3();
  24924. const _quaternion$1 = /*@__PURE__*/new Quaternion();
  24925. const _scale$1 = /*@__PURE__*/new Vector3();
  24926. const _orientation$1 = /*@__PURE__*/new Vector3();
  24927. class AudioListener extends Object3D {
  24928. constructor() {
  24929. super();
  24930. this.type = 'AudioListener';
  24931. this.context = AudioContext.getContext();
  24932. this.gain = this.context.createGain();
  24933. this.gain.connect(this.context.destination);
  24934. this.filter = null;
  24935. this.timeDelta = 0; // private
  24936. this._clock = new Clock();
  24937. }
  24938. getInput() {
  24939. return this.gain;
  24940. }
  24941. removeFilter() {
  24942. if (this.filter !== null) {
  24943. this.gain.disconnect(this.filter);
  24944. this.filter.disconnect(this.context.destination);
  24945. this.gain.connect(this.context.destination);
  24946. this.filter = null;
  24947. }
  24948. return this;
  24949. }
  24950. getFilter() {
  24951. return this.filter;
  24952. }
  24953. setFilter(value) {
  24954. if (this.filter !== null) {
  24955. this.gain.disconnect(this.filter);
  24956. this.filter.disconnect(this.context.destination);
  24957. } else {
  24958. this.gain.disconnect(this.context.destination);
  24959. }
  24960. this.filter = value;
  24961. this.gain.connect(this.filter);
  24962. this.filter.connect(this.context.destination);
  24963. return this;
  24964. }
  24965. getMasterVolume() {
  24966. return this.gain.gain.value;
  24967. }
  24968. setMasterVolume(value) {
  24969. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  24970. return this;
  24971. }
  24972. updateMatrixWorld(force) {
  24973. super.updateMatrixWorld(force);
  24974. const listener = this.context.listener;
  24975. const up = this.up;
  24976. this.timeDelta = this._clock.getDelta();
  24977. this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1);
  24978. _orientation$1.set(0, 0, -1).applyQuaternion(_quaternion$1);
  24979. if (listener.positionX) {
  24980. // code path for Chrome (see #14393)
  24981. const endTime = this.context.currentTime + this.timeDelta;
  24982. listener.positionX.linearRampToValueAtTime(_position$1.x, endTime);
  24983. listener.positionY.linearRampToValueAtTime(_position$1.y, endTime);
  24984. listener.positionZ.linearRampToValueAtTime(_position$1.z, endTime);
  24985. listener.forwardX.linearRampToValueAtTime(_orientation$1.x, endTime);
  24986. listener.forwardY.linearRampToValueAtTime(_orientation$1.y, endTime);
  24987. listener.forwardZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  24988. listener.upX.linearRampToValueAtTime(up.x, endTime);
  24989. listener.upY.linearRampToValueAtTime(up.y, endTime);
  24990. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  24991. } else {
  24992. listener.setPosition(_position$1.x, _position$1.y, _position$1.z);
  24993. listener.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z);
  24994. }
  24995. }
  24996. }
  24997. class Audio extends Object3D {
  24998. constructor(listener) {
  24999. super();
  25000. this.type = 'Audio';
  25001. this.listener = listener;
  25002. this.context = listener.context;
  25003. this.gain = this.context.createGain();
  25004. this.gain.connect(listener.getInput());
  25005. this.autoplay = false;
  25006. this.buffer = null;
  25007. this.detune = 0;
  25008. this.loop = false;
  25009. this.loopStart = 0;
  25010. this.loopEnd = 0;
  25011. this.offset = 0;
  25012. this.duration = undefined;
  25013. this.playbackRate = 1;
  25014. this.isPlaying = false;
  25015. this.hasPlaybackControl = true;
  25016. this.source = null;
  25017. this.sourceType = 'empty';
  25018. this._startedAt = 0;
  25019. this._progress = 0;
  25020. this._connected = false;
  25021. this.filters = [];
  25022. }
  25023. getOutput() {
  25024. return this.gain;
  25025. }
  25026. setNodeSource(audioNode) {
  25027. this.hasPlaybackControl = false;
  25028. this.sourceType = 'audioNode';
  25029. this.source = audioNode;
  25030. this.connect();
  25031. return this;
  25032. }
  25033. setMediaElementSource(mediaElement) {
  25034. this.hasPlaybackControl = false;
  25035. this.sourceType = 'mediaNode';
  25036. this.source = this.context.createMediaElementSource(mediaElement);
  25037. this.connect();
  25038. return this;
  25039. }
  25040. setMediaStreamSource(mediaStream) {
  25041. this.hasPlaybackControl = false;
  25042. this.sourceType = 'mediaStreamNode';
  25043. this.source = this.context.createMediaStreamSource(mediaStream);
  25044. this.connect();
  25045. return this;
  25046. }
  25047. setBuffer(audioBuffer) {
  25048. this.buffer = audioBuffer;
  25049. this.sourceType = 'buffer';
  25050. if (this.autoplay) this.play();
  25051. return this;
  25052. }
  25053. play(delay = 0) {
  25054. if (this.isPlaying === true) {
  25055. console.warn('THREE.Audio: Audio is already playing.');
  25056. return;
  25057. }
  25058. if (this.hasPlaybackControl === false) {
  25059. console.warn('THREE.Audio: this Audio has no playback control.');
  25060. return;
  25061. }
  25062. this._startedAt = this.context.currentTime + delay;
  25063. const source = this.context.createBufferSource();
  25064. source.buffer = this.buffer;
  25065. source.loop = this.loop;
  25066. source.loopStart = this.loopStart;
  25067. source.loopEnd = this.loopEnd;
  25068. source.onended = this.onEnded.bind(this);
  25069. source.start(this._startedAt, this._progress + this.offset, this.duration);
  25070. this.isPlaying = true;
  25071. this.source = source;
  25072. this.setDetune(this.detune);
  25073. this.setPlaybackRate(this.playbackRate);
  25074. return this.connect();
  25075. }
  25076. pause() {
  25077. if (this.hasPlaybackControl === false) {
  25078. console.warn('THREE.Audio: this Audio has no playback control.');
  25079. return;
  25080. }
  25081. if (this.isPlaying === true) {
  25082. // update current progress
  25083. this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  25084. if (this.loop === true) {
  25085. // ensure _progress does not exceed duration with looped audios
  25086. this._progress = this._progress % (this.duration || this.buffer.duration);
  25087. }
  25088. this.source.stop();
  25089. this.source.onended = null;
  25090. this.isPlaying = false;
  25091. }
  25092. return this;
  25093. }
  25094. stop() {
  25095. if (this.hasPlaybackControl === false) {
  25096. console.warn('THREE.Audio: this Audio has no playback control.');
  25097. return;
  25098. }
  25099. this._progress = 0;
  25100. this.source.stop();
  25101. this.source.onended = null;
  25102. this.isPlaying = false;
  25103. return this;
  25104. }
  25105. connect() {
  25106. if (this.filters.length > 0) {
  25107. this.source.connect(this.filters[0]);
  25108. for (let i = 1, l = this.filters.length; i < l; i++) {
  25109. this.filters[i - 1].connect(this.filters[i]);
  25110. }
  25111. this.filters[this.filters.length - 1].connect(this.getOutput());
  25112. } else {
  25113. this.source.connect(this.getOutput());
  25114. }
  25115. this._connected = true;
  25116. return this;
  25117. }
  25118. disconnect() {
  25119. if (this.filters.length > 0) {
  25120. this.source.disconnect(this.filters[0]);
  25121. for (let i = 1, l = this.filters.length; i < l; i++) {
  25122. this.filters[i - 1].disconnect(this.filters[i]);
  25123. }
  25124. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  25125. } else {
  25126. this.source.disconnect(this.getOutput());
  25127. }
  25128. this._connected = false;
  25129. return this;
  25130. }
  25131. getFilters() {
  25132. return this.filters;
  25133. }
  25134. setFilters(value) {
  25135. if (!value) value = [];
  25136. if (this._connected === true) {
  25137. this.disconnect();
  25138. this.filters = value.slice();
  25139. this.connect();
  25140. } else {
  25141. this.filters = value.slice();
  25142. }
  25143. return this;
  25144. }
  25145. setDetune(value) {
  25146. this.detune = value;
  25147. if (this.source.detune === undefined) return; // only set detune when available
  25148. if (this.isPlaying === true) {
  25149. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  25150. }
  25151. return this;
  25152. }
  25153. getDetune() {
  25154. return this.detune;
  25155. }
  25156. getFilter() {
  25157. return this.getFilters()[0];
  25158. }
  25159. setFilter(filter) {
  25160. return this.setFilters(filter ? [filter] : []);
  25161. }
  25162. setPlaybackRate(value) {
  25163. if (this.hasPlaybackControl === false) {
  25164. console.warn('THREE.Audio: this Audio has no playback control.');
  25165. return;
  25166. }
  25167. this.playbackRate = value;
  25168. if (this.isPlaying === true) {
  25169. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  25170. }
  25171. return this;
  25172. }
  25173. getPlaybackRate() {
  25174. return this.playbackRate;
  25175. }
  25176. onEnded() {
  25177. this.isPlaying = false;
  25178. }
  25179. getLoop() {
  25180. if (this.hasPlaybackControl === false) {
  25181. console.warn('THREE.Audio: this Audio has no playback control.');
  25182. return false;
  25183. }
  25184. return this.loop;
  25185. }
  25186. setLoop(value) {
  25187. if (this.hasPlaybackControl === false) {
  25188. console.warn('THREE.Audio: this Audio has no playback control.');
  25189. return;
  25190. }
  25191. this.loop = value;
  25192. if (this.isPlaying === true) {
  25193. this.source.loop = this.loop;
  25194. }
  25195. return this;
  25196. }
  25197. setLoopStart(value) {
  25198. this.loopStart = value;
  25199. return this;
  25200. }
  25201. setLoopEnd(value) {
  25202. this.loopEnd = value;
  25203. return this;
  25204. }
  25205. getVolume() {
  25206. return this.gain.gain.value;
  25207. }
  25208. setVolume(value) {
  25209. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25210. return this;
  25211. }
  25212. }
  25213. const _position = /*@__PURE__*/new Vector3();
  25214. const _quaternion = /*@__PURE__*/new Quaternion();
  25215. const _scale = /*@__PURE__*/new Vector3();
  25216. const _orientation = /*@__PURE__*/new Vector3();
  25217. class PositionalAudio extends Audio {
  25218. constructor(listener) {
  25219. super(listener);
  25220. this.panner = this.context.createPanner();
  25221. this.panner.panningModel = 'HRTF';
  25222. this.panner.connect(this.gain);
  25223. }
  25224. getOutput() {
  25225. return this.panner;
  25226. }
  25227. getRefDistance() {
  25228. return this.panner.refDistance;
  25229. }
  25230. setRefDistance(value) {
  25231. this.panner.refDistance = value;
  25232. return this;
  25233. }
  25234. getRolloffFactor() {
  25235. return this.panner.rolloffFactor;
  25236. }
  25237. setRolloffFactor(value) {
  25238. this.panner.rolloffFactor = value;
  25239. return this;
  25240. }
  25241. getDistanceModel() {
  25242. return this.panner.distanceModel;
  25243. }
  25244. setDistanceModel(value) {
  25245. this.panner.distanceModel = value;
  25246. return this;
  25247. }
  25248. getMaxDistance() {
  25249. return this.panner.maxDistance;
  25250. }
  25251. setMaxDistance(value) {
  25252. this.panner.maxDistance = value;
  25253. return this;
  25254. }
  25255. setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25256. this.panner.coneInnerAngle = coneInnerAngle;
  25257. this.panner.coneOuterAngle = coneOuterAngle;
  25258. this.panner.coneOuterGain = coneOuterGain;
  25259. return this;
  25260. }
  25261. updateMatrixWorld(force) {
  25262. super.updateMatrixWorld(force);
  25263. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  25264. this.matrixWorld.decompose(_position, _quaternion, _scale);
  25265. _orientation.set(0, 0, 1).applyQuaternion(_quaternion);
  25266. const panner = this.panner;
  25267. if (panner.positionX) {
  25268. // code path for Chrome and Firefox (see #14393)
  25269. const endTime = this.context.currentTime + this.listener.timeDelta;
  25270. panner.positionX.linearRampToValueAtTime(_position.x, endTime);
  25271. panner.positionY.linearRampToValueAtTime(_position.y, endTime);
  25272. panner.positionZ.linearRampToValueAtTime(_position.z, endTime);
  25273. panner.orientationX.linearRampToValueAtTime(_orientation.x, endTime);
  25274. panner.orientationY.linearRampToValueAtTime(_orientation.y, endTime);
  25275. panner.orientationZ.linearRampToValueAtTime(_orientation.z, endTime);
  25276. } else {
  25277. panner.setPosition(_position.x, _position.y, _position.z);
  25278. panner.setOrientation(_orientation.x, _orientation.y, _orientation.z);
  25279. }
  25280. }
  25281. }
  25282. class AudioAnalyser {
  25283. constructor(audio, fftSize = 2048) {
  25284. this.analyser = audio.context.createAnalyser();
  25285. this.analyser.fftSize = fftSize;
  25286. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  25287. audio.getOutput().connect(this.analyser);
  25288. }
  25289. getFrequencyData() {
  25290. this.analyser.getByteFrequencyData(this.data);
  25291. return this.data;
  25292. }
  25293. getAverageFrequency() {
  25294. let value = 0;
  25295. const data = this.getFrequencyData();
  25296. for (let i = 0; i < data.length; i++) {
  25297. value += data[i];
  25298. }
  25299. return value / data.length;
  25300. }
  25301. }
  25302. class PropertyMixer {
  25303. constructor(binding, typeName, valueSize) {
  25304. this.binding = binding;
  25305. this.valueSize = valueSize;
  25306. let mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  25307. //
  25308. // interpolators can use .buffer as their .result
  25309. // the data then goes to 'incoming'
  25310. //
  25311. // 'accu0' and 'accu1' are used frame-interleaved for
  25312. // the cumulative result and are compared to detect
  25313. // changes
  25314. //
  25315. // 'orig' stores the original state of the property
  25316. //
  25317. // 'add' is used for additive cumulative results
  25318. //
  25319. // 'work' is optional and is only present for quaternion types. It is used
  25320. // to store intermediate quaternion multiplication results
  25321. switch (typeName) {
  25322. case 'quaternion':
  25323. mixFunction = this._slerp;
  25324. mixFunctionAdditive = this._slerpAdditive;
  25325. setIdentity = this._setAdditiveIdentityQuaternion;
  25326. this.buffer = new Float64Array(valueSize * 6);
  25327. this._workIndex = 5;
  25328. break;
  25329. case 'string':
  25330. case 'bool':
  25331. mixFunction = this._select; // Use the regular mix function and for additive on these types,
  25332. // additive is not relevant for non-numeric types
  25333. mixFunctionAdditive = this._select;
  25334. setIdentity = this._setAdditiveIdentityOther;
  25335. this.buffer = new Array(valueSize * 5);
  25336. break;
  25337. default:
  25338. mixFunction = this._lerp;
  25339. mixFunctionAdditive = this._lerpAdditive;
  25340. setIdentity = this._setAdditiveIdentityNumeric;
  25341. this.buffer = new Float64Array(valueSize * 5);
  25342. }
  25343. this._mixBufferRegion = mixFunction;
  25344. this._mixBufferRegionAdditive = mixFunctionAdditive;
  25345. this._setIdentity = setIdentity;
  25346. this._origIndex = 3;
  25347. this._addIndex = 4;
  25348. this.cumulativeWeight = 0;
  25349. this.cumulativeWeightAdditive = 0;
  25350. this.useCount = 0;
  25351. this.referenceCount = 0;
  25352. } // accumulate data in the 'incoming' region into 'accu<i>'
  25353. accumulate(accuIndex, weight) {
  25354. // note: happily accumulating nothing when weight = 0, the caller knows
  25355. // the weight and shouldn't have made the call in the first place
  25356. const buffer = this.buffer,
  25357. stride = this.valueSize,
  25358. offset = accuIndex * stride + stride;
  25359. let currentWeight = this.cumulativeWeight;
  25360. if (currentWeight === 0) {
  25361. // accuN := incoming * weight
  25362. for (let i = 0; i !== stride; ++i) {
  25363. buffer[offset + i] = buffer[i];
  25364. }
  25365. currentWeight = weight;
  25366. } else {
  25367. // accuN := accuN + incoming * weight
  25368. currentWeight += weight;
  25369. const mix = weight / currentWeight;
  25370. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  25371. }
  25372. this.cumulativeWeight = currentWeight;
  25373. } // accumulate data in the 'incoming' region into 'add'
  25374. accumulateAdditive(weight) {
  25375. const buffer = this.buffer,
  25376. stride = this.valueSize,
  25377. offset = stride * this._addIndex;
  25378. if (this.cumulativeWeightAdditive === 0) {
  25379. // add = identity
  25380. this._setIdentity();
  25381. } // add := add + incoming * weight
  25382. this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
  25383. this.cumulativeWeightAdditive += weight;
  25384. } // apply the state of 'accu<i>' to the binding when accus differ
  25385. apply(accuIndex) {
  25386. const stride = this.valueSize,
  25387. buffer = this.buffer,
  25388. offset = accuIndex * stride + stride,
  25389. weight = this.cumulativeWeight,
  25390. weightAdditive = this.cumulativeWeightAdditive,
  25391. binding = this.binding;
  25392. this.cumulativeWeight = 0;
  25393. this.cumulativeWeightAdditive = 0;
  25394. if (weight < 1) {
  25395. // accuN := accuN + original * ( 1 - cumulativeWeight )
  25396. const originalValueOffset = stride * this._origIndex;
  25397. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  25398. }
  25399. if (weightAdditive > 0) {
  25400. // accuN := accuN + additive accuN
  25401. this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
  25402. }
  25403. for (let i = stride, e = stride + stride; i !== e; ++i) {
  25404. if (buffer[i] !== buffer[i + stride]) {
  25405. // value has changed -> update scene graph
  25406. binding.setValue(buffer, offset);
  25407. break;
  25408. }
  25409. }
  25410. } // remember the state of the bound property and copy it to both accus
  25411. saveOriginalState() {
  25412. const binding = this.binding;
  25413. const buffer = this.buffer,
  25414. stride = this.valueSize,
  25415. originalValueOffset = stride * this._origIndex;
  25416. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  25417. for (let i = stride, e = originalValueOffset; i !== e; ++i) {
  25418. buffer[i] = buffer[originalValueOffset + i % stride];
  25419. } // Add to identity for additive
  25420. this._setIdentity();
  25421. this.cumulativeWeight = 0;
  25422. this.cumulativeWeightAdditive = 0;
  25423. } // apply the state previously taken via 'saveOriginalState' to the binding
  25424. restoreOriginalState() {
  25425. const originalValueOffset = this.valueSize * 3;
  25426. this.binding.setValue(this.buffer, originalValueOffset);
  25427. }
  25428. _setAdditiveIdentityNumeric() {
  25429. const startIndex = this._addIndex * this.valueSize;
  25430. const endIndex = startIndex + this.valueSize;
  25431. for (let i = startIndex; i < endIndex; i++) {
  25432. this.buffer[i] = 0;
  25433. }
  25434. }
  25435. _setAdditiveIdentityQuaternion() {
  25436. this._setAdditiveIdentityNumeric();
  25437. this.buffer[this._addIndex * this.valueSize + 3] = 1;
  25438. }
  25439. _setAdditiveIdentityOther() {
  25440. const startIndex = this._origIndex * this.valueSize;
  25441. const targetIndex = this._addIndex * this.valueSize;
  25442. for (let i = 0; i < this.valueSize; i++) {
  25443. this.buffer[targetIndex + i] = this.buffer[startIndex + i];
  25444. }
  25445. } // mix functions
  25446. _select(buffer, dstOffset, srcOffset, t, stride) {
  25447. if (t >= 0.5) {
  25448. for (let i = 0; i !== stride; ++i) {
  25449. buffer[dstOffset + i] = buffer[srcOffset + i];
  25450. }
  25451. }
  25452. }
  25453. _slerp(buffer, dstOffset, srcOffset, t) {
  25454. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  25455. }
  25456. _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  25457. const workOffset = this._workIndex * stride; // Store result in intermediate buffer offset
  25458. Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
  25459. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
  25460. }
  25461. _lerp(buffer, dstOffset, srcOffset, t, stride) {
  25462. const s = 1 - t;
  25463. for (let i = 0; i !== stride; ++i) {
  25464. const j = dstOffset + i;
  25465. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  25466. }
  25467. }
  25468. _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  25469. for (let i = 0; i !== stride; ++i) {
  25470. const j = dstOffset + i;
  25471. buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
  25472. }
  25473. }
  25474. }
  25475. // Characters [].:/ are reserved for track binding syntax.
  25476. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  25477. const _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  25478. // only latin characters, and the unicode \p{L} is not yet supported. So
  25479. // instead, we exclude reserved characters and match everything else.
  25480. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  25481. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  25482. // be matched to parse the rest of the track name.
  25483. const _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  25484. const _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  25485. // characters. Accessor may contain any character except closing bracket.
  25486. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  25487. // contain any non-bracket characters.
  25488. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  25489. const _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  25490. const _supportedObjectNames = ['material', 'materials', 'bones'];
  25491. class Composite {
  25492. constructor(targetGroup, path, optionalParsedPath) {
  25493. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  25494. this._targetGroup = targetGroup;
  25495. this._bindings = targetGroup.subscribe_(path, parsedPath);
  25496. }
  25497. getValue(array, offset) {
  25498. this.bind(); // bind all binding
  25499. const firstValidIndex = this._targetGroup.nCachedObjects_,
  25500. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  25501. if (binding !== undefined) binding.getValue(array, offset);
  25502. }
  25503. setValue(array, offset) {
  25504. const bindings = this._bindings;
  25505. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25506. bindings[i].setValue(array, offset);
  25507. }
  25508. }
  25509. bind() {
  25510. const bindings = this._bindings;
  25511. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25512. bindings[i].bind();
  25513. }
  25514. }
  25515. unbind() {
  25516. const bindings = this._bindings;
  25517. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25518. bindings[i].unbind();
  25519. }
  25520. }
  25521. } // Note: This class uses a State pattern on a per-method basis:
  25522. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  25523. // prototype version of these methods with one that represents
  25524. // the bound state. When the property is not found, the methods
  25525. // become no-ops.
  25526. class PropertyBinding {
  25527. constructor(rootNode, path, parsedPath) {
  25528. this.path = path;
  25529. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  25530. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  25531. this.rootNode = rootNode; // initial state of these methods that calls 'bind'
  25532. this.getValue = this._getValue_unbound;
  25533. this.setValue = this._setValue_unbound;
  25534. }
  25535. static create(root, path, parsedPath) {
  25536. if (!(root && root.isAnimationObjectGroup)) {
  25537. return new PropertyBinding(root, path, parsedPath);
  25538. } else {
  25539. return new PropertyBinding.Composite(root, path, parsedPath);
  25540. }
  25541. }
  25542. /**
  25543. * Replaces spaces with underscores and removes unsupported characters from
  25544. * node names, to ensure compatibility with parseTrackName().
  25545. *
  25546. * @param {string} name Node name to be sanitized.
  25547. * @return {string}
  25548. */
  25549. static sanitizeNodeName(name) {
  25550. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  25551. }
  25552. static parseTrackName(trackName) {
  25553. const matches = _trackRe.exec(trackName);
  25554. if (!matches) {
  25555. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  25556. }
  25557. const results = {
  25558. // directoryName: matches[ 1 ], // (tschw) currently unused
  25559. nodeName: matches[2],
  25560. objectName: matches[3],
  25561. objectIndex: matches[4],
  25562. propertyName: matches[5],
  25563. // required
  25564. propertyIndex: matches[6]
  25565. };
  25566. const lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  25567. if (lastDot !== undefined && lastDot !== -1) {
  25568. const objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
  25569. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  25570. // 'bar' could be the objectName, or part of a nodeName (which can
  25571. // include '.' characters).
  25572. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  25573. results.nodeName = results.nodeName.substring(0, lastDot);
  25574. results.objectName = objectName;
  25575. }
  25576. }
  25577. if (results.propertyName === null || results.propertyName.length === 0) {
  25578. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  25579. }
  25580. return results;
  25581. }
  25582. static findNode(root, nodeName) {
  25583. if (!nodeName || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  25584. return root;
  25585. } // search into skeleton bones.
  25586. if (root.skeleton) {
  25587. const bone = root.skeleton.getBoneByName(nodeName);
  25588. if (bone !== undefined) {
  25589. return bone;
  25590. }
  25591. } // search into node subtree.
  25592. if (root.children) {
  25593. const searchNodeSubtree = function (children) {
  25594. for (let i = 0; i < children.length; i++) {
  25595. const childNode = children[i];
  25596. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  25597. return childNode;
  25598. }
  25599. const result = searchNodeSubtree(childNode.children);
  25600. if (result) return result;
  25601. }
  25602. return null;
  25603. };
  25604. const subTreeNode = searchNodeSubtree(root.children);
  25605. if (subTreeNode) {
  25606. return subTreeNode;
  25607. }
  25608. }
  25609. return null;
  25610. } // these are used to "bind" a nonexistent property
  25611. _getValue_unavailable() {}
  25612. _setValue_unavailable() {} // Getters
  25613. _getValue_direct(buffer, offset) {
  25614. buffer[offset] = this.targetObject[this.propertyName];
  25615. }
  25616. _getValue_array(buffer, offset) {
  25617. const source = this.resolvedProperty;
  25618. for (let i = 0, n = source.length; i !== n; ++i) {
  25619. buffer[offset++] = source[i];
  25620. }
  25621. }
  25622. _getValue_arrayElement(buffer, offset) {
  25623. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  25624. }
  25625. _getValue_toArray(buffer, offset) {
  25626. this.resolvedProperty.toArray(buffer, offset);
  25627. } // Direct
  25628. _setValue_direct(buffer, offset) {
  25629. this.targetObject[this.propertyName] = buffer[offset];
  25630. }
  25631. _setValue_direct_setNeedsUpdate(buffer, offset) {
  25632. this.targetObject[this.propertyName] = buffer[offset];
  25633. this.targetObject.needsUpdate = true;
  25634. }
  25635. _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  25636. this.targetObject[this.propertyName] = buffer[offset];
  25637. this.targetObject.matrixWorldNeedsUpdate = true;
  25638. } // EntireArray
  25639. _setValue_array(buffer, offset) {
  25640. const dest = this.resolvedProperty;
  25641. for (let i = 0, n = dest.length; i !== n; ++i) {
  25642. dest[i] = buffer[offset++];
  25643. }
  25644. }
  25645. _setValue_array_setNeedsUpdate(buffer, offset) {
  25646. const dest = this.resolvedProperty;
  25647. for (let i = 0, n = dest.length; i !== n; ++i) {
  25648. dest[i] = buffer[offset++];
  25649. }
  25650. this.targetObject.needsUpdate = true;
  25651. }
  25652. _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  25653. const dest = this.resolvedProperty;
  25654. for (let i = 0, n = dest.length; i !== n; ++i) {
  25655. dest[i] = buffer[offset++];
  25656. }
  25657. this.targetObject.matrixWorldNeedsUpdate = true;
  25658. } // ArrayElement
  25659. _setValue_arrayElement(buffer, offset) {
  25660. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25661. }
  25662. _setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  25663. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25664. this.targetObject.needsUpdate = true;
  25665. }
  25666. _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  25667. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25668. this.targetObject.matrixWorldNeedsUpdate = true;
  25669. } // HasToFromArray
  25670. _setValue_fromArray(buffer, offset) {
  25671. this.resolvedProperty.fromArray(buffer, offset);
  25672. }
  25673. _setValue_fromArray_setNeedsUpdate(buffer, offset) {
  25674. this.resolvedProperty.fromArray(buffer, offset);
  25675. this.targetObject.needsUpdate = true;
  25676. }
  25677. _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  25678. this.resolvedProperty.fromArray(buffer, offset);
  25679. this.targetObject.matrixWorldNeedsUpdate = true;
  25680. }
  25681. _getValue_unbound(targetArray, offset) {
  25682. this.bind();
  25683. this.getValue(targetArray, offset);
  25684. }
  25685. _setValue_unbound(sourceArray, offset) {
  25686. this.bind();
  25687. this.setValue(sourceArray, offset);
  25688. } // create getter / setter pair for a property in the scene graph
  25689. bind() {
  25690. let targetObject = this.node;
  25691. const parsedPath = this.parsedPath;
  25692. const objectName = parsedPath.objectName;
  25693. const propertyName = parsedPath.propertyName;
  25694. let propertyIndex = parsedPath.propertyIndex;
  25695. if (!targetObject) {
  25696. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  25697. this.node = targetObject;
  25698. } // set fail state so we can just 'return' on error
  25699. this.getValue = this._getValue_unavailable;
  25700. this.setValue = this._setValue_unavailable; // ensure there is a value node
  25701. if (!targetObject) {
  25702. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  25703. return;
  25704. }
  25705. if (objectName) {
  25706. let objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  25707. switch (objectName) {
  25708. case 'materials':
  25709. if (!targetObject.material) {
  25710. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  25711. return;
  25712. }
  25713. if (!targetObject.material.materials) {
  25714. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  25715. return;
  25716. }
  25717. targetObject = targetObject.material.materials;
  25718. break;
  25719. case 'bones':
  25720. if (!targetObject.skeleton) {
  25721. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  25722. return;
  25723. } // potential future optimization: skip this if propertyIndex is already an integer
  25724. // and convert the integer string to a true integer.
  25725. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  25726. for (let i = 0; i < targetObject.length; i++) {
  25727. if (targetObject[i].name === objectIndex) {
  25728. objectIndex = i;
  25729. break;
  25730. }
  25731. }
  25732. break;
  25733. default:
  25734. if (targetObject[objectName] === undefined) {
  25735. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  25736. return;
  25737. }
  25738. targetObject = targetObject[objectName];
  25739. }
  25740. if (objectIndex !== undefined) {
  25741. if (targetObject[objectIndex] === undefined) {
  25742. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  25743. return;
  25744. }
  25745. targetObject = targetObject[objectIndex];
  25746. }
  25747. } // resolve property
  25748. const nodeProperty = targetObject[propertyName];
  25749. if (nodeProperty === undefined) {
  25750. const nodeName = parsedPath.nodeName;
  25751. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  25752. return;
  25753. } // determine versioning scheme
  25754. let versioning = this.Versioning.None;
  25755. this.targetObject = targetObject;
  25756. if (targetObject.needsUpdate !== undefined) {
  25757. // material
  25758. versioning = this.Versioning.NeedsUpdate;
  25759. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  25760. // node transform
  25761. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  25762. } // determine how the property gets bound
  25763. let bindingType = this.BindingType.Direct;
  25764. if (propertyIndex !== undefined) {
  25765. // access a sub element of the property array (only primitives are supported right now)
  25766. if (propertyName === 'morphTargetInfluences') {
  25767. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  25768. // support resolving morphTarget names into indices.
  25769. if (!targetObject.geometry) {
  25770. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  25771. return;
  25772. }
  25773. if (targetObject.geometry.isBufferGeometry) {
  25774. if (!targetObject.geometry.morphAttributes) {
  25775. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  25776. return;
  25777. }
  25778. if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
  25779. propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
  25780. }
  25781. } else {
  25782. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this);
  25783. return;
  25784. }
  25785. }
  25786. bindingType = this.BindingType.ArrayElement;
  25787. this.resolvedProperty = nodeProperty;
  25788. this.propertyIndex = propertyIndex;
  25789. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  25790. // must use copy for Object3D.Euler/Quaternion
  25791. bindingType = this.BindingType.HasFromToArray;
  25792. this.resolvedProperty = nodeProperty;
  25793. } else if (Array.isArray(nodeProperty)) {
  25794. bindingType = this.BindingType.EntireArray;
  25795. this.resolvedProperty = nodeProperty;
  25796. } else {
  25797. this.propertyName = propertyName;
  25798. } // select getter / setter
  25799. this.getValue = this.GetterByBindingType[bindingType];
  25800. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  25801. }
  25802. unbind() {
  25803. this.node = null; // back to the prototype version of getValue / setValue
  25804. // note: avoiding to mutate the shape of 'this' via 'delete'
  25805. this.getValue = this._getValue_unbound;
  25806. this.setValue = this._setValue_unbound;
  25807. }
  25808. }
  25809. PropertyBinding.Composite = Composite;
  25810. PropertyBinding.prototype.BindingType = {
  25811. Direct: 0,
  25812. EntireArray: 1,
  25813. ArrayElement: 2,
  25814. HasFromToArray: 3
  25815. };
  25816. PropertyBinding.prototype.Versioning = {
  25817. None: 0,
  25818. NeedsUpdate: 1,
  25819. MatrixWorldNeedsUpdate: 2
  25820. };
  25821. PropertyBinding.prototype.GetterByBindingType = [PropertyBinding.prototype._getValue_direct, PropertyBinding.prototype._getValue_array, PropertyBinding.prototype._getValue_arrayElement, PropertyBinding.prototype._getValue_toArray];
  25822. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [[// Direct
  25823. PropertyBinding.prototype._setValue_direct, PropertyBinding.prototype._setValue_direct_setNeedsUpdate, PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate], [// EntireArray
  25824. PropertyBinding.prototype._setValue_array, PropertyBinding.prototype._setValue_array_setNeedsUpdate, PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate], [// ArrayElement
  25825. PropertyBinding.prototype._setValue_arrayElement, PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate], [// HasToFromArray
  25826. PropertyBinding.prototype._setValue_fromArray, PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];
  25827. /**
  25828. *
  25829. * A group of objects that receives a shared animation state.
  25830. *
  25831. * Usage:
  25832. *
  25833. * - Add objects you would otherwise pass as 'root' to the
  25834. * constructor or the .clipAction method of AnimationMixer.
  25835. *
  25836. * - Instead pass this object as 'root'.
  25837. *
  25838. * - You can also add and remove objects later when the mixer
  25839. * is running.
  25840. *
  25841. * Note:
  25842. *
  25843. * Objects of this class appear as one object to the mixer,
  25844. * so cache control of the individual objects must be done
  25845. * on the group.
  25846. *
  25847. * Limitation:
  25848. *
  25849. * - The animated properties must be compatible among the
  25850. * all objects in the group.
  25851. *
  25852. * - A single property can either be controlled through a
  25853. * target group or directly, but not both.
  25854. */
  25855. class AnimationObjectGroup {
  25856. constructor() {
  25857. this.uuid = generateUUID(); // cached objects followed by the active ones
  25858. this._objects = Array.prototype.slice.call(arguments);
  25859. this.nCachedObjects_ = 0; // threshold
  25860. // note: read by PropertyBinding.Composite
  25861. const indices = {};
  25862. this._indicesByUUID = indices; // for bookkeeping
  25863. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25864. indices[arguments[i].uuid] = i;
  25865. }
  25866. this._paths = []; // inside: string
  25867. this._parsedPaths = []; // inside: { we don't care, here }
  25868. this._bindings = []; // inside: Array< PropertyBinding >
  25869. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  25870. const scope = this;
  25871. this.stats = {
  25872. objects: {
  25873. get total() {
  25874. return scope._objects.length;
  25875. },
  25876. get inUse() {
  25877. return this.total - scope.nCachedObjects_;
  25878. }
  25879. },
  25880. get bindingsPerObject() {
  25881. return scope._bindings.length;
  25882. }
  25883. };
  25884. }
  25885. add() {
  25886. const objects = this._objects,
  25887. indicesByUUID = this._indicesByUUID,
  25888. paths = this._paths,
  25889. parsedPaths = this._parsedPaths,
  25890. bindings = this._bindings,
  25891. nBindings = bindings.length;
  25892. let knownObject = undefined,
  25893. nObjects = objects.length,
  25894. nCachedObjects = this.nCachedObjects_;
  25895. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25896. const object = arguments[i],
  25897. uuid = object.uuid;
  25898. let index = indicesByUUID[uuid];
  25899. if (index === undefined) {
  25900. // unknown object -> add it to the ACTIVE region
  25901. index = nObjects++;
  25902. indicesByUUID[uuid] = index;
  25903. objects.push(object); // accounting is done, now do the same for all bindings
  25904. for (let j = 0, m = nBindings; j !== m; ++j) {
  25905. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  25906. }
  25907. } else if (index < nCachedObjects) {
  25908. knownObject = objects[index]; // move existing object to the ACTIVE region
  25909. const firstActiveIndex = --nCachedObjects,
  25910. lastCachedObject = objects[firstActiveIndex];
  25911. indicesByUUID[lastCachedObject.uuid] = index;
  25912. objects[index] = lastCachedObject;
  25913. indicesByUUID[uuid] = firstActiveIndex;
  25914. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  25915. for (let j = 0, m = nBindings; j !== m; ++j) {
  25916. const bindingsForPath = bindings[j],
  25917. lastCached = bindingsForPath[firstActiveIndex];
  25918. let binding = bindingsForPath[index];
  25919. bindingsForPath[index] = lastCached;
  25920. if (binding === undefined) {
  25921. // since we do not bother to create new bindings
  25922. // for objects that are cached, the binding may
  25923. // or may not exist
  25924. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  25925. }
  25926. bindingsForPath[firstActiveIndex] = binding;
  25927. }
  25928. } else if (objects[index] !== knownObject) {
  25929. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  25930. } // else the object is already where we want it to be
  25931. } // for arguments
  25932. this.nCachedObjects_ = nCachedObjects;
  25933. }
  25934. remove() {
  25935. const objects = this._objects,
  25936. indicesByUUID = this._indicesByUUID,
  25937. bindings = this._bindings,
  25938. nBindings = bindings.length;
  25939. let nCachedObjects = this.nCachedObjects_;
  25940. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25941. const object = arguments[i],
  25942. uuid = object.uuid,
  25943. index = indicesByUUID[uuid];
  25944. if (index !== undefined && index >= nCachedObjects) {
  25945. // move existing object into the CACHED region
  25946. const lastCachedIndex = nCachedObjects++,
  25947. firstActiveObject = objects[lastCachedIndex];
  25948. indicesByUUID[firstActiveObject.uuid] = index;
  25949. objects[index] = firstActiveObject;
  25950. indicesByUUID[uuid] = lastCachedIndex;
  25951. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  25952. for (let j = 0, m = nBindings; j !== m; ++j) {
  25953. const bindingsForPath = bindings[j],
  25954. firstActive = bindingsForPath[lastCachedIndex],
  25955. binding = bindingsForPath[index];
  25956. bindingsForPath[index] = firstActive;
  25957. bindingsForPath[lastCachedIndex] = binding;
  25958. }
  25959. }
  25960. } // for arguments
  25961. this.nCachedObjects_ = nCachedObjects;
  25962. } // remove & forget
  25963. uncache() {
  25964. const objects = this._objects,
  25965. indicesByUUID = this._indicesByUUID,
  25966. bindings = this._bindings,
  25967. nBindings = bindings.length;
  25968. let nCachedObjects = this.nCachedObjects_,
  25969. nObjects = objects.length;
  25970. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25971. const object = arguments[i],
  25972. uuid = object.uuid,
  25973. index = indicesByUUID[uuid];
  25974. if (index !== undefined) {
  25975. delete indicesByUUID[uuid];
  25976. if (index < nCachedObjects) {
  25977. // object is cached, shrink the CACHED region
  25978. const firstActiveIndex = --nCachedObjects,
  25979. lastCachedObject = objects[firstActiveIndex],
  25980. lastIndex = --nObjects,
  25981. lastObject = objects[lastIndex]; // last cached object takes this object's place
  25982. indicesByUUID[lastCachedObject.uuid] = index;
  25983. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  25984. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  25985. objects[firstActiveIndex] = lastObject;
  25986. objects.pop(); // accounting is done, now do the same for all bindings
  25987. for (let j = 0, m = nBindings; j !== m; ++j) {
  25988. const bindingsForPath = bindings[j],
  25989. lastCached = bindingsForPath[firstActiveIndex],
  25990. last = bindingsForPath[lastIndex];
  25991. bindingsForPath[index] = lastCached;
  25992. bindingsForPath[firstActiveIndex] = last;
  25993. bindingsForPath.pop();
  25994. }
  25995. } else {
  25996. // object is active, just swap with the last and pop
  25997. const lastIndex = --nObjects,
  25998. lastObject = objects[lastIndex];
  25999. if (lastIndex > 0) {
  26000. indicesByUUID[lastObject.uuid] = index;
  26001. }
  26002. objects[index] = lastObject;
  26003. objects.pop(); // accounting is done, now do the same for all bindings
  26004. for (let j = 0, m = nBindings; j !== m; ++j) {
  26005. const bindingsForPath = bindings[j];
  26006. bindingsForPath[index] = bindingsForPath[lastIndex];
  26007. bindingsForPath.pop();
  26008. }
  26009. } // cached or active
  26010. } // if object is known
  26011. } // for arguments
  26012. this.nCachedObjects_ = nCachedObjects;
  26013. } // Internal interface used by befriended PropertyBinding.Composite:
  26014. subscribe_(path, parsedPath) {
  26015. // returns an array of bindings for the given path that is changed
  26016. // according to the contained objects in the group
  26017. const indicesByPath = this._bindingsIndicesByPath;
  26018. let index = indicesByPath[path];
  26019. const bindings = this._bindings;
  26020. if (index !== undefined) return bindings[index];
  26021. const paths = this._paths,
  26022. parsedPaths = this._parsedPaths,
  26023. objects = this._objects,
  26024. nObjects = objects.length,
  26025. nCachedObjects = this.nCachedObjects_,
  26026. bindingsForPath = new Array(nObjects);
  26027. index = bindings.length;
  26028. indicesByPath[path] = index;
  26029. paths.push(path);
  26030. parsedPaths.push(parsedPath);
  26031. bindings.push(bindingsForPath);
  26032. for (let i = nCachedObjects, n = objects.length; i !== n; ++i) {
  26033. const object = objects[i];
  26034. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  26035. }
  26036. return bindingsForPath;
  26037. }
  26038. unsubscribe_(path) {
  26039. // tells the group to forget about a property path and no longer
  26040. // update the array previously obtained with 'subscribe_'
  26041. const indicesByPath = this._bindingsIndicesByPath,
  26042. index = indicesByPath[path];
  26043. if (index !== undefined) {
  26044. const paths = this._paths,
  26045. parsedPaths = this._parsedPaths,
  26046. bindings = this._bindings,
  26047. lastBindingsIndex = bindings.length - 1,
  26048. lastBindings = bindings[lastBindingsIndex],
  26049. lastBindingsPath = path[lastBindingsIndex];
  26050. indicesByPath[lastBindingsPath] = index;
  26051. bindings[index] = lastBindings;
  26052. bindings.pop();
  26053. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  26054. parsedPaths.pop();
  26055. paths[index] = paths[lastBindingsIndex];
  26056. paths.pop();
  26057. }
  26058. }
  26059. }
  26060. AnimationObjectGroup.prototype.isAnimationObjectGroup = true;
  26061. class AnimationAction {
  26062. constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) {
  26063. this._mixer = mixer;
  26064. this._clip = clip;
  26065. this._localRoot = localRoot;
  26066. this.blendMode = blendMode;
  26067. const tracks = clip.tracks,
  26068. nTracks = tracks.length,
  26069. interpolants = new Array(nTracks);
  26070. const interpolantSettings = {
  26071. endingStart: ZeroCurvatureEnding,
  26072. endingEnd: ZeroCurvatureEnding
  26073. };
  26074. for (let i = 0; i !== nTracks; ++i) {
  26075. const interpolant = tracks[i].createInterpolant(null);
  26076. interpolants[i] = interpolant;
  26077. interpolant.settings = interpolantSettings;
  26078. }
  26079. this._interpolantSettings = interpolantSettings;
  26080. this._interpolants = interpolants; // bound by the mixer
  26081. // inside: PropertyMixer (managed by the mixer)
  26082. this._propertyBindings = new Array(nTracks);
  26083. this._cacheIndex = null; // for the memory manager
  26084. this._byClipCacheIndex = null; // for the memory manager
  26085. this._timeScaleInterpolant = null;
  26086. this._weightInterpolant = null;
  26087. this.loop = LoopRepeat;
  26088. this._loopCount = -1; // global mixer time when the action is to be started
  26089. // it's set back to 'null' upon start of the action
  26090. this._startTime = null; // scaled local time of the action
  26091. // gets clamped or wrapped to 0..clip.duration according to loop
  26092. this.time = 0;
  26093. this.timeScale = 1;
  26094. this._effectiveTimeScale = 1;
  26095. this.weight = 1;
  26096. this._effectiveWeight = 1;
  26097. this.repetitions = Infinity; // no. of repetitions when looping
  26098. this.paused = false; // true -> zero effective time scale
  26099. this.enabled = true; // false -> zero effective weight
  26100. this.clampWhenFinished = false; // keep feeding the last frame?
  26101. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  26102. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  26103. } // State & Scheduling
  26104. play() {
  26105. this._mixer._activateAction(this);
  26106. return this;
  26107. }
  26108. stop() {
  26109. this._mixer._deactivateAction(this);
  26110. return this.reset();
  26111. }
  26112. reset() {
  26113. this.paused = false;
  26114. this.enabled = true;
  26115. this.time = 0; // restart clip
  26116. this._loopCount = -1; // forget previous loops
  26117. this._startTime = null; // forget scheduling
  26118. return this.stopFading().stopWarping();
  26119. }
  26120. isRunning() {
  26121. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  26122. } // return true when play has been called
  26123. isScheduled() {
  26124. return this._mixer._isActiveAction(this);
  26125. }
  26126. startAt(time) {
  26127. this._startTime = time;
  26128. return this;
  26129. }
  26130. setLoop(mode, repetitions) {
  26131. this.loop = mode;
  26132. this.repetitions = repetitions;
  26133. return this;
  26134. } // Weight
  26135. // set the weight stopping any scheduled fading
  26136. // although .enabled = false yields an effective weight of zero, this
  26137. // method does *not* change .enabled, because it would be confusing
  26138. setEffectiveWeight(weight) {
  26139. this.weight = weight; // note: same logic as when updated at runtime
  26140. this._effectiveWeight = this.enabled ? weight : 0;
  26141. return this.stopFading();
  26142. } // return the weight considering fading and .enabled
  26143. getEffectiveWeight() {
  26144. return this._effectiveWeight;
  26145. }
  26146. fadeIn(duration) {
  26147. return this._scheduleFading(duration, 0, 1);
  26148. }
  26149. fadeOut(duration) {
  26150. return this._scheduleFading(duration, 1, 0);
  26151. }
  26152. crossFadeFrom(fadeOutAction, duration, warp) {
  26153. fadeOutAction.fadeOut(duration);
  26154. this.fadeIn(duration);
  26155. if (warp) {
  26156. const fadeInDuration = this._clip.duration,
  26157. fadeOutDuration = fadeOutAction._clip.duration,
  26158. startEndRatio = fadeOutDuration / fadeInDuration,
  26159. endStartRatio = fadeInDuration / fadeOutDuration;
  26160. fadeOutAction.warp(1.0, startEndRatio, duration);
  26161. this.warp(endStartRatio, 1.0, duration);
  26162. }
  26163. return this;
  26164. }
  26165. crossFadeTo(fadeInAction, duration, warp) {
  26166. return fadeInAction.crossFadeFrom(this, duration, warp);
  26167. }
  26168. stopFading() {
  26169. const weightInterpolant = this._weightInterpolant;
  26170. if (weightInterpolant !== null) {
  26171. this._weightInterpolant = null;
  26172. this._mixer._takeBackControlInterpolant(weightInterpolant);
  26173. }
  26174. return this;
  26175. } // Time Scale Control
  26176. // set the time scale stopping any scheduled warping
  26177. // although .paused = true yields an effective time scale of zero, this
  26178. // method does *not* change .paused, because it would be confusing
  26179. setEffectiveTimeScale(timeScale) {
  26180. this.timeScale = timeScale;
  26181. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  26182. return this.stopWarping();
  26183. } // return the time scale considering warping and .paused
  26184. getEffectiveTimeScale() {
  26185. return this._effectiveTimeScale;
  26186. }
  26187. setDuration(duration) {
  26188. this.timeScale = this._clip.duration / duration;
  26189. return this.stopWarping();
  26190. }
  26191. syncWith(action) {
  26192. this.time = action.time;
  26193. this.timeScale = action.timeScale;
  26194. return this.stopWarping();
  26195. }
  26196. halt(duration) {
  26197. return this.warp(this._effectiveTimeScale, 0, duration);
  26198. }
  26199. warp(startTimeScale, endTimeScale, duration) {
  26200. const mixer = this._mixer,
  26201. now = mixer.time,
  26202. timeScale = this.timeScale;
  26203. let interpolant = this._timeScaleInterpolant;
  26204. if (interpolant === null) {
  26205. interpolant = mixer._lendControlInterpolant();
  26206. this._timeScaleInterpolant = interpolant;
  26207. }
  26208. const times = interpolant.parameterPositions,
  26209. values = interpolant.sampleValues;
  26210. times[0] = now;
  26211. times[1] = now + duration;
  26212. values[0] = startTimeScale / timeScale;
  26213. values[1] = endTimeScale / timeScale;
  26214. return this;
  26215. }
  26216. stopWarping() {
  26217. const timeScaleInterpolant = this._timeScaleInterpolant;
  26218. if (timeScaleInterpolant !== null) {
  26219. this._timeScaleInterpolant = null;
  26220. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  26221. }
  26222. return this;
  26223. } // Object Accessors
  26224. getMixer() {
  26225. return this._mixer;
  26226. }
  26227. getClip() {
  26228. return this._clip;
  26229. }
  26230. getRoot() {
  26231. return this._localRoot || this._mixer._root;
  26232. } // Interna
  26233. _update(time, deltaTime, timeDirection, accuIndex) {
  26234. // called by the mixer
  26235. if (!this.enabled) {
  26236. // call ._updateWeight() to update ._effectiveWeight
  26237. this._updateWeight(time);
  26238. return;
  26239. }
  26240. const startTime = this._startTime;
  26241. if (startTime !== null) {
  26242. // check for scheduled start of action
  26243. const timeRunning = (time - startTime) * timeDirection;
  26244. if (timeRunning < 0 || timeDirection === 0) {
  26245. return; // yet to come / don't decide when delta = 0
  26246. } // start
  26247. this._startTime = null; // unschedule
  26248. deltaTime = timeDirection * timeRunning;
  26249. } // apply time scale and advance time
  26250. deltaTime *= this._updateTimeScale(time);
  26251. const clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  26252. // an effective weight of 0
  26253. const weight = this._updateWeight(time);
  26254. if (weight > 0) {
  26255. const interpolants = this._interpolants;
  26256. const propertyMixers = this._propertyBindings;
  26257. switch (this.blendMode) {
  26258. case AdditiveAnimationBlendMode:
  26259. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26260. interpolants[j].evaluate(clipTime);
  26261. propertyMixers[j].accumulateAdditive(weight);
  26262. }
  26263. break;
  26264. case NormalAnimationBlendMode:
  26265. default:
  26266. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26267. interpolants[j].evaluate(clipTime);
  26268. propertyMixers[j].accumulate(accuIndex, weight);
  26269. }
  26270. }
  26271. }
  26272. }
  26273. _updateWeight(time) {
  26274. let weight = 0;
  26275. if (this.enabled) {
  26276. weight = this.weight;
  26277. const interpolant = this._weightInterpolant;
  26278. if (interpolant !== null) {
  26279. const interpolantValue = interpolant.evaluate(time)[0];
  26280. weight *= interpolantValue;
  26281. if (time > interpolant.parameterPositions[1]) {
  26282. this.stopFading();
  26283. if (interpolantValue === 0) {
  26284. // faded out, disable
  26285. this.enabled = false;
  26286. }
  26287. }
  26288. }
  26289. }
  26290. this._effectiveWeight = weight;
  26291. return weight;
  26292. }
  26293. _updateTimeScale(time) {
  26294. let timeScale = 0;
  26295. if (!this.paused) {
  26296. timeScale = this.timeScale;
  26297. const interpolant = this._timeScaleInterpolant;
  26298. if (interpolant !== null) {
  26299. const interpolantValue = interpolant.evaluate(time)[0];
  26300. timeScale *= interpolantValue;
  26301. if (time > interpolant.parameterPositions[1]) {
  26302. this.stopWarping();
  26303. if (timeScale === 0) {
  26304. // motion has halted, pause
  26305. this.paused = true;
  26306. } else {
  26307. // warp done - apply final time scale
  26308. this.timeScale = timeScale;
  26309. }
  26310. }
  26311. }
  26312. }
  26313. this._effectiveTimeScale = timeScale;
  26314. return timeScale;
  26315. }
  26316. _updateTime(deltaTime) {
  26317. const duration = this._clip.duration;
  26318. const loop = this.loop;
  26319. let time = this.time + deltaTime;
  26320. let loopCount = this._loopCount;
  26321. const pingPong = loop === LoopPingPong;
  26322. if (deltaTime === 0) {
  26323. if (loopCount === -1) return time;
  26324. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  26325. }
  26326. if (loop === LoopOnce) {
  26327. if (loopCount === -1) {
  26328. // just started
  26329. this._loopCount = 0;
  26330. this._setEndings(true, true, false);
  26331. }
  26332. handle_stop: {
  26333. if (time >= duration) {
  26334. time = duration;
  26335. } else if (time < 0) {
  26336. time = 0;
  26337. } else {
  26338. this.time = time;
  26339. break handle_stop;
  26340. }
  26341. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26342. this.time = time;
  26343. this._mixer.dispatchEvent({
  26344. type: 'finished',
  26345. action: this,
  26346. direction: deltaTime < 0 ? -1 : 1
  26347. });
  26348. }
  26349. } else {
  26350. // repetitive Repeat or PingPong
  26351. if (loopCount === -1) {
  26352. // just started
  26353. if (deltaTime >= 0) {
  26354. loopCount = 0;
  26355. this._setEndings(true, this.repetitions === 0, pingPong);
  26356. } else {
  26357. // when looping in reverse direction, the initial
  26358. // transition through zero counts as a repetition,
  26359. // so leave loopCount at -1
  26360. this._setEndings(this.repetitions === 0, true, pingPong);
  26361. }
  26362. }
  26363. if (time >= duration || time < 0) {
  26364. // wrap around
  26365. const loopDelta = Math.floor(time / duration); // signed
  26366. time -= duration * loopDelta;
  26367. loopCount += Math.abs(loopDelta);
  26368. const pending = this.repetitions - loopCount;
  26369. if (pending <= 0) {
  26370. // have to stop (switch state, clamp time, fire event)
  26371. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26372. time = deltaTime > 0 ? duration : 0;
  26373. this.time = time;
  26374. this._mixer.dispatchEvent({
  26375. type: 'finished',
  26376. action: this,
  26377. direction: deltaTime > 0 ? 1 : -1
  26378. });
  26379. } else {
  26380. // keep running
  26381. if (pending === 1) {
  26382. // entering the last round
  26383. const atStart = deltaTime < 0;
  26384. this._setEndings(atStart, !atStart, pingPong);
  26385. } else {
  26386. this._setEndings(false, false, pingPong);
  26387. }
  26388. this._loopCount = loopCount;
  26389. this.time = time;
  26390. this._mixer.dispatchEvent({
  26391. type: 'loop',
  26392. action: this,
  26393. loopDelta: loopDelta
  26394. });
  26395. }
  26396. } else {
  26397. this.time = time;
  26398. }
  26399. if (pingPong && (loopCount & 1) === 1) {
  26400. // invert time for the "pong round"
  26401. return duration - time;
  26402. }
  26403. }
  26404. return time;
  26405. }
  26406. _setEndings(atStart, atEnd, pingPong) {
  26407. const settings = this._interpolantSettings;
  26408. if (pingPong) {
  26409. settings.endingStart = ZeroSlopeEnding;
  26410. settings.endingEnd = ZeroSlopeEnding;
  26411. } else {
  26412. // assuming for LoopOnce atStart == atEnd == true
  26413. if (atStart) {
  26414. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26415. } else {
  26416. settings.endingStart = WrapAroundEnding;
  26417. }
  26418. if (atEnd) {
  26419. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26420. } else {
  26421. settings.endingEnd = WrapAroundEnding;
  26422. }
  26423. }
  26424. }
  26425. _scheduleFading(duration, weightNow, weightThen) {
  26426. const mixer = this._mixer,
  26427. now = mixer.time;
  26428. let interpolant = this._weightInterpolant;
  26429. if (interpolant === null) {
  26430. interpolant = mixer._lendControlInterpolant();
  26431. this._weightInterpolant = interpolant;
  26432. }
  26433. const times = interpolant.parameterPositions,
  26434. values = interpolant.sampleValues;
  26435. times[0] = now;
  26436. values[0] = weightNow;
  26437. times[1] = now + duration;
  26438. values[1] = weightThen;
  26439. return this;
  26440. }
  26441. }
  26442. class AnimationMixer extends EventDispatcher {
  26443. constructor(root) {
  26444. super();
  26445. this._root = root;
  26446. this._initMemoryManager();
  26447. this._accuIndex = 0;
  26448. this.time = 0;
  26449. this.timeScale = 1.0;
  26450. }
  26451. _bindAction(action, prototypeAction) {
  26452. const root = action._localRoot || this._root,
  26453. tracks = action._clip.tracks,
  26454. nTracks = tracks.length,
  26455. bindings = action._propertyBindings,
  26456. interpolants = action._interpolants,
  26457. rootUuid = root.uuid,
  26458. bindingsByRoot = this._bindingsByRootAndName;
  26459. let bindingsByName = bindingsByRoot[rootUuid];
  26460. if (bindingsByName === undefined) {
  26461. bindingsByName = {};
  26462. bindingsByRoot[rootUuid] = bindingsByName;
  26463. }
  26464. for (let i = 0; i !== nTracks; ++i) {
  26465. const track = tracks[i],
  26466. trackName = track.name;
  26467. let binding = bindingsByName[trackName];
  26468. if (binding !== undefined) {
  26469. bindings[i] = binding;
  26470. } else {
  26471. binding = bindings[i];
  26472. if (binding !== undefined) {
  26473. // existing binding, make sure the cache knows
  26474. if (binding._cacheIndex === null) {
  26475. ++binding.referenceCount;
  26476. this._addInactiveBinding(binding, rootUuid, trackName);
  26477. }
  26478. continue;
  26479. }
  26480. const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  26481. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  26482. ++binding.referenceCount;
  26483. this._addInactiveBinding(binding, rootUuid, trackName);
  26484. bindings[i] = binding;
  26485. }
  26486. interpolants[i].resultBuffer = binding.buffer;
  26487. }
  26488. }
  26489. _activateAction(action) {
  26490. if (!this._isActiveAction(action)) {
  26491. if (action._cacheIndex === null) {
  26492. // this action has been forgotten by the cache, but the user
  26493. // appears to be still using it -> rebind
  26494. const rootUuid = (action._localRoot || this._root).uuid,
  26495. clipUuid = action._clip.uuid,
  26496. actionsForClip = this._actionsByClip[clipUuid];
  26497. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  26498. this._addInactiveAction(action, clipUuid, rootUuid);
  26499. }
  26500. const bindings = action._propertyBindings; // increment reference counts / sort out state
  26501. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26502. const binding = bindings[i];
  26503. if (binding.useCount++ === 0) {
  26504. this._lendBinding(binding);
  26505. binding.saveOriginalState();
  26506. }
  26507. }
  26508. this._lendAction(action);
  26509. }
  26510. }
  26511. _deactivateAction(action) {
  26512. if (this._isActiveAction(action)) {
  26513. const bindings = action._propertyBindings; // decrement reference counts / sort out state
  26514. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26515. const binding = bindings[i];
  26516. if (--binding.useCount === 0) {
  26517. binding.restoreOriginalState();
  26518. this._takeBackBinding(binding);
  26519. }
  26520. }
  26521. this._takeBackAction(action);
  26522. }
  26523. } // Memory manager
  26524. _initMemoryManager() {
  26525. this._actions = []; // 'nActiveActions' followed by inactive ones
  26526. this._nActiveActions = 0;
  26527. this._actionsByClip = {}; // inside:
  26528. // {
  26529. // knownActions: Array< AnimationAction > - used as prototypes
  26530. // actionByRoot: AnimationAction - lookup
  26531. // }
  26532. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  26533. this._nActiveBindings = 0;
  26534. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  26535. this._controlInterpolants = []; // same game as above
  26536. this._nActiveControlInterpolants = 0;
  26537. const scope = this;
  26538. this.stats = {
  26539. actions: {
  26540. get total() {
  26541. return scope._actions.length;
  26542. },
  26543. get inUse() {
  26544. return scope._nActiveActions;
  26545. }
  26546. },
  26547. bindings: {
  26548. get total() {
  26549. return scope._bindings.length;
  26550. },
  26551. get inUse() {
  26552. return scope._nActiveBindings;
  26553. }
  26554. },
  26555. controlInterpolants: {
  26556. get total() {
  26557. return scope._controlInterpolants.length;
  26558. },
  26559. get inUse() {
  26560. return scope._nActiveControlInterpolants;
  26561. }
  26562. }
  26563. };
  26564. } // Memory management for AnimationAction objects
  26565. _isActiveAction(action) {
  26566. const index = action._cacheIndex;
  26567. return index !== null && index < this._nActiveActions;
  26568. }
  26569. _addInactiveAction(action, clipUuid, rootUuid) {
  26570. const actions = this._actions,
  26571. actionsByClip = this._actionsByClip;
  26572. let actionsForClip = actionsByClip[clipUuid];
  26573. if (actionsForClip === undefined) {
  26574. actionsForClip = {
  26575. knownActions: [action],
  26576. actionByRoot: {}
  26577. };
  26578. action._byClipCacheIndex = 0;
  26579. actionsByClip[clipUuid] = actionsForClip;
  26580. } else {
  26581. const knownActions = actionsForClip.knownActions;
  26582. action._byClipCacheIndex = knownActions.length;
  26583. knownActions.push(action);
  26584. }
  26585. action._cacheIndex = actions.length;
  26586. actions.push(action);
  26587. actionsForClip.actionByRoot[rootUuid] = action;
  26588. }
  26589. _removeInactiveAction(action) {
  26590. const actions = this._actions,
  26591. lastInactiveAction = actions[actions.length - 1],
  26592. cacheIndex = action._cacheIndex;
  26593. lastInactiveAction._cacheIndex = cacheIndex;
  26594. actions[cacheIndex] = lastInactiveAction;
  26595. actions.pop();
  26596. action._cacheIndex = null;
  26597. const clipUuid = action._clip.uuid,
  26598. actionsByClip = this._actionsByClip,
  26599. actionsForClip = actionsByClip[clipUuid],
  26600. knownActionsForClip = actionsForClip.knownActions,
  26601. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  26602. byClipCacheIndex = action._byClipCacheIndex;
  26603. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  26604. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  26605. knownActionsForClip.pop();
  26606. action._byClipCacheIndex = null;
  26607. const actionByRoot = actionsForClip.actionByRoot,
  26608. rootUuid = (action._localRoot || this._root).uuid;
  26609. delete actionByRoot[rootUuid];
  26610. if (knownActionsForClip.length === 0) {
  26611. delete actionsByClip[clipUuid];
  26612. }
  26613. this._removeInactiveBindingsForAction(action);
  26614. }
  26615. _removeInactiveBindingsForAction(action) {
  26616. const bindings = action._propertyBindings;
  26617. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26618. const binding = bindings[i];
  26619. if (--binding.referenceCount === 0) {
  26620. this._removeInactiveBinding(binding);
  26621. }
  26622. }
  26623. }
  26624. _lendAction(action) {
  26625. // [ active actions | inactive actions ]
  26626. // [ active actions >| inactive actions ]
  26627. // s a
  26628. // <-swap->
  26629. // a s
  26630. const actions = this._actions,
  26631. prevIndex = action._cacheIndex,
  26632. lastActiveIndex = this._nActiveActions++,
  26633. firstInactiveAction = actions[lastActiveIndex];
  26634. action._cacheIndex = lastActiveIndex;
  26635. actions[lastActiveIndex] = action;
  26636. firstInactiveAction._cacheIndex = prevIndex;
  26637. actions[prevIndex] = firstInactiveAction;
  26638. }
  26639. _takeBackAction(action) {
  26640. // [ active actions | inactive actions ]
  26641. // [ active actions |< inactive actions ]
  26642. // a s
  26643. // <-swap->
  26644. // s a
  26645. const actions = this._actions,
  26646. prevIndex = action._cacheIndex,
  26647. firstInactiveIndex = --this._nActiveActions,
  26648. lastActiveAction = actions[firstInactiveIndex];
  26649. action._cacheIndex = firstInactiveIndex;
  26650. actions[firstInactiveIndex] = action;
  26651. lastActiveAction._cacheIndex = prevIndex;
  26652. actions[prevIndex] = lastActiveAction;
  26653. } // Memory management for PropertyMixer objects
  26654. _addInactiveBinding(binding, rootUuid, trackName) {
  26655. const bindingsByRoot = this._bindingsByRootAndName,
  26656. bindings = this._bindings;
  26657. let bindingByName = bindingsByRoot[rootUuid];
  26658. if (bindingByName === undefined) {
  26659. bindingByName = {};
  26660. bindingsByRoot[rootUuid] = bindingByName;
  26661. }
  26662. bindingByName[trackName] = binding;
  26663. binding._cacheIndex = bindings.length;
  26664. bindings.push(binding);
  26665. }
  26666. _removeInactiveBinding(binding) {
  26667. const bindings = this._bindings,
  26668. propBinding = binding.binding,
  26669. rootUuid = propBinding.rootNode.uuid,
  26670. trackName = propBinding.path,
  26671. bindingsByRoot = this._bindingsByRootAndName,
  26672. bindingByName = bindingsByRoot[rootUuid],
  26673. lastInactiveBinding = bindings[bindings.length - 1],
  26674. cacheIndex = binding._cacheIndex;
  26675. lastInactiveBinding._cacheIndex = cacheIndex;
  26676. bindings[cacheIndex] = lastInactiveBinding;
  26677. bindings.pop();
  26678. delete bindingByName[trackName];
  26679. if (Object.keys(bindingByName).length === 0) {
  26680. delete bindingsByRoot[rootUuid];
  26681. }
  26682. }
  26683. _lendBinding(binding) {
  26684. const bindings = this._bindings,
  26685. prevIndex = binding._cacheIndex,
  26686. lastActiveIndex = this._nActiveBindings++,
  26687. firstInactiveBinding = bindings[lastActiveIndex];
  26688. binding._cacheIndex = lastActiveIndex;
  26689. bindings[lastActiveIndex] = binding;
  26690. firstInactiveBinding._cacheIndex = prevIndex;
  26691. bindings[prevIndex] = firstInactiveBinding;
  26692. }
  26693. _takeBackBinding(binding) {
  26694. const bindings = this._bindings,
  26695. prevIndex = binding._cacheIndex,
  26696. firstInactiveIndex = --this._nActiveBindings,
  26697. lastActiveBinding = bindings[firstInactiveIndex];
  26698. binding._cacheIndex = firstInactiveIndex;
  26699. bindings[firstInactiveIndex] = binding;
  26700. lastActiveBinding._cacheIndex = prevIndex;
  26701. bindings[prevIndex] = lastActiveBinding;
  26702. } // Memory management of Interpolants for weight and time scale
  26703. _lendControlInterpolant() {
  26704. const interpolants = this._controlInterpolants,
  26705. lastActiveIndex = this._nActiveControlInterpolants++;
  26706. let interpolant = interpolants[lastActiveIndex];
  26707. if (interpolant === undefined) {
  26708. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  26709. interpolant.__cacheIndex = lastActiveIndex;
  26710. interpolants[lastActiveIndex] = interpolant;
  26711. }
  26712. return interpolant;
  26713. }
  26714. _takeBackControlInterpolant(interpolant) {
  26715. const interpolants = this._controlInterpolants,
  26716. prevIndex = interpolant.__cacheIndex,
  26717. firstInactiveIndex = --this._nActiveControlInterpolants,
  26718. lastActiveInterpolant = interpolants[firstInactiveIndex];
  26719. interpolant.__cacheIndex = firstInactiveIndex;
  26720. interpolants[firstInactiveIndex] = interpolant;
  26721. lastActiveInterpolant.__cacheIndex = prevIndex;
  26722. interpolants[prevIndex] = lastActiveInterpolant;
  26723. } // return an action for a clip optionally using a custom root target
  26724. // object (this method allocates a lot of dynamic memory in case a
  26725. // previously unknown clip/root combination is specified)
  26726. clipAction(clip, optionalRoot, blendMode) {
  26727. const root = optionalRoot || this._root,
  26728. rootUuid = root.uuid;
  26729. let clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
  26730. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  26731. const actionsForClip = this._actionsByClip[clipUuid];
  26732. let prototypeAction = null;
  26733. if (blendMode === undefined) {
  26734. if (clipObject !== null) {
  26735. blendMode = clipObject.blendMode;
  26736. } else {
  26737. blendMode = NormalAnimationBlendMode;
  26738. }
  26739. }
  26740. if (actionsForClip !== undefined) {
  26741. const existingAction = actionsForClip.actionByRoot[rootUuid];
  26742. if (existingAction !== undefined && existingAction.blendMode === blendMode) {
  26743. return existingAction;
  26744. } // we know the clip, so we don't have to parse all
  26745. // the bindings again but can just copy
  26746. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  26747. if (clipObject === null) clipObject = prototypeAction._clip;
  26748. } // clip must be known when specified via string
  26749. if (clipObject === null) return null; // allocate all resources required to run it
  26750. const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
  26751. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  26752. this._addInactiveAction(newAction, clipUuid, rootUuid);
  26753. return newAction;
  26754. } // get an existing action
  26755. existingAction(clip, optionalRoot) {
  26756. const root = optionalRoot || this._root,
  26757. rootUuid = root.uuid,
  26758. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  26759. clipUuid = clipObject ? clipObject.uuid : clip,
  26760. actionsForClip = this._actionsByClip[clipUuid];
  26761. if (actionsForClip !== undefined) {
  26762. return actionsForClip.actionByRoot[rootUuid] || null;
  26763. }
  26764. return null;
  26765. } // deactivates all previously scheduled actions
  26766. stopAllAction() {
  26767. const actions = this._actions,
  26768. nActions = this._nActiveActions;
  26769. for (let i = nActions - 1; i >= 0; --i) {
  26770. actions[i].stop();
  26771. }
  26772. return this;
  26773. } // advance the time and update apply the animation
  26774. update(deltaTime) {
  26775. deltaTime *= this.timeScale;
  26776. const actions = this._actions,
  26777. nActions = this._nActiveActions,
  26778. time = this.time += deltaTime,
  26779. timeDirection = Math.sign(deltaTime),
  26780. accuIndex = this._accuIndex ^= 1; // run active actions
  26781. for (let i = 0; i !== nActions; ++i) {
  26782. const action = actions[i];
  26783. action._update(time, deltaTime, timeDirection, accuIndex);
  26784. } // update scene graph
  26785. const bindings = this._bindings,
  26786. nBindings = this._nActiveBindings;
  26787. for (let i = 0; i !== nBindings; ++i) {
  26788. bindings[i].apply(accuIndex);
  26789. }
  26790. return this;
  26791. } // Allows you to seek to a specific time in an animation.
  26792. setTime(timeInSeconds) {
  26793. this.time = 0; // Zero out time attribute for AnimationMixer object;
  26794. for (let i = 0; i < this._actions.length; i++) {
  26795. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  26796. }
  26797. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  26798. } // return this mixer's root target object
  26799. getRoot() {
  26800. return this._root;
  26801. } // free all resources specific to a particular clip
  26802. uncacheClip(clip) {
  26803. const actions = this._actions,
  26804. clipUuid = clip.uuid,
  26805. actionsByClip = this._actionsByClip,
  26806. actionsForClip = actionsByClip[clipUuid];
  26807. if (actionsForClip !== undefined) {
  26808. // note: just calling _removeInactiveAction would mess up the
  26809. // iteration state and also require updating the state we can
  26810. // just throw away
  26811. const actionsToRemove = actionsForClip.knownActions;
  26812. for (let i = 0, n = actionsToRemove.length; i !== n; ++i) {
  26813. const action = actionsToRemove[i];
  26814. this._deactivateAction(action);
  26815. const cacheIndex = action._cacheIndex,
  26816. lastInactiveAction = actions[actions.length - 1];
  26817. action._cacheIndex = null;
  26818. action._byClipCacheIndex = null;
  26819. lastInactiveAction._cacheIndex = cacheIndex;
  26820. actions[cacheIndex] = lastInactiveAction;
  26821. actions.pop();
  26822. this._removeInactiveBindingsForAction(action);
  26823. }
  26824. delete actionsByClip[clipUuid];
  26825. }
  26826. } // free all resources specific to a particular root target object
  26827. uncacheRoot(root) {
  26828. const rootUuid = root.uuid,
  26829. actionsByClip = this._actionsByClip;
  26830. for (const clipUuid in actionsByClip) {
  26831. const actionByRoot = actionsByClip[clipUuid].actionByRoot,
  26832. action = actionByRoot[rootUuid];
  26833. if (action !== undefined) {
  26834. this._deactivateAction(action);
  26835. this._removeInactiveAction(action);
  26836. }
  26837. }
  26838. const bindingsByRoot = this._bindingsByRootAndName,
  26839. bindingByName = bindingsByRoot[rootUuid];
  26840. if (bindingByName !== undefined) {
  26841. for (const trackName in bindingByName) {
  26842. const binding = bindingByName[trackName];
  26843. binding.restoreOriginalState();
  26844. this._removeInactiveBinding(binding);
  26845. }
  26846. }
  26847. } // remove a targeted clip from the cache
  26848. uncacheAction(clip, optionalRoot) {
  26849. const action = this.existingAction(clip, optionalRoot);
  26850. if (action !== null) {
  26851. this._deactivateAction(action);
  26852. this._removeInactiveAction(action);
  26853. }
  26854. }
  26855. }
  26856. AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array(1);
  26857. class Uniform {
  26858. constructor(value) {
  26859. if (typeof value === 'string') {
  26860. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  26861. value = arguments[1];
  26862. }
  26863. this.value = value;
  26864. }
  26865. clone() {
  26866. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  26867. }
  26868. }
  26869. class InstancedInterleavedBuffer extends InterleavedBuffer {
  26870. constructor(array, stride, meshPerAttribute = 1) {
  26871. super(array, stride);
  26872. this.meshPerAttribute = meshPerAttribute;
  26873. }
  26874. copy(source) {
  26875. super.copy(source);
  26876. this.meshPerAttribute = source.meshPerAttribute;
  26877. return this;
  26878. }
  26879. clone(data) {
  26880. const ib = super.clone(data);
  26881. ib.meshPerAttribute = this.meshPerAttribute;
  26882. return ib;
  26883. }
  26884. toJSON(data) {
  26885. const json = super.toJSON(data);
  26886. json.isInstancedInterleavedBuffer = true;
  26887. json.meshPerAttribute = this.meshPerAttribute;
  26888. return json;
  26889. }
  26890. }
  26891. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  26892. class GLBufferAttribute {
  26893. constructor(buffer, type, itemSize, elementSize, count) {
  26894. this.buffer = buffer;
  26895. this.type = type;
  26896. this.itemSize = itemSize;
  26897. this.elementSize = elementSize;
  26898. this.count = count;
  26899. this.version = 0;
  26900. }
  26901. set needsUpdate(value) {
  26902. if (value === true) this.version++;
  26903. }
  26904. setBuffer(buffer) {
  26905. this.buffer = buffer;
  26906. return this;
  26907. }
  26908. setType(type, elementSize) {
  26909. this.type = type;
  26910. this.elementSize = elementSize;
  26911. return this;
  26912. }
  26913. setItemSize(itemSize) {
  26914. this.itemSize = itemSize;
  26915. return this;
  26916. }
  26917. setCount(count) {
  26918. this.count = count;
  26919. return this;
  26920. }
  26921. }
  26922. GLBufferAttribute.prototype.isGLBufferAttribute = true;
  26923. class Raycaster {
  26924. constructor(origin, direction, near = 0, far = Infinity) {
  26925. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  26926. this.near = near;
  26927. this.far = far;
  26928. this.camera = null;
  26929. this.layers = new Layers();
  26930. this.params = {
  26931. Mesh: {},
  26932. Line: {
  26933. threshold: 1
  26934. },
  26935. LOD: {},
  26936. Points: {
  26937. threshold: 1
  26938. },
  26939. Sprite: {}
  26940. };
  26941. }
  26942. set(origin, direction) {
  26943. // direction is assumed to be normalized (for accurate distance calculations)
  26944. this.ray.set(origin, direction);
  26945. }
  26946. setFromCamera(coords, camera) {
  26947. if (camera && camera.isPerspectiveCamera) {
  26948. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  26949. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  26950. this.camera = camera;
  26951. } else if (camera && camera.isOrthographicCamera) {
  26952. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  26953. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  26954. this.camera = camera;
  26955. } else {
  26956. console.error('THREE.Raycaster: Unsupported camera type: ' + camera.type);
  26957. }
  26958. }
  26959. intersectObject(object, recursive = false, intersects = []) {
  26960. intersectObject(object, this, intersects, recursive);
  26961. intersects.sort(ascSort);
  26962. return intersects;
  26963. }
  26964. intersectObjects(objects, recursive = false, intersects = []) {
  26965. for (let i = 0, l = objects.length; i < l; i++) {
  26966. intersectObject(objects[i], this, intersects, recursive);
  26967. }
  26968. intersects.sort(ascSort);
  26969. return intersects;
  26970. }
  26971. }
  26972. function ascSort(a, b) {
  26973. return a.distance - b.distance;
  26974. }
  26975. function intersectObject(object, raycaster, intersects, recursive) {
  26976. if (object.layers.test(raycaster.layers)) {
  26977. object.raycast(raycaster, intersects);
  26978. }
  26979. if (recursive === true) {
  26980. const children = object.children;
  26981. for (let i = 0, l = children.length; i < l; i++) {
  26982. intersectObject(children[i], raycaster, intersects, true);
  26983. }
  26984. }
  26985. }
  26986. /**
  26987. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  26988. *
  26989. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  26990. * The azimuthal angle (theta) is measured from the positive z-axis.
  26991. */
  26992. class Spherical {
  26993. constructor(radius = 1, phi = 0, theta = 0) {
  26994. this.radius = radius;
  26995. this.phi = phi; // polar angle
  26996. this.theta = theta; // azimuthal angle
  26997. return this;
  26998. }
  26999. set(radius, phi, theta) {
  27000. this.radius = radius;
  27001. this.phi = phi;
  27002. this.theta = theta;
  27003. return this;
  27004. }
  27005. copy(other) {
  27006. this.radius = other.radius;
  27007. this.phi = other.phi;
  27008. this.theta = other.theta;
  27009. return this;
  27010. } // restrict phi to be betwee EPS and PI-EPS
  27011. makeSafe() {
  27012. const EPS = 0.000001;
  27013. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  27014. return this;
  27015. }
  27016. setFromVector3(v) {
  27017. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27018. }
  27019. setFromCartesianCoords(x, y, z) {
  27020. this.radius = Math.sqrt(x * x + y * y + z * z);
  27021. if (this.radius === 0) {
  27022. this.theta = 0;
  27023. this.phi = 0;
  27024. } else {
  27025. this.theta = Math.atan2(x, z);
  27026. this.phi = Math.acos(clamp(y / this.radius, -1, 1));
  27027. }
  27028. return this;
  27029. }
  27030. clone() {
  27031. return new this.constructor().copy(this);
  27032. }
  27033. }
  27034. /**
  27035. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27036. */
  27037. class Cylindrical {
  27038. constructor(radius = 1, theta = 0, y = 0) {
  27039. this.radius = radius; // distance from the origin to a point in the x-z plane
  27040. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27041. this.y = y; // height above the x-z plane
  27042. return this;
  27043. }
  27044. set(radius, theta, y) {
  27045. this.radius = radius;
  27046. this.theta = theta;
  27047. this.y = y;
  27048. return this;
  27049. }
  27050. copy(other) {
  27051. this.radius = other.radius;
  27052. this.theta = other.theta;
  27053. this.y = other.y;
  27054. return this;
  27055. }
  27056. setFromVector3(v) {
  27057. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27058. }
  27059. setFromCartesianCoords(x, y, z) {
  27060. this.radius = Math.sqrt(x * x + z * z);
  27061. this.theta = Math.atan2(x, z);
  27062. this.y = y;
  27063. return this;
  27064. }
  27065. clone() {
  27066. return new this.constructor().copy(this);
  27067. }
  27068. }
  27069. const _vector$4 = /*@__PURE__*/new Vector2();
  27070. class Box2 {
  27071. constructor(min = new Vector2(+Infinity, +Infinity), max = new Vector2(-Infinity, -Infinity)) {
  27072. this.min = min;
  27073. this.max = max;
  27074. }
  27075. set(min, max) {
  27076. this.min.copy(min);
  27077. this.max.copy(max);
  27078. return this;
  27079. }
  27080. setFromPoints(points) {
  27081. this.makeEmpty();
  27082. for (let i = 0, il = points.length; i < il; i++) {
  27083. this.expandByPoint(points[i]);
  27084. }
  27085. return this;
  27086. }
  27087. setFromCenterAndSize(center, size) {
  27088. const halfSize = _vector$4.copy(size).multiplyScalar(0.5);
  27089. this.min.copy(center).sub(halfSize);
  27090. this.max.copy(center).add(halfSize);
  27091. return this;
  27092. }
  27093. clone() {
  27094. return new this.constructor().copy(this);
  27095. }
  27096. copy(box) {
  27097. this.min.copy(box.min);
  27098. this.max.copy(box.max);
  27099. return this;
  27100. }
  27101. makeEmpty() {
  27102. this.min.x = this.min.y = +Infinity;
  27103. this.max.x = this.max.y = -Infinity;
  27104. return this;
  27105. }
  27106. isEmpty() {
  27107. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27108. return this.max.x < this.min.x || this.max.y < this.min.y;
  27109. }
  27110. getCenter(target) {
  27111. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  27112. }
  27113. getSize(target) {
  27114. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  27115. }
  27116. expandByPoint(point) {
  27117. this.min.min(point);
  27118. this.max.max(point);
  27119. return this;
  27120. }
  27121. expandByVector(vector) {
  27122. this.min.sub(vector);
  27123. this.max.add(vector);
  27124. return this;
  27125. }
  27126. expandByScalar(scalar) {
  27127. this.min.addScalar(-scalar);
  27128. this.max.addScalar(scalar);
  27129. return this;
  27130. }
  27131. containsPoint(point) {
  27132. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  27133. }
  27134. containsBox(box) {
  27135. 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;
  27136. }
  27137. getParameter(point, target) {
  27138. // This can potentially have a divide by zero if the box
  27139. // has a size dimension of 0.
  27140. 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));
  27141. }
  27142. intersectsBox(box) {
  27143. // using 4 splitting planes to rule out intersections
  27144. 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;
  27145. }
  27146. clampPoint(point, target) {
  27147. return target.copy(point).clamp(this.min, this.max);
  27148. }
  27149. distanceToPoint(point) {
  27150. const clampedPoint = _vector$4.copy(point).clamp(this.min, this.max);
  27151. return clampedPoint.sub(point).length();
  27152. }
  27153. intersect(box) {
  27154. this.min.max(box.min);
  27155. this.max.min(box.max);
  27156. return this;
  27157. }
  27158. union(box) {
  27159. this.min.min(box.min);
  27160. this.max.max(box.max);
  27161. return this;
  27162. }
  27163. translate(offset) {
  27164. this.min.add(offset);
  27165. this.max.add(offset);
  27166. return this;
  27167. }
  27168. equals(box) {
  27169. return box.min.equals(this.min) && box.max.equals(this.max);
  27170. }
  27171. }
  27172. Box2.prototype.isBox2 = true;
  27173. const _startP = /*@__PURE__*/new Vector3();
  27174. const _startEnd = /*@__PURE__*/new Vector3();
  27175. class Line3 {
  27176. constructor(start = new Vector3(), end = new Vector3()) {
  27177. this.start = start;
  27178. this.end = end;
  27179. }
  27180. set(start, end) {
  27181. this.start.copy(start);
  27182. this.end.copy(end);
  27183. return this;
  27184. }
  27185. copy(line) {
  27186. this.start.copy(line.start);
  27187. this.end.copy(line.end);
  27188. return this;
  27189. }
  27190. getCenter(target) {
  27191. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  27192. }
  27193. delta(target) {
  27194. return target.subVectors(this.end, this.start);
  27195. }
  27196. distanceSq() {
  27197. return this.start.distanceToSquared(this.end);
  27198. }
  27199. distance() {
  27200. return this.start.distanceTo(this.end);
  27201. }
  27202. at(t, target) {
  27203. return this.delta(target).multiplyScalar(t).add(this.start);
  27204. }
  27205. closestPointToPointParameter(point, clampToLine) {
  27206. _startP.subVectors(point, this.start);
  27207. _startEnd.subVectors(this.end, this.start);
  27208. const startEnd2 = _startEnd.dot(_startEnd);
  27209. const startEnd_startP = _startEnd.dot(_startP);
  27210. let t = startEnd_startP / startEnd2;
  27211. if (clampToLine) {
  27212. t = clamp(t, 0, 1);
  27213. }
  27214. return t;
  27215. }
  27216. closestPointToPoint(point, clampToLine, target) {
  27217. const t = this.closestPointToPointParameter(point, clampToLine);
  27218. return this.delta(target).multiplyScalar(t).add(this.start);
  27219. }
  27220. applyMatrix4(matrix) {
  27221. this.start.applyMatrix4(matrix);
  27222. this.end.applyMatrix4(matrix);
  27223. return this;
  27224. }
  27225. equals(line) {
  27226. return line.start.equals(this.start) && line.end.equals(this.end);
  27227. }
  27228. clone() {
  27229. return new this.constructor().copy(this);
  27230. }
  27231. }
  27232. class ImmediateRenderObject extends Object3D {
  27233. constructor(material) {
  27234. super();
  27235. this.material = material;
  27236. this.render = function () {};
  27237. this.hasPositions = false;
  27238. this.hasNormals = false;
  27239. this.hasColors = false;
  27240. this.hasUvs = false;
  27241. this.positionArray = null;
  27242. this.normalArray = null;
  27243. this.colorArray = null;
  27244. this.uvArray = null;
  27245. this.count = 0;
  27246. }
  27247. }
  27248. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  27249. const _vector$3 = /*@__PURE__*/new Vector3();
  27250. class SpotLightHelper extends Object3D {
  27251. constructor(light, color) {
  27252. super();
  27253. this.light = light;
  27254. this.light.updateMatrixWorld();
  27255. this.matrix = light.matrixWorld;
  27256. this.matrixAutoUpdate = false;
  27257. this.color = color;
  27258. const geometry = new BufferGeometry();
  27259. 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];
  27260. for (let i = 0, j = 1, l = 32; i < l; i++, j++) {
  27261. const p1 = i / l * Math.PI * 2;
  27262. const p2 = j / l * Math.PI * 2;
  27263. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  27264. }
  27265. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27266. const material = new LineBasicMaterial({
  27267. fog: false,
  27268. toneMapped: false
  27269. });
  27270. this.cone = new LineSegments(geometry, material);
  27271. this.add(this.cone);
  27272. this.update();
  27273. }
  27274. dispose() {
  27275. this.cone.geometry.dispose();
  27276. this.cone.material.dispose();
  27277. }
  27278. update() {
  27279. this.light.updateMatrixWorld();
  27280. const coneLength = this.light.distance ? this.light.distance : 1000;
  27281. const coneWidth = coneLength * Math.tan(this.light.angle);
  27282. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  27283. _vector$3.setFromMatrixPosition(this.light.target.matrixWorld);
  27284. this.cone.lookAt(_vector$3);
  27285. if (this.color !== undefined) {
  27286. this.cone.material.color.set(this.color);
  27287. } else {
  27288. this.cone.material.color.copy(this.light.color);
  27289. }
  27290. }
  27291. }
  27292. const _vector$2 = /*@__PURE__*/new Vector3();
  27293. const _boneMatrix = /*@__PURE__*/new Matrix4();
  27294. const _matrixWorldInv = /*@__PURE__*/new Matrix4();
  27295. class SkeletonHelper extends LineSegments {
  27296. constructor(object) {
  27297. const bones = getBoneList(object);
  27298. const geometry = new BufferGeometry();
  27299. const vertices = [];
  27300. const colors = [];
  27301. const color1 = new Color(0, 0, 1);
  27302. const color2 = new Color(0, 1, 0);
  27303. for (let i = 0; i < bones.length; i++) {
  27304. const bone = bones[i];
  27305. if (bone.parent && bone.parent.isBone) {
  27306. vertices.push(0, 0, 0);
  27307. vertices.push(0, 0, 0);
  27308. colors.push(color1.r, color1.g, color1.b);
  27309. colors.push(color2.r, color2.g, color2.b);
  27310. }
  27311. }
  27312. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27313. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27314. const material = new LineBasicMaterial({
  27315. vertexColors: true,
  27316. depthTest: false,
  27317. depthWrite: false,
  27318. toneMapped: false,
  27319. transparent: true
  27320. });
  27321. super(geometry, material);
  27322. this.type = 'SkeletonHelper';
  27323. this.isSkeletonHelper = true;
  27324. this.root = object;
  27325. this.bones = bones;
  27326. this.matrix = object.matrixWorld;
  27327. this.matrixAutoUpdate = false;
  27328. }
  27329. updateMatrixWorld(force) {
  27330. const bones = this.bones;
  27331. const geometry = this.geometry;
  27332. const position = geometry.getAttribute('position');
  27333. _matrixWorldInv.copy(this.root.matrixWorld).invert();
  27334. for (let i = 0, j = 0; i < bones.length; i++) {
  27335. const bone = bones[i];
  27336. if (bone.parent && bone.parent.isBone) {
  27337. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  27338. _vector$2.setFromMatrixPosition(_boneMatrix);
  27339. position.setXYZ(j, _vector$2.x, _vector$2.y, _vector$2.z);
  27340. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  27341. _vector$2.setFromMatrixPosition(_boneMatrix);
  27342. position.setXYZ(j + 1, _vector$2.x, _vector$2.y, _vector$2.z);
  27343. j += 2;
  27344. }
  27345. }
  27346. geometry.getAttribute('position').needsUpdate = true;
  27347. super.updateMatrixWorld(force);
  27348. }
  27349. }
  27350. function getBoneList(object) {
  27351. const boneList = [];
  27352. if (object && object.isBone) {
  27353. boneList.push(object);
  27354. }
  27355. for (let i = 0; i < object.children.length; i++) {
  27356. boneList.push.apply(boneList, getBoneList(object.children[i]));
  27357. }
  27358. return boneList;
  27359. }
  27360. class PointLightHelper extends Mesh {
  27361. constructor(light, sphereSize, color) {
  27362. const geometry = new SphereGeometry(sphereSize, 4, 2);
  27363. const material = new MeshBasicMaterial({
  27364. wireframe: true,
  27365. fog: false,
  27366. toneMapped: false
  27367. });
  27368. super(geometry, material);
  27369. this.light = light;
  27370. this.light.updateMatrixWorld();
  27371. this.color = color;
  27372. this.type = 'PointLightHelper';
  27373. this.matrix = this.light.matrixWorld;
  27374. this.matrixAutoUpdate = false;
  27375. this.update();
  27376. /*
  27377. // TODO: delete this comment?
  27378. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  27379. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  27380. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  27381. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  27382. const d = light.distance;
  27383. if ( d === 0.0 ) {
  27384. this.lightDistance.visible = false;
  27385. } else {
  27386. this.lightDistance.scale.set( d, d, d );
  27387. }
  27388. this.add( this.lightDistance );
  27389. */
  27390. }
  27391. dispose() {
  27392. this.geometry.dispose();
  27393. this.material.dispose();
  27394. }
  27395. update() {
  27396. if (this.color !== undefined) {
  27397. this.material.color.set(this.color);
  27398. } else {
  27399. this.material.color.copy(this.light.color);
  27400. }
  27401. /*
  27402. const d = this.light.distance;
  27403. if ( d === 0.0 ) {
  27404. this.lightDistance.visible = false;
  27405. } else {
  27406. this.lightDistance.visible = true;
  27407. this.lightDistance.scale.set( d, d, d );
  27408. }
  27409. */
  27410. }
  27411. }
  27412. const _vector$1 = /*@__PURE__*/new Vector3();
  27413. const _color1 = /*@__PURE__*/new Color();
  27414. const _color2 = /*@__PURE__*/new Color();
  27415. class HemisphereLightHelper extends Object3D {
  27416. constructor(light, size, color) {
  27417. super();
  27418. this.light = light;
  27419. this.light.updateMatrixWorld();
  27420. this.matrix = light.matrixWorld;
  27421. this.matrixAutoUpdate = false;
  27422. this.color = color;
  27423. const geometry = new OctahedronGeometry(size);
  27424. geometry.rotateY(Math.PI * 0.5);
  27425. this.material = new MeshBasicMaterial({
  27426. wireframe: true,
  27427. fog: false,
  27428. toneMapped: false
  27429. });
  27430. if (this.color === undefined) this.material.vertexColors = true;
  27431. const position = geometry.getAttribute('position');
  27432. const colors = new Float32Array(position.count * 3);
  27433. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  27434. this.add(new Mesh(geometry, this.material));
  27435. this.update();
  27436. }
  27437. dispose() {
  27438. this.children[0].geometry.dispose();
  27439. this.children[0].material.dispose();
  27440. }
  27441. update() {
  27442. const mesh = this.children[0];
  27443. if (this.color !== undefined) {
  27444. this.material.color.set(this.color);
  27445. } else {
  27446. const colors = mesh.geometry.getAttribute('color');
  27447. _color1.copy(this.light.color);
  27448. _color2.copy(this.light.groundColor);
  27449. for (let i = 0, l = colors.count; i < l; i++) {
  27450. const color = i < l / 2 ? _color1 : _color2;
  27451. colors.setXYZ(i, color.r, color.g, color.b);
  27452. }
  27453. colors.needsUpdate = true;
  27454. }
  27455. mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate());
  27456. }
  27457. }
  27458. class GridHelper extends LineSegments {
  27459. constructor(size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888) {
  27460. color1 = new Color(color1);
  27461. color2 = new Color(color2);
  27462. const center = divisions / 2;
  27463. const step = size / divisions;
  27464. const halfSize = size / 2;
  27465. const vertices = [],
  27466. colors = [];
  27467. for (let i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  27468. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  27469. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  27470. const color = i === center ? color1 : color2;
  27471. color.toArray(colors, j);
  27472. j += 3;
  27473. color.toArray(colors, j);
  27474. j += 3;
  27475. color.toArray(colors, j);
  27476. j += 3;
  27477. color.toArray(colors, j);
  27478. j += 3;
  27479. }
  27480. const geometry = new BufferGeometry();
  27481. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27482. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27483. const material = new LineBasicMaterial({
  27484. vertexColors: true,
  27485. toneMapped: false
  27486. });
  27487. super(geometry, material);
  27488. this.type = 'GridHelper';
  27489. }
  27490. }
  27491. class PolarGridHelper extends LineSegments {
  27492. constructor(radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888) {
  27493. color1 = new Color(color1);
  27494. color2 = new Color(color2);
  27495. const vertices = [];
  27496. const colors = []; // create the radials
  27497. for (let i = 0; i <= radials; i++) {
  27498. const v = i / radials * (Math.PI * 2);
  27499. const x = Math.sin(v) * radius;
  27500. const z = Math.cos(v) * radius;
  27501. vertices.push(0, 0, 0);
  27502. vertices.push(x, 0, z);
  27503. const color = i & 1 ? color1 : color2;
  27504. colors.push(color.r, color.g, color.b);
  27505. colors.push(color.r, color.g, color.b);
  27506. } // create the circles
  27507. for (let i = 0; i <= circles; i++) {
  27508. const color = i & 1 ? color1 : color2;
  27509. const r = radius - radius / circles * i;
  27510. for (let j = 0; j < divisions; j++) {
  27511. // first vertex
  27512. let v = j / divisions * (Math.PI * 2);
  27513. let x = Math.sin(v) * r;
  27514. let z = Math.cos(v) * r;
  27515. vertices.push(x, 0, z);
  27516. colors.push(color.r, color.g, color.b); // second vertex
  27517. v = (j + 1) / divisions * (Math.PI * 2);
  27518. x = Math.sin(v) * r;
  27519. z = Math.cos(v) * r;
  27520. vertices.push(x, 0, z);
  27521. colors.push(color.r, color.g, color.b);
  27522. }
  27523. }
  27524. const geometry = new BufferGeometry();
  27525. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27526. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27527. const material = new LineBasicMaterial({
  27528. vertexColors: true,
  27529. toneMapped: false
  27530. });
  27531. super(geometry, material);
  27532. this.type = 'PolarGridHelper';
  27533. }
  27534. }
  27535. const _v1 = /*@__PURE__*/new Vector3();
  27536. const _v2 = /*@__PURE__*/new Vector3();
  27537. const _v3 = /*@__PURE__*/new Vector3();
  27538. class DirectionalLightHelper extends Object3D {
  27539. constructor(light, size, color) {
  27540. super();
  27541. this.light = light;
  27542. this.light.updateMatrixWorld();
  27543. this.matrix = light.matrixWorld;
  27544. this.matrixAutoUpdate = false;
  27545. this.color = color;
  27546. if (size === undefined) size = 1;
  27547. let geometry = new BufferGeometry();
  27548. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  27549. const material = new LineBasicMaterial({
  27550. fog: false,
  27551. toneMapped: false
  27552. });
  27553. this.lightPlane = new Line(geometry, material);
  27554. this.add(this.lightPlane);
  27555. geometry = new BufferGeometry();
  27556. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  27557. this.targetLine = new Line(geometry, material);
  27558. this.add(this.targetLine);
  27559. this.update();
  27560. }
  27561. dispose() {
  27562. this.lightPlane.geometry.dispose();
  27563. this.lightPlane.material.dispose();
  27564. this.targetLine.geometry.dispose();
  27565. this.targetLine.material.dispose();
  27566. }
  27567. update() {
  27568. _v1.setFromMatrixPosition(this.light.matrixWorld);
  27569. _v2.setFromMatrixPosition(this.light.target.matrixWorld);
  27570. _v3.subVectors(_v2, _v1);
  27571. this.lightPlane.lookAt(_v2);
  27572. if (this.color !== undefined) {
  27573. this.lightPlane.material.color.set(this.color);
  27574. this.targetLine.material.color.set(this.color);
  27575. } else {
  27576. this.lightPlane.material.color.copy(this.light.color);
  27577. this.targetLine.material.color.copy(this.light.color);
  27578. }
  27579. this.targetLine.lookAt(_v2);
  27580. this.targetLine.scale.z = _v3.length();
  27581. }
  27582. }
  27583. const _vector = /*@__PURE__*/new Vector3();
  27584. const _camera = /*@__PURE__*/new Camera();
  27585. /**
  27586. * - shows frustum, line of sight and up of the camera
  27587. * - suitable for fast updates
  27588. * - based on frustum visualization in lightgl.js shadowmap example
  27589. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  27590. */
  27591. class CameraHelper extends LineSegments {
  27592. constructor(camera) {
  27593. const geometry = new BufferGeometry();
  27594. const material = new LineBasicMaterial({
  27595. color: 0xffffff,
  27596. vertexColors: true,
  27597. toneMapped: false
  27598. });
  27599. const vertices = [];
  27600. const colors = [];
  27601. const pointMap = {}; // colors
  27602. const colorFrustum = new Color(0xffaa00);
  27603. const colorCone = new Color(0xff0000);
  27604. const colorUp = new Color(0x00aaff);
  27605. const colorTarget = new Color(0xffffff);
  27606. const colorCross = new Color(0x333333); // near
  27607. addLine('n1', 'n2', colorFrustum);
  27608. addLine('n2', 'n4', colorFrustum);
  27609. addLine('n4', 'n3', colorFrustum);
  27610. addLine('n3', 'n1', colorFrustum); // far
  27611. addLine('f1', 'f2', colorFrustum);
  27612. addLine('f2', 'f4', colorFrustum);
  27613. addLine('f4', 'f3', colorFrustum);
  27614. addLine('f3', 'f1', colorFrustum); // sides
  27615. addLine('n1', 'f1', colorFrustum);
  27616. addLine('n2', 'f2', colorFrustum);
  27617. addLine('n3', 'f3', colorFrustum);
  27618. addLine('n4', 'f4', colorFrustum); // cone
  27619. addLine('p', 'n1', colorCone);
  27620. addLine('p', 'n2', colorCone);
  27621. addLine('p', 'n3', colorCone);
  27622. addLine('p', 'n4', colorCone); // up
  27623. addLine('u1', 'u2', colorUp);
  27624. addLine('u2', 'u3', colorUp);
  27625. addLine('u3', 'u1', colorUp); // target
  27626. addLine('c', 't', colorTarget);
  27627. addLine('p', 'c', colorCross); // cross
  27628. addLine('cn1', 'cn2', colorCross);
  27629. addLine('cn3', 'cn4', colorCross);
  27630. addLine('cf1', 'cf2', colorCross);
  27631. addLine('cf3', 'cf4', colorCross);
  27632. function addLine(a, b, color) {
  27633. addPoint(a, color);
  27634. addPoint(b, color);
  27635. }
  27636. function addPoint(id, color) {
  27637. vertices.push(0, 0, 0);
  27638. colors.push(color.r, color.g, color.b);
  27639. if (pointMap[id] === undefined) {
  27640. pointMap[id] = [];
  27641. }
  27642. pointMap[id].push(vertices.length / 3 - 1);
  27643. }
  27644. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27645. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27646. super(geometry, material);
  27647. this.type = 'CameraHelper';
  27648. this.camera = camera;
  27649. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  27650. this.matrix = camera.matrixWorld;
  27651. this.matrixAutoUpdate = false;
  27652. this.pointMap = pointMap;
  27653. this.update();
  27654. }
  27655. update() {
  27656. const geometry = this.geometry;
  27657. const pointMap = this.pointMap;
  27658. const w = 1,
  27659. h = 1; // we need just camera projection matrix inverse
  27660. // world matrix must be identity
  27661. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  27662. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  27663. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  27664. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  27665. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  27666. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  27667. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  27668. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  27669. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  27670. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  27671. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  27672. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  27673. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  27674. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  27675. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  27676. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  27677. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  27678. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  27679. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  27680. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  27681. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  27682. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  27683. geometry.getAttribute('position').needsUpdate = true;
  27684. }
  27685. dispose() {
  27686. this.geometry.dispose();
  27687. this.material.dispose();
  27688. }
  27689. }
  27690. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  27691. _vector.set(x, y, z).unproject(camera);
  27692. const points = pointMap[point];
  27693. if (points !== undefined) {
  27694. const position = geometry.getAttribute('position');
  27695. for (let i = 0, l = points.length; i < l; i++) {
  27696. position.setXYZ(points[i], _vector.x, _vector.y, _vector.z);
  27697. }
  27698. }
  27699. }
  27700. const _box = /*@__PURE__*/new Box3();
  27701. class BoxHelper extends LineSegments {
  27702. constructor(object, color = 0xffff00) {
  27703. 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]);
  27704. const positions = new Float32Array(8 * 3);
  27705. const geometry = new BufferGeometry();
  27706. geometry.setIndex(new BufferAttribute(indices, 1));
  27707. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  27708. super(geometry, new LineBasicMaterial({
  27709. color: color,
  27710. toneMapped: false
  27711. }));
  27712. this.object = object;
  27713. this.type = 'BoxHelper';
  27714. this.matrixAutoUpdate = false;
  27715. this.update();
  27716. }
  27717. update(object) {
  27718. if (object !== undefined) {
  27719. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  27720. }
  27721. if (this.object !== undefined) {
  27722. _box.setFromObject(this.object);
  27723. }
  27724. if (_box.isEmpty()) return;
  27725. const min = _box.min;
  27726. const max = _box.max;
  27727. /*
  27728. 5____4
  27729. 1/___0/|
  27730. | 6__|_7
  27731. 2/___3/
  27732. 0: max.x, max.y, max.z
  27733. 1: min.x, max.y, max.z
  27734. 2: min.x, min.y, max.z
  27735. 3: max.x, min.y, max.z
  27736. 4: max.x, max.y, min.z
  27737. 5: min.x, max.y, min.z
  27738. 6: min.x, min.y, min.z
  27739. 7: max.x, min.y, min.z
  27740. */
  27741. const position = this.geometry.attributes.position;
  27742. const array = position.array;
  27743. array[0] = max.x;
  27744. array[1] = max.y;
  27745. array[2] = max.z;
  27746. array[3] = min.x;
  27747. array[4] = max.y;
  27748. array[5] = max.z;
  27749. array[6] = min.x;
  27750. array[7] = min.y;
  27751. array[8] = max.z;
  27752. array[9] = max.x;
  27753. array[10] = min.y;
  27754. array[11] = max.z;
  27755. array[12] = max.x;
  27756. array[13] = max.y;
  27757. array[14] = min.z;
  27758. array[15] = min.x;
  27759. array[16] = max.y;
  27760. array[17] = min.z;
  27761. array[18] = min.x;
  27762. array[19] = min.y;
  27763. array[20] = min.z;
  27764. array[21] = max.x;
  27765. array[22] = min.y;
  27766. array[23] = min.z;
  27767. position.needsUpdate = true;
  27768. this.geometry.computeBoundingSphere();
  27769. }
  27770. setFromObject(object) {
  27771. this.object = object;
  27772. this.update();
  27773. return this;
  27774. }
  27775. copy(source) {
  27776. LineSegments.prototype.copy.call(this, source);
  27777. this.object = source.object;
  27778. return this;
  27779. }
  27780. }
  27781. class Box3Helper extends LineSegments {
  27782. constructor(box, color = 0xffff00) {
  27783. 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]);
  27784. 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];
  27785. const geometry = new BufferGeometry();
  27786. geometry.setIndex(new BufferAttribute(indices, 1));
  27787. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27788. super(geometry, new LineBasicMaterial({
  27789. color: color,
  27790. toneMapped: false
  27791. }));
  27792. this.box = box;
  27793. this.type = 'Box3Helper';
  27794. this.geometry.computeBoundingSphere();
  27795. }
  27796. updateMatrixWorld(force) {
  27797. const box = this.box;
  27798. if (box.isEmpty()) return;
  27799. box.getCenter(this.position);
  27800. box.getSize(this.scale);
  27801. this.scale.multiplyScalar(0.5);
  27802. super.updateMatrixWorld(force);
  27803. }
  27804. }
  27805. class PlaneHelper extends Line {
  27806. constructor(plane, size = 1, hex = 0xffff00) {
  27807. const color = hex;
  27808. 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];
  27809. const geometry = new BufferGeometry();
  27810. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27811. geometry.computeBoundingSphere();
  27812. super(geometry, new LineBasicMaterial({
  27813. color: color,
  27814. toneMapped: false
  27815. }));
  27816. this.type = 'PlaneHelper';
  27817. this.plane = plane;
  27818. this.size = size;
  27819. const positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  27820. const geometry2 = new BufferGeometry();
  27821. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  27822. geometry2.computeBoundingSphere();
  27823. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  27824. color: color,
  27825. opacity: 0.2,
  27826. transparent: true,
  27827. depthWrite: false,
  27828. toneMapped: false
  27829. })));
  27830. }
  27831. updateMatrixWorld(force) {
  27832. let scale = -this.plane.constant;
  27833. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  27834. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  27835. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  27836. this.lookAt(this.plane.normal);
  27837. super.updateMatrixWorld(force);
  27838. }
  27839. }
  27840. const _axis = /*@__PURE__*/new Vector3();
  27841. let _lineGeometry, _coneGeometry;
  27842. class ArrowHelper extends Object3D {
  27843. // dir is assumed to be normalized
  27844. 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) {
  27845. super();
  27846. this.type = 'ArrowHelper';
  27847. if (_lineGeometry === undefined) {
  27848. _lineGeometry = new BufferGeometry();
  27849. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  27850. _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1);
  27851. _coneGeometry.translate(0, -0.5, 0);
  27852. }
  27853. this.position.copy(origin);
  27854. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  27855. color: color,
  27856. toneMapped: false
  27857. }));
  27858. this.line.matrixAutoUpdate = false;
  27859. this.add(this.line);
  27860. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  27861. color: color,
  27862. toneMapped: false
  27863. }));
  27864. this.cone.matrixAutoUpdate = false;
  27865. this.add(this.cone);
  27866. this.setDirection(dir);
  27867. this.setLength(length, headLength, headWidth);
  27868. }
  27869. setDirection(dir) {
  27870. // dir is assumed to be normalized
  27871. if (dir.y > 0.99999) {
  27872. this.quaternion.set(0, 0, 0, 1);
  27873. } else if (dir.y < -0.99999) {
  27874. this.quaternion.set(1, 0, 0, 0);
  27875. } else {
  27876. _axis.set(dir.z, 0, -dir.x).normalize();
  27877. const radians = Math.acos(dir.y);
  27878. this.quaternion.setFromAxisAngle(_axis, radians);
  27879. }
  27880. }
  27881. setLength(length, headLength = length * 0.2, headWidth = headLength * 0.2) {
  27882. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  27883. this.line.updateMatrix();
  27884. this.cone.scale.set(headWidth, headLength, headWidth);
  27885. this.cone.position.y = length;
  27886. this.cone.updateMatrix();
  27887. }
  27888. setColor(color) {
  27889. this.line.material.color.set(color);
  27890. this.cone.material.color.set(color);
  27891. }
  27892. copy(source) {
  27893. super.copy(source, false);
  27894. this.line.copy(source.line);
  27895. this.cone.copy(source.cone);
  27896. return this;
  27897. }
  27898. }
  27899. class AxesHelper extends LineSegments {
  27900. constructor(size = 1) {
  27901. const vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  27902. const colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  27903. const geometry = new BufferGeometry();
  27904. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27905. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27906. const material = new LineBasicMaterial({
  27907. vertexColors: true,
  27908. toneMapped: false
  27909. });
  27910. super(geometry, material);
  27911. this.type = 'AxesHelper';
  27912. }
  27913. setColors(xAxisColor, yAxisColor, zAxisColor) {
  27914. const color = new Color();
  27915. const array = this.geometry.attributes.color.array;
  27916. color.set(xAxisColor);
  27917. color.toArray(array, 0);
  27918. color.toArray(array, 3);
  27919. color.set(yAxisColor);
  27920. color.toArray(array, 6);
  27921. color.toArray(array, 9);
  27922. color.set(zAxisColor);
  27923. color.toArray(array, 12);
  27924. color.toArray(array, 15);
  27925. this.geometry.attributes.color.needsUpdate = true;
  27926. return this;
  27927. }
  27928. dispose() {
  27929. this.geometry.dispose();
  27930. this.material.dispose();
  27931. }
  27932. }
  27933. const _floatView = new Float32Array(1);
  27934. const _int32View = new Int32Array(_floatView.buffer);
  27935. class DataUtils {
  27936. // Converts float32 to float16 (stored as uint16 value).
  27937. static toHalfFloat(val) {
  27938. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  27939. /* This method is faster than the OpenEXR implementation (very often
  27940. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  27941. * by James Tursa?s half-precision code. */
  27942. _floatView[0] = val;
  27943. const x = _int32View[0];
  27944. let bits = x >> 16 & 0x8000;
  27945. /* Get the sign */
  27946. let m = x >> 12 & 0x07ff;
  27947. /* Keep one extra bit for rounding */
  27948. const e = x >> 23 & 0xff;
  27949. /* Using int is faster here */
  27950. /* If zero, or denormal, or exponent underflows too much for a denormal
  27951. * half, return signed zero. */
  27952. if (e < 103) return bits;
  27953. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  27954. if (e > 142) {
  27955. bits |= 0x7c00;
  27956. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  27957. * not Inf, so make sure we set one mantissa bit too. */
  27958. bits |= (e == 255 ? 0 : 1) && x & 0x007fffff;
  27959. return bits;
  27960. }
  27961. /* If exponent underflows but not too much, return a denormal */
  27962. if (e < 113) {
  27963. m |= 0x0800;
  27964. /* Extra rounding may overflow and set mantissa to 0 and exponent
  27965. * to 1, which is OK. */
  27966. bits |= (m >> 114 - e) + (m >> 113 - e & 1);
  27967. return bits;
  27968. }
  27969. bits |= e - 112 << 10 | m >> 1;
  27970. /* Extra rounding. An overflow will set mantissa to 0 and increment
  27971. * the exponent, which is OK. */
  27972. bits += m & 1;
  27973. return bits;
  27974. }
  27975. }
  27976. const LineStrip = 0;
  27977. const LinePieces = 1;
  27978. const NoColors = 0;
  27979. const FaceColors = 1;
  27980. const VertexColors = 2;
  27981. function MeshFaceMaterial(materials) {
  27982. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  27983. return materials;
  27984. }
  27985. function MultiMaterial(materials = []) {
  27986. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  27987. materials.isMultiMaterial = true;
  27988. materials.materials = materials;
  27989. materials.clone = function () {
  27990. return materials.slice();
  27991. };
  27992. return materials;
  27993. }
  27994. function PointCloud(geometry, material) {
  27995. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  27996. return new Points(geometry, material);
  27997. }
  27998. function Particle(material) {
  27999. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  28000. return new Sprite(material);
  28001. }
  28002. function ParticleSystem(geometry, material) {
  28003. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  28004. return new Points(geometry, material);
  28005. }
  28006. function PointCloudMaterial(parameters) {
  28007. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  28008. return new PointsMaterial(parameters);
  28009. }
  28010. function ParticleBasicMaterial(parameters) {
  28011. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  28012. return new PointsMaterial(parameters);
  28013. }
  28014. function ParticleSystemMaterial(parameters) {
  28015. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  28016. return new PointsMaterial(parameters);
  28017. }
  28018. function Vertex(x, y, z) {
  28019. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  28020. return new Vector3(x, y, z);
  28021. } //
  28022. function DynamicBufferAttribute(array, itemSize) {
  28023. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.');
  28024. return new BufferAttribute(array, itemSize).setUsage(DynamicDrawUsage);
  28025. }
  28026. function Int8Attribute(array, itemSize) {
  28027. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  28028. return new Int8BufferAttribute(array, itemSize);
  28029. }
  28030. function Uint8Attribute(array, itemSize) {
  28031. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  28032. return new Uint8BufferAttribute(array, itemSize);
  28033. }
  28034. function Uint8ClampedAttribute(array, itemSize) {
  28035. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  28036. return new Uint8ClampedBufferAttribute(array, itemSize);
  28037. }
  28038. function Int16Attribute(array, itemSize) {
  28039. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  28040. return new Int16BufferAttribute(array, itemSize);
  28041. }
  28042. function Uint16Attribute(array, itemSize) {
  28043. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  28044. return new Uint16BufferAttribute(array, itemSize);
  28045. }
  28046. function Int32Attribute(array, itemSize) {
  28047. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  28048. return new Int32BufferAttribute(array, itemSize);
  28049. }
  28050. function Uint32Attribute(array, itemSize) {
  28051. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  28052. return new Uint32BufferAttribute(array, itemSize);
  28053. }
  28054. function Float32Attribute(array, itemSize) {
  28055. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  28056. return new Float32BufferAttribute(array, itemSize);
  28057. }
  28058. function Float64Attribute(array, itemSize) {
  28059. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  28060. return new Float64BufferAttribute(array, itemSize);
  28061. } //
  28062. Curve.create = function (construct, getPoint) {
  28063. console.log('THREE.Curve.create() has been deprecated');
  28064. construct.prototype = Object.create(Curve.prototype);
  28065. construct.prototype.constructor = construct;
  28066. construct.prototype.getPoint = getPoint;
  28067. return construct;
  28068. }; //
  28069. Path.prototype.fromPoints = function (points) {
  28070. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  28071. return this.setFromPoints(points);
  28072. }; //
  28073. function AxisHelper(size) {
  28074. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  28075. return new AxesHelper(size);
  28076. }
  28077. function BoundingBoxHelper(object, color) {
  28078. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  28079. return new BoxHelper(object, color);
  28080. }
  28081. function EdgesHelper(object, hex) {
  28082. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  28083. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  28084. color: hex !== undefined ? hex : 0xffffff
  28085. }));
  28086. }
  28087. GridHelper.prototype.setColors = function () {
  28088. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  28089. };
  28090. SkeletonHelper.prototype.update = function () {
  28091. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  28092. };
  28093. function WireframeHelper(object, hex) {
  28094. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  28095. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  28096. color: hex !== undefined ? hex : 0xffffff
  28097. }));
  28098. } //
  28099. Loader.prototype.extractUrlBase = function (url) {
  28100. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  28101. return LoaderUtils.extractUrlBase(url);
  28102. };
  28103. Loader.Handlers = {
  28104. add: function () {
  28105. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  28106. },
  28107. get: function () {
  28108. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  28109. }
  28110. };
  28111. function XHRLoader(manager) {
  28112. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  28113. return new FileLoader(manager);
  28114. }
  28115. function BinaryTextureLoader(manager) {
  28116. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  28117. return new DataTextureLoader(manager);
  28118. } //
  28119. Box2.prototype.center = function (optionalTarget) {
  28120. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  28121. return this.getCenter(optionalTarget);
  28122. };
  28123. Box2.prototype.empty = function () {
  28124. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  28125. return this.isEmpty();
  28126. };
  28127. Box2.prototype.isIntersectionBox = function (box) {
  28128. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  28129. return this.intersectsBox(box);
  28130. };
  28131. Box2.prototype.size = function (optionalTarget) {
  28132. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  28133. return this.getSize(optionalTarget);
  28134. }; //
  28135. Box3.prototype.center = function (optionalTarget) {
  28136. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  28137. return this.getCenter(optionalTarget);
  28138. };
  28139. Box3.prototype.empty = function () {
  28140. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  28141. return this.isEmpty();
  28142. };
  28143. Box3.prototype.isIntersectionBox = function (box) {
  28144. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  28145. return this.intersectsBox(box);
  28146. };
  28147. Box3.prototype.isIntersectionSphere = function (sphere) {
  28148. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  28149. return this.intersectsSphere(sphere);
  28150. };
  28151. Box3.prototype.size = function (optionalTarget) {
  28152. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  28153. return this.getSize(optionalTarget);
  28154. }; //
  28155. Sphere.prototype.empty = function () {
  28156. console.warn('THREE.Sphere: .empty() has been renamed to .isEmpty().');
  28157. return this.isEmpty();
  28158. }; //
  28159. Frustum.prototype.setFromMatrix = function (m) {
  28160. console.warn('THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().');
  28161. return this.setFromProjectionMatrix(m);
  28162. }; //
  28163. Line3.prototype.center = function (optionalTarget) {
  28164. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  28165. return this.getCenter(optionalTarget);
  28166. }; //
  28167. Matrix3.prototype.flattenToArrayOffset = function (array, offset) {
  28168. console.warn('THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  28169. return this.toArray(array, offset);
  28170. };
  28171. Matrix3.prototype.multiplyVector3 = function (vector) {
  28172. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  28173. return vector.applyMatrix3(this);
  28174. };
  28175. Matrix3.prototype.multiplyVector3Array = function () {
  28176. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  28177. };
  28178. Matrix3.prototype.applyToBufferAttribute = function (attribute) {
  28179. console.warn('THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.');
  28180. return attribute.applyMatrix3(this);
  28181. };
  28182. Matrix3.prototype.applyToVector3Array = function () {
  28183. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  28184. };
  28185. Matrix3.prototype.getInverse = function (matrix) {
  28186. console.warn('THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  28187. return this.copy(matrix).invert();
  28188. }; //
  28189. Matrix4.prototype.extractPosition = function (m) {
  28190. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  28191. return this.copyPosition(m);
  28192. };
  28193. Matrix4.prototype.flattenToArrayOffset = function (array, offset) {
  28194. console.warn('THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  28195. return this.toArray(array, offset);
  28196. };
  28197. Matrix4.prototype.getPosition = function () {
  28198. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  28199. return new Vector3().setFromMatrixColumn(this, 3);
  28200. };
  28201. Matrix4.prototype.setRotationFromQuaternion = function (q) {
  28202. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  28203. return this.makeRotationFromQuaternion(q);
  28204. };
  28205. Matrix4.prototype.multiplyToArray = function () {
  28206. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  28207. };
  28208. Matrix4.prototype.multiplyVector3 = function (vector) {
  28209. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28210. return vector.applyMatrix4(this);
  28211. };
  28212. Matrix4.prototype.multiplyVector4 = function (vector) {
  28213. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28214. return vector.applyMatrix4(this);
  28215. };
  28216. Matrix4.prototype.multiplyVector3Array = function () {
  28217. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  28218. };
  28219. Matrix4.prototype.rotateAxis = function (v) {
  28220. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  28221. v.transformDirection(this);
  28222. };
  28223. Matrix4.prototype.crossVector = function (vector) {
  28224. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28225. return vector.applyMatrix4(this);
  28226. };
  28227. Matrix4.prototype.translate = function () {
  28228. console.error('THREE.Matrix4: .translate() has been removed.');
  28229. };
  28230. Matrix4.prototype.rotateX = function () {
  28231. console.error('THREE.Matrix4: .rotateX() has been removed.');
  28232. };
  28233. Matrix4.prototype.rotateY = function () {
  28234. console.error('THREE.Matrix4: .rotateY() has been removed.');
  28235. };
  28236. Matrix4.prototype.rotateZ = function () {
  28237. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  28238. };
  28239. Matrix4.prototype.rotateByAxis = function () {
  28240. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  28241. };
  28242. Matrix4.prototype.applyToBufferAttribute = function (attribute) {
  28243. console.warn('THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.');
  28244. return attribute.applyMatrix4(this);
  28245. };
  28246. Matrix4.prototype.applyToVector3Array = function () {
  28247. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  28248. };
  28249. Matrix4.prototype.makeFrustum = function (left, right, bottom, top, near, far) {
  28250. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  28251. return this.makePerspective(left, right, top, bottom, near, far);
  28252. };
  28253. Matrix4.prototype.getInverse = function (matrix) {
  28254. console.warn('THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  28255. return this.copy(matrix).invert();
  28256. }; //
  28257. Plane.prototype.isIntersectionLine = function (line) {
  28258. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  28259. return this.intersectsLine(line);
  28260. }; //
  28261. Quaternion.prototype.multiplyVector3 = function (vector) {
  28262. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  28263. return vector.applyQuaternion(this);
  28264. };
  28265. Quaternion.prototype.inverse = function () {
  28266. console.warn('THREE.Quaternion: .inverse() has been renamed to invert().');
  28267. return this.invert();
  28268. }; //
  28269. Ray.prototype.isIntersectionBox = function (box) {
  28270. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  28271. return this.intersectsBox(box);
  28272. };
  28273. Ray.prototype.isIntersectionPlane = function (plane) {
  28274. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  28275. return this.intersectsPlane(plane);
  28276. };
  28277. Ray.prototype.isIntersectionSphere = function (sphere) {
  28278. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  28279. return this.intersectsSphere(sphere);
  28280. }; //
  28281. Triangle.prototype.area = function () {
  28282. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  28283. return this.getArea();
  28284. };
  28285. Triangle.prototype.barycoordFromPoint = function (point, target) {
  28286. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28287. return this.getBarycoord(point, target);
  28288. };
  28289. Triangle.prototype.midpoint = function (target) {
  28290. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  28291. return this.getMidpoint(target);
  28292. };
  28293. Triangle.prototypenormal = function (target) {
  28294. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28295. return this.getNormal(target);
  28296. };
  28297. Triangle.prototype.plane = function (target) {
  28298. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  28299. return this.getPlane(target);
  28300. };
  28301. Triangle.barycoordFromPoint = function (point, a, b, c, target) {
  28302. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28303. return Triangle.getBarycoord(point, a, b, c, target);
  28304. };
  28305. Triangle.normal = function (a, b, c, target) {
  28306. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28307. return Triangle.getNormal(a, b, c, target);
  28308. }; //
  28309. Shape.prototype.extractAllPoints = function (divisions) {
  28310. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  28311. return this.extractPoints(divisions);
  28312. };
  28313. Shape.prototype.extrude = function (options) {
  28314. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  28315. return new ExtrudeGeometry(this, options);
  28316. };
  28317. Shape.prototype.makeGeometry = function (options) {
  28318. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  28319. return new ShapeGeometry(this, options);
  28320. }; //
  28321. Vector2.prototype.fromAttribute = function (attribute, index, offset) {
  28322. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28323. return this.fromBufferAttribute(attribute, index, offset);
  28324. };
  28325. Vector2.prototype.distanceToManhattan = function (v) {
  28326. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28327. return this.manhattanDistanceTo(v);
  28328. };
  28329. Vector2.prototype.lengthManhattan = function () {
  28330. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  28331. return this.manhattanLength();
  28332. }; //
  28333. Vector3.prototype.setEulerFromRotationMatrix = function () {
  28334. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  28335. };
  28336. Vector3.prototype.setEulerFromQuaternion = function () {
  28337. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  28338. };
  28339. Vector3.prototype.getPositionFromMatrix = function (m) {
  28340. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  28341. return this.setFromMatrixPosition(m);
  28342. };
  28343. Vector3.prototype.getScaleFromMatrix = function (m) {
  28344. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  28345. return this.setFromMatrixScale(m);
  28346. };
  28347. Vector3.prototype.getColumnFromMatrix = function (index, matrix) {
  28348. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  28349. return this.setFromMatrixColumn(matrix, index);
  28350. };
  28351. Vector3.prototype.applyProjection = function (m) {
  28352. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  28353. return this.applyMatrix4(m);
  28354. };
  28355. Vector3.prototype.fromAttribute = function (attribute, index, offset) {
  28356. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28357. return this.fromBufferAttribute(attribute, index, offset);
  28358. };
  28359. Vector3.prototype.distanceToManhattan = function (v) {
  28360. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28361. return this.manhattanDistanceTo(v);
  28362. };
  28363. Vector3.prototype.lengthManhattan = function () {
  28364. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  28365. return this.manhattanLength();
  28366. }; //
  28367. Vector4.prototype.fromAttribute = function (attribute, index, offset) {
  28368. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28369. return this.fromBufferAttribute(attribute, index, offset);
  28370. };
  28371. Vector4.prototype.lengthManhattan = function () {
  28372. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  28373. return this.manhattanLength();
  28374. }; //
  28375. Object3D.prototype.getChildByName = function (name) {
  28376. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  28377. return this.getObjectByName(name);
  28378. };
  28379. Object3D.prototype.renderDepth = function () {
  28380. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  28381. };
  28382. Object3D.prototype.translate = function (distance, axis) {
  28383. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  28384. return this.translateOnAxis(axis, distance);
  28385. };
  28386. Object3D.prototype.getWorldRotation = function () {
  28387. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  28388. };
  28389. Object3D.prototype.applyMatrix = function (matrix) {
  28390. console.warn('THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().');
  28391. return this.applyMatrix4(matrix);
  28392. };
  28393. Object.defineProperties(Object3D.prototype, {
  28394. eulerOrder: {
  28395. get: function () {
  28396. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28397. return this.rotation.order;
  28398. },
  28399. set: function (value) {
  28400. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28401. this.rotation.order = value;
  28402. }
  28403. },
  28404. useQuaternion: {
  28405. get: function () {
  28406. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28407. },
  28408. set: function () {
  28409. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28410. }
  28411. }
  28412. });
  28413. Mesh.prototype.setDrawMode = function () {
  28414. console.error('THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28415. };
  28416. Object.defineProperties(Mesh.prototype, {
  28417. drawMode: {
  28418. get: function () {
  28419. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.');
  28420. return TrianglesDrawMode;
  28421. },
  28422. set: function () {
  28423. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28424. }
  28425. }
  28426. });
  28427. SkinnedMesh.prototype.initBones = function () {
  28428. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  28429. }; //
  28430. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  28431. console.warn('THREE.PerspectiveCamera.setLens is deprecated. ' + 'Use .setFocalLength and .filmGauge for a photographic setup.');
  28432. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  28433. this.setFocalLength(focalLength);
  28434. }; //
  28435. Object.defineProperties(Light.prototype, {
  28436. onlyShadow: {
  28437. set: function () {
  28438. console.warn('THREE.Light: .onlyShadow has been removed.');
  28439. }
  28440. },
  28441. shadowCameraFov: {
  28442. set: function (value) {
  28443. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  28444. this.shadow.camera.fov = value;
  28445. }
  28446. },
  28447. shadowCameraLeft: {
  28448. set: function (value) {
  28449. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  28450. this.shadow.camera.left = value;
  28451. }
  28452. },
  28453. shadowCameraRight: {
  28454. set: function (value) {
  28455. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  28456. this.shadow.camera.right = value;
  28457. }
  28458. },
  28459. shadowCameraTop: {
  28460. set: function (value) {
  28461. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  28462. this.shadow.camera.top = value;
  28463. }
  28464. },
  28465. shadowCameraBottom: {
  28466. set: function (value) {
  28467. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  28468. this.shadow.camera.bottom = value;
  28469. }
  28470. },
  28471. shadowCameraNear: {
  28472. set: function (value) {
  28473. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  28474. this.shadow.camera.near = value;
  28475. }
  28476. },
  28477. shadowCameraFar: {
  28478. set: function (value) {
  28479. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  28480. this.shadow.camera.far = value;
  28481. }
  28482. },
  28483. shadowCameraVisible: {
  28484. set: function () {
  28485. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  28486. }
  28487. },
  28488. shadowBias: {
  28489. set: function (value) {
  28490. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  28491. this.shadow.bias = value;
  28492. }
  28493. },
  28494. shadowDarkness: {
  28495. set: function () {
  28496. console.warn('THREE.Light: .shadowDarkness has been removed.');
  28497. }
  28498. },
  28499. shadowMapWidth: {
  28500. set: function (value) {
  28501. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  28502. this.shadow.mapSize.width = value;
  28503. }
  28504. },
  28505. shadowMapHeight: {
  28506. set: function (value) {
  28507. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  28508. this.shadow.mapSize.height = value;
  28509. }
  28510. }
  28511. }); //
  28512. Object.defineProperties(BufferAttribute.prototype, {
  28513. length: {
  28514. get: function () {
  28515. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  28516. return this.array.length;
  28517. }
  28518. },
  28519. dynamic: {
  28520. get: function () {
  28521. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28522. return this.usage === DynamicDrawUsage;
  28523. },
  28524. set: function () {
  28525. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28526. this.setUsage(DynamicDrawUsage);
  28527. }
  28528. }
  28529. });
  28530. BufferAttribute.prototype.setDynamic = function (value) {
  28531. console.warn('THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28532. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28533. return this;
  28534. };
  28535. BufferAttribute.prototype.copyIndicesArray = function () {
  28536. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  28537. }, BufferAttribute.prototype.setArray = function () {
  28538. console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28539. }; //
  28540. BufferGeometry.prototype.addIndex = function (index) {
  28541. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  28542. this.setIndex(index);
  28543. };
  28544. BufferGeometry.prototype.addAttribute = function (name, attribute) {
  28545. console.warn('THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().');
  28546. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  28547. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  28548. return this.setAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  28549. }
  28550. if (name === 'index') {
  28551. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  28552. this.setIndex(attribute);
  28553. return this;
  28554. }
  28555. return this.setAttribute(name, attribute);
  28556. };
  28557. BufferGeometry.prototype.addDrawCall = function (start, count, indexOffset) {
  28558. if (indexOffset !== undefined) {
  28559. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  28560. }
  28561. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  28562. this.addGroup(start, count);
  28563. };
  28564. BufferGeometry.prototype.clearDrawCalls = function () {
  28565. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  28566. this.clearGroups();
  28567. };
  28568. BufferGeometry.prototype.computeOffsets = function () {
  28569. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  28570. };
  28571. BufferGeometry.prototype.removeAttribute = function (name) {
  28572. console.warn('THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().');
  28573. return this.deleteAttribute(name);
  28574. };
  28575. BufferGeometry.prototype.applyMatrix = function (matrix) {
  28576. console.warn('THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().');
  28577. return this.applyMatrix4(matrix);
  28578. };
  28579. Object.defineProperties(BufferGeometry.prototype, {
  28580. drawcalls: {
  28581. get: function () {
  28582. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  28583. return this.groups;
  28584. }
  28585. },
  28586. offsets: {
  28587. get: function () {
  28588. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  28589. return this.groups;
  28590. }
  28591. }
  28592. });
  28593. InterleavedBuffer.prototype.setDynamic = function (value) {
  28594. console.warn('THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28595. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28596. return this;
  28597. };
  28598. InterleavedBuffer.prototype.setArray = function () {
  28599. console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28600. }; //
  28601. ExtrudeGeometry.prototype.getArrays = function () {
  28602. console.error('THREE.ExtrudeGeometry: .getArrays() has been removed.');
  28603. };
  28604. ExtrudeGeometry.prototype.addShapeList = function () {
  28605. console.error('THREE.ExtrudeGeometry: .addShapeList() has been removed.');
  28606. };
  28607. ExtrudeGeometry.prototype.addShape = function () {
  28608. console.error('THREE.ExtrudeGeometry: .addShape() has been removed.');
  28609. }; //
  28610. Scene.prototype.dispose = function () {
  28611. console.error('THREE.Scene: .dispose() has been removed.');
  28612. }; //
  28613. Uniform.prototype.onUpdate = function () {
  28614. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  28615. return this;
  28616. }; //
  28617. Object.defineProperties(Material.prototype, {
  28618. wrapAround: {
  28619. get: function () {
  28620. console.warn('THREE.Material: .wrapAround has been removed.');
  28621. },
  28622. set: function () {
  28623. console.warn('THREE.Material: .wrapAround has been removed.');
  28624. }
  28625. },
  28626. overdraw: {
  28627. get: function () {
  28628. console.warn('THREE.Material: .overdraw has been removed.');
  28629. },
  28630. set: function () {
  28631. console.warn('THREE.Material: .overdraw has been removed.');
  28632. }
  28633. },
  28634. wrapRGB: {
  28635. get: function () {
  28636. console.warn('THREE.Material: .wrapRGB has been removed.');
  28637. return new Color();
  28638. }
  28639. },
  28640. shading: {
  28641. get: function () {
  28642. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28643. },
  28644. set: function (value) {
  28645. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28646. this.flatShading = value === FlatShading;
  28647. }
  28648. },
  28649. stencilMask: {
  28650. get: function () {
  28651. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28652. return this.stencilFuncMask;
  28653. },
  28654. set: function (value) {
  28655. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28656. this.stencilFuncMask = value;
  28657. }
  28658. },
  28659. vertexTangents: {
  28660. get: function () {
  28661. console.warn('THREE.' + this.type + ': .vertexTangents has been removed.');
  28662. },
  28663. set: function () {
  28664. console.warn('THREE.' + this.type + ': .vertexTangents has been removed.');
  28665. }
  28666. }
  28667. });
  28668. Object.defineProperties(ShaderMaterial.prototype, {
  28669. derivatives: {
  28670. get: function () {
  28671. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28672. return this.extensions.derivatives;
  28673. },
  28674. set: function (value) {
  28675. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28676. this.extensions.derivatives = value;
  28677. }
  28678. }
  28679. }); //
  28680. WebGLRenderer.prototype.clearTarget = function (renderTarget, color, depth, stencil) {
  28681. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  28682. this.setRenderTarget(renderTarget);
  28683. this.clear(color, depth, stencil);
  28684. };
  28685. WebGLRenderer.prototype.animate = function (callback) {
  28686. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  28687. this.setAnimationLoop(callback);
  28688. };
  28689. WebGLRenderer.prototype.getCurrentRenderTarget = function () {
  28690. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  28691. return this.getRenderTarget();
  28692. };
  28693. WebGLRenderer.prototype.getMaxAnisotropy = function () {
  28694. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  28695. return this.capabilities.getMaxAnisotropy();
  28696. };
  28697. WebGLRenderer.prototype.getPrecision = function () {
  28698. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  28699. return this.capabilities.precision;
  28700. };
  28701. WebGLRenderer.prototype.resetGLState = function () {
  28702. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  28703. return this.state.reset();
  28704. };
  28705. WebGLRenderer.prototype.supportsFloatTextures = function () {
  28706. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  28707. return this.extensions.get('OES_texture_float');
  28708. };
  28709. WebGLRenderer.prototype.supportsHalfFloatTextures = function () {
  28710. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  28711. return this.extensions.get('OES_texture_half_float');
  28712. };
  28713. WebGLRenderer.prototype.supportsStandardDerivatives = function () {
  28714. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  28715. return this.extensions.get('OES_standard_derivatives');
  28716. };
  28717. WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () {
  28718. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  28719. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  28720. };
  28721. WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () {
  28722. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  28723. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  28724. };
  28725. WebGLRenderer.prototype.supportsBlendMinMax = function () {
  28726. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  28727. return this.extensions.get('EXT_blend_minmax');
  28728. };
  28729. WebGLRenderer.prototype.supportsVertexTextures = function () {
  28730. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  28731. return this.capabilities.vertexTextures;
  28732. };
  28733. WebGLRenderer.prototype.supportsInstancedArrays = function () {
  28734. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  28735. return this.extensions.get('ANGLE_instanced_arrays');
  28736. };
  28737. WebGLRenderer.prototype.enableScissorTest = function (boolean) {
  28738. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  28739. this.setScissorTest(boolean);
  28740. };
  28741. WebGLRenderer.prototype.initMaterial = function () {
  28742. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  28743. };
  28744. WebGLRenderer.prototype.addPrePlugin = function () {
  28745. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  28746. };
  28747. WebGLRenderer.prototype.addPostPlugin = function () {
  28748. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  28749. };
  28750. WebGLRenderer.prototype.updateShadowMap = function () {
  28751. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  28752. };
  28753. WebGLRenderer.prototype.setFaceCulling = function () {
  28754. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  28755. };
  28756. WebGLRenderer.prototype.allocTextureUnit = function () {
  28757. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  28758. };
  28759. WebGLRenderer.prototype.setTexture = function () {
  28760. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  28761. };
  28762. WebGLRenderer.prototype.setTexture2D = function () {
  28763. console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
  28764. };
  28765. WebGLRenderer.prototype.setTextureCube = function () {
  28766. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  28767. };
  28768. WebGLRenderer.prototype.getActiveMipMapLevel = function () {
  28769. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  28770. return this.getActiveMipmapLevel();
  28771. };
  28772. Object.defineProperties(WebGLRenderer.prototype, {
  28773. shadowMapEnabled: {
  28774. get: function () {
  28775. return this.shadowMap.enabled;
  28776. },
  28777. set: function (value) {
  28778. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  28779. this.shadowMap.enabled = value;
  28780. }
  28781. },
  28782. shadowMapType: {
  28783. get: function () {
  28784. return this.shadowMap.type;
  28785. },
  28786. set: function (value) {
  28787. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  28788. this.shadowMap.type = value;
  28789. }
  28790. },
  28791. shadowMapCullFace: {
  28792. get: function () {
  28793. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  28794. return undefined;
  28795. },
  28796. set: function () {
  28797. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  28798. }
  28799. },
  28800. context: {
  28801. get: function () {
  28802. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  28803. return this.getContext();
  28804. }
  28805. },
  28806. vr: {
  28807. get: function () {
  28808. console.warn('THREE.WebGLRenderer: .vr has been renamed to .xr');
  28809. return this.xr;
  28810. }
  28811. },
  28812. gammaInput: {
  28813. get: function () {
  28814. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  28815. return false;
  28816. },
  28817. set: function () {
  28818. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  28819. }
  28820. },
  28821. gammaOutput: {
  28822. get: function () {
  28823. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  28824. return false;
  28825. },
  28826. set: function (value) {
  28827. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  28828. this.outputEncoding = value === true ? sRGBEncoding : LinearEncoding;
  28829. }
  28830. },
  28831. toneMappingWhitePoint: {
  28832. get: function () {
  28833. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  28834. return 1.0;
  28835. },
  28836. set: function () {
  28837. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  28838. }
  28839. }
  28840. });
  28841. Object.defineProperties(WebGLShadowMap.prototype, {
  28842. cullFace: {
  28843. get: function () {
  28844. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  28845. return undefined;
  28846. },
  28847. set: function () {
  28848. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  28849. }
  28850. },
  28851. renderReverseSided: {
  28852. get: function () {
  28853. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  28854. return undefined;
  28855. },
  28856. set: function () {
  28857. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  28858. }
  28859. },
  28860. renderSingleSided: {
  28861. get: function () {
  28862. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  28863. return undefined;
  28864. },
  28865. set: function () {
  28866. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  28867. }
  28868. }
  28869. });
  28870. function WebGLRenderTargetCube(width, height, options) {
  28871. console.warn('THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).');
  28872. return new WebGLCubeRenderTarget(width, options);
  28873. } //
  28874. Object.defineProperties(WebGLRenderTarget.prototype, {
  28875. wrapS: {
  28876. get: function () {
  28877. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  28878. return this.texture.wrapS;
  28879. },
  28880. set: function (value) {
  28881. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  28882. this.texture.wrapS = value;
  28883. }
  28884. },
  28885. wrapT: {
  28886. get: function () {
  28887. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  28888. return this.texture.wrapT;
  28889. },
  28890. set: function (value) {
  28891. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  28892. this.texture.wrapT = value;
  28893. }
  28894. },
  28895. magFilter: {
  28896. get: function () {
  28897. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  28898. return this.texture.magFilter;
  28899. },
  28900. set: function (value) {
  28901. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  28902. this.texture.magFilter = value;
  28903. }
  28904. },
  28905. minFilter: {
  28906. get: function () {
  28907. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  28908. return this.texture.minFilter;
  28909. },
  28910. set: function (value) {
  28911. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  28912. this.texture.minFilter = value;
  28913. }
  28914. },
  28915. anisotropy: {
  28916. get: function () {
  28917. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  28918. return this.texture.anisotropy;
  28919. },
  28920. set: function (value) {
  28921. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  28922. this.texture.anisotropy = value;
  28923. }
  28924. },
  28925. offset: {
  28926. get: function () {
  28927. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  28928. return this.texture.offset;
  28929. },
  28930. set: function (value) {
  28931. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  28932. this.texture.offset = value;
  28933. }
  28934. },
  28935. repeat: {
  28936. get: function () {
  28937. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  28938. return this.texture.repeat;
  28939. },
  28940. set: function (value) {
  28941. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  28942. this.texture.repeat = value;
  28943. }
  28944. },
  28945. format: {
  28946. get: function () {
  28947. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  28948. return this.texture.format;
  28949. },
  28950. set: function (value) {
  28951. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  28952. this.texture.format = value;
  28953. }
  28954. },
  28955. type: {
  28956. get: function () {
  28957. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  28958. return this.texture.type;
  28959. },
  28960. set: function (value) {
  28961. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  28962. this.texture.type = value;
  28963. }
  28964. },
  28965. generateMipmaps: {
  28966. get: function () {
  28967. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  28968. return this.texture.generateMipmaps;
  28969. },
  28970. set: function (value) {
  28971. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  28972. this.texture.generateMipmaps = value;
  28973. }
  28974. }
  28975. }); //
  28976. Audio.prototype.load = function (file) {
  28977. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  28978. const scope = this;
  28979. const audioLoader = new AudioLoader();
  28980. audioLoader.load(file, function (buffer) {
  28981. scope.setBuffer(buffer);
  28982. });
  28983. return this;
  28984. };
  28985. AudioAnalyser.prototype.getData = function () {
  28986. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  28987. return this.getFrequencyData();
  28988. }; //
  28989. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  28990. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  28991. return this.update(renderer, scene);
  28992. };
  28993. CubeCamera.prototype.clear = function (renderer, color, depth, stencil) {
  28994. console.warn('THREE.CubeCamera: .clear() is now .renderTarget.clear().');
  28995. return this.renderTarget.clear(renderer, color, depth, stencil);
  28996. };
  28997. ImageUtils.crossOrigin = undefined;
  28998. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  28999. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  29000. const loader = new TextureLoader();
  29001. loader.setCrossOrigin(this.crossOrigin);
  29002. const texture = loader.load(url, onLoad, undefined, onError);
  29003. if (mapping) texture.mapping = mapping;
  29004. return texture;
  29005. };
  29006. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  29007. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  29008. const loader = new CubeTextureLoader();
  29009. loader.setCrossOrigin(this.crossOrigin);
  29010. const texture = loader.load(urls, onLoad, undefined, onError);
  29011. if (mapping) texture.mapping = mapping;
  29012. return texture;
  29013. };
  29014. ImageUtils.loadCompressedTexture = function () {
  29015. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  29016. };
  29017. ImageUtils.loadCompressedTextureCube = function () {
  29018. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  29019. }; //
  29020. function CanvasRenderer() {
  29021. console.error('THREE.CanvasRenderer has been removed');
  29022. } //
  29023. function JSONLoader() {
  29024. console.error('THREE.JSONLoader has been removed.');
  29025. } //
  29026. const SceneUtils = {
  29027. createMultiMaterialObject: function () {
  29028. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  29029. },
  29030. detach: function () {
  29031. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  29032. },
  29033. attach: function () {
  29034. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  29035. }
  29036. }; //
  29037. function LensFlare() {
  29038. console.error('THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js');
  29039. }
  29040. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  29041. /* eslint-disable no-undef */
  29042. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  29043. detail: {
  29044. revision: REVISION
  29045. }
  29046. }));
  29047. /* eslint-enable no-undef */
  29048. }
  29049. if (typeof window !== 'undefined') {
  29050. if (window.__THREE__) {
  29051. console.warn('WARNING: Multiple instances of Three.js being imported.');
  29052. } else {
  29053. window.__THREE__ = REVISION;
  29054. }
  29055. }
  29056. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  29057. exports.AddEquation = AddEquation;
  29058. exports.AddOperation = AddOperation;
  29059. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  29060. exports.AdditiveBlending = AdditiveBlending;
  29061. exports.AlphaFormat = AlphaFormat;
  29062. exports.AlwaysDepth = AlwaysDepth;
  29063. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  29064. exports.AmbientLight = AmbientLight;
  29065. exports.AmbientLightProbe = AmbientLightProbe;
  29066. exports.AnimationClip = AnimationClip;
  29067. exports.AnimationLoader = AnimationLoader;
  29068. exports.AnimationMixer = AnimationMixer;
  29069. exports.AnimationObjectGroup = AnimationObjectGroup;
  29070. exports.AnimationUtils = AnimationUtils;
  29071. exports.ArcCurve = ArcCurve;
  29072. exports.ArrayCamera = ArrayCamera;
  29073. exports.ArrowHelper = ArrowHelper;
  29074. exports.Audio = Audio;
  29075. exports.AudioAnalyser = AudioAnalyser;
  29076. exports.AudioContext = AudioContext;
  29077. exports.AudioListener = AudioListener;
  29078. exports.AudioLoader = AudioLoader;
  29079. exports.AxesHelper = AxesHelper;
  29080. exports.AxisHelper = AxisHelper;
  29081. exports.BackSide = BackSide;
  29082. exports.BasicDepthPacking = BasicDepthPacking;
  29083. exports.BasicShadowMap = BasicShadowMap;
  29084. exports.BinaryTextureLoader = BinaryTextureLoader;
  29085. exports.Bone = Bone;
  29086. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  29087. exports.BoundingBoxHelper = BoundingBoxHelper;
  29088. exports.Box2 = Box2;
  29089. exports.Box3 = Box3;
  29090. exports.Box3Helper = Box3Helper;
  29091. exports.BoxBufferGeometry = BoxGeometry;
  29092. exports.BoxGeometry = BoxGeometry;
  29093. exports.BoxHelper = BoxHelper;
  29094. exports.BufferAttribute = BufferAttribute;
  29095. exports.BufferGeometry = BufferGeometry;
  29096. exports.BufferGeometryLoader = BufferGeometryLoader;
  29097. exports.ByteType = ByteType;
  29098. exports.Cache = Cache;
  29099. exports.Camera = Camera;
  29100. exports.CameraHelper = CameraHelper;
  29101. exports.CanvasRenderer = CanvasRenderer;
  29102. exports.CanvasTexture = CanvasTexture;
  29103. exports.CatmullRomCurve3 = CatmullRomCurve3;
  29104. exports.CineonToneMapping = CineonToneMapping;
  29105. exports.CircleBufferGeometry = CircleGeometry;
  29106. exports.CircleGeometry = CircleGeometry;
  29107. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  29108. exports.Clock = Clock;
  29109. exports.Color = Color;
  29110. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  29111. exports.CompressedTexture = CompressedTexture;
  29112. exports.CompressedTextureLoader = CompressedTextureLoader;
  29113. exports.ConeBufferGeometry = ConeGeometry;
  29114. exports.ConeGeometry = ConeGeometry;
  29115. exports.CubeCamera = CubeCamera;
  29116. exports.CubeReflectionMapping = CubeReflectionMapping;
  29117. exports.CubeRefractionMapping = CubeRefractionMapping;
  29118. exports.CubeTexture = CubeTexture;
  29119. exports.CubeTextureLoader = CubeTextureLoader;
  29120. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  29121. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  29122. exports.CubicBezierCurve = CubicBezierCurve;
  29123. exports.CubicBezierCurve3 = CubicBezierCurve3;
  29124. exports.CubicInterpolant = CubicInterpolant;
  29125. exports.CullFaceBack = CullFaceBack;
  29126. exports.CullFaceFront = CullFaceFront;
  29127. exports.CullFaceFrontBack = CullFaceFrontBack;
  29128. exports.CullFaceNone = CullFaceNone;
  29129. exports.Curve = Curve;
  29130. exports.CurvePath = CurvePath;
  29131. exports.CustomBlending = CustomBlending;
  29132. exports.CustomToneMapping = CustomToneMapping;
  29133. exports.CylinderBufferGeometry = CylinderGeometry;
  29134. exports.CylinderGeometry = CylinderGeometry;
  29135. exports.Cylindrical = Cylindrical;
  29136. exports.DataTexture = DataTexture;
  29137. exports.DataTexture2DArray = DataTexture2DArray;
  29138. exports.DataTexture3D = DataTexture3D;
  29139. exports.DataTextureLoader = DataTextureLoader;
  29140. exports.DataUtils = DataUtils;
  29141. exports.DecrementStencilOp = DecrementStencilOp;
  29142. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  29143. exports.DefaultLoadingManager = DefaultLoadingManager;
  29144. exports.DepthFormat = DepthFormat;
  29145. exports.DepthStencilFormat = DepthStencilFormat;
  29146. exports.DepthTexture = DepthTexture;
  29147. exports.DirectionalLight = DirectionalLight;
  29148. exports.DirectionalLightHelper = DirectionalLightHelper;
  29149. exports.DiscreteInterpolant = DiscreteInterpolant;
  29150. exports.DodecahedronBufferGeometry = DodecahedronGeometry;
  29151. exports.DodecahedronGeometry = DodecahedronGeometry;
  29152. exports.DoubleSide = DoubleSide;
  29153. exports.DstAlphaFactor = DstAlphaFactor;
  29154. exports.DstColorFactor = DstColorFactor;
  29155. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  29156. exports.DynamicCopyUsage = DynamicCopyUsage;
  29157. exports.DynamicDrawUsage = DynamicDrawUsage;
  29158. exports.DynamicReadUsage = DynamicReadUsage;
  29159. exports.EdgesGeometry = EdgesGeometry;
  29160. exports.EdgesHelper = EdgesHelper;
  29161. exports.EllipseCurve = EllipseCurve;
  29162. exports.EqualDepth = EqualDepth;
  29163. exports.EqualStencilFunc = EqualStencilFunc;
  29164. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  29165. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  29166. exports.Euler = Euler;
  29167. exports.EventDispatcher = EventDispatcher;
  29168. exports.ExtrudeBufferGeometry = ExtrudeGeometry;
  29169. exports.ExtrudeGeometry = ExtrudeGeometry;
  29170. exports.FaceColors = FaceColors;
  29171. exports.FileLoader = FileLoader;
  29172. exports.FlatShading = FlatShading;
  29173. exports.Float16BufferAttribute = Float16BufferAttribute;
  29174. exports.Float32Attribute = Float32Attribute;
  29175. exports.Float32BufferAttribute = Float32BufferAttribute;
  29176. exports.Float64Attribute = Float64Attribute;
  29177. exports.Float64BufferAttribute = Float64BufferAttribute;
  29178. exports.FloatType = FloatType;
  29179. exports.Fog = Fog;
  29180. exports.FogExp2 = FogExp2;
  29181. exports.Font = Font;
  29182. exports.FontLoader = FontLoader;
  29183. exports.FrontSide = FrontSide;
  29184. exports.Frustum = Frustum;
  29185. exports.GLBufferAttribute = GLBufferAttribute;
  29186. exports.GLSL1 = GLSL1;
  29187. exports.GLSL3 = GLSL3;
  29188. exports.GammaEncoding = GammaEncoding;
  29189. exports.GreaterDepth = GreaterDepth;
  29190. exports.GreaterEqualDepth = GreaterEqualDepth;
  29191. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  29192. exports.GreaterStencilFunc = GreaterStencilFunc;
  29193. exports.GridHelper = GridHelper;
  29194. exports.Group = Group;
  29195. exports.HalfFloatType = HalfFloatType;
  29196. exports.HemisphereLight = HemisphereLight;
  29197. exports.HemisphereLightHelper = HemisphereLightHelper;
  29198. exports.HemisphereLightProbe = HemisphereLightProbe;
  29199. exports.IcosahedronBufferGeometry = IcosahedronGeometry;
  29200. exports.IcosahedronGeometry = IcosahedronGeometry;
  29201. exports.ImageBitmapLoader = ImageBitmapLoader;
  29202. exports.ImageLoader = ImageLoader;
  29203. exports.ImageUtils = ImageUtils;
  29204. exports.ImmediateRenderObject = ImmediateRenderObject;
  29205. exports.IncrementStencilOp = IncrementStencilOp;
  29206. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  29207. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  29208. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  29209. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  29210. exports.InstancedMesh = InstancedMesh;
  29211. exports.Int16Attribute = Int16Attribute;
  29212. exports.Int16BufferAttribute = Int16BufferAttribute;
  29213. exports.Int32Attribute = Int32Attribute;
  29214. exports.Int32BufferAttribute = Int32BufferAttribute;
  29215. exports.Int8Attribute = Int8Attribute;
  29216. exports.Int8BufferAttribute = Int8BufferAttribute;
  29217. exports.IntType = IntType;
  29218. exports.InterleavedBuffer = InterleavedBuffer;
  29219. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  29220. exports.Interpolant = Interpolant;
  29221. exports.InterpolateDiscrete = InterpolateDiscrete;
  29222. exports.InterpolateLinear = InterpolateLinear;
  29223. exports.InterpolateSmooth = InterpolateSmooth;
  29224. exports.InvertStencilOp = InvertStencilOp;
  29225. exports.JSONLoader = JSONLoader;
  29226. exports.KeepStencilOp = KeepStencilOp;
  29227. exports.KeyframeTrack = KeyframeTrack;
  29228. exports.LOD = LOD;
  29229. exports.LatheBufferGeometry = LatheGeometry;
  29230. exports.LatheGeometry = LatheGeometry;
  29231. exports.Layers = Layers;
  29232. exports.LensFlare = LensFlare;
  29233. exports.LessDepth = LessDepth;
  29234. exports.LessEqualDepth = LessEqualDepth;
  29235. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  29236. exports.LessStencilFunc = LessStencilFunc;
  29237. exports.Light = Light;
  29238. exports.LightProbe = LightProbe;
  29239. exports.Line = Line;
  29240. exports.Line3 = Line3;
  29241. exports.LineBasicMaterial = LineBasicMaterial;
  29242. exports.LineCurve = LineCurve;
  29243. exports.LineCurve3 = LineCurve3;
  29244. exports.LineDashedMaterial = LineDashedMaterial;
  29245. exports.LineLoop = LineLoop;
  29246. exports.LinePieces = LinePieces;
  29247. exports.LineSegments = LineSegments;
  29248. exports.LineStrip = LineStrip;
  29249. exports.LinearEncoding = LinearEncoding;
  29250. exports.LinearFilter = LinearFilter;
  29251. exports.LinearInterpolant = LinearInterpolant;
  29252. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  29253. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  29254. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  29255. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  29256. exports.LinearToneMapping = LinearToneMapping;
  29257. exports.Loader = Loader;
  29258. exports.LoaderUtils = LoaderUtils;
  29259. exports.LoadingManager = LoadingManager;
  29260. exports.LogLuvEncoding = LogLuvEncoding;
  29261. exports.LoopOnce = LoopOnce;
  29262. exports.LoopPingPong = LoopPingPong;
  29263. exports.LoopRepeat = LoopRepeat;
  29264. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  29265. exports.LuminanceFormat = LuminanceFormat;
  29266. exports.MOUSE = MOUSE;
  29267. exports.Material = Material;
  29268. exports.MaterialLoader = MaterialLoader;
  29269. exports.Math = MathUtils;
  29270. exports.MathUtils = MathUtils;
  29271. exports.Matrix3 = Matrix3;
  29272. exports.Matrix4 = Matrix4;
  29273. exports.MaxEquation = MaxEquation;
  29274. exports.Mesh = Mesh;
  29275. exports.MeshBasicMaterial = MeshBasicMaterial;
  29276. exports.MeshDepthMaterial = MeshDepthMaterial;
  29277. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  29278. exports.MeshFaceMaterial = MeshFaceMaterial;
  29279. exports.MeshLambertMaterial = MeshLambertMaterial;
  29280. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  29281. exports.MeshNormalMaterial = MeshNormalMaterial;
  29282. exports.MeshPhongMaterial = MeshPhongMaterial;
  29283. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  29284. exports.MeshStandardMaterial = MeshStandardMaterial;
  29285. exports.MeshToonMaterial = MeshToonMaterial;
  29286. exports.MinEquation = MinEquation;
  29287. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  29288. exports.MixOperation = MixOperation;
  29289. exports.MultiMaterial = MultiMaterial;
  29290. exports.MultiplyBlending = MultiplyBlending;
  29291. exports.MultiplyOperation = MultiplyOperation;
  29292. exports.NearestFilter = NearestFilter;
  29293. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  29294. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  29295. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  29296. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  29297. exports.NeverDepth = NeverDepth;
  29298. exports.NeverStencilFunc = NeverStencilFunc;
  29299. exports.NoBlending = NoBlending;
  29300. exports.NoColors = NoColors;
  29301. exports.NoToneMapping = NoToneMapping;
  29302. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  29303. exports.NormalBlending = NormalBlending;
  29304. exports.NotEqualDepth = NotEqualDepth;
  29305. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  29306. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  29307. exports.Object3D = Object3D;
  29308. exports.ObjectLoader = ObjectLoader;
  29309. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  29310. exports.OctahedronBufferGeometry = OctahedronGeometry;
  29311. exports.OctahedronGeometry = OctahedronGeometry;
  29312. exports.OneFactor = OneFactor;
  29313. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  29314. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  29315. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  29316. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  29317. exports.OrthographicCamera = OrthographicCamera;
  29318. exports.PCFShadowMap = PCFShadowMap;
  29319. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  29320. exports.PMREMGenerator = PMREMGenerator;
  29321. exports.ParametricBufferGeometry = ParametricGeometry;
  29322. exports.ParametricGeometry = ParametricGeometry;
  29323. exports.Particle = Particle;
  29324. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  29325. exports.ParticleSystem = ParticleSystem;
  29326. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  29327. exports.Path = Path;
  29328. exports.PerspectiveCamera = PerspectiveCamera;
  29329. exports.Plane = Plane;
  29330. exports.PlaneBufferGeometry = PlaneGeometry;
  29331. exports.PlaneGeometry = PlaneGeometry;
  29332. exports.PlaneHelper = PlaneHelper;
  29333. exports.PointCloud = PointCloud;
  29334. exports.PointCloudMaterial = PointCloudMaterial;
  29335. exports.PointLight = PointLight;
  29336. exports.PointLightHelper = PointLightHelper;
  29337. exports.Points = Points;
  29338. exports.PointsMaterial = PointsMaterial;
  29339. exports.PolarGridHelper = PolarGridHelper;
  29340. exports.PolyhedronBufferGeometry = PolyhedronGeometry;
  29341. exports.PolyhedronGeometry = PolyhedronGeometry;
  29342. exports.PositionalAudio = PositionalAudio;
  29343. exports.PropertyBinding = PropertyBinding;
  29344. exports.PropertyMixer = PropertyMixer;
  29345. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  29346. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  29347. exports.Quaternion = Quaternion;
  29348. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  29349. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  29350. exports.REVISION = REVISION;
  29351. exports.RGBADepthPacking = RGBADepthPacking;
  29352. exports.RGBAFormat = RGBAFormat;
  29353. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  29354. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  29355. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  29356. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  29357. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  29358. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  29359. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  29360. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  29361. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  29362. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  29363. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  29364. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  29365. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  29366. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  29367. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  29368. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  29369. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  29370. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  29371. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  29372. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  29373. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  29374. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  29375. exports.RGBDEncoding = RGBDEncoding;
  29376. exports.RGBEEncoding = RGBEEncoding;
  29377. exports.RGBEFormat = RGBEFormat;
  29378. exports.RGBFormat = RGBFormat;
  29379. exports.RGBIntegerFormat = RGBIntegerFormat;
  29380. exports.RGBM16Encoding = RGBM16Encoding;
  29381. exports.RGBM7Encoding = RGBM7Encoding;
  29382. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  29383. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  29384. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  29385. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  29386. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  29387. exports.RGFormat = RGFormat;
  29388. exports.RGIntegerFormat = RGIntegerFormat;
  29389. exports.RawShaderMaterial = RawShaderMaterial;
  29390. exports.Ray = Ray;
  29391. exports.Raycaster = Raycaster;
  29392. exports.RectAreaLight = RectAreaLight;
  29393. exports.RedFormat = RedFormat;
  29394. exports.RedIntegerFormat = RedIntegerFormat;
  29395. exports.ReinhardToneMapping = ReinhardToneMapping;
  29396. exports.RepeatWrapping = RepeatWrapping;
  29397. exports.ReplaceStencilOp = ReplaceStencilOp;
  29398. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  29399. exports.RingBufferGeometry = RingGeometry;
  29400. exports.RingGeometry = RingGeometry;
  29401. exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
  29402. exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
  29403. exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
  29404. exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
  29405. exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
  29406. exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
  29407. exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
  29408. exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
  29409. exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
  29410. exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
  29411. exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
  29412. exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
  29413. exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
  29414. exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
  29415. exports.Scene = Scene;
  29416. exports.SceneUtils = SceneUtils;
  29417. exports.ShaderChunk = ShaderChunk;
  29418. exports.ShaderLib = ShaderLib;
  29419. exports.ShaderMaterial = ShaderMaterial;
  29420. exports.ShadowMaterial = ShadowMaterial;
  29421. exports.Shape = Shape;
  29422. exports.ShapeBufferGeometry = ShapeGeometry;
  29423. exports.ShapeGeometry = ShapeGeometry;
  29424. exports.ShapePath = ShapePath;
  29425. exports.ShapeUtils = ShapeUtils;
  29426. exports.ShortType = ShortType;
  29427. exports.Skeleton = Skeleton;
  29428. exports.SkeletonHelper = SkeletonHelper;
  29429. exports.SkinnedMesh = SkinnedMesh;
  29430. exports.SmoothShading = SmoothShading;
  29431. exports.Sphere = Sphere;
  29432. exports.SphereBufferGeometry = SphereGeometry;
  29433. exports.SphereGeometry = SphereGeometry;
  29434. exports.Spherical = Spherical;
  29435. exports.SphericalHarmonics3 = SphericalHarmonics3;
  29436. exports.SplineCurve = SplineCurve;
  29437. exports.SpotLight = SpotLight;
  29438. exports.SpotLightHelper = SpotLightHelper;
  29439. exports.Sprite = Sprite;
  29440. exports.SpriteMaterial = SpriteMaterial;
  29441. exports.SrcAlphaFactor = SrcAlphaFactor;
  29442. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  29443. exports.SrcColorFactor = SrcColorFactor;
  29444. exports.StaticCopyUsage = StaticCopyUsage;
  29445. exports.StaticDrawUsage = StaticDrawUsage;
  29446. exports.StaticReadUsage = StaticReadUsage;
  29447. exports.StereoCamera = StereoCamera;
  29448. exports.StreamCopyUsage = StreamCopyUsage;
  29449. exports.StreamDrawUsage = StreamDrawUsage;
  29450. exports.StreamReadUsage = StreamReadUsage;
  29451. exports.StringKeyframeTrack = StringKeyframeTrack;
  29452. exports.SubtractEquation = SubtractEquation;
  29453. exports.SubtractiveBlending = SubtractiveBlending;
  29454. exports.TOUCH = TOUCH;
  29455. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  29456. exports.TetrahedronBufferGeometry = TetrahedronGeometry;
  29457. exports.TetrahedronGeometry = TetrahedronGeometry;
  29458. exports.TextBufferGeometry = TextGeometry;
  29459. exports.TextGeometry = TextGeometry;
  29460. exports.Texture = Texture;
  29461. exports.TextureLoader = TextureLoader;
  29462. exports.TorusBufferGeometry = TorusGeometry;
  29463. exports.TorusGeometry = TorusGeometry;
  29464. exports.TorusKnotBufferGeometry = TorusKnotGeometry;
  29465. exports.TorusKnotGeometry = TorusKnotGeometry;
  29466. exports.Triangle = Triangle;
  29467. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  29468. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  29469. exports.TrianglesDrawMode = TrianglesDrawMode;
  29470. exports.TubeBufferGeometry = TubeGeometry;
  29471. exports.TubeGeometry = TubeGeometry;
  29472. exports.UVMapping = UVMapping;
  29473. exports.Uint16Attribute = Uint16Attribute;
  29474. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  29475. exports.Uint32Attribute = Uint32Attribute;
  29476. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  29477. exports.Uint8Attribute = Uint8Attribute;
  29478. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  29479. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  29480. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  29481. exports.Uniform = Uniform;
  29482. exports.UniformsLib = UniformsLib;
  29483. exports.UniformsUtils = UniformsUtils;
  29484. exports.UnsignedByteType = UnsignedByteType;
  29485. exports.UnsignedInt248Type = UnsignedInt248Type;
  29486. exports.UnsignedIntType = UnsignedIntType;
  29487. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  29488. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  29489. exports.UnsignedShort565Type = UnsignedShort565Type;
  29490. exports.UnsignedShortType = UnsignedShortType;
  29491. exports.VSMShadowMap = VSMShadowMap;
  29492. exports.Vector2 = Vector2;
  29493. exports.Vector3 = Vector3;
  29494. exports.Vector4 = Vector4;
  29495. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  29496. exports.Vertex = Vertex;
  29497. exports.VertexColors = VertexColors;
  29498. exports.VideoTexture = VideoTexture;
  29499. exports.WebGL1Renderer = WebGL1Renderer;
  29500. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  29501. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  29502. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  29503. exports.WebGLRenderTarget = WebGLRenderTarget;
  29504. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  29505. exports.WebGLRenderer = WebGLRenderer;
  29506. exports.WebGLUtils = WebGLUtils;
  29507. exports.WireframeGeometry = WireframeGeometry;
  29508. exports.WireframeHelper = WireframeHelper;
  29509. exports.WrapAroundEnding = WrapAroundEnding;
  29510. exports.XHRLoader = XHRLoader;
  29511. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  29512. exports.ZeroFactor = ZeroFactor;
  29513. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  29514. exports.ZeroStencilOp = ZeroStencilOp;
  29515. exports.sRGBEncoding = sRGBEncoding;
  29516. Object.defineProperty(exports, '__esModule', { value: true });
  29517. })));