three.js 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406
  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 = '132dev';
  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.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  1596. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1597. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  1598. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1599. }
  1600. setTexture(texture) {
  1601. texture.image = {
  1602. width: this.width,
  1603. height: this.height,
  1604. depth: this.depth
  1605. };
  1606. this.texture = texture;
  1607. }
  1608. setSize(width, height, depth = 1) {
  1609. if (this.width !== width || this.height !== height || this.depth !== depth) {
  1610. this.width = width;
  1611. this.height = height;
  1612. this.depth = depth;
  1613. this.texture.image.width = width;
  1614. this.texture.image.height = height;
  1615. this.texture.image.depth = depth;
  1616. this.dispose();
  1617. }
  1618. this.viewport.set(0, 0, width, height);
  1619. this.scissor.set(0, 0, width, height);
  1620. }
  1621. clone() {
  1622. return new this.constructor().copy(this);
  1623. }
  1624. copy(source) {
  1625. this.width = source.width;
  1626. this.height = source.height;
  1627. this.depth = source.depth;
  1628. this.viewport.copy(source.viewport);
  1629. this.texture = source.texture.clone();
  1630. this.texture.image = { ...this.texture.image
  1631. }; // See #20328.
  1632. this.depthBuffer = source.depthBuffer;
  1633. this.stencilBuffer = source.stencilBuffer;
  1634. this.depthTexture = source.depthTexture;
  1635. return this;
  1636. }
  1637. dispose() {
  1638. this.dispatchEvent({
  1639. type: 'dispose'
  1640. });
  1641. }
  1642. }
  1643. WebGLRenderTarget.prototype.isWebGLRenderTarget = true;
  1644. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  1645. constructor(width, height, count) {
  1646. super(width, height);
  1647. const texture = this.texture;
  1648. this.texture = [];
  1649. for (let i = 0; i < count; i++) {
  1650. this.texture[i] = texture.clone();
  1651. }
  1652. }
  1653. setSize(width, height, depth = 1) {
  1654. if (this.width !== width || this.height !== height || this.depth !== depth) {
  1655. this.width = width;
  1656. this.height = height;
  1657. this.depth = depth;
  1658. for (let i = 0, il = this.texture.length; i < il; i++) {
  1659. this.texture[i].image.width = width;
  1660. this.texture[i].image.height = height;
  1661. this.texture[i].image.depth = depth;
  1662. }
  1663. this.dispose();
  1664. }
  1665. this.viewport.set(0, 0, width, height);
  1666. this.scissor.set(0, 0, width, height);
  1667. return this;
  1668. }
  1669. copy(source) {
  1670. this.dispose();
  1671. this.width = source.width;
  1672. this.height = source.height;
  1673. this.depth = source.depth;
  1674. this.viewport.set(0, 0, this.width, this.height);
  1675. this.scissor.set(0, 0, this.width, this.height);
  1676. this.depthBuffer = source.depthBuffer;
  1677. this.stencilBuffer = source.stencilBuffer;
  1678. this.depthTexture = source.depthTexture;
  1679. this.texture.length = 0;
  1680. for (let i = 0, il = source.texture.length; i < il; i++) {
  1681. this.texture[i] = source.texture[i].clone();
  1682. }
  1683. return this;
  1684. }
  1685. }
  1686. WebGLMultipleRenderTargets.prototype.isWebGLMultipleRenderTargets = true;
  1687. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  1688. constructor(width, height, options) {
  1689. super(width, height, options);
  1690. this.samples = 4;
  1691. }
  1692. copy(source) {
  1693. super.copy.call(this, source);
  1694. this.samples = source.samples;
  1695. return this;
  1696. }
  1697. }
  1698. WebGLMultisampleRenderTarget.prototype.isWebGLMultisampleRenderTarget = true;
  1699. class Quaternion {
  1700. constructor(x = 0, y = 0, z = 0, w = 1) {
  1701. this._x = x;
  1702. this._y = y;
  1703. this._z = z;
  1704. this._w = w;
  1705. }
  1706. static slerp(qa, qb, qm, t) {
  1707. console.warn('THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead.');
  1708. return qm.slerpQuaternions(qa, qb, t);
  1709. }
  1710. static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  1711. // fuzz-free, array-based Quaternion SLERP operation
  1712. let x0 = src0[srcOffset0 + 0],
  1713. y0 = src0[srcOffset0 + 1],
  1714. z0 = src0[srcOffset0 + 2],
  1715. w0 = src0[srcOffset0 + 3];
  1716. const x1 = src1[srcOffset1 + 0],
  1717. y1 = src1[srcOffset1 + 1],
  1718. z1 = src1[srcOffset1 + 2],
  1719. w1 = src1[srcOffset1 + 3];
  1720. if (t === 0) {
  1721. dst[dstOffset + 0] = x0;
  1722. dst[dstOffset + 1] = y0;
  1723. dst[dstOffset + 2] = z0;
  1724. dst[dstOffset + 3] = w0;
  1725. return;
  1726. }
  1727. if (t === 1) {
  1728. dst[dstOffset + 0] = x1;
  1729. dst[dstOffset + 1] = y1;
  1730. dst[dstOffset + 2] = z1;
  1731. dst[dstOffset + 3] = w1;
  1732. return;
  1733. }
  1734. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  1735. let s = 1 - t;
  1736. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1737. dir = cos >= 0 ? 1 : -1,
  1738. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  1739. if (sqrSin > Number.EPSILON) {
  1740. const sin = Math.sqrt(sqrSin),
  1741. len = Math.atan2(sin, cos * dir);
  1742. s = Math.sin(s * len) / sin;
  1743. t = Math.sin(t * len) / sin;
  1744. }
  1745. const tDir = t * dir;
  1746. x0 = x0 * s + x1 * tDir;
  1747. y0 = y0 * s + y1 * tDir;
  1748. z0 = z0 * s + z1 * tDir;
  1749. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  1750. if (s === 1 - t) {
  1751. const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  1752. x0 *= f;
  1753. y0 *= f;
  1754. z0 *= f;
  1755. w0 *= f;
  1756. }
  1757. }
  1758. dst[dstOffset] = x0;
  1759. dst[dstOffset + 1] = y0;
  1760. dst[dstOffset + 2] = z0;
  1761. dst[dstOffset + 3] = w0;
  1762. }
  1763. static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
  1764. const x0 = src0[srcOffset0];
  1765. const y0 = src0[srcOffset0 + 1];
  1766. const z0 = src0[srcOffset0 + 2];
  1767. const w0 = src0[srcOffset0 + 3];
  1768. const x1 = src1[srcOffset1];
  1769. const y1 = src1[srcOffset1 + 1];
  1770. const z1 = src1[srcOffset1 + 2];
  1771. const w1 = src1[srcOffset1 + 3];
  1772. dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  1773. dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  1774. dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  1775. dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  1776. return dst;
  1777. }
  1778. get x() {
  1779. return this._x;
  1780. }
  1781. set x(value) {
  1782. this._x = value;
  1783. this._onChangeCallback();
  1784. }
  1785. get y() {
  1786. return this._y;
  1787. }
  1788. set y(value) {
  1789. this._y = value;
  1790. this._onChangeCallback();
  1791. }
  1792. get z() {
  1793. return this._z;
  1794. }
  1795. set z(value) {
  1796. this._z = value;
  1797. this._onChangeCallback();
  1798. }
  1799. get w() {
  1800. return this._w;
  1801. }
  1802. set w(value) {
  1803. this._w = value;
  1804. this._onChangeCallback();
  1805. }
  1806. set(x, y, z, w) {
  1807. this._x = x;
  1808. this._y = y;
  1809. this._z = z;
  1810. this._w = w;
  1811. this._onChangeCallback();
  1812. return this;
  1813. }
  1814. clone() {
  1815. return new this.constructor(this._x, this._y, this._z, this._w);
  1816. }
  1817. copy(quaternion) {
  1818. this._x = quaternion.x;
  1819. this._y = quaternion.y;
  1820. this._z = quaternion.z;
  1821. this._w = quaternion.w;
  1822. this._onChangeCallback();
  1823. return this;
  1824. }
  1825. setFromEuler(euler, update) {
  1826. if (!(euler && euler.isEuler)) {
  1827. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  1828. }
  1829. const x = euler._x,
  1830. y = euler._y,
  1831. z = euler._z,
  1832. order = euler._order; // http://www.mathworks.com/matlabcentral/fileexchange/
  1833. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1834. // content/SpinCalc.m
  1835. const cos = Math.cos;
  1836. const sin = Math.sin;
  1837. const c1 = cos(x / 2);
  1838. const c2 = cos(y / 2);
  1839. const c3 = cos(z / 2);
  1840. const s1 = sin(x / 2);
  1841. const s2 = sin(y / 2);
  1842. const s3 = sin(z / 2);
  1843. switch (order) {
  1844. case 'XYZ':
  1845. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1846. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1847. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1848. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1849. break;
  1850. case 'YXZ':
  1851. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1852. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1853. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1854. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1855. break;
  1856. case 'ZXY':
  1857. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1858. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1859. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1860. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1861. break;
  1862. case 'ZYX':
  1863. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1864. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1865. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1866. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1867. break;
  1868. case 'YZX':
  1869. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1870. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1871. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1872. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1873. break;
  1874. case 'XZY':
  1875. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1876. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1877. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1878. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1879. break;
  1880. default:
  1881. console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
  1882. }
  1883. if (update !== false) this._onChangeCallback();
  1884. return this;
  1885. }
  1886. setFromAxisAngle(axis, angle) {
  1887. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1888. // assumes axis is normalized
  1889. const halfAngle = angle / 2,
  1890. s = Math.sin(halfAngle);
  1891. this._x = axis.x * s;
  1892. this._y = axis.y * s;
  1893. this._z = axis.z * s;
  1894. this._w = Math.cos(halfAngle);
  1895. this._onChangeCallback();
  1896. return this;
  1897. }
  1898. setFromRotationMatrix(m) {
  1899. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1900. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1901. const te = m.elements,
  1902. m11 = te[0],
  1903. m12 = te[4],
  1904. m13 = te[8],
  1905. m21 = te[1],
  1906. m22 = te[5],
  1907. m23 = te[9],
  1908. m31 = te[2],
  1909. m32 = te[6],
  1910. m33 = te[10],
  1911. trace = m11 + m22 + m33;
  1912. if (trace > 0) {
  1913. const s = 0.5 / Math.sqrt(trace + 1.0);
  1914. this._w = 0.25 / s;
  1915. this._x = (m32 - m23) * s;
  1916. this._y = (m13 - m31) * s;
  1917. this._z = (m21 - m12) * s;
  1918. } else if (m11 > m22 && m11 > m33) {
  1919. const s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1920. this._w = (m32 - m23) / s;
  1921. this._x = 0.25 * s;
  1922. this._y = (m12 + m21) / s;
  1923. this._z = (m13 + m31) / s;
  1924. } else if (m22 > m33) {
  1925. const s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1926. this._w = (m13 - m31) / s;
  1927. this._x = (m12 + m21) / s;
  1928. this._y = 0.25 * s;
  1929. this._z = (m23 + m32) / s;
  1930. } else {
  1931. const s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1932. this._w = (m21 - m12) / s;
  1933. this._x = (m13 + m31) / s;
  1934. this._y = (m23 + m32) / s;
  1935. this._z = 0.25 * s;
  1936. }
  1937. this._onChangeCallback();
  1938. return this;
  1939. }
  1940. setFromUnitVectors(vFrom, vTo) {
  1941. // assumes direction vectors vFrom and vTo are normalized
  1942. let r = vFrom.dot(vTo) + 1;
  1943. if (r < Number.EPSILON) {
  1944. // vFrom and vTo point in opposite directions
  1945. r = 0;
  1946. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  1947. this._x = -vFrom.y;
  1948. this._y = vFrom.x;
  1949. this._z = 0;
  1950. this._w = r;
  1951. } else {
  1952. this._x = 0;
  1953. this._y = -vFrom.z;
  1954. this._z = vFrom.y;
  1955. this._w = r;
  1956. }
  1957. } else {
  1958. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  1959. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  1960. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  1961. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  1962. this._w = r;
  1963. }
  1964. return this.normalize();
  1965. }
  1966. angleTo(q) {
  1967. return 2 * Math.acos(Math.abs(clamp(this.dot(q), -1, 1)));
  1968. }
  1969. rotateTowards(q, step) {
  1970. const angle = this.angleTo(q);
  1971. if (angle === 0) return this;
  1972. const t = Math.min(1, step / angle);
  1973. this.slerp(q, t);
  1974. return this;
  1975. }
  1976. identity() {
  1977. return this.set(0, 0, 0, 1);
  1978. }
  1979. invert() {
  1980. // quaternion is assumed to have unit length
  1981. return this.conjugate();
  1982. }
  1983. conjugate() {
  1984. this._x *= -1;
  1985. this._y *= -1;
  1986. this._z *= -1;
  1987. this._onChangeCallback();
  1988. return this;
  1989. }
  1990. dot(v) {
  1991. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1992. }
  1993. lengthSq() {
  1994. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1995. }
  1996. length() {
  1997. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  1998. }
  1999. normalize() {
  2000. let l = this.length();
  2001. if (l === 0) {
  2002. this._x = 0;
  2003. this._y = 0;
  2004. this._z = 0;
  2005. this._w = 1;
  2006. } else {
  2007. l = 1 / l;
  2008. this._x = this._x * l;
  2009. this._y = this._y * l;
  2010. this._z = this._z * l;
  2011. this._w = this._w * l;
  2012. }
  2013. this._onChangeCallback();
  2014. return this;
  2015. }
  2016. multiply(q, p) {
  2017. if (p !== undefined) {
  2018. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  2019. return this.multiplyQuaternions(q, p);
  2020. }
  2021. return this.multiplyQuaternions(this, q);
  2022. }
  2023. premultiply(q) {
  2024. return this.multiplyQuaternions(q, this);
  2025. }
  2026. multiplyQuaternions(a, b) {
  2027. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2028. const qax = a._x,
  2029. qay = a._y,
  2030. qaz = a._z,
  2031. qaw = a._w;
  2032. const qbx = b._x,
  2033. qby = b._y,
  2034. qbz = b._z,
  2035. qbw = b._w;
  2036. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2037. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2038. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2039. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2040. this._onChangeCallback();
  2041. return this;
  2042. }
  2043. slerp(qb, t) {
  2044. if (t === 0) return this;
  2045. if (t === 1) return this.copy(qb);
  2046. const x = this._x,
  2047. y = this._y,
  2048. z = this._z,
  2049. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2050. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2051. if (cosHalfTheta < 0) {
  2052. this._w = -qb._w;
  2053. this._x = -qb._x;
  2054. this._y = -qb._y;
  2055. this._z = -qb._z;
  2056. cosHalfTheta = -cosHalfTheta;
  2057. } else {
  2058. this.copy(qb);
  2059. }
  2060. if (cosHalfTheta >= 1.0) {
  2061. this._w = w;
  2062. this._x = x;
  2063. this._y = y;
  2064. this._z = z;
  2065. return this;
  2066. }
  2067. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2068. if (sqrSinHalfTheta <= Number.EPSILON) {
  2069. const s = 1 - t;
  2070. this._w = s * w + t * this._w;
  2071. this._x = s * x + t * this._x;
  2072. this._y = s * y + t * this._y;
  2073. this._z = s * z + t * this._z;
  2074. this.normalize();
  2075. this._onChangeCallback();
  2076. return this;
  2077. }
  2078. const sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2079. const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2080. const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2081. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2082. this._w = w * ratioA + this._w * ratioB;
  2083. this._x = x * ratioA + this._x * ratioB;
  2084. this._y = y * ratioA + this._y * ratioB;
  2085. this._z = z * ratioA + this._z * ratioB;
  2086. this._onChangeCallback();
  2087. return this;
  2088. }
  2089. slerpQuaternions(qa, qb, t) {
  2090. this.copy(qa).slerp(qb, t);
  2091. }
  2092. equals(quaternion) {
  2093. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2094. }
  2095. fromArray(array, offset = 0) {
  2096. this._x = array[offset];
  2097. this._y = array[offset + 1];
  2098. this._z = array[offset + 2];
  2099. this._w = array[offset + 3];
  2100. this._onChangeCallback();
  2101. return this;
  2102. }
  2103. toArray(array = [], offset = 0) {
  2104. array[offset] = this._x;
  2105. array[offset + 1] = this._y;
  2106. array[offset + 2] = this._z;
  2107. array[offset + 3] = this._w;
  2108. return array;
  2109. }
  2110. fromBufferAttribute(attribute, index) {
  2111. this._x = attribute.getX(index);
  2112. this._y = attribute.getY(index);
  2113. this._z = attribute.getZ(index);
  2114. this._w = attribute.getW(index);
  2115. return this;
  2116. }
  2117. _onChange(callback) {
  2118. this._onChangeCallback = callback;
  2119. return this;
  2120. }
  2121. _onChangeCallback() {}
  2122. }
  2123. Quaternion.prototype.isQuaternion = true;
  2124. class Vector3 {
  2125. constructor(x = 0, y = 0, z = 0) {
  2126. this.x = x;
  2127. this.y = y;
  2128. this.z = z;
  2129. }
  2130. set(x, y, z) {
  2131. if (z === undefined) z = this.z; // sprite.scale.set(x,y)
  2132. this.x = x;
  2133. this.y = y;
  2134. this.z = z;
  2135. return this;
  2136. }
  2137. setScalar(scalar) {
  2138. this.x = scalar;
  2139. this.y = scalar;
  2140. this.z = scalar;
  2141. return this;
  2142. }
  2143. setX(x) {
  2144. this.x = x;
  2145. return this;
  2146. }
  2147. setY(y) {
  2148. this.y = y;
  2149. return this;
  2150. }
  2151. setZ(z) {
  2152. this.z = z;
  2153. return this;
  2154. }
  2155. setComponent(index, value) {
  2156. switch (index) {
  2157. case 0:
  2158. this.x = value;
  2159. break;
  2160. case 1:
  2161. this.y = value;
  2162. break;
  2163. case 2:
  2164. this.z = value;
  2165. break;
  2166. default:
  2167. throw new Error('index is out of range: ' + index);
  2168. }
  2169. return this;
  2170. }
  2171. getComponent(index) {
  2172. switch (index) {
  2173. case 0:
  2174. return this.x;
  2175. case 1:
  2176. return this.y;
  2177. case 2:
  2178. return this.z;
  2179. default:
  2180. throw new Error('index is out of range: ' + index);
  2181. }
  2182. }
  2183. clone() {
  2184. return new this.constructor(this.x, this.y, this.z);
  2185. }
  2186. copy(v) {
  2187. this.x = v.x;
  2188. this.y = v.y;
  2189. this.z = v.z;
  2190. return this;
  2191. }
  2192. add(v, w) {
  2193. if (w !== undefined) {
  2194. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2195. return this.addVectors(v, w);
  2196. }
  2197. this.x += v.x;
  2198. this.y += v.y;
  2199. this.z += v.z;
  2200. return this;
  2201. }
  2202. addScalar(s) {
  2203. this.x += s;
  2204. this.y += s;
  2205. this.z += s;
  2206. return this;
  2207. }
  2208. addVectors(a, b) {
  2209. this.x = a.x + b.x;
  2210. this.y = a.y + b.y;
  2211. this.z = a.z + b.z;
  2212. return this;
  2213. }
  2214. addScaledVector(v, s) {
  2215. this.x += v.x * s;
  2216. this.y += v.y * s;
  2217. this.z += v.z * s;
  2218. return this;
  2219. }
  2220. sub(v, w) {
  2221. if (w !== undefined) {
  2222. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2223. return this.subVectors(v, w);
  2224. }
  2225. this.x -= v.x;
  2226. this.y -= v.y;
  2227. this.z -= v.z;
  2228. return this;
  2229. }
  2230. subScalar(s) {
  2231. this.x -= s;
  2232. this.y -= s;
  2233. this.z -= s;
  2234. return this;
  2235. }
  2236. subVectors(a, b) {
  2237. this.x = a.x - b.x;
  2238. this.y = a.y - b.y;
  2239. this.z = a.z - b.z;
  2240. return this;
  2241. }
  2242. multiply(v, w) {
  2243. if (w !== undefined) {
  2244. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  2245. return this.multiplyVectors(v, w);
  2246. }
  2247. this.x *= v.x;
  2248. this.y *= v.y;
  2249. this.z *= v.z;
  2250. return this;
  2251. }
  2252. multiplyScalar(scalar) {
  2253. this.x *= scalar;
  2254. this.y *= scalar;
  2255. this.z *= scalar;
  2256. return this;
  2257. }
  2258. multiplyVectors(a, b) {
  2259. this.x = a.x * b.x;
  2260. this.y = a.y * b.y;
  2261. this.z = a.z * b.z;
  2262. return this;
  2263. }
  2264. applyEuler(euler) {
  2265. if (!(euler && euler.isEuler)) {
  2266. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2267. }
  2268. return this.applyQuaternion(_quaternion$4.setFromEuler(euler));
  2269. }
  2270. applyAxisAngle(axis, angle) {
  2271. return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle));
  2272. }
  2273. applyMatrix3(m) {
  2274. const x = this.x,
  2275. y = this.y,
  2276. z = this.z;
  2277. const e = m.elements;
  2278. this.x = e[0] * x + e[3] * y + e[6] * z;
  2279. this.y = e[1] * x + e[4] * y + e[7] * z;
  2280. this.z = e[2] * x + e[5] * y + e[8] * z;
  2281. return this;
  2282. }
  2283. applyNormalMatrix(m) {
  2284. return this.applyMatrix3(m).normalize();
  2285. }
  2286. applyMatrix4(m) {
  2287. const x = this.x,
  2288. y = this.y,
  2289. z = this.z;
  2290. const e = m.elements;
  2291. const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2292. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2293. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2294. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2295. return this;
  2296. }
  2297. applyQuaternion(q) {
  2298. const x = this.x,
  2299. y = this.y,
  2300. z = this.z;
  2301. const qx = q.x,
  2302. qy = q.y,
  2303. qz = q.z,
  2304. qw = q.w; // calculate quat * vector
  2305. const ix = qw * x + qy * z - qz * y;
  2306. const iy = qw * y + qz * x - qx * z;
  2307. const iz = qw * z + qx * y - qy * x;
  2308. const iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  2309. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2310. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2311. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2312. return this;
  2313. }
  2314. project(camera) {
  2315. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  2316. }
  2317. unproject(camera) {
  2318. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  2319. }
  2320. transformDirection(m) {
  2321. // input: THREE.Matrix4 affine matrix
  2322. // vector interpreted as a direction
  2323. const x = this.x,
  2324. y = this.y,
  2325. z = this.z;
  2326. const e = m.elements;
  2327. this.x = e[0] * x + e[4] * y + e[8] * z;
  2328. this.y = e[1] * x + e[5] * y + e[9] * z;
  2329. this.z = e[2] * x + e[6] * y + e[10] * z;
  2330. return this.normalize();
  2331. }
  2332. divide(v) {
  2333. this.x /= v.x;
  2334. this.y /= v.y;
  2335. this.z /= v.z;
  2336. return this;
  2337. }
  2338. divideScalar(scalar) {
  2339. return this.multiplyScalar(1 / scalar);
  2340. }
  2341. min(v) {
  2342. this.x = Math.min(this.x, v.x);
  2343. this.y = Math.min(this.y, v.y);
  2344. this.z = Math.min(this.z, v.z);
  2345. return this;
  2346. }
  2347. max(v) {
  2348. this.x = Math.max(this.x, v.x);
  2349. this.y = Math.max(this.y, v.y);
  2350. this.z = Math.max(this.z, v.z);
  2351. return this;
  2352. }
  2353. clamp(min, max) {
  2354. // assumes min < max, componentwise
  2355. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2356. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2357. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2358. return this;
  2359. }
  2360. clampScalar(minVal, maxVal) {
  2361. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2362. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2363. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2364. return this;
  2365. }
  2366. clampLength(min, max) {
  2367. const length = this.length();
  2368. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2369. }
  2370. floor() {
  2371. this.x = Math.floor(this.x);
  2372. this.y = Math.floor(this.y);
  2373. this.z = Math.floor(this.z);
  2374. return this;
  2375. }
  2376. ceil() {
  2377. this.x = Math.ceil(this.x);
  2378. this.y = Math.ceil(this.y);
  2379. this.z = Math.ceil(this.z);
  2380. return this;
  2381. }
  2382. round() {
  2383. this.x = Math.round(this.x);
  2384. this.y = Math.round(this.y);
  2385. this.z = Math.round(this.z);
  2386. return this;
  2387. }
  2388. roundToZero() {
  2389. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2390. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2391. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2392. return this;
  2393. }
  2394. negate() {
  2395. this.x = -this.x;
  2396. this.y = -this.y;
  2397. this.z = -this.z;
  2398. return this;
  2399. }
  2400. dot(v) {
  2401. return this.x * v.x + this.y * v.y + this.z * v.z;
  2402. } // TODO lengthSquared?
  2403. lengthSq() {
  2404. return this.x * this.x + this.y * this.y + this.z * this.z;
  2405. }
  2406. length() {
  2407. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2408. }
  2409. manhattanLength() {
  2410. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  2411. }
  2412. normalize() {
  2413. return this.divideScalar(this.length() || 1);
  2414. }
  2415. setLength(length) {
  2416. return this.normalize().multiplyScalar(length);
  2417. }
  2418. lerp(v, alpha) {
  2419. this.x += (v.x - this.x) * alpha;
  2420. this.y += (v.y - this.y) * alpha;
  2421. this.z += (v.z - this.z) * alpha;
  2422. return this;
  2423. }
  2424. lerpVectors(v1, v2, alpha) {
  2425. this.x = v1.x + (v2.x - v1.x) * alpha;
  2426. this.y = v1.y + (v2.y - v1.y) * alpha;
  2427. this.z = v1.z + (v2.z - v1.z) * alpha;
  2428. return this;
  2429. }
  2430. cross(v, w) {
  2431. if (w !== undefined) {
  2432. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  2433. return this.crossVectors(v, w);
  2434. }
  2435. return this.crossVectors(this, v);
  2436. }
  2437. crossVectors(a, b) {
  2438. const ax = a.x,
  2439. ay = a.y,
  2440. az = a.z;
  2441. const bx = b.x,
  2442. by = b.y,
  2443. bz = b.z;
  2444. this.x = ay * bz - az * by;
  2445. this.y = az * bx - ax * bz;
  2446. this.z = ax * by - ay * bx;
  2447. return this;
  2448. }
  2449. projectOnVector(v) {
  2450. const denominator = v.lengthSq();
  2451. if (denominator === 0) return this.set(0, 0, 0);
  2452. const scalar = v.dot(this) / denominator;
  2453. return this.copy(v).multiplyScalar(scalar);
  2454. }
  2455. projectOnPlane(planeNormal) {
  2456. _vector$c.copy(this).projectOnVector(planeNormal);
  2457. return this.sub(_vector$c);
  2458. }
  2459. reflect(normal) {
  2460. // reflect incident vector off plane orthogonal to normal
  2461. // normal is assumed to have unit length
  2462. return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal)));
  2463. }
  2464. angleTo(v) {
  2465. const denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  2466. if (denominator === 0) return Math.PI / 2;
  2467. const theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  2468. return Math.acos(clamp(theta, -1, 1));
  2469. }
  2470. distanceTo(v) {
  2471. return Math.sqrt(this.distanceToSquared(v));
  2472. }
  2473. distanceToSquared(v) {
  2474. const dx = this.x - v.x,
  2475. dy = this.y - v.y,
  2476. dz = this.z - v.z;
  2477. return dx * dx + dy * dy + dz * dz;
  2478. }
  2479. manhattanDistanceTo(v) {
  2480. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  2481. }
  2482. setFromSpherical(s) {
  2483. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  2484. }
  2485. setFromSphericalCoords(radius, phi, theta) {
  2486. const sinPhiRadius = Math.sin(phi) * radius;
  2487. this.x = sinPhiRadius * Math.sin(theta);
  2488. this.y = Math.cos(phi) * radius;
  2489. this.z = sinPhiRadius * Math.cos(theta);
  2490. return this;
  2491. }
  2492. setFromCylindrical(c) {
  2493. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  2494. }
  2495. setFromCylindricalCoords(radius, theta, y) {
  2496. this.x = radius * Math.sin(theta);
  2497. this.y = y;
  2498. this.z = radius * Math.cos(theta);
  2499. return this;
  2500. }
  2501. setFromMatrixPosition(m) {
  2502. const e = m.elements;
  2503. this.x = e[12];
  2504. this.y = e[13];
  2505. this.z = e[14];
  2506. return this;
  2507. }
  2508. setFromMatrixScale(m) {
  2509. const sx = this.setFromMatrixColumn(m, 0).length();
  2510. const sy = this.setFromMatrixColumn(m, 1).length();
  2511. const sz = this.setFromMatrixColumn(m, 2).length();
  2512. this.x = sx;
  2513. this.y = sy;
  2514. this.z = sz;
  2515. return this;
  2516. }
  2517. setFromMatrixColumn(m, index) {
  2518. return this.fromArray(m.elements, index * 4);
  2519. }
  2520. setFromMatrix3Column(m, index) {
  2521. return this.fromArray(m.elements, index * 3);
  2522. }
  2523. equals(v) {
  2524. return v.x === this.x && v.y === this.y && v.z === this.z;
  2525. }
  2526. fromArray(array, offset = 0) {
  2527. this.x = array[offset];
  2528. this.y = array[offset + 1];
  2529. this.z = array[offset + 2];
  2530. return this;
  2531. }
  2532. toArray(array = [], offset = 0) {
  2533. array[offset] = this.x;
  2534. array[offset + 1] = this.y;
  2535. array[offset + 2] = this.z;
  2536. return array;
  2537. }
  2538. fromBufferAttribute(attribute, index, offset) {
  2539. if (offset !== undefined) {
  2540. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  2541. }
  2542. this.x = attribute.getX(index);
  2543. this.y = attribute.getY(index);
  2544. this.z = attribute.getZ(index);
  2545. return this;
  2546. }
  2547. random() {
  2548. this.x = Math.random();
  2549. this.y = Math.random();
  2550. this.z = Math.random();
  2551. return this;
  2552. }
  2553. }
  2554. Vector3.prototype.isVector3 = true;
  2555. const _vector$c = /*@__PURE__*/new Vector3();
  2556. const _quaternion$4 = /*@__PURE__*/new Quaternion();
  2557. class Box3 {
  2558. constructor(min = new Vector3(+Infinity, +Infinity, +Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity)) {
  2559. this.min = min;
  2560. this.max = max;
  2561. }
  2562. set(min, max) {
  2563. this.min.copy(min);
  2564. this.max.copy(max);
  2565. return this;
  2566. }
  2567. setFromArray(array) {
  2568. let minX = +Infinity;
  2569. let minY = +Infinity;
  2570. let minZ = +Infinity;
  2571. let maxX = -Infinity;
  2572. let maxY = -Infinity;
  2573. let maxZ = -Infinity;
  2574. for (let i = 0, l = array.length; i < l; i += 3) {
  2575. const x = array[i];
  2576. const y = array[i + 1];
  2577. const z = array[i + 2];
  2578. if (x < minX) minX = x;
  2579. if (y < minY) minY = y;
  2580. if (z < minZ) minZ = z;
  2581. if (x > maxX) maxX = x;
  2582. if (y > maxY) maxY = y;
  2583. if (z > maxZ) maxZ = z;
  2584. }
  2585. this.min.set(minX, minY, minZ);
  2586. this.max.set(maxX, maxY, maxZ);
  2587. return this;
  2588. }
  2589. setFromBufferAttribute(attribute) {
  2590. let minX = +Infinity;
  2591. let minY = +Infinity;
  2592. let minZ = +Infinity;
  2593. let maxX = -Infinity;
  2594. let maxY = -Infinity;
  2595. let maxZ = -Infinity;
  2596. for (let i = 0, l = attribute.count; i < l; i++) {
  2597. const x = attribute.getX(i);
  2598. const y = attribute.getY(i);
  2599. const z = attribute.getZ(i);
  2600. if (x < minX) minX = x;
  2601. if (y < minY) minY = y;
  2602. if (z < minZ) minZ = z;
  2603. if (x > maxX) maxX = x;
  2604. if (y > maxY) maxY = y;
  2605. if (z > maxZ) maxZ = z;
  2606. }
  2607. this.min.set(minX, minY, minZ);
  2608. this.max.set(maxX, maxY, maxZ);
  2609. return this;
  2610. }
  2611. setFromPoints(points) {
  2612. this.makeEmpty();
  2613. for (let i = 0, il = points.length; i < il; i++) {
  2614. this.expandByPoint(points[i]);
  2615. }
  2616. return this;
  2617. }
  2618. setFromCenterAndSize(center, size) {
  2619. const halfSize = _vector$b.copy(size).multiplyScalar(0.5);
  2620. this.min.copy(center).sub(halfSize);
  2621. this.max.copy(center).add(halfSize);
  2622. return this;
  2623. }
  2624. setFromObject(object) {
  2625. this.makeEmpty();
  2626. return this.expandByObject(object);
  2627. }
  2628. clone() {
  2629. return new this.constructor().copy(this);
  2630. }
  2631. copy(box) {
  2632. this.min.copy(box.min);
  2633. this.max.copy(box.max);
  2634. return this;
  2635. }
  2636. makeEmpty() {
  2637. this.min.x = this.min.y = this.min.z = +Infinity;
  2638. this.max.x = this.max.y = this.max.z = -Infinity;
  2639. return this;
  2640. }
  2641. isEmpty() {
  2642. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2643. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  2644. }
  2645. getCenter(target) {
  2646. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  2647. }
  2648. getSize(target) {
  2649. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  2650. }
  2651. expandByPoint(point) {
  2652. this.min.min(point);
  2653. this.max.max(point);
  2654. return this;
  2655. }
  2656. expandByVector(vector) {
  2657. this.min.sub(vector);
  2658. this.max.add(vector);
  2659. return this;
  2660. }
  2661. expandByScalar(scalar) {
  2662. this.min.addScalar(-scalar);
  2663. this.max.addScalar(scalar);
  2664. return this;
  2665. }
  2666. expandByObject(object) {
  2667. // Computes the world-axis-aligned bounding box of an object (including its children),
  2668. // accounting for both the object's, and children's, world transforms
  2669. object.updateWorldMatrix(false, false);
  2670. const geometry = object.geometry;
  2671. if (geometry !== undefined) {
  2672. if (geometry.boundingBox === null) {
  2673. geometry.computeBoundingBox();
  2674. }
  2675. _box$3.copy(geometry.boundingBox);
  2676. _box$3.applyMatrix4(object.matrixWorld);
  2677. this.union(_box$3);
  2678. }
  2679. const children = object.children;
  2680. for (let i = 0, l = children.length; i < l; i++) {
  2681. this.expandByObject(children[i]);
  2682. }
  2683. return this;
  2684. }
  2685. containsPoint(point) {
  2686. 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;
  2687. }
  2688. containsBox(box) {
  2689. 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;
  2690. }
  2691. getParameter(point, target) {
  2692. // This can potentially have a divide by zero if the box
  2693. // has a size dimension of 0.
  2694. 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));
  2695. }
  2696. intersectsBox(box) {
  2697. // using 6 splitting planes to rule out intersections.
  2698. 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;
  2699. }
  2700. intersectsSphere(sphere) {
  2701. // Find the point on the AABB closest to the sphere center.
  2702. this.clampPoint(sphere.center, _vector$b); // If that point is inside the sphere, the AABB and sphere intersect.
  2703. return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  2704. }
  2705. intersectsPlane(plane) {
  2706. // We compute the minimum and maximum dot product values. If those values
  2707. // are on the same side (back or front) of the plane, then there is no intersection.
  2708. let min, max;
  2709. if (plane.normal.x > 0) {
  2710. min = plane.normal.x * this.min.x;
  2711. max = plane.normal.x * this.max.x;
  2712. } else {
  2713. min = plane.normal.x * this.max.x;
  2714. max = plane.normal.x * this.min.x;
  2715. }
  2716. if (plane.normal.y > 0) {
  2717. min += plane.normal.y * this.min.y;
  2718. max += plane.normal.y * this.max.y;
  2719. } else {
  2720. min += plane.normal.y * this.max.y;
  2721. max += plane.normal.y * this.min.y;
  2722. }
  2723. if (plane.normal.z > 0) {
  2724. min += plane.normal.z * this.min.z;
  2725. max += plane.normal.z * this.max.z;
  2726. } else {
  2727. min += plane.normal.z * this.max.z;
  2728. max += plane.normal.z * this.min.z;
  2729. }
  2730. return min <= -plane.constant && max >= -plane.constant;
  2731. }
  2732. intersectsTriangle(triangle) {
  2733. if (this.isEmpty()) {
  2734. return false;
  2735. } // compute box center and extents
  2736. this.getCenter(_center);
  2737. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  2738. _v0$2.subVectors(triangle.a, _center);
  2739. _v1$7.subVectors(triangle.b, _center);
  2740. _v2$3.subVectors(triangle.c, _center); // compute edge vectors for triangle
  2741. _f0.subVectors(_v1$7, _v0$2);
  2742. _f1.subVectors(_v2$3, _v1$7);
  2743. _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
  2744. // 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
  2745. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2746. 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];
  2747. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  2748. return false;
  2749. } // test 3 face normals from the aabb
  2750. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  2751. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  2752. return false;
  2753. } // finally testing the face normal of the triangle
  2754. // use already existing triangle edge vectors here
  2755. _triangleNormal.crossVectors(_f0, _f1);
  2756. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  2757. return satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents);
  2758. }
  2759. clampPoint(point, target) {
  2760. return target.copy(point).clamp(this.min, this.max);
  2761. }
  2762. distanceToPoint(point) {
  2763. const clampedPoint = _vector$b.copy(point).clamp(this.min, this.max);
  2764. return clampedPoint.sub(point).length();
  2765. }
  2766. getBoundingSphere(target) {
  2767. this.getCenter(target.center);
  2768. target.radius = this.getSize(_vector$b).length() * 0.5;
  2769. return target;
  2770. }
  2771. intersect(box) {
  2772. this.min.max(box.min);
  2773. 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.
  2774. if (this.isEmpty()) this.makeEmpty();
  2775. return this;
  2776. }
  2777. union(box) {
  2778. this.min.min(box.min);
  2779. this.max.max(box.max);
  2780. return this;
  2781. }
  2782. applyMatrix4(matrix) {
  2783. // transform of empty box is an empty box.
  2784. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2785. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  2786. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  2787. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  2788. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  2789. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  2790. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  2791. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  2792. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  2793. this.setFromPoints(_points);
  2794. return this;
  2795. }
  2796. translate(offset) {
  2797. this.min.add(offset);
  2798. this.max.add(offset);
  2799. return this;
  2800. }
  2801. equals(box) {
  2802. return box.min.equals(this.min) && box.max.equals(this.max);
  2803. }
  2804. }
  2805. Box3.prototype.isBox3 = true;
  2806. 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()];
  2807. const _vector$b = /*@__PURE__*/new Vector3();
  2808. const _box$3 = /*@__PURE__*/new Box3(); // triangle centered vertices
  2809. const _v0$2 = /*@__PURE__*/new Vector3();
  2810. const _v1$7 = /*@__PURE__*/new Vector3();
  2811. const _v2$3 = /*@__PURE__*/new Vector3(); // triangle edge vectors
  2812. const _f0 = /*@__PURE__*/new Vector3();
  2813. const _f1 = /*@__PURE__*/new Vector3();
  2814. const _f2 = /*@__PURE__*/new Vector3();
  2815. const _center = /*@__PURE__*/new Vector3();
  2816. const _extents = /*@__PURE__*/new Vector3();
  2817. const _triangleNormal = /*@__PURE__*/new Vector3();
  2818. const _testAxis = /*@__PURE__*/new Vector3();
  2819. function satForAxes(axes, v0, v1, v2, extents) {
  2820. for (let i = 0, j = axes.length - 3; i <= j; i += 3) {
  2821. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  2822. 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
  2823. const p0 = v0.dot(_testAxis);
  2824. const p1 = v1.dot(_testAxis);
  2825. const p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  2826. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  2827. // points of the projected triangle are outside the projected half-length of the aabb
  2828. // the axis is seperating and we can exit
  2829. return false;
  2830. }
  2831. }
  2832. return true;
  2833. }
  2834. const _box$2 = /*@__PURE__*/new Box3();
  2835. const _v1$6 = /*@__PURE__*/new Vector3();
  2836. const _toFarthestPoint = /*@__PURE__*/new Vector3();
  2837. const _toPoint = /*@__PURE__*/new Vector3();
  2838. class Sphere {
  2839. constructor(center = new Vector3(), radius = -1) {
  2840. this.center = center;
  2841. this.radius = radius;
  2842. }
  2843. set(center, radius) {
  2844. this.center.copy(center);
  2845. this.radius = radius;
  2846. return this;
  2847. }
  2848. setFromPoints(points, optionalCenter) {
  2849. const center = this.center;
  2850. if (optionalCenter !== undefined) {
  2851. center.copy(optionalCenter);
  2852. } else {
  2853. _box$2.setFromPoints(points).getCenter(center);
  2854. }
  2855. let maxRadiusSq = 0;
  2856. for (let i = 0, il = points.length; i < il; i++) {
  2857. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  2858. }
  2859. this.radius = Math.sqrt(maxRadiusSq);
  2860. return this;
  2861. }
  2862. copy(sphere) {
  2863. this.center.copy(sphere.center);
  2864. this.radius = sphere.radius;
  2865. return this;
  2866. }
  2867. isEmpty() {
  2868. return this.radius < 0;
  2869. }
  2870. makeEmpty() {
  2871. this.center.set(0, 0, 0);
  2872. this.radius = -1;
  2873. return this;
  2874. }
  2875. containsPoint(point) {
  2876. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  2877. }
  2878. distanceToPoint(point) {
  2879. return point.distanceTo(this.center) - this.radius;
  2880. }
  2881. intersectsSphere(sphere) {
  2882. const radiusSum = this.radius + sphere.radius;
  2883. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  2884. }
  2885. intersectsBox(box) {
  2886. return box.intersectsSphere(this);
  2887. }
  2888. intersectsPlane(plane) {
  2889. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  2890. }
  2891. clampPoint(point, target) {
  2892. const deltaLengthSq = this.center.distanceToSquared(point);
  2893. target.copy(point);
  2894. if (deltaLengthSq > this.radius * this.radius) {
  2895. target.sub(this.center).normalize();
  2896. target.multiplyScalar(this.radius).add(this.center);
  2897. }
  2898. return target;
  2899. }
  2900. getBoundingBox(target) {
  2901. if (this.isEmpty()) {
  2902. // Empty sphere produces empty bounding box
  2903. target.makeEmpty();
  2904. return target;
  2905. }
  2906. target.set(this.center, this.center);
  2907. target.expandByScalar(this.radius);
  2908. return target;
  2909. }
  2910. applyMatrix4(matrix) {
  2911. this.center.applyMatrix4(matrix);
  2912. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2913. return this;
  2914. }
  2915. translate(offset) {
  2916. this.center.add(offset);
  2917. return this;
  2918. }
  2919. expandByPoint(point) {
  2920. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  2921. _toPoint.subVectors(point, this.center);
  2922. const lengthSq = _toPoint.lengthSq();
  2923. if (lengthSq > this.radius * this.radius) {
  2924. const length = Math.sqrt(lengthSq);
  2925. const missingRadiusHalf = (length - this.radius) * 0.5; // Nudge this sphere towards the target point. Add half the missing distance to radius,
  2926. // and the other half to position. This gives a tighter enclosure, instead of if
  2927. // the whole missing distance were just added to radius.
  2928. this.center.add(_toPoint.multiplyScalar(missingRadiusHalf / length));
  2929. this.radius += missingRadiusHalf;
  2930. }
  2931. return this;
  2932. }
  2933. union(sphere) {
  2934. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  2935. // To enclose another sphere into this sphere, we only need to enclose two points:
  2936. // 1) Enclose the farthest point on the other sphere into this sphere.
  2937. // 2) Enclose the opposite point of the farthest point into this sphere.
  2938. _toFarthestPoint.subVectors(sphere.center, this.center).normalize().multiplyScalar(sphere.radius);
  2939. this.expandByPoint(_v1$6.copy(sphere.center).add(_toFarthestPoint));
  2940. this.expandByPoint(_v1$6.copy(sphere.center).sub(_toFarthestPoint));
  2941. return this;
  2942. }
  2943. equals(sphere) {
  2944. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  2945. }
  2946. clone() {
  2947. return new this.constructor().copy(this);
  2948. }
  2949. }
  2950. const _vector$a = /*@__PURE__*/new Vector3();
  2951. const _segCenter = /*@__PURE__*/new Vector3();
  2952. const _segDir = /*@__PURE__*/new Vector3();
  2953. const _diff = /*@__PURE__*/new Vector3();
  2954. const _edge1 = /*@__PURE__*/new Vector3();
  2955. const _edge2 = /*@__PURE__*/new Vector3();
  2956. const _normal$1 = /*@__PURE__*/new Vector3();
  2957. class Ray {
  2958. constructor(origin = new Vector3(), direction = new Vector3(0, 0, -1)) {
  2959. this.origin = origin;
  2960. this.direction = direction;
  2961. }
  2962. set(origin, direction) {
  2963. this.origin.copy(origin);
  2964. this.direction.copy(direction);
  2965. return this;
  2966. }
  2967. copy(ray) {
  2968. this.origin.copy(ray.origin);
  2969. this.direction.copy(ray.direction);
  2970. return this;
  2971. }
  2972. at(t, target) {
  2973. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  2974. }
  2975. lookAt(v) {
  2976. this.direction.copy(v).sub(this.origin).normalize();
  2977. return this;
  2978. }
  2979. recast(t) {
  2980. this.origin.copy(this.at(t, _vector$a));
  2981. return this;
  2982. }
  2983. closestPointToPoint(point, target) {
  2984. target.subVectors(point, this.origin);
  2985. const directionDistance = target.dot(this.direction);
  2986. if (directionDistance < 0) {
  2987. return target.copy(this.origin);
  2988. }
  2989. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  2990. }
  2991. distanceToPoint(point) {
  2992. return Math.sqrt(this.distanceSqToPoint(point));
  2993. }
  2994. distanceSqToPoint(point) {
  2995. const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  2996. if (directionDistance < 0) {
  2997. return this.origin.distanceToSquared(point);
  2998. }
  2999. _vector$a.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3000. return _vector$a.distanceToSquared(point);
  3001. }
  3002. distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  3003. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3004. // It returns the min distance between the ray and the segment
  3005. // defined by v0 and v1
  3006. // It can also set two optional targets :
  3007. // - The closest point on the ray
  3008. // - The closest point on the segment
  3009. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  3010. _segDir.copy(v1).sub(v0).normalize();
  3011. _diff.copy(this.origin).sub(_segCenter);
  3012. const segExtent = v0.distanceTo(v1) * 0.5;
  3013. const a01 = -this.direction.dot(_segDir);
  3014. const b0 = _diff.dot(this.direction);
  3015. const b1 = -_diff.dot(_segDir);
  3016. const c = _diff.lengthSq();
  3017. const det = Math.abs(1 - a01 * a01);
  3018. let s0, s1, sqrDist, extDet;
  3019. if (det > 0) {
  3020. // The ray and segment are not parallel.
  3021. s0 = a01 * b1 - b0;
  3022. s1 = a01 * b0 - b1;
  3023. extDet = segExtent * det;
  3024. if (s0 >= 0) {
  3025. if (s1 >= -extDet) {
  3026. if (s1 <= extDet) {
  3027. // region 0
  3028. // Minimum at interior points of ray and segment.
  3029. const invDet = 1 / det;
  3030. s0 *= invDet;
  3031. s1 *= invDet;
  3032. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  3033. } else {
  3034. // region 1
  3035. s1 = segExtent;
  3036. s0 = Math.max(0, -(a01 * s1 + b0));
  3037. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3038. }
  3039. } else {
  3040. // region 5
  3041. s1 = -segExtent;
  3042. s0 = Math.max(0, -(a01 * s1 + b0));
  3043. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3044. }
  3045. } else {
  3046. if (s1 <= -extDet) {
  3047. // region 4
  3048. s0 = Math.max(0, -(-a01 * segExtent + b0));
  3049. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3050. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3051. } else if (s1 <= extDet) {
  3052. // region 3
  3053. s0 = 0;
  3054. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  3055. sqrDist = s1 * (s1 + 2 * b1) + c;
  3056. } else {
  3057. // region 2
  3058. s0 = Math.max(0, -(a01 * segExtent + b0));
  3059. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3060. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3061. }
  3062. }
  3063. } else {
  3064. // Ray and segment are parallel.
  3065. s1 = a01 > 0 ? -segExtent : segExtent;
  3066. s0 = Math.max(0, -(a01 * s1 + b0));
  3067. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3068. }
  3069. if (optionalPointOnRay) {
  3070. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  3071. }
  3072. if (optionalPointOnSegment) {
  3073. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  3074. }
  3075. return sqrDist;
  3076. }
  3077. intersectSphere(sphere, target) {
  3078. _vector$a.subVectors(sphere.center, this.origin);
  3079. const tca = _vector$a.dot(this.direction);
  3080. const d2 = _vector$a.dot(_vector$a) - tca * tca;
  3081. const radius2 = sphere.radius * sphere.radius;
  3082. if (d2 > radius2) return null;
  3083. const thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  3084. const t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  3085. const t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  3086. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  3087. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3088. // in order to always return an intersect point that is in front of the ray.
  3089. 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
  3090. return this.at(t0, target);
  3091. }
  3092. intersectsSphere(sphere) {
  3093. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  3094. }
  3095. distanceToPlane(plane) {
  3096. const denominator = plane.normal.dot(this.direction);
  3097. if (denominator === 0) {
  3098. // line is coplanar, return origin
  3099. if (plane.distanceToPoint(this.origin) === 0) {
  3100. return 0;
  3101. } // Null is preferable to undefined since undefined means.... it is undefined
  3102. return null;
  3103. }
  3104. const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  3105. return t >= 0 ? t : null;
  3106. }
  3107. intersectPlane(plane, target) {
  3108. const t = this.distanceToPlane(plane);
  3109. if (t === null) {
  3110. return null;
  3111. }
  3112. return this.at(t, target);
  3113. }
  3114. intersectsPlane(plane) {
  3115. // check if the ray lies on the plane first
  3116. const distToPoint = plane.distanceToPoint(this.origin);
  3117. if (distToPoint === 0) {
  3118. return true;
  3119. }
  3120. const denominator = plane.normal.dot(this.direction);
  3121. if (denominator * distToPoint < 0) {
  3122. return true;
  3123. } // ray origin is behind the plane (and is pointing behind it)
  3124. return false;
  3125. }
  3126. intersectBox(box, target) {
  3127. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3128. const invdirx = 1 / this.direction.x,
  3129. invdiry = 1 / this.direction.y,
  3130. invdirz = 1 / this.direction.z;
  3131. const origin = this.origin;
  3132. if (invdirx >= 0) {
  3133. tmin = (box.min.x - origin.x) * invdirx;
  3134. tmax = (box.max.x - origin.x) * invdirx;
  3135. } else {
  3136. tmin = (box.max.x - origin.x) * invdirx;
  3137. tmax = (box.min.x - origin.x) * invdirx;
  3138. }
  3139. if (invdiry >= 0) {
  3140. tymin = (box.min.y - origin.y) * invdiry;
  3141. tymax = (box.max.y - origin.y) * invdiry;
  3142. } else {
  3143. tymin = (box.max.y - origin.y) * invdiry;
  3144. tymax = (box.min.y - origin.y) * invdiry;
  3145. }
  3146. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  3147. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3148. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  3149. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  3150. if (invdirz >= 0) {
  3151. tzmin = (box.min.z - origin.z) * invdirz;
  3152. tzmax = (box.max.z - origin.z) * invdirz;
  3153. } else {
  3154. tzmin = (box.max.z - origin.z) * invdirz;
  3155. tzmax = (box.min.z - origin.z) * invdirz;
  3156. }
  3157. if (tmin > tzmax || tzmin > tmax) return null;
  3158. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  3159. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  3160. if (tmax < 0) return null;
  3161. return this.at(tmin >= 0 ? tmin : tmax, target);
  3162. }
  3163. intersectsBox(box) {
  3164. return this.intersectBox(box, _vector$a) !== null;
  3165. }
  3166. intersectTriangle(a, b, c, backfaceCulling, target) {
  3167. // Compute the offset origin, edges, and normal.
  3168. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3169. _edge1.subVectors(b, a);
  3170. _edge2.subVectors(c, a);
  3171. _normal$1.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3172. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3173. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3174. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3175. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3176. let DdN = this.direction.dot(_normal$1);
  3177. let sign;
  3178. if (DdN > 0) {
  3179. if (backfaceCulling) return null;
  3180. sign = 1;
  3181. } else if (DdN < 0) {
  3182. sign = -1;
  3183. DdN = -DdN;
  3184. } else {
  3185. return null;
  3186. }
  3187. _diff.subVectors(this.origin, a);
  3188. const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  3189. if (DdQxE2 < 0) {
  3190. return null;
  3191. }
  3192. const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  3193. if (DdE1xQ < 0) {
  3194. return null;
  3195. } // b1+b2 > 1, no intersection
  3196. if (DdQxE2 + DdE1xQ > DdN) {
  3197. return null;
  3198. } // Line intersects triangle, check if ray does.
  3199. const QdN = -sign * _diff.dot(_normal$1); // t < 0, no intersection
  3200. if (QdN < 0) {
  3201. return null;
  3202. } // Ray intersects triangle.
  3203. return this.at(QdN / DdN, target);
  3204. }
  3205. applyMatrix4(matrix4) {
  3206. this.origin.applyMatrix4(matrix4);
  3207. this.direction.transformDirection(matrix4);
  3208. return this;
  3209. }
  3210. equals(ray) {
  3211. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  3212. }
  3213. clone() {
  3214. return new this.constructor().copy(this);
  3215. }
  3216. }
  3217. class Matrix4 {
  3218. constructor() {
  3219. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  3220. if (arguments.length > 0) {
  3221. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  3222. }
  3223. }
  3224. set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  3225. const te = this.elements;
  3226. te[0] = n11;
  3227. te[4] = n12;
  3228. te[8] = n13;
  3229. te[12] = n14;
  3230. te[1] = n21;
  3231. te[5] = n22;
  3232. te[9] = n23;
  3233. te[13] = n24;
  3234. te[2] = n31;
  3235. te[6] = n32;
  3236. te[10] = n33;
  3237. te[14] = n34;
  3238. te[3] = n41;
  3239. te[7] = n42;
  3240. te[11] = n43;
  3241. te[15] = n44;
  3242. return this;
  3243. }
  3244. identity() {
  3245. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3246. return this;
  3247. }
  3248. clone() {
  3249. return new Matrix4().fromArray(this.elements);
  3250. }
  3251. copy(m) {
  3252. const te = this.elements;
  3253. const me = m.elements;
  3254. te[0] = me[0];
  3255. te[1] = me[1];
  3256. te[2] = me[2];
  3257. te[3] = me[3];
  3258. te[4] = me[4];
  3259. te[5] = me[5];
  3260. te[6] = me[6];
  3261. te[7] = me[7];
  3262. te[8] = me[8];
  3263. te[9] = me[9];
  3264. te[10] = me[10];
  3265. te[11] = me[11];
  3266. te[12] = me[12];
  3267. te[13] = me[13];
  3268. te[14] = me[14];
  3269. te[15] = me[15];
  3270. return this;
  3271. }
  3272. copyPosition(m) {
  3273. const te = this.elements,
  3274. me = m.elements;
  3275. te[12] = me[12];
  3276. te[13] = me[13];
  3277. te[14] = me[14];
  3278. return this;
  3279. }
  3280. setFromMatrix3(m) {
  3281. const me = m.elements;
  3282. 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);
  3283. return this;
  3284. }
  3285. extractBasis(xAxis, yAxis, zAxis) {
  3286. xAxis.setFromMatrixColumn(this, 0);
  3287. yAxis.setFromMatrixColumn(this, 1);
  3288. zAxis.setFromMatrixColumn(this, 2);
  3289. return this;
  3290. }
  3291. makeBasis(xAxis, yAxis, zAxis) {
  3292. 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);
  3293. return this;
  3294. }
  3295. extractRotation(m) {
  3296. // this method does not support reflection matrices
  3297. const te = this.elements;
  3298. const me = m.elements;
  3299. const scaleX = 1 / _v1$5.setFromMatrixColumn(m, 0).length();
  3300. const scaleY = 1 / _v1$5.setFromMatrixColumn(m, 1).length();
  3301. const scaleZ = 1 / _v1$5.setFromMatrixColumn(m, 2).length();
  3302. te[0] = me[0] * scaleX;
  3303. te[1] = me[1] * scaleX;
  3304. te[2] = me[2] * scaleX;
  3305. te[3] = 0;
  3306. te[4] = me[4] * scaleY;
  3307. te[5] = me[5] * scaleY;
  3308. te[6] = me[6] * scaleY;
  3309. te[7] = 0;
  3310. te[8] = me[8] * scaleZ;
  3311. te[9] = me[9] * scaleZ;
  3312. te[10] = me[10] * scaleZ;
  3313. te[11] = 0;
  3314. te[12] = 0;
  3315. te[13] = 0;
  3316. te[14] = 0;
  3317. te[15] = 1;
  3318. return this;
  3319. }
  3320. makeRotationFromEuler(euler) {
  3321. if (!(euler && euler.isEuler)) {
  3322. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  3323. }
  3324. const te = this.elements;
  3325. const x = euler.x,
  3326. y = euler.y,
  3327. z = euler.z;
  3328. const a = Math.cos(x),
  3329. b = Math.sin(x);
  3330. const c = Math.cos(y),
  3331. d = Math.sin(y);
  3332. const e = Math.cos(z),
  3333. f = Math.sin(z);
  3334. if (euler.order === 'XYZ') {
  3335. const ae = a * e,
  3336. af = a * f,
  3337. be = b * e,
  3338. bf = b * f;
  3339. te[0] = c * e;
  3340. te[4] = -c * f;
  3341. te[8] = d;
  3342. te[1] = af + be * d;
  3343. te[5] = ae - bf * d;
  3344. te[9] = -b * c;
  3345. te[2] = bf - ae * d;
  3346. te[6] = be + af * d;
  3347. te[10] = a * c;
  3348. } else if (euler.order === 'YXZ') {
  3349. const ce = c * e,
  3350. cf = c * f,
  3351. de = d * e,
  3352. df = d * f;
  3353. te[0] = ce + df * b;
  3354. te[4] = de * b - cf;
  3355. te[8] = a * d;
  3356. te[1] = a * f;
  3357. te[5] = a * e;
  3358. te[9] = -b;
  3359. te[2] = cf * b - de;
  3360. te[6] = df + ce * b;
  3361. te[10] = a * c;
  3362. } else if (euler.order === 'ZXY') {
  3363. const ce = c * e,
  3364. cf = c * f,
  3365. de = d * e,
  3366. df = d * f;
  3367. te[0] = ce - df * b;
  3368. te[4] = -a * f;
  3369. te[8] = de + cf * b;
  3370. te[1] = cf + de * b;
  3371. te[5] = a * e;
  3372. te[9] = df - ce * b;
  3373. te[2] = -a * d;
  3374. te[6] = b;
  3375. te[10] = a * c;
  3376. } else if (euler.order === 'ZYX') {
  3377. const ae = a * e,
  3378. af = a * f,
  3379. be = b * e,
  3380. bf = b * f;
  3381. te[0] = c * e;
  3382. te[4] = be * d - af;
  3383. te[8] = ae * d + bf;
  3384. te[1] = c * f;
  3385. te[5] = bf * d + ae;
  3386. te[9] = af * d - be;
  3387. te[2] = -d;
  3388. te[6] = b * c;
  3389. te[10] = a * c;
  3390. } else if (euler.order === 'YZX') {
  3391. const ac = a * c,
  3392. ad = a * d,
  3393. bc = b * c,
  3394. bd = b * d;
  3395. te[0] = c * e;
  3396. te[4] = bd - ac * f;
  3397. te[8] = bc * f + ad;
  3398. te[1] = f;
  3399. te[5] = a * e;
  3400. te[9] = -b * e;
  3401. te[2] = -d * e;
  3402. te[6] = ad * f + bc;
  3403. te[10] = ac - bd * f;
  3404. } else if (euler.order === 'XZY') {
  3405. const ac = a * c,
  3406. ad = a * d,
  3407. bc = b * c,
  3408. bd = b * d;
  3409. te[0] = c * e;
  3410. te[4] = -f;
  3411. te[8] = d * e;
  3412. te[1] = ac * f + bd;
  3413. te[5] = a * e;
  3414. te[9] = ad * f - bc;
  3415. te[2] = bc * f - ad;
  3416. te[6] = b * e;
  3417. te[10] = bd * f + ac;
  3418. } // bottom row
  3419. te[3] = 0;
  3420. te[7] = 0;
  3421. te[11] = 0; // last column
  3422. te[12] = 0;
  3423. te[13] = 0;
  3424. te[14] = 0;
  3425. te[15] = 1;
  3426. return this;
  3427. }
  3428. makeRotationFromQuaternion(q) {
  3429. return this.compose(_zero, q, _one);
  3430. }
  3431. lookAt(eye, target, up) {
  3432. const te = this.elements;
  3433. _z.subVectors(eye, target);
  3434. if (_z.lengthSq() === 0) {
  3435. // eye and target are in the same position
  3436. _z.z = 1;
  3437. }
  3438. _z.normalize();
  3439. _x.crossVectors(up, _z);
  3440. if (_x.lengthSq() === 0) {
  3441. // up and z are parallel
  3442. if (Math.abs(up.z) === 1) {
  3443. _z.x += 0.0001;
  3444. } else {
  3445. _z.z += 0.0001;
  3446. }
  3447. _z.normalize();
  3448. _x.crossVectors(up, _z);
  3449. }
  3450. _x.normalize();
  3451. _y.crossVectors(_z, _x);
  3452. te[0] = _x.x;
  3453. te[4] = _y.x;
  3454. te[8] = _z.x;
  3455. te[1] = _x.y;
  3456. te[5] = _y.y;
  3457. te[9] = _z.y;
  3458. te[2] = _x.z;
  3459. te[6] = _y.z;
  3460. te[10] = _z.z;
  3461. return this;
  3462. }
  3463. multiply(m, n) {
  3464. if (n !== undefined) {
  3465. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  3466. return this.multiplyMatrices(m, n);
  3467. }
  3468. return this.multiplyMatrices(this, m);
  3469. }
  3470. premultiply(m) {
  3471. return this.multiplyMatrices(m, this);
  3472. }
  3473. multiplyMatrices(a, b) {
  3474. const ae = a.elements;
  3475. const be = b.elements;
  3476. const te = this.elements;
  3477. const a11 = ae[0],
  3478. a12 = ae[4],
  3479. a13 = ae[8],
  3480. a14 = ae[12];
  3481. const a21 = ae[1],
  3482. a22 = ae[5],
  3483. a23 = ae[9],
  3484. a24 = ae[13];
  3485. const a31 = ae[2],
  3486. a32 = ae[6],
  3487. a33 = ae[10],
  3488. a34 = ae[14];
  3489. const a41 = ae[3],
  3490. a42 = ae[7],
  3491. a43 = ae[11],
  3492. a44 = ae[15];
  3493. const b11 = be[0],
  3494. b12 = be[4],
  3495. b13 = be[8],
  3496. b14 = be[12];
  3497. const b21 = be[1],
  3498. b22 = be[5],
  3499. b23 = be[9],
  3500. b24 = be[13];
  3501. const b31 = be[2],
  3502. b32 = be[6],
  3503. b33 = be[10],
  3504. b34 = be[14];
  3505. const b41 = be[3],
  3506. b42 = be[7],
  3507. b43 = be[11],
  3508. b44 = be[15];
  3509. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3510. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3511. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3512. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3513. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3514. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3515. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3516. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3517. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3518. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3519. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3520. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3521. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3522. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3523. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3524. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3525. return this;
  3526. }
  3527. multiplyScalar(s) {
  3528. const te = this.elements;
  3529. te[0] *= s;
  3530. te[4] *= s;
  3531. te[8] *= s;
  3532. te[12] *= s;
  3533. te[1] *= s;
  3534. te[5] *= s;
  3535. te[9] *= s;
  3536. te[13] *= s;
  3537. te[2] *= s;
  3538. te[6] *= s;
  3539. te[10] *= s;
  3540. te[14] *= s;
  3541. te[3] *= s;
  3542. te[7] *= s;
  3543. te[11] *= s;
  3544. te[15] *= s;
  3545. return this;
  3546. }
  3547. determinant() {
  3548. const te = this.elements;
  3549. const n11 = te[0],
  3550. n12 = te[4],
  3551. n13 = te[8],
  3552. n14 = te[12];
  3553. const n21 = te[1],
  3554. n22 = te[5],
  3555. n23 = te[9],
  3556. n24 = te[13];
  3557. const n31 = te[2],
  3558. n32 = te[6],
  3559. n33 = te[10],
  3560. n34 = te[14];
  3561. const n41 = te[3],
  3562. n42 = te[7],
  3563. n43 = te[11],
  3564. n44 = te[15]; //TODO: make this more efficient
  3565. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3566. 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);
  3567. }
  3568. transpose() {
  3569. const te = this.elements;
  3570. let tmp;
  3571. tmp = te[1];
  3572. te[1] = te[4];
  3573. te[4] = tmp;
  3574. tmp = te[2];
  3575. te[2] = te[8];
  3576. te[8] = tmp;
  3577. tmp = te[6];
  3578. te[6] = te[9];
  3579. te[9] = tmp;
  3580. tmp = te[3];
  3581. te[3] = te[12];
  3582. te[12] = tmp;
  3583. tmp = te[7];
  3584. te[7] = te[13];
  3585. te[13] = tmp;
  3586. tmp = te[11];
  3587. te[11] = te[14];
  3588. te[14] = tmp;
  3589. return this;
  3590. }
  3591. setPosition(x, y, z) {
  3592. const te = this.elements;
  3593. if (x.isVector3) {
  3594. te[12] = x.x;
  3595. te[13] = x.y;
  3596. te[14] = x.z;
  3597. } else {
  3598. te[12] = x;
  3599. te[13] = y;
  3600. te[14] = z;
  3601. }
  3602. return this;
  3603. }
  3604. invert() {
  3605. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3606. const te = this.elements,
  3607. n11 = te[0],
  3608. n21 = te[1],
  3609. n31 = te[2],
  3610. n41 = te[3],
  3611. n12 = te[4],
  3612. n22 = te[5],
  3613. n32 = te[6],
  3614. n42 = te[7],
  3615. n13 = te[8],
  3616. n23 = te[9],
  3617. n33 = te[10],
  3618. n43 = te[11],
  3619. n14 = te[12],
  3620. n24 = te[13],
  3621. n34 = te[14],
  3622. n44 = te[15],
  3623. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3624. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3625. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3626. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3627. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3628. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  3629. const detInv = 1 / det;
  3630. te[0] = t11 * detInv;
  3631. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  3632. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  3633. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  3634. te[4] = t12 * detInv;
  3635. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  3636. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  3637. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  3638. te[8] = t13 * detInv;
  3639. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  3640. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  3641. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  3642. te[12] = t14 * detInv;
  3643. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  3644. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  3645. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  3646. return this;
  3647. }
  3648. scale(v) {
  3649. const te = this.elements;
  3650. const x = v.x,
  3651. y = v.y,
  3652. z = v.z;
  3653. te[0] *= x;
  3654. te[4] *= y;
  3655. te[8] *= z;
  3656. te[1] *= x;
  3657. te[5] *= y;
  3658. te[9] *= z;
  3659. te[2] *= x;
  3660. te[6] *= y;
  3661. te[10] *= z;
  3662. te[3] *= x;
  3663. te[7] *= y;
  3664. te[11] *= z;
  3665. return this;
  3666. }
  3667. getMaxScaleOnAxis() {
  3668. const te = this.elements;
  3669. const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  3670. const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  3671. const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  3672. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  3673. }
  3674. makeTranslation(x, y, z) {
  3675. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  3676. return this;
  3677. }
  3678. makeRotationX(theta) {
  3679. const c = Math.cos(theta),
  3680. s = Math.sin(theta);
  3681. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  3682. return this;
  3683. }
  3684. makeRotationY(theta) {
  3685. const c = Math.cos(theta),
  3686. s = Math.sin(theta);
  3687. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  3688. return this;
  3689. }
  3690. makeRotationZ(theta) {
  3691. const c = Math.cos(theta),
  3692. s = Math.sin(theta);
  3693. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3694. return this;
  3695. }
  3696. makeRotationAxis(axis, angle) {
  3697. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3698. const c = Math.cos(angle);
  3699. const s = Math.sin(angle);
  3700. const t = 1 - c;
  3701. const x = axis.x,
  3702. y = axis.y,
  3703. z = axis.z;
  3704. const tx = t * x,
  3705. ty = t * y;
  3706. 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);
  3707. return this;
  3708. }
  3709. makeScale(x, y, z) {
  3710. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  3711. return this;
  3712. }
  3713. makeShear(xy, xz, yx, yz, zx, zy) {
  3714. this.set(1, yx, zx, 0, xy, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1);
  3715. return this;
  3716. }
  3717. compose(position, quaternion, scale) {
  3718. const te = this.elements;
  3719. const x = quaternion._x,
  3720. y = quaternion._y,
  3721. z = quaternion._z,
  3722. w = quaternion._w;
  3723. const x2 = x + x,
  3724. y2 = y + y,
  3725. z2 = z + z;
  3726. const xx = x * x2,
  3727. xy = x * y2,
  3728. xz = x * z2;
  3729. const yy = y * y2,
  3730. yz = y * z2,
  3731. zz = z * z2;
  3732. const wx = w * x2,
  3733. wy = w * y2,
  3734. wz = w * z2;
  3735. const sx = scale.x,
  3736. sy = scale.y,
  3737. sz = scale.z;
  3738. te[0] = (1 - (yy + zz)) * sx;
  3739. te[1] = (xy + wz) * sx;
  3740. te[2] = (xz - wy) * sx;
  3741. te[3] = 0;
  3742. te[4] = (xy - wz) * sy;
  3743. te[5] = (1 - (xx + zz)) * sy;
  3744. te[6] = (yz + wx) * sy;
  3745. te[7] = 0;
  3746. te[8] = (xz + wy) * sz;
  3747. te[9] = (yz - wx) * sz;
  3748. te[10] = (1 - (xx + yy)) * sz;
  3749. te[11] = 0;
  3750. te[12] = position.x;
  3751. te[13] = position.y;
  3752. te[14] = position.z;
  3753. te[15] = 1;
  3754. return this;
  3755. }
  3756. decompose(position, quaternion, scale) {
  3757. const te = this.elements;
  3758. let sx = _v1$5.set(te[0], te[1], te[2]).length();
  3759. const sy = _v1$5.set(te[4], te[5], te[6]).length();
  3760. const sz = _v1$5.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  3761. const det = this.determinant();
  3762. if (det < 0) sx = -sx;
  3763. position.x = te[12];
  3764. position.y = te[13];
  3765. position.z = te[14]; // scale the rotation part
  3766. _m1$2.copy(this);
  3767. const invSX = 1 / sx;
  3768. const invSY = 1 / sy;
  3769. const invSZ = 1 / sz;
  3770. _m1$2.elements[0] *= invSX;
  3771. _m1$2.elements[1] *= invSX;
  3772. _m1$2.elements[2] *= invSX;
  3773. _m1$2.elements[4] *= invSY;
  3774. _m1$2.elements[5] *= invSY;
  3775. _m1$2.elements[6] *= invSY;
  3776. _m1$2.elements[8] *= invSZ;
  3777. _m1$2.elements[9] *= invSZ;
  3778. _m1$2.elements[10] *= invSZ;
  3779. quaternion.setFromRotationMatrix(_m1$2);
  3780. scale.x = sx;
  3781. scale.y = sy;
  3782. scale.z = sz;
  3783. return this;
  3784. }
  3785. makePerspective(left, right, top, bottom, near, far) {
  3786. if (far === undefined) {
  3787. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  3788. }
  3789. const te = this.elements;
  3790. const x = 2 * near / (right - left);
  3791. const y = 2 * near / (top - bottom);
  3792. const a = (right + left) / (right - left);
  3793. const b = (top + bottom) / (top - bottom);
  3794. const c = -(far + near) / (far - near);
  3795. const d = -2 * far * near / (far - near);
  3796. te[0] = x;
  3797. te[4] = 0;
  3798. te[8] = a;
  3799. te[12] = 0;
  3800. te[1] = 0;
  3801. te[5] = y;
  3802. te[9] = b;
  3803. te[13] = 0;
  3804. te[2] = 0;
  3805. te[6] = 0;
  3806. te[10] = c;
  3807. te[14] = d;
  3808. te[3] = 0;
  3809. te[7] = 0;
  3810. te[11] = -1;
  3811. te[15] = 0;
  3812. return this;
  3813. }
  3814. makeOrthographic(left, right, top, bottom, near, far) {
  3815. const te = this.elements;
  3816. const w = 1.0 / (right - left);
  3817. const h = 1.0 / (top - bottom);
  3818. const p = 1.0 / (far - near);
  3819. const x = (right + left) * w;
  3820. const y = (top + bottom) * h;
  3821. const z = (far + near) * p;
  3822. te[0] = 2 * w;
  3823. te[4] = 0;
  3824. te[8] = 0;
  3825. te[12] = -x;
  3826. te[1] = 0;
  3827. te[5] = 2 * h;
  3828. te[9] = 0;
  3829. te[13] = -y;
  3830. te[2] = 0;
  3831. te[6] = 0;
  3832. te[10] = -2 * p;
  3833. te[14] = -z;
  3834. te[3] = 0;
  3835. te[7] = 0;
  3836. te[11] = 0;
  3837. te[15] = 1;
  3838. return this;
  3839. }
  3840. equals(matrix) {
  3841. const te = this.elements;
  3842. const me = matrix.elements;
  3843. for (let i = 0; i < 16; i++) {
  3844. if (te[i] !== me[i]) return false;
  3845. }
  3846. return true;
  3847. }
  3848. fromArray(array, offset = 0) {
  3849. for (let i = 0; i < 16; i++) {
  3850. this.elements[i] = array[i + offset];
  3851. }
  3852. return this;
  3853. }
  3854. toArray(array = [], offset = 0) {
  3855. const te = this.elements;
  3856. array[offset] = te[0];
  3857. array[offset + 1] = te[1];
  3858. array[offset + 2] = te[2];
  3859. array[offset + 3] = te[3];
  3860. array[offset + 4] = te[4];
  3861. array[offset + 5] = te[5];
  3862. array[offset + 6] = te[6];
  3863. array[offset + 7] = te[7];
  3864. array[offset + 8] = te[8];
  3865. array[offset + 9] = te[9];
  3866. array[offset + 10] = te[10];
  3867. array[offset + 11] = te[11];
  3868. array[offset + 12] = te[12];
  3869. array[offset + 13] = te[13];
  3870. array[offset + 14] = te[14];
  3871. array[offset + 15] = te[15];
  3872. return array;
  3873. }
  3874. }
  3875. Matrix4.prototype.isMatrix4 = true;
  3876. const _v1$5 = /*@__PURE__*/new Vector3();
  3877. const _m1$2 = /*@__PURE__*/new Matrix4();
  3878. const _zero = /*@__PURE__*/new Vector3(0, 0, 0);
  3879. const _one = /*@__PURE__*/new Vector3(1, 1, 1);
  3880. const _x = /*@__PURE__*/new Vector3();
  3881. const _y = /*@__PURE__*/new Vector3();
  3882. const _z = /*@__PURE__*/new Vector3();
  3883. const _matrix$1 = /*@__PURE__*/new Matrix4();
  3884. const _quaternion$3 = /*@__PURE__*/new Quaternion();
  3885. class Euler {
  3886. constructor(x = 0, y = 0, z = 0, order = Euler.DefaultOrder) {
  3887. this._x = x;
  3888. this._y = y;
  3889. this._z = z;
  3890. this._order = order;
  3891. }
  3892. get x() {
  3893. return this._x;
  3894. }
  3895. set x(value) {
  3896. this._x = value;
  3897. this._onChangeCallback();
  3898. }
  3899. get y() {
  3900. return this._y;
  3901. }
  3902. set y(value) {
  3903. this._y = value;
  3904. this._onChangeCallback();
  3905. }
  3906. get z() {
  3907. return this._z;
  3908. }
  3909. set z(value) {
  3910. this._z = value;
  3911. this._onChangeCallback();
  3912. }
  3913. get order() {
  3914. return this._order;
  3915. }
  3916. set order(value) {
  3917. this._order = value;
  3918. this._onChangeCallback();
  3919. }
  3920. set(x, y, z, order = this._order) {
  3921. this._x = x;
  3922. this._y = y;
  3923. this._z = z;
  3924. this._order = order;
  3925. this._onChangeCallback();
  3926. return this;
  3927. }
  3928. clone() {
  3929. return new this.constructor(this._x, this._y, this._z, this._order);
  3930. }
  3931. copy(euler) {
  3932. this._x = euler._x;
  3933. this._y = euler._y;
  3934. this._z = euler._z;
  3935. this._order = euler._order;
  3936. this._onChangeCallback();
  3937. return this;
  3938. }
  3939. setFromRotationMatrix(m, order = this._order, update = true) {
  3940. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3941. const te = m.elements;
  3942. const m11 = te[0],
  3943. m12 = te[4],
  3944. m13 = te[8];
  3945. const m21 = te[1],
  3946. m22 = te[5],
  3947. m23 = te[9];
  3948. const m31 = te[2],
  3949. m32 = te[6],
  3950. m33 = te[10];
  3951. switch (order) {
  3952. case 'XYZ':
  3953. this._y = Math.asin(clamp(m13, -1, 1));
  3954. if (Math.abs(m13) < 0.9999999) {
  3955. this._x = Math.atan2(-m23, m33);
  3956. this._z = Math.atan2(-m12, m11);
  3957. } else {
  3958. this._x = Math.atan2(m32, m22);
  3959. this._z = 0;
  3960. }
  3961. break;
  3962. case 'YXZ':
  3963. this._x = Math.asin(-clamp(m23, -1, 1));
  3964. if (Math.abs(m23) < 0.9999999) {
  3965. this._y = Math.atan2(m13, m33);
  3966. this._z = Math.atan2(m21, m22);
  3967. } else {
  3968. this._y = Math.atan2(-m31, m11);
  3969. this._z = 0;
  3970. }
  3971. break;
  3972. case 'ZXY':
  3973. this._x = Math.asin(clamp(m32, -1, 1));
  3974. if (Math.abs(m32) < 0.9999999) {
  3975. this._y = Math.atan2(-m31, m33);
  3976. this._z = Math.atan2(-m12, m22);
  3977. } else {
  3978. this._y = 0;
  3979. this._z = Math.atan2(m21, m11);
  3980. }
  3981. break;
  3982. case 'ZYX':
  3983. this._y = Math.asin(-clamp(m31, -1, 1));
  3984. if (Math.abs(m31) < 0.9999999) {
  3985. this._x = Math.atan2(m32, m33);
  3986. this._z = Math.atan2(m21, m11);
  3987. } else {
  3988. this._x = 0;
  3989. this._z = Math.atan2(-m12, m22);
  3990. }
  3991. break;
  3992. case 'YZX':
  3993. this._z = Math.asin(clamp(m21, -1, 1));
  3994. if (Math.abs(m21) < 0.9999999) {
  3995. this._x = Math.atan2(-m23, m22);
  3996. this._y = Math.atan2(-m31, m11);
  3997. } else {
  3998. this._x = 0;
  3999. this._y = Math.atan2(m13, m33);
  4000. }
  4001. break;
  4002. case 'XZY':
  4003. this._z = Math.asin(-clamp(m12, -1, 1));
  4004. if (Math.abs(m12) < 0.9999999) {
  4005. this._x = Math.atan2(m32, m22);
  4006. this._y = Math.atan2(m13, m11);
  4007. } else {
  4008. this._x = Math.atan2(-m23, m33);
  4009. this._y = 0;
  4010. }
  4011. break;
  4012. default:
  4013. console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
  4014. }
  4015. this._order = order;
  4016. if (update === true) this._onChangeCallback();
  4017. return this;
  4018. }
  4019. setFromQuaternion(q, order, update) {
  4020. _matrix$1.makeRotationFromQuaternion(q);
  4021. return this.setFromRotationMatrix(_matrix$1, order, update);
  4022. }
  4023. setFromVector3(v, order = this._order) {
  4024. return this.set(v.x, v.y, v.z, order);
  4025. }
  4026. reorder(newOrder) {
  4027. // WARNING: this discards revolution information -bhouston
  4028. _quaternion$3.setFromEuler(this);
  4029. return this.setFromQuaternion(_quaternion$3, newOrder);
  4030. }
  4031. equals(euler) {
  4032. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4033. }
  4034. fromArray(array) {
  4035. this._x = array[0];
  4036. this._y = array[1];
  4037. this._z = array[2];
  4038. if (array[3] !== undefined) this._order = array[3];
  4039. this._onChangeCallback();
  4040. return this;
  4041. }
  4042. toArray(array = [], offset = 0) {
  4043. array[offset] = this._x;
  4044. array[offset + 1] = this._y;
  4045. array[offset + 2] = this._z;
  4046. array[offset + 3] = this._order;
  4047. return array;
  4048. }
  4049. toVector3(optionalResult) {
  4050. if (optionalResult) {
  4051. return optionalResult.set(this._x, this._y, this._z);
  4052. } else {
  4053. return new Vector3(this._x, this._y, this._z);
  4054. }
  4055. }
  4056. _onChange(callback) {
  4057. this._onChangeCallback = callback;
  4058. return this;
  4059. }
  4060. _onChangeCallback() {}
  4061. }
  4062. Euler.prototype.isEuler = true;
  4063. Euler.DefaultOrder = 'XYZ';
  4064. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4065. class Layers {
  4066. constructor() {
  4067. this.mask = 1 | 0;
  4068. }
  4069. set(channel) {
  4070. this.mask = 1 << channel | 0;
  4071. }
  4072. enable(channel) {
  4073. this.mask |= 1 << channel | 0;
  4074. }
  4075. enableAll() {
  4076. this.mask = 0xffffffff | 0;
  4077. }
  4078. toggle(channel) {
  4079. this.mask ^= 1 << channel | 0;
  4080. }
  4081. disable(channel) {
  4082. this.mask &= ~(1 << channel | 0);
  4083. }
  4084. disableAll() {
  4085. this.mask = 0;
  4086. }
  4087. test(layers) {
  4088. return (this.mask & layers.mask) !== 0;
  4089. }
  4090. }
  4091. let _object3DId = 0;
  4092. const _v1$4 = /*@__PURE__*/new Vector3();
  4093. const _q1 = /*@__PURE__*/new Quaternion();
  4094. const _m1$1 = /*@__PURE__*/new Matrix4();
  4095. const _target = /*@__PURE__*/new Vector3();
  4096. const _position$3 = /*@__PURE__*/new Vector3();
  4097. const _scale$2 = /*@__PURE__*/new Vector3();
  4098. const _quaternion$2 = /*@__PURE__*/new Quaternion();
  4099. const _xAxis = /*@__PURE__*/new Vector3(1, 0, 0);
  4100. const _yAxis = /*@__PURE__*/new Vector3(0, 1, 0);
  4101. const _zAxis = /*@__PURE__*/new Vector3(0, 0, 1);
  4102. const _addedEvent = {
  4103. type: 'added'
  4104. };
  4105. const _removedEvent = {
  4106. type: 'removed'
  4107. };
  4108. class Object3D extends EventDispatcher {
  4109. constructor() {
  4110. super();
  4111. Object.defineProperty(this, 'id', {
  4112. value: _object3DId++
  4113. });
  4114. this.uuid = generateUUID();
  4115. this.name = '';
  4116. this.type = 'Object3D';
  4117. this.parent = null;
  4118. this.children = [];
  4119. this.up = Object3D.DefaultUp.clone();
  4120. const position = new Vector3();
  4121. const rotation = new Euler();
  4122. const quaternion = new Quaternion();
  4123. const scale = new Vector3(1, 1, 1);
  4124. function onRotationChange() {
  4125. quaternion.setFromEuler(rotation, false);
  4126. }
  4127. function onQuaternionChange() {
  4128. rotation.setFromQuaternion(quaternion, undefined, false);
  4129. }
  4130. rotation._onChange(onRotationChange);
  4131. quaternion._onChange(onQuaternionChange);
  4132. Object.defineProperties(this, {
  4133. position: {
  4134. configurable: true,
  4135. enumerable: true,
  4136. value: position
  4137. },
  4138. rotation: {
  4139. configurable: true,
  4140. enumerable: true,
  4141. value: rotation
  4142. },
  4143. quaternion: {
  4144. configurable: true,
  4145. enumerable: true,
  4146. value: quaternion
  4147. },
  4148. scale: {
  4149. configurable: true,
  4150. enumerable: true,
  4151. value: scale
  4152. },
  4153. modelViewMatrix: {
  4154. value: new Matrix4()
  4155. },
  4156. normalMatrix: {
  4157. value: new Matrix3()
  4158. }
  4159. });
  4160. this.matrix = new Matrix4();
  4161. this.matrixWorld = new Matrix4();
  4162. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4163. this.matrixWorldNeedsUpdate = false;
  4164. this.layers = new Layers();
  4165. this.visible = true;
  4166. this.castShadow = false;
  4167. this.receiveShadow = false;
  4168. this.frustumCulled = true;
  4169. this.renderOrder = 0;
  4170. this.animations = [];
  4171. this.userData = {};
  4172. }
  4173. onBeforeRender() {}
  4174. onAfterRender() {}
  4175. applyMatrix4(matrix) {
  4176. if (this.matrixAutoUpdate) this.updateMatrix();
  4177. this.matrix.premultiply(matrix);
  4178. this.matrix.decompose(this.position, this.quaternion, this.scale);
  4179. }
  4180. applyQuaternion(q) {
  4181. this.quaternion.premultiply(q);
  4182. return this;
  4183. }
  4184. setRotationFromAxisAngle(axis, angle) {
  4185. // assumes axis is normalized
  4186. this.quaternion.setFromAxisAngle(axis, angle);
  4187. }
  4188. setRotationFromEuler(euler) {
  4189. this.quaternion.setFromEuler(euler, true);
  4190. }
  4191. setRotationFromMatrix(m) {
  4192. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4193. this.quaternion.setFromRotationMatrix(m);
  4194. }
  4195. setRotationFromQuaternion(q) {
  4196. // assumes q is normalized
  4197. this.quaternion.copy(q);
  4198. }
  4199. rotateOnAxis(axis, angle) {
  4200. // rotate object on axis in object space
  4201. // axis is assumed to be normalized
  4202. _q1.setFromAxisAngle(axis, angle);
  4203. this.quaternion.multiply(_q1);
  4204. return this;
  4205. }
  4206. rotateOnWorldAxis(axis, angle) {
  4207. // rotate object on axis in world space
  4208. // axis is assumed to be normalized
  4209. // method assumes no rotated parent
  4210. _q1.setFromAxisAngle(axis, angle);
  4211. this.quaternion.premultiply(_q1);
  4212. return this;
  4213. }
  4214. rotateX(angle) {
  4215. return this.rotateOnAxis(_xAxis, angle);
  4216. }
  4217. rotateY(angle) {
  4218. return this.rotateOnAxis(_yAxis, angle);
  4219. }
  4220. rotateZ(angle) {
  4221. return this.rotateOnAxis(_zAxis, angle);
  4222. }
  4223. translateOnAxis(axis, distance) {
  4224. // translate object by distance along axis in object space
  4225. // axis is assumed to be normalized
  4226. _v1$4.copy(axis).applyQuaternion(this.quaternion);
  4227. this.position.add(_v1$4.multiplyScalar(distance));
  4228. return this;
  4229. }
  4230. translateX(distance) {
  4231. return this.translateOnAxis(_xAxis, distance);
  4232. }
  4233. translateY(distance) {
  4234. return this.translateOnAxis(_yAxis, distance);
  4235. }
  4236. translateZ(distance) {
  4237. return this.translateOnAxis(_zAxis, distance);
  4238. }
  4239. localToWorld(vector) {
  4240. return vector.applyMatrix4(this.matrixWorld);
  4241. }
  4242. worldToLocal(vector) {
  4243. return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
  4244. }
  4245. lookAt(x, y, z) {
  4246. // This method does not support objects having non-uniformly-scaled parent(s)
  4247. if (x.isVector3) {
  4248. _target.copy(x);
  4249. } else {
  4250. _target.set(x, y, z);
  4251. }
  4252. const parent = this.parent;
  4253. this.updateWorldMatrix(true, false);
  4254. _position$3.setFromMatrixPosition(this.matrixWorld);
  4255. if (this.isCamera || this.isLight) {
  4256. _m1$1.lookAt(_position$3, _target, this.up);
  4257. } else {
  4258. _m1$1.lookAt(_target, _position$3, this.up);
  4259. }
  4260. this.quaternion.setFromRotationMatrix(_m1$1);
  4261. if (parent) {
  4262. _m1$1.extractRotation(parent.matrixWorld);
  4263. _q1.setFromRotationMatrix(_m1$1);
  4264. this.quaternion.premultiply(_q1.invert());
  4265. }
  4266. }
  4267. add(object) {
  4268. if (arguments.length > 1) {
  4269. for (let i = 0; i < arguments.length; i++) {
  4270. this.add(arguments[i]);
  4271. }
  4272. return this;
  4273. }
  4274. if (object === this) {
  4275. console.error('THREE.Object3D.add: object can\'t be added as a child of itself.', object);
  4276. return this;
  4277. }
  4278. if (object && object.isObject3D) {
  4279. if (object.parent !== null) {
  4280. object.parent.remove(object);
  4281. }
  4282. object.parent = this;
  4283. this.children.push(object);
  4284. object.dispatchEvent(_addedEvent);
  4285. } else {
  4286. console.error('THREE.Object3D.add: object not an instance of THREE.Object3D.', object);
  4287. }
  4288. return this;
  4289. }
  4290. remove(object) {
  4291. if (arguments.length > 1) {
  4292. for (let i = 0; i < arguments.length; i++) {
  4293. this.remove(arguments[i]);
  4294. }
  4295. return this;
  4296. }
  4297. const index = this.children.indexOf(object);
  4298. if (index !== -1) {
  4299. object.parent = null;
  4300. this.children.splice(index, 1);
  4301. object.dispatchEvent(_removedEvent);
  4302. }
  4303. return this;
  4304. }
  4305. removeFromParent() {
  4306. const parent = this.parent;
  4307. if (parent !== null) {
  4308. parent.remove(this);
  4309. }
  4310. return this;
  4311. }
  4312. clear() {
  4313. for (let i = 0; i < this.children.length; i++) {
  4314. const object = this.children[i];
  4315. object.parent = null;
  4316. object.dispatchEvent(_removedEvent);
  4317. }
  4318. this.children.length = 0;
  4319. return this;
  4320. }
  4321. attach(object) {
  4322. // adds object as a child of this, while maintaining the object's world transform
  4323. this.updateWorldMatrix(true, false);
  4324. _m1$1.copy(this.matrixWorld).invert();
  4325. if (object.parent !== null) {
  4326. object.parent.updateWorldMatrix(true, false);
  4327. _m1$1.multiply(object.parent.matrixWorld);
  4328. }
  4329. object.applyMatrix4(_m1$1);
  4330. this.add(object);
  4331. object.updateWorldMatrix(false, true);
  4332. return this;
  4333. }
  4334. getObjectById(id) {
  4335. return this.getObjectByProperty('id', id);
  4336. }
  4337. getObjectByName(name) {
  4338. return this.getObjectByProperty('name', name);
  4339. }
  4340. getObjectByProperty(name, value) {
  4341. if (this[name] === value) return this;
  4342. for (let i = 0, l = this.children.length; i < l; i++) {
  4343. const child = this.children[i];
  4344. const object = child.getObjectByProperty(name, value);
  4345. if (object !== undefined) {
  4346. return object;
  4347. }
  4348. }
  4349. return undefined;
  4350. }
  4351. getWorldPosition(target) {
  4352. this.updateWorldMatrix(true, false);
  4353. return target.setFromMatrixPosition(this.matrixWorld);
  4354. }
  4355. getWorldQuaternion(target) {
  4356. this.updateWorldMatrix(true, false);
  4357. this.matrixWorld.decompose(_position$3, target, _scale$2);
  4358. return target;
  4359. }
  4360. getWorldScale(target) {
  4361. this.updateWorldMatrix(true, false);
  4362. this.matrixWorld.decompose(_position$3, _quaternion$2, target);
  4363. return target;
  4364. }
  4365. getWorldDirection(target) {
  4366. this.updateWorldMatrix(true, false);
  4367. const e = this.matrixWorld.elements;
  4368. return target.set(e[8], e[9], e[10]).normalize();
  4369. }
  4370. raycast() {}
  4371. traverse(callback) {
  4372. callback(this);
  4373. const children = this.children;
  4374. for (let i = 0, l = children.length; i < l; i++) {
  4375. children[i].traverse(callback);
  4376. }
  4377. }
  4378. traverseVisible(callback) {
  4379. if (this.visible === false) return;
  4380. callback(this);
  4381. const children = this.children;
  4382. for (let i = 0, l = children.length; i < l; i++) {
  4383. children[i].traverseVisible(callback);
  4384. }
  4385. }
  4386. traverseAncestors(callback) {
  4387. const parent = this.parent;
  4388. if (parent !== null) {
  4389. callback(parent);
  4390. parent.traverseAncestors(callback);
  4391. }
  4392. }
  4393. updateMatrix() {
  4394. this.matrix.compose(this.position, this.quaternion, this.scale);
  4395. this.matrixWorldNeedsUpdate = true;
  4396. }
  4397. updateMatrixWorld(force) {
  4398. if (this.matrixAutoUpdate) this.updateMatrix();
  4399. if (this.matrixWorldNeedsUpdate || force) {
  4400. if (this.parent === null) {
  4401. this.matrixWorld.copy(this.matrix);
  4402. } else {
  4403. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4404. }
  4405. this.matrixWorldNeedsUpdate = false;
  4406. force = true;
  4407. } // update children
  4408. const children = this.children;
  4409. for (let i = 0, l = children.length; i < l; i++) {
  4410. children[i].updateMatrixWorld(force);
  4411. }
  4412. }
  4413. updateWorldMatrix(updateParents, updateChildren) {
  4414. const parent = this.parent;
  4415. if (updateParents === true && parent !== null) {
  4416. parent.updateWorldMatrix(true, false);
  4417. }
  4418. if (this.matrixAutoUpdate) this.updateMatrix();
  4419. if (this.parent === null) {
  4420. this.matrixWorld.copy(this.matrix);
  4421. } else {
  4422. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4423. } // update children
  4424. if (updateChildren === true) {
  4425. const children = this.children;
  4426. for (let i = 0, l = children.length; i < l; i++) {
  4427. children[i].updateWorldMatrix(false, true);
  4428. }
  4429. }
  4430. }
  4431. toJSON(meta) {
  4432. // meta is a string when called from JSON.stringify
  4433. const isRootObject = meta === undefined || typeof meta === 'string';
  4434. const output = {}; // meta is a hash used to collect geometries, materials.
  4435. // not providing it implies that this is the root object
  4436. // being serialized.
  4437. if (isRootObject) {
  4438. // initialize meta obj
  4439. meta = {
  4440. geometries: {},
  4441. materials: {},
  4442. textures: {},
  4443. images: {},
  4444. shapes: {},
  4445. skeletons: {},
  4446. animations: {}
  4447. };
  4448. output.metadata = {
  4449. version: 4.5,
  4450. type: 'Object',
  4451. generator: 'Object3D.toJSON'
  4452. };
  4453. } // standard Object3D serialization
  4454. const object = {};
  4455. object.uuid = this.uuid;
  4456. object.type = this.type;
  4457. if (this.name !== '') object.name = this.name;
  4458. if (this.castShadow === true) object.castShadow = true;
  4459. if (this.receiveShadow === true) object.receiveShadow = true;
  4460. if (this.visible === false) object.visible = false;
  4461. if (this.frustumCulled === false) object.frustumCulled = false;
  4462. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  4463. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  4464. object.layers = this.layers.mask;
  4465. object.matrix = this.matrix.toArray();
  4466. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  4467. if (this.isInstancedMesh) {
  4468. object.type = 'InstancedMesh';
  4469. object.count = this.count;
  4470. object.instanceMatrix = this.instanceMatrix.toJSON();
  4471. if (this.instanceColor !== null) object.instanceColor = this.instanceColor.toJSON();
  4472. } //
  4473. function serialize(library, element) {
  4474. if (library[element.uuid] === undefined) {
  4475. library[element.uuid] = element.toJSON(meta);
  4476. }
  4477. return element.uuid;
  4478. }
  4479. if (this.isScene) {
  4480. if (this.background) {
  4481. if (this.background.isColor) {
  4482. object.background = this.background.toJSON();
  4483. } else if (this.background.isTexture) {
  4484. object.background = this.background.toJSON(meta).uuid;
  4485. }
  4486. }
  4487. if (this.environment && this.environment.isTexture) {
  4488. object.environment = this.environment.toJSON(meta).uuid;
  4489. }
  4490. } else if (this.isMesh || this.isLine || this.isPoints) {
  4491. object.geometry = serialize(meta.geometries, this.geometry);
  4492. const parameters = this.geometry.parameters;
  4493. if (parameters !== undefined && parameters.shapes !== undefined) {
  4494. const shapes = parameters.shapes;
  4495. if (Array.isArray(shapes)) {
  4496. for (let i = 0, l = shapes.length; i < l; i++) {
  4497. const shape = shapes[i];
  4498. serialize(meta.shapes, shape);
  4499. }
  4500. } else {
  4501. serialize(meta.shapes, shapes);
  4502. }
  4503. }
  4504. }
  4505. if (this.isSkinnedMesh) {
  4506. object.bindMode = this.bindMode;
  4507. object.bindMatrix = this.bindMatrix.toArray();
  4508. if (this.skeleton !== undefined) {
  4509. serialize(meta.skeletons, this.skeleton);
  4510. object.skeleton = this.skeleton.uuid;
  4511. }
  4512. }
  4513. if (this.material !== undefined) {
  4514. if (Array.isArray(this.material)) {
  4515. const uuids = [];
  4516. for (let i = 0, l = this.material.length; i < l; i++) {
  4517. uuids.push(serialize(meta.materials, this.material[i]));
  4518. }
  4519. object.material = uuids;
  4520. } else {
  4521. object.material = serialize(meta.materials, this.material);
  4522. }
  4523. } //
  4524. if (this.children.length > 0) {
  4525. object.children = [];
  4526. for (let i = 0; i < this.children.length; i++) {
  4527. object.children.push(this.children[i].toJSON(meta).object);
  4528. }
  4529. } //
  4530. if (this.animations.length > 0) {
  4531. object.animations = [];
  4532. for (let i = 0; i < this.animations.length; i++) {
  4533. const animation = this.animations[i];
  4534. object.animations.push(serialize(meta.animations, animation));
  4535. }
  4536. }
  4537. if (isRootObject) {
  4538. const geometries = extractFromCache(meta.geometries);
  4539. const materials = extractFromCache(meta.materials);
  4540. const textures = extractFromCache(meta.textures);
  4541. const images = extractFromCache(meta.images);
  4542. const shapes = extractFromCache(meta.shapes);
  4543. const skeletons = extractFromCache(meta.skeletons);
  4544. const animations = extractFromCache(meta.animations);
  4545. if (geometries.length > 0) output.geometries = geometries;
  4546. if (materials.length > 0) output.materials = materials;
  4547. if (textures.length > 0) output.textures = textures;
  4548. if (images.length > 0) output.images = images;
  4549. if (shapes.length > 0) output.shapes = shapes;
  4550. if (skeletons.length > 0) output.skeletons = skeletons;
  4551. if (animations.length > 0) output.animations = animations;
  4552. }
  4553. output.object = object;
  4554. return output; // extract data from the cache hash
  4555. // remove metadata on each item
  4556. // and return as array
  4557. function extractFromCache(cache) {
  4558. const values = [];
  4559. for (const key in cache) {
  4560. const data = cache[key];
  4561. delete data.metadata;
  4562. values.push(data);
  4563. }
  4564. return values;
  4565. }
  4566. }
  4567. clone(recursive) {
  4568. return new this.constructor().copy(this, recursive);
  4569. }
  4570. copy(source, recursive = true) {
  4571. this.name = source.name;
  4572. this.up.copy(source.up);
  4573. this.position.copy(source.position);
  4574. this.rotation.order = source.rotation.order;
  4575. this.quaternion.copy(source.quaternion);
  4576. this.scale.copy(source.scale);
  4577. this.matrix.copy(source.matrix);
  4578. this.matrixWorld.copy(source.matrixWorld);
  4579. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4580. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4581. this.layers.mask = source.layers.mask;
  4582. this.visible = source.visible;
  4583. this.castShadow = source.castShadow;
  4584. this.receiveShadow = source.receiveShadow;
  4585. this.frustumCulled = source.frustumCulled;
  4586. this.renderOrder = source.renderOrder;
  4587. this.userData = JSON.parse(JSON.stringify(source.userData));
  4588. if (recursive === true) {
  4589. for (let i = 0; i < source.children.length; i++) {
  4590. const child = source.children[i];
  4591. this.add(child.clone());
  4592. }
  4593. }
  4594. return this;
  4595. }
  4596. }
  4597. Object3D.DefaultUp = new Vector3(0, 1, 0);
  4598. Object3D.DefaultMatrixAutoUpdate = true;
  4599. Object3D.prototype.isObject3D = true;
  4600. const _v0$1 = /*@__PURE__*/new Vector3();
  4601. const _v1$3 = /*@__PURE__*/new Vector3();
  4602. const _v2$2 = /*@__PURE__*/new Vector3();
  4603. const _v3$1 = /*@__PURE__*/new Vector3();
  4604. const _vab = /*@__PURE__*/new Vector3();
  4605. const _vac = /*@__PURE__*/new Vector3();
  4606. const _vbc = /*@__PURE__*/new Vector3();
  4607. const _vap = /*@__PURE__*/new Vector3();
  4608. const _vbp = /*@__PURE__*/new Vector3();
  4609. const _vcp = /*@__PURE__*/new Vector3();
  4610. class Triangle {
  4611. constructor(a = new Vector3(), b = new Vector3(), c = new Vector3()) {
  4612. this.a = a;
  4613. this.b = b;
  4614. this.c = c;
  4615. }
  4616. static getNormal(a, b, c, target) {
  4617. target.subVectors(c, b);
  4618. _v0$1.subVectors(a, b);
  4619. target.cross(_v0$1);
  4620. const targetLengthSq = target.lengthSq();
  4621. if (targetLengthSq > 0) {
  4622. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  4623. }
  4624. return target.set(0, 0, 0);
  4625. } // static/instance method to calculate barycentric coordinates
  4626. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4627. static getBarycoord(point, a, b, c, target) {
  4628. _v0$1.subVectors(c, a);
  4629. _v1$3.subVectors(b, a);
  4630. _v2$2.subVectors(point, a);
  4631. const dot00 = _v0$1.dot(_v0$1);
  4632. const dot01 = _v0$1.dot(_v1$3);
  4633. const dot02 = _v0$1.dot(_v2$2);
  4634. const dot11 = _v1$3.dot(_v1$3);
  4635. const dot12 = _v1$3.dot(_v2$2);
  4636. const denom = dot00 * dot11 - dot01 * dot01; // collinear or singular triangle
  4637. if (denom === 0) {
  4638. // arbitrary location outside of triangle?
  4639. // not sure if this is the best idea, maybe should be returning undefined
  4640. return target.set(-2, -1, -1);
  4641. }
  4642. const invDenom = 1 / denom;
  4643. const u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  4644. const v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  4645. return target.set(1 - u - v, v, u);
  4646. }
  4647. static containsPoint(point, a, b, c) {
  4648. this.getBarycoord(point, a, b, c, _v3$1);
  4649. return _v3$1.x >= 0 && _v3$1.y >= 0 && _v3$1.x + _v3$1.y <= 1;
  4650. }
  4651. static getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
  4652. this.getBarycoord(point, p1, p2, p3, _v3$1);
  4653. target.set(0, 0);
  4654. target.addScaledVector(uv1, _v3$1.x);
  4655. target.addScaledVector(uv2, _v3$1.y);
  4656. target.addScaledVector(uv3, _v3$1.z);
  4657. return target;
  4658. }
  4659. static isFrontFacing(a, b, c, direction) {
  4660. _v0$1.subVectors(c, b);
  4661. _v1$3.subVectors(a, b); // strictly front facing
  4662. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  4663. }
  4664. set(a, b, c) {
  4665. this.a.copy(a);
  4666. this.b.copy(b);
  4667. this.c.copy(c);
  4668. return this;
  4669. }
  4670. setFromPointsAndIndices(points, i0, i1, i2) {
  4671. this.a.copy(points[i0]);
  4672. this.b.copy(points[i1]);
  4673. this.c.copy(points[i2]);
  4674. return this;
  4675. }
  4676. clone() {
  4677. return new this.constructor().copy(this);
  4678. }
  4679. copy(triangle) {
  4680. this.a.copy(triangle.a);
  4681. this.b.copy(triangle.b);
  4682. this.c.copy(triangle.c);
  4683. return this;
  4684. }
  4685. getArea() {
  4686. _v0$1.subVectors(this.c, this.b);
  4687. _v1$3.subVectors(this.a, this.b);
  4688. return _v0$1.cross(_v1$3).length() * 0.5;
  4689. }
  4690. getMidpoint(target) {
  4691. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  4692. }
  4693. getNormal(target) {
  4694. return Triangle.getNormal(this.a, this.b, this.c, target);
  4695. }
  4696. getPlane(target) {
  4697. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  4698. }
  4699. getBarycoord(point, target) {
  4700. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  4701. }
  4702. getUV(point, uv1, uv2, uv3, target) {
  4703. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  4704. }
  4705. containsPoint(point) {
  4706. return Triangle.containsPoint(point, this.a, this.b, this.c);
  4707. }
  4708. isFrontFacing(direction) {
  4709. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  4710. }
  4711. intersectsBox(box) {
  4712. return box.intersectsTriangle(this);
  4713. }
  4714. closestPointToPoint(p, target) {
  4715. const a = this.a,
  4716. b = this.b,
  4717. c = this.c;
  4718. let v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4719. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4720. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4721. // basically, we're distinguishing which of the voronoi regions of the triangle
  4722. // the point lies in with the minimum amount of redundant computation.
  4723. _vab.subVectors(b, a);
  4724. _vac.subVectors(c, a);
  4725. _vap.subVectors(p, a);
  4726. const d1 = _vab.dot(_vap);
  4727. const d2 = _vac.dot(_vap);
  4728. if (d1 <= 0 && d2 <= 0) {
  4729. // vertex region of A; barycentric coords (1, 0, 0)
  4730. return target.copy(a);
  4731. }
  4732. _vbp.subVectors(p, b);
  4733. const d3 = _vab.dot(_vbp);
  4734. const d4 = _vac.dot(_vbp);
  4735. if (d3 >= 0 && d4 <= d3) {
  4736. // vertex region of B; barycentric coords (0, 1, 0)
  4737. return target.copy(b);
  4738. }
  4739. const vc = d1 * d4 - d3 * d2;
  4740. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  4741. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  4742. return target.copy(a).addScaledVector(_vab, v);
  4743. }
  4744. _vcp.subVectors(p, c);
  4745. const d5 = _vab.dot(_vcp);
  4746. const d6 = _vac.dot(_vcp);
  4747. if (d6 >= 0 && d5 <= d6) {
  4748. // vertex region of C; barycentric coords (0, 0, 1)
  4749. return target.copy(c);
  4750. }
  4751. const vb = d5 * d2 - d1 * d6;
  4752. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  4753. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  4754. return target.copy(a).addScaledVector(_vac, w);
  4755. }
  4756. const va = d3 * d6 - d5 * d4;
  4757. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  4758. _vbc.subVectors(c, b);
  4759. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  4760. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  4761. } // face region
  4762. const denom = 1 / (va + vb + vc); // u = va * denom
  4763. v = vb * denom;
  4764. w = vc * denom;
  4765. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  4766. }
  4767. equals(triangle) {
  4768. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  4769. }
  4770. }
  4771. let materialId = 0;
  4772. class Material extends EventDispatcher {
  4773. constructor() {
  4774. super();
  4775. Object.defineProperty(this, 'id', {
  4776. value: materialId++
  4777. });
  4778. this.uuid = generateUUID();
  4779. this.name = '';
  4780. this.type = 'Material';
  4781. this.fog = true;
  4782. this.blending = NormalBlending;
  4783. this.side = FrontSide;
  4784. this.vertexColors = false;
  4785. this.opacity = 1;
  4786. this.transparent = false;
  4787. this.blendSrc = SrcAlphaFactor;
  4788. this.blendDst = OneMinusSrcAlphaFactor;
  4789. this.blendEquation = AddEquation;
  4790. this.blendSrcAlpha = null;
  4791. this.blendDstAlpha = null;
  4792. this.blendEquationAlpha = null;
  4793. this.depthFunc = LessEqualDepth;
  4794. this.depthTest = true;
  4795. this.depthWrite = true;
  4796. this.stencilWriteMask = 0xff;
  4797. this.stencilFunc = AlwaysStencilFunc;
  4798. this.stencilRef = 0;
  4799. this.stencilFuncMask = 0xff;
  4800. this.stencilFail = KeepStencilOp;
  4801. this.stencilZFail = KeepStencilOp;
  4802. this.stencilZPass = KeepStencilOp;
  4803. this.stencilWrite = false;
  4804. this.clippingPlanes = null;
  4805. this.clipIntersection = false;
  4806. this.clipShadows = false;
  4807. this.shadowSide = null;
  4808. this.colorWrite = true;
  4809. this.precision = null; // override the renderer's default precision for this material
  4810. this.polygonOffset = false;
  4811. this.polygonOffsetFactor = 0;
  4812. this.polygonOffsetUnits = 0;
  4813. this.dithering = false;
  4814. this.alphaTest = 0;
  4815. this.alphaToCoverage = false;
  4816. this.premultipliedAlpha = false;
  4817. this.visible = true;
  4818. this.toneMapped = true;
  4819. this.userData = {};
  4820. this.version = 0;
  4821. }
  4822. onBuild() {}
  4823. onBeforeCompile() {}
  4824. customProgramCacheKey() {
  4825. return this.onBeforeCompile.toString();
  4826. }
  4827. setValues(values) {
  4828. if (values === undefined) return;
  4829. for (const key in values) {
  4830. const newValue = values[key];
  4831. if (newValue === undefined) {
  4832. console.warn('THREE.Material: \'' + key + '\' parameter is undefined.');
  4833. continue;
  4834. } // for backward compatability if shading is set in the constructor
  4835. if (key === 'shading') {
  4836. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  4837. this.flatShading = newValue === FlatShading ? true : false;
  4838. continue;
  4839. }
  4840. const currentValue = this[key];
  4841. if (currentValue === undefined) {
  4842. console.warn('THREE.' + this.type + ': \'' + key + '\' is not a property of this material.');
  4843. continue;
  4844. }
  4845. if (currentValue && currentValue.isColor) {
  4846. currentValue.set(newValue);
  4847. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  4848. currentValue.copy(newValue);
  4849. } else {
  4850. this[key] = newValue;
  4851. }
  4852. }
  4853. }
  4854. toJSON(meta) {
  4855. const isRoot = meta === undefined || typeof meta === 'string';
  4856. if (isRoot) {
  4857. meta = {
  4858. textures: {},
  4859. images: {}
  4860. };
  4861. }
  4862. const data = {
  4863. metadata: {
  4864. version: 4.5,
  4865. type: 'Material',
  4866. generator: 'Material.toJSON'
  4867. }
  4868. }; // standard Material serialization
  4869. data.uuid = this.uuid;
  4870. data.type = this.type;
  4871. if (this.name !== '') data.name = this.name;
  4872. if (this.color && this.color.isColor) data.color = this.color.getHex();
  4873. if (this.roughness !== undefined) data.roughness = this.roughness;
  4874. if (this.metalness !== undefined) data.metalness = this.metalness;
  4875. if (this.sheen && this.sheen.isColor) data.sheen = this.sheen.getHex();
  4876. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  4877. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  4878. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  4879. if (this.specularIntensity !== undefined) data.specularIntensity = this.specularIntensity;
  4880. if (this.specularTint && this.specularTint.isColor) data.specularTint = this.specularTint.getHex();
  4881. if (this.shininess !== undefined) data.shininess = this.shininess;
  4882. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  4883. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  4884. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  4885. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  4886. }
  4887. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  4888. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  4889. }
  4890. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  4891. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  4892. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  4893. }
  4894. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  4895. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  4896. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  4897. if (this.lightMap && this.lightMap.isTexture) {
  4898. data.lightMap = this.lightMap.toJSON(meta).uuid;
  4899. data.lightMapIntensity = this.lightMapIntensity;
  4900. }
  4901. if (this.aoMap && this.aoMap.isTexture) {
  4902. data.aoMap = this.aoMap.toJSON(meta).uuid;
  4903. data.aoMapIntensity = this.aoMapIntensity;
  4904. }
  4905. if (this.bumpMap && this.bumpMap.isTexture) {
  4906. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  4907. data.bumpScale = this.bumpScale;
  4908. }
  4909. if (this.normalMap && this.normalMap.isTexture) {
  4910. data.normalMap = this.normalMap.toJSON(meta).uuid;
  4911. data.normalMapType = this.normalMapType;
  4912. data.normalScale = this.normalScale.toArray();
  4913. }
  4914. if (this.displacementMap && this.displacementMap.isTexture) {
  4915. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  4916. data.displacementScale = this.displacementScale;
  4917. data.displacementBias = this.displacementBias;
  4918. }
  4919. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  4920. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  4921. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  4922. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  4923. if (this.specularIntensityMap && this.specularIntensityMap.isTexture) data.specularIntensityMap = this.specularIntensityMap.toJSON(meta).uuid;
  4924. if (this.specularTintMap && this.specularTintMap.isTexture) data.specularTintMap = this.specularTintMap.toJSON(meta).uuid;
  4925. if (this.envMap && this.envMap.isTexture) {
  4926. data.envMap = this.envMap.toJSON(meta).uuid;
  4927. if (this.combine !== undefined) data.combine = this.combine;
  4928. }
  4929. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  4930. if (this.reflectivity !== undefined) data.reflectivity = this.reflectivity;
  4931. if (this.refractionRatio !== undefined) data.refractionRatio = this.refractionRatio;
  4932. if (this.gradientMap && this.gradientMap.isTexture) {
  4933. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  4934. }
  4935. if (this.transmission !== undefined) data.transmission = this.transmission;
  4936. if (this.transmissionMap && this.transmissionMap.isTexture) data.transmissionMap = this.transmissionMap.toJSON(meta).uuid;
  4937. if (this.thickness !== undefined) data.thickness = this.thickness;
  4938. if (this.thicknessMap && this.thicknessMap.isTexture) data.thicknessMap = this.thicknessMap.toJSON(meta).uuid;
  4939. if (this.attenuationDistance !== undefined) data.attenuationDistance = this.attenuationDistance;
  4940. if (this.attenuationTint !== undefined) data.attenuationTint = this.attenuationTint.getHex();
  4941. if (this.size !== undefined) data.size = this.size;
  4942. if (this.shadowSide !== null) data.shadowSide = this.shadowSide;
  4943. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  4944. if (this.blending !== NormalBlending) data.blending = this.blending;
  4945. if (this.side !== FrontSide) data.side = this.side;
  4946. if (this.vertexColors) data.vertexColors = true;
  4947. if (this.opacity < 1) data.opacity = this.opacity;
  4948. if (this.transparent === true) data.transparent = this.transparent;
  4949. data.depthFunc = this.depthFunc;
  4950. data.depthTest = this.depthTest;
  4951. data.depthWrite = this.depthWrite;
  4952. data.colorWrite = this.colorWrite;
  4953. data.stencilWrite = this.stencilWrite;
  4954. data.stencilWriteMask = this.stencilWriteMask;
  4955. data.stencilFunc = this.stencilFunc;
  4956. data.stencilRef = this.stencilRef;
  4957. data.stencilFuncMask = this.stencilFuncMask;
  4958. data.stencilFail = this.stencilFail;
  4959. data.stencilZFail = this.stencilZFail;
  4960. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  4961. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  4962. if (this.polygonOffset === true) data.polygonOffset = true;
  4963. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  4964. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  4965. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  4966. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  4967. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  4968. if (this.scale !== undefined) data.scale = this.scale;
  4969. if (this.dithering === true) data.dithering = true;
  4970. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  4971. if (this.alphaToCoverage === true) data.alphaToCoverage = this.alphaToCoverage;
  4972. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  4973. if (this.wireframe === true) data.wireframe = this.wireframe;
  4974. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  4975. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  4976. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  4977. if (this.flatShading === true) data.flatShading = this.flatShading;
  4978. if (this.visible === false) data.visible = false;
  4979. if (this.toneMapped === false) data.toneMapped = false;
  4980. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  4981. function extractFromCache(cache) {
  4982. const values = [];
  4983. for (const key in cache) {
  4984. const data = cache[key];
  4985. delete data.metadata;
  4986. values.push(data);
  4987. }
  4988. return values;
  4989. }
  4990. if (isRoot) {
  4991. const textures = extractFromCache(meta.textures);
  4992. const images = extractFromCache(meta.images);
  4993. if (textures.length > 0) data.textures = textures;
  4994. if (images.length > 0) data.images = images;
  4995. }
  4996. return data;
  4997. }
  4998. clone() {
  4999. return new this.constructor().copy(this);
  5000. }
  5001. copy(source) {
  5002. this.name = source.name;
  5003. this.fog = source.fog;
  5004. this.blending = source.blending;
  5005. this.side = source.side;
  5006. this.vertexColors = source.vertexColors;
  5007. this.opacity = source.opacity;
  5008. this.transparent = source.transparent;
  5009. this.blendSrc = source.blendSrc;
  5010. this.blendDst = source.blendDst;
  5011. this.blendEquation = source.blendEquation;
  5012. this.blendSrcAlpha = source.blendSrcAlpha;
  5013. this.blendDstAlpha = source.blendDstAlpha;
  5014. this.blendEquationAlpha = source.blendEquationAlpha;
  5015. this.depthFunc = source.depthFunc;
  5016. this.depthTest = source.depthTest;
  5017. this.depthWrite = source.depthWrite;
  5018. this.stencilWriteMask = source.stencilWriteMask;
  5019. this.stencilFunc = source.stencilFunc;
  5020. this.stencilRef = source.stencilRef;
  5021. this.stencilFuncMask = source.stencilFuncMask;
  5022. this.stencilFail = source.stencilFail;
  5023. this.stencilZFail = source.stencilZFail;
  5024. this.stencilZPass = source.stencilZPass;
  5025. this.stencilWrite = source.stencilWrite;
  5026. const srcPlanes = source.clippingPlanes;
  5027. let dstPlanes = null;
  5028. if (srcPlanes !== null) {
  5029. const n = srcPlanes.length;
  5030. dstPlanes = new Array(n);
  5031. for (let i = 0; i !== n; ++i) {
  5032. dstPlanes[i] = srcPlanes[i].clone();
  5033. }
  5034. }
  5035. this.clippingPlanes = dstPlanes;
  5036. this.clipIntersection = source.clipIntersection;
  5037. this.clipShadows = source.clipShadows;
  5038. this.shadowSide = source.shadowSide;
  5039. this.colorWrite = source.colorWrite;
  5040. this.precision = source.precision;
  5041. this.polygonOffset = source.polygonOffset;
  5042. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5043. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5044. this.dithering = source.dithering;
  5045. this.alphaTest = source.alphaTest;
  5046. this.alphaToCoverage = source.alphaToCoverage;
  5047. this.premultipliedAlpha = source.premultipliedAlpha;
  5048. this.visible = source.visible;
  5049. this.toneMapped = source.toneMapped;
  5050. this.userData = JSON.parse(JSON.stringify(source.userData));
  5051. return this;
  5052. }
  5053. dispose() {
  5054. this.dispatchEvent({
  5055. type: 'dispose'
  5056. });
  5057. }
  5058. set needsUpdate(value) {
  5059. if (value === true) this.version++;
  5060. }
  5061. }
  5062. Material.prototype.isMaterial = true;
  5063. const _colorKeywords = {
  5064. 'aliceblue': 0xF0F8FF,
  5065. 'antiquewhite': 0xFAEBD7,
  5066. 'aqua': 0x00FFFF,
  5067. 'aquamarine': 0x7FFFD4,
  5068. 'azure': 0xF0FFFF,
  5069. 'beige': 0xF5F5DC,
  5070. 'bisque': 0xFFE4C4,
  5071. 'black': 0x000000,
  5072. 'blanchedalmond': 0xFFEBCD,
  5073. 'blue': 0x0000FF,
  5074. 'blueviolet': 0x8A2BE2,
  5075. 'brown': 0xA52A2A,
  5076. 'burlywood': 0xDEB887,
  5077. 'cadetblue': 0x5F9EA0,
  5078. 'chartreuse': 0x7FFF00,
  5079. 'chocolate': 0xD2691E,
  5080. 'coral': 0xFF7F50,
  5081. 'cornflowerblue': 0x6495ED,
  5082. 'cornsilk': 0xFFF8DC,
  5083. 'crimson': 0xDC143C,
  5084. 'cyan': 0x00FFFF,
  5085. 'darkblue': 0x00008B,
  5086. 'darkcyan': 0x008B8B,
  5087. 'darkgoldenrod': 0xB8860B,
  5088. 'darkgray': 0xA9A9A9,
  5089. 'darkgreen': 0x006400,
  5090. 'darkgrey': 0xA9A9A9,
  5091. 'darkkhaki': 0xBDB76B,
  5092. 'darkmagenta': 0x8B008B,
  5093. 'darkolivegreen': 0x556B2F,
  5094. 'darkorange': 0xFF8C00,
  5095. 'darkorchid': 0x9932CC,
  5096. 'darkred': 0x8B0000,
  5097. 'darksalmon': 0xE9967A,
  5098. 'darkseagreen': 0x8FBC8F,
  5099. 'darkslateblue': 0x483D8B,
  5100. 'darkslategray': 0x2F4F4F,
  5101. 'darkslategrey': 0x2F4F4F,
  5102. 'darkturquoise': 0x00CED1,
  5103. 'darkviolet': 0x9400D3,
  5104. 'deeppink': 0xFF1493,
  5105. 'deepskyblue': 0x00BFFF,
  5106. 'dimgray': 0x696969,
  5107. 'dimgrey': 0x696969,
  5108. 'dodgerblue': 0x1E90FF,
  5109. 'firebrick': 0xB22222,
  5110. 'floralwhite': 0xFFFAF0,
  5111. 'forestgreen': 0x228B22,
  5112. 'fuchsia': 0xFF00FF,
  5113. 'gainsboro': 0xDCDCDC,
  5114. 'ghostwhite': 0xF8F8FF,
  5115. 'gold': 0xFFD700,
  5116. 'goldenrod': 0xDAA520,
  5117. 'gray': 0x808080,
  5118. 'green': 0x008000,
  5119. 'greenyellow': 0xADFF2F,
  5120. 'grey': 0x808080,
  5121. 'honeydew': 0xF0FFF0,
  5122. 'hotpink': 0xFF69B4,
  5123. 'indianred': 0xCD5C5C,
  5124. 'indigo': 0x4B0082,
  5125. 'ivory': 0xFFFFF0,
  5126. 'khaki': 0xF0E68C,
  5127. 'lavender': 0xE6E6FA,
  5128. 'lavenderblush': 0xFFF0F5,
  5129. 'lawngreen': 0x7CFC00,
  5130. 'lemonchiffon': 0xFFFACD,
  5131. 'lightblue': 0xADD8E6,
  5132. 'lightcoral': 0xF08080,
  5133. 'lightcyan': 0xE0FFFF,
  5134. 'lightgoldenrodyellow': 0xFAFAD2,
  5135. 'lightgray': 0xD3D3D3,
  5136. 'lightgreen': 0x90EE90,
  5137. 'lightgrey': 0xD3D3D3,
  5138. 'lightpink': 0xFFB6C1,
  5139. 'lightsalmon': 0xFFA07A,
  5140. 'lightseagreen': 0x20B2AA,
  5141. 'lightskyblue': 0x87CEFA,
  5142. 'lightslategray': 0x778899,
  5143. 'lightslategrey': 0x778899,
  5144. 'lightsteelblue': 0xB0C4DE,
  5145. 'lightyellow': 0xFFFFE0,
  5146. 'lime': 0x00FF00,
  5147. 'limegreen': 0x32CD32,
  5148. 'linen': 0xFAF0E6,
  5149. 'magenta': 0xFF00FF,
  5150. 'maroon': 0x800000,
  5151. 'mediumaquamarine': 0x66CDAA,
  5152. 'mediumblue': 0x0000CD,
  5153. 'mediumorchid': 0xBA55D3,
  5154. 'mediumpurple': 0x9370DB,
  5155. 'mediumseagreen': 0x3CB371,
  5156. 'mediumslateblue': 0x7B68EE,
  5157. 'mediumspringgreen': 0x00FA9A,
  5158. 'mediumturquoise': 0x48D1CC,
  5159. 'mediumvioletred': 0xC71585,
  5160. 'midnightblue': 0x191970,
  5161. 'mintcream': 0xF5FFFA,
  5162. 'mistyrose': 0xFFE4E1,
  5163. 'moccasin': 0xFFE4B5,
  5164. 'navajowhite': 0xFFDEAD,
  5165. 'navy': 0x000080,
  5166. 'oldlace': 0xFDF5E6,
  5167. 'olive': 0x808000,
  5168. 'olivedrab': 0x6B8E23,
  5169. 'orange': 0xFFA500,
  5170. 'orangered': 0xFF4500,
  5171. 'orchid': 0xDA70D6,
  5172. 'palegoldenrod': 0xEEE8AA,
  5173. 'palegreen': 0x98FB98,
  5174. 'paleturquoise': 0xAFEEEE,
  5175. 'palevioletred': 0xDB7093,
  5176. 'papayawhip': 0xFFEFD5,
  5177. 'peachpuff': 0xFFDAB9,
  5178. 'peru': 0xCD853F,
  5179. 'pink': 0xFFC0CB,
  5180. 'plum': 0xDDA0DD,
  5181. 'powderblue': 0xB0E0E6,
  5182. 'purple': 0x800080,
  5183. 'rebeccapurple': 0x663399,
  5184. 'red': 0xFF0000,
  5185. 'rosybrown': 0xBC8F8F,
  5186. 'royalblue': 0x4169E1,
  5187. 'saddlebrown': 0x8B4513,
  5188. 'salmon': 0xFA8072,
  5189. 'sandybrown': 0xF4A460,
  5190. 'seagreen': 0x2E8B57,
  5191. 'seashell': 0xFFF5EE,
  5192. 'sienna': 0xA0522D,
  5193. 'silver': 0xC0C0C0,
  5194. 'skyblue': 0x87CEEB,
  5195. 'slateblue': 0x6A5ACD,
  5196. 'slategray': 0x708090,
  5197. 'slategrey': 0x708090,
  5198. 'snow': 0xFFFAFA,
  5199. 'springgreen': 0x00FF7F,
  5200. 'steelblue': 0x4682B4,
  5201. 'tan': 0xD2B48C,
  5202. 'teal': 0x008080,
  5203. 'thistle': 0xD8BFD8,
  5204. 'tomato': 0xFF6347,
  5205. 'turquoise': 0x40E0D0,
  5206. 'violet': 0xEE82EE,
  5207. 'wheat': 0xF5DEB3,
  5208. 'white': 0xFFFFFF,
  5209. 'whitesmoke': 0xF5F5F5,
  5210. 'yellow': 0xFFFF00,
  5211. 'yellowgreen': 0x9ACD32
  5212. };
  5213. const _hslA = {
  5214. h: 0,
  5215. s: 0,
  5216. l: 0
  5217. };
  5218. const _hslB = {
  5219. h: 0,
  5220. s: 0,
  5221. l: 0
  5222. };
  5223. function hue2rgb(p, q, t) {
  5224. if (t < 0) t += 1;
  5225. if (t > 1) t -= 1;
  5226. if (t < 1 / 6) return p + (q - p) * 6 * t;
  5227. if (t < 1 / 2) return q;
  5228. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  5229. return p;
  5230. }
  5231. function SRGBToLinear(c) {
  5232. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  5233. }
  5234. function LinearToSRGB(c) {
  5235. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  5236. }
  5237. class Color {
  5238. constructor(r, g, b) {
  5239. if (g === undefined && b === undefined) {
  5240. // r is THREE.Color, hex or string
  5241. return this.set(r);
  5242. }
  5243. return this.setRGB(r, g, b);
  5244. }
  5245. set(value) {
  5246. if (value && value.isColor) {
  5247. this.copy(value);
  5248. } else if (typeof value === 'number') {
  5249. this.setHex(value);
  5250. } else if (typeof value === 'string') {
  5251. this.setStyle(value);
  5252. }
  5253. return this;
  5254. }
  5255. setScalar(scalar) {
  5256. this.r = scalar;
  5257. this.g = scalar;
  5258. this.b = scalar;
  5259. return this;
  5260. }
  5261. setHex(hex) {
  5262. hex = Math.floor(hex);
  5263. this.r = (hex >> 16 & 255) / 255;
  5264. this.g = (hex >> 8 & 255) / 255;
  5265. this.b = (hex & 255) / 255;
  5266. return this;
  5267. }
  5268. setRGB(r, g, b) {
  5269. this.r = r;
  5270. this.g = g;
  5271. this.b = b;
  5272. return this;
  5273. }
  5274. setHSL(h, s, l) {
  5275. // h,s,l ranges are in 0.0 - 1.0
  5276. h = euclideanModulo(h, 1);
  5277. s = clamp(s, 0, 1);
  5278. l = clamp(l, 0, 1);
  5279. if (s === 0) {
  5280. this.r = this.g = this.b = l;
  5281. } else {
  5282. const p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  5283. const q = 2 * l - p;
  5284. this.r = hue2rgb(q, p, h + 1 / 3);
  5285. this.g = hue2rgb(q, p, h);
  5286. this.b = hue2rgb(q, p, h - 1 / 3);
  5287. }
  5288. return this;
  5289. }
  5290. setStyle(style) {
  5291. function handleAlpha(string) {
  5292. if (string === undefined) return;
  5293. if (parseFloat(string) < 1) {
  5294. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  5295. }
  5296. }
  5297. let m;
  5298. if (m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style)) {
  5299. // rgb / hsl
  5300. let color;
  5301. const name = m[1];
  5302. const components = m[2];
  5303. switch (name) {
  5304. case 'rgb':
  5305. case 'rgba':
  5306. if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5307. // rgb(255,0,0) rgba(255,0,0,0.5)
  5308. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  5309. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  5310. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  5311. handleAlpha(color[4]);
  5312. return this;
  5313. }
  5314. if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5315. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5316. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  5317. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  5318. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  5319. handleAlpha(color[4]);
  5320. return this;
  5321. }
  5322. break;
  5323. case 'hsl':
  5324. case 'hsla':
  5325. if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5326. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5327. const h = parseFloat(color[1]) / 360;
  5328. const s = parseInt(color[2], 10) / 100;
  5329. const l = parseInt(color[3], 10) / 100;
  5330. handleAlpha(color[4]);
  5331. return this.setHSL(h, s, l);
  5332. }
  5333. break;
  5334. }
  5335. } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) {
  5336. // hex color
  5337. const hex = m[1];
  5338. const size = hex.length;
  5339. if (size === 3) {
  5340. // #ff0
  5341. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  5342. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  5343. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  5344. return this;
  5345. } else if (size === 6) {
  5346. // #ff0000
  5347. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  5348. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  5349. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  5350. return this;
  5351. }
  5352. }
  5353. if (style && style.length > 0) {
  5354. return this.setColorName(style);
  5355. }
  5356. return this;
  5357. }
  5358. setColorName(style) {
  5359. // color keywords
  5360. const hex = _colorKeywords[style.toLowerCase()];
  5361. if (hex !== undefined) {
  5362. // red
  5363. this.setHex(hex);
  5364. } else {
  5365. // unknown color
  5366. console.warn('THREE.Color: Unknown color ' + style);
  5367. }
  5368. return this;
  5369. }
  5370. clone() {
  5371. return new this.constructor(this.r, this.g, this.b);
  5372. }
  5373. copy(color) {
  5374. this.r = color.r;
  5375. this.g = color.g;
  5376. this.b = color.b;
  5377. return this;
  5378. }
  5379. copyGammaToLinear(color, gammaFactor = 2.0) {
  5380. this.r = Math.pow(color.r, gammaFactor);
  5381. this.g = Math.pow(color.g, gammaFactor);
  5382. this.b = Math.pow(color.b, gammaFactor);
  5383. return this;
  5384. }
  5385. copyLinearToGamma(color, gammaFactor = 2.0) {
  5386. const safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  5387. this.r = Math.pow(color.r, safeInverse);
  5388. this.g = Math.pow(color.g, safeInverse);
  5389. this.b = Math.pow(color.b, safeInverse);
  5390. return this;
  5391. }
  5392. convertGammaToLinear(gammaFactor) {
  5393. this.copyGammaToLinear(this, gammaFactor);
  5394. return this;
  5395. }
  5396. convertLinearToGamma(gammaFactor) {
  5397. this.copyLinearToGamma(this, gammaFactor);
  5398. return this;
  5399. }
  5400. copySRGBToLinear(color) {
  5401. this.r = SRGBToLinear(color.r);
  5402. this.g = SRGBToLinear(color.g);
  5403. this.b = SRGBToLinear(color.b);
  5404. return this;
  5405. }
  5406. copyLinearToSRGB(color) {
  5407. this.r = LinearToSRGB(color.r);
  5408. this.g = LinearToSRGB(color.g);
  5409. this.b = LinearToSRGB(color.b);
  5410. return this;
  5411. }
  5412. convertSRGBToLinear() {
  5413. this.copySRGBToLinear(this);
  5414. return this;
  5415. }
  5416. convertLinearToSRGB() {
  5417. this.copyLinearToSRGB(this);
  5418. return this;
  5419. }
  5420. getHex() {
  5421. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  5422. }
  5423. getHexString() {
  5424. return ('000000' + this.getHex().toString(16)).slice(-6);
  5425. }
  5426. getHSL(target) {
  5427. // h,s,l ranges are in 0.0 - 1.0
  5428. const r = this.r,
  5429. g = this.g,
  5430. b = this.b;
  5431. const max = Math.max(r, g, b);
  5432. const min = Math.min(r, g, b);
  5433. let hue, saturation;
  5434. const lightness = (min + max) / 2.0;
  5435. if (min === max) {
  5436. hue = 0;
  5437. saturation = 0;
  5438. } else {
  5439. const delta = max - min;
  5440. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  5441. switch (max) {
  5442. case r:
  5443. hue = (g - b) / delta + (g < b ? 6 : 0);
  5444. break;
  5445. case g:
  5446. hue = (b - r) / delta + 2;
  5447. break;
  5448. case b:
  5449. hue = (r - g) / delta + 4;
  5450. break;
  5451. }
  5452. hue /= 6;
  5453. }
  5454. target.h = hue;
  5455. target.s = saturation;
  5456. target.l = lightness;
  5457. return target;
  5458. }
  5459. getStyle() {
  5460. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  5461. }
  5462. offsetHSL(h, s, l) {
  5463. this.getHSL(_hslA);
  5464. _hslA.h += h;
  5465. _hslA.s += s;
  5466. _hslA.l += l;
  5467. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  5468. return this;
  5469. }
  5470. add(color) {
  5471. this.r += color.r;
  5472. this.g += color.g;
  5473. this.b += color.b;
  5474. return this;
  5475. }
  5476. addColors(color1, color2) {
  5477. this.r = color1.r + color2.r;
  5478. this.g = color1.g + color2.g;
  5479. this.b = color1.b + color2.b;
  5480. return this;
  5481. }
  5482. addScalar(s) {
  5483. this.r += s;
  5484. this.g += s;
  5485. this.b += s;
  5486. return this;
  5487. }
  5488. sub(color) {
  5489. this.r = Math.max(0, this.r - color.r);
  5490. this.g = Math.max(0, this.g - color.g);
  5491. this.b = Math.max(0, this.b - color.b);
  5492. return this;
  5493. }
  5494. multiply(color) {
  5495. this.r *= color.r;
  5496. this.g *= color.g;
  5497. this.b *= color.b;
  5498. return this;
  5499. }
  5500. multiplyScalar(s) {
  5501. this.r *= s;
  5502. this.g *= s;
  5503. this.b *= s;
  5504. return this;
  5505. }
  5506. lerp(color, alpha) {
  5507. this.r += (color.r - this.r) * alpha;
  5508. this.g += (color.g - this.g) * alpha;
  5509. this.b += (color.b - this.b) * alpha;
  5510. return this;
  5511. }
  5512. lerpColors(color1, color2, alpha) {
  5513. this.r = color1.r + (color2.r - color1.r) * alpha;
  5514. this.g = color1.g + (color2.g - color1.g) * alpha;
  5515. this.b = color1.b + (color2.b - color1.b) * alpha;
  5516. return this;
  5517. }
  5518. lerpHSL(color, alpha) {
  5519. this.getHSL(_hslA);
  5520. color.getHSL(_hslB);
  5521. const h = lerp(_hslA.h, _hslB.h, alpha);
  5522. const s = lerp(_hslA.s, _hslB.s, alpha);
  5523. const l = lerp(_hslA.l, _hslB.l, alpha);
  5524. this.setHSL(h, s, l);
  5525. return this;
  5526. }
  5527. equals(c) {
  5528. return c.r === this.r && c.g === this.g && c.b === this.b;
  5529. }
  5530. fromArray(array, offset = 0) {
  5531. this.r = array[offset];
  5532. this.g = array[offset + 1];
  5533. this.b = array[offset + 2];
  5534. return this;
  5535. }
  5536. toArray(array = [], offset = 0) {
  5537. array[offset] = this.r;
  5538. array[offset + 1] = this.g;
  5539. array[offset + 2] = this.b;
  5540. return array;
  5541. }
  5542. fromBufferAttribute(attribute, index) {
  5543. this.r = attribute.getX(index);
  5544. this.g = attribute.getY(index);
  5545. this.b = attribute.getZ(index);
  5546. if (attribute.normalized === true) {
  5547. // assuming Uint8Array
  5548. this.r /= 255;
  5549. this.g /= 255;
  5550. this.b /= 255;
  5551. }
  5552. return this;
  5553. }
  5554. toJSON() {
  5555. return this.getHex();
  5556. }
  5557. }
  5558. Color.NAMES = _colorKeywords;
  5559. Color.prototype.isColor = true;
  5560. Color.prototype.r = 1;
  5561. Color.prototype.g = 1;
  5562. Color.prototype.b = 1;
  5563. /**
  5564. * parameters = {
  5565. * color: <hex>,
  5566. * opacity: <float>,
  5567. * map: new THREE.Texture( <Image> ),
  5568. *
  5569. * lightMap: new THREE.Texture( <Image> ),
  5570. * lightMapIntensity: <float>
  5571. *
  5572. * aoMap: new THREE.Texture( <Image> ),
  5573. * aoMapIntensity: <float>
  5574. *
  5575. * specularMap: new THREE.Texture( <Image> ),
  5576. *
  5577. * alphaMap: new THREE.Texture( <Image> ),
  5578. *
  5579. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  5580. * combine: THREE.Multiply,
  5581. * reflectivity: <float>,
  5582. * refractionRatio: <float>,
  5583. *
  5584. * depthTest: <bool>,
  5585. * depthWrite: <bool>,
  5586. *
  5587. * wireframe: <boolean>,
  5588. * wireframeLinewidth: <float>,
  5589. * }
  5590. */
  5591. class MeshBasicMaterial extends Material {
  5592. constructor(parameters) {
  5593. super();
  5594. this.type = 'MeshBasicMaterial';
  5595. this.color = new Color(0xffffff); // emissive
  5596. this.map = null;
  5597. this.lightMap = null;
  5598. this.lightMapIntensity = 1.0;
  5599. this.aoMap = null;
  5600. this.aoMapIntensity = 1.0;
  5601. this.specularMap = null;
  5602. this.alphaMap = null;
  5603. this.envMap = null;
  5604. this.combine = MultiplyOperation;
  5605. this.reflectivity = 1;
  5606. this.refractionRatio = 0.98;
  5607. this.wireframe = false;
  5608. this.wireframeLinewidth = 1;
  5609. this.wireframeLinecap = 'round';
  5610. this.wireframeLinejoin = 'round';
  5611. this.setValues(parameters);
  5612. }
  5613. copy(source) {
  5614. super.copy(source);
  5615. this.color.copy(source.color);
  5616. this.map = source.map;
  5617. this.lightMap = source.lightMap;
  5618. this.lightMapIntensity = source.lightMapIntensity;
  5619. this.aoMap = source.aoMap;
  5620. this.aoMapIntensity = source.aoMapIntensity;
  5621. this.specularMap = source.specularMap;
  5622. this.alphaMap = source.alphaMap;
  5623. this.envMap = source.envMap;
  5624. this.combine = source.combine;
  5625. this.reflectivity = source.reflectivity;
  5626. this.refractionRatio = source.refractionRatio;
  5627. this.wireframe = source.wireframe;
  5628. this.wireframeLinewidth = source.wireframeLinewidth;
  5629. this.wireframeLinecap = source.wireframeLinecap;
  5630. this.wireframeLinejoin = source.wireframeLinejoin;
  5631. return this;
  5632. }
  5633. }
  5634. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  5635. const _vector$9 = /*@__PURE__*/new Vector3();
  5636. const _vector2$1 = /*@__PURE__*/new Vector2();
  5637. class BufferAttribute {
  5638. constructor(array, itemSize, normalized) {
  5639. if (Array.isArray(array)) {
  5640. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  5641. }
  5642. this.name = '';
  5643. this.array = array;
  5644. this.itemSize = itemSize;
  5645. this.count = array !== undefined ? array.length / itemSize : 0;
  5646. this.normalized = normalized === true;
  5647. this.usage = StaticDrawUsage;
  5648. this.updateRange = {
  5649. offset: 0,
  5650. count: -1
  5651. };
  5652. this.version = 0;
  5653. }
  5654. onUploadCallback() {}
  5655. set needsUpdate(value) {
  5656. if (value === true) this.version++;
  5657. }
  5658. setUsage(value) {
  5659. this.usage = value;
  5660. return this;
  5661. }
  5662. copy(source) {
  5663. this.name = source.name;
  5664. this.array = new source.array.constructor(source.array);
  5665. this.itemSize = source.itemSize;
  5666. this.count = source.count;
  5667. this.normalized = source.normalized;
  5668. this.usage = source.usage;
  5669. return this;
  5670. }
  5671. copyAt(index1, attribute, index2) {
  5672. index1 *= this.itemSize;
  5673. index2 *= attribute.itemSize;
  5674. for (let i = 0, l = this.itemSize; i < l; i++) {
  5675. this.array[index1 + i] = attribute.array[index2 + i];
  5676. }
  5677. return this;
  5678. }
  5679. copyArray(array) {
  5680. this.array.set(array);
  5681. return this;
  5682. }
  5683. copyColorsArray(colors) {
  5684. const array = this.array;
  5685. let offset = 0;
  5686. for (let i = 0, l = colors.length; i < l; i++) {
  5687. let color = colors[i];
  5688. if (color === undefined) {
  5689. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  5690. color = new Color();
  5691. }
  5692. array[offset++] = color.r;
  5693. array[offset++] = color.g;
  5694. array[offset++] = color.b;
  5695. }
  5696. return this;
  5697. }
  5698. copyVector2sArray(vectors) {
  5699. const array = this.array;
  5700. let offset = 0;
  5701. for (let i = 0, l = vectors.length; i < l; i++) {
  5702. let vector = vectors[i];
  5703. if (vector === undefined) {
  5704. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  5705. vector = new Vector2();
  5706. }
  5707. array[offset++] = vector.x;
  5708. array[offset++] = vector.y;
  5709. }
  5710. return this;
  5711. }
  5712. copyVector3sArray(vectors) {
  5713. const array = this.array;
  5714. let offset = 0;
  5715. for (let i = 0, l = vectors.length; i < l; i++) {
  5716. let vector = vectors[i];
  5717. if (vector === undefined) {
  5718. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  5719. vector = new Vector3();
  5720. }
  5721. array[offset++] = vector.x;
  5722. array[offset++] = vector.y;
  5723. array[offset++] = vector.z;
  5724. }
  5725. return this;
  5726. }
  5727. copyVector4sArray(vectors) {
  5728. const array = this.array;
  5729. let offset = 0;
  5730. for (let i = 0, l = vectors.length; i < l; i++) {
  5731. let vector = vectors[i];
  5732. if (vector === undefined) {
  5733. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  5734. vector = new Vector4();
  5735. }
  5736. array[offset++] = vector.x;
  5737. array[offset++] = vector.y;
  5738. array[offset++] = vector.z;
  5739. array[offset++] = vector.w;
  5740. }
  5741. return this;
  5742. }
  5743. applyMatrix3(m) {
  5744. if (this.itemSize === 2) {
  5745. for (let i = 0, l = this.count; i < l; i++) {
  5746. _vector2$1.fromBufferAttribute(this, i);
  5747. _vector2$1.applyMatrix3(m);
  5748. this.setXY(i, _vector2$1.x, _vector2$1.y);
  5749. }
  5750. } else if (this.itemSize === 3) {
  5751. for (let i = 0, l = this.count; i < l; i++) {
  5752. _vector$9.fromBufferAttribute(this, i);
  5753. _vector$9.applyMatrix3(m);
  5754. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5755. }
  5756. }
  5757. return this;
  5758. }
  5759. applyMatrix4(m) {
  5760. for (let i = 0, l = this.count; i < l; i++) {
  5761. _vector$9.x = this.getX(i);
  5762. _vector$9.y = this.getY(i);
  5763. _vector$9.z = this.getZ(i);
  5764. _vector$9.applyMatrix4(m);
  5765. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5766. }
  5767. return this;
  5768. }
  5769. applyNormalMatrix(m) {
  5770. for (let i = 0, l = this.count; i < l; i++) {
  5771. _vector$9.x = this.getX(i);
  5772. _vector$9.y = this.getY(i);
  5773. _vector$9.z = this.getZ(i);
  5774. _vector$9.applyNormalMatrix(m);
  5775. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5776. }
  5777. return this;
  5778. }
  5779. transformDirection(m) {
  5780. for (let i = 0, l = this.count; i < l; i++) {
  5781. _vector$9.x = this.getX(i);
  5782. _vector$9.y = this.getY(i);
  5783. _vector$9.z = this.getZ(i);
  5784. _vector$9.transformDirection(m);
  5785. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5786. }
  5787. return this;
  5788. }
  5789. set(value, offset = 0) {
  5790. this.array.set(value, offset);
  5791. return this;
  5792. }
  5793. getX(index) {
  5794. return this.array[index * this.itemSize];
  5795. }
  5796. setX(index, x) {
  5797. this.array[index * this.itemSize] = x;
  5798. return this;
  5799. }
  5800. getY(index) {
  5801. return this.array[index * this.itemSize + 1];
  5802. }
  5803. setY(index, y) {
  5804. this.array[index * this.itemSize + 1] = y;
  5805. return this;
  5806. }
  5807. getZ(index) {
  5808. return this.array[index * this.itemSize + 2];
  5809. }
  5810. setZ(index, z) {
  5811. this.array[index * this.itemSize + 2] = z;
  5812. return this;
  5813. }
  5814. getW(index) {
  5815. return this.array[index * this.itemSize + 3];
  5816. }
  5817. setW(index, w) {
  5818. this.array[index * this.itemSize + 3] = w;
  5819. return this;
  5820. }
  5821. setXY(index, x, y) {
  5822. index *= this.itemSize;
  5823. this.array[index + 0] = x;
  5824. this.array[index + 1] = y;
  5825. return this;
  5826. }
  5827. setXYZ(index, x, y, z) {
  5828. index *= this.itemSize;
  5829. this.array[index + 0] = x;
  5830. this.array[index + 1] = y;
  5831. this.array[index + 2] = z;
  5832. return this;
  5833. }
  5834. setXYZW(index, x, y, z, w) {
  5835. index *= this.itemSize;
  5836. this.array[index + 0] = x;
  5837. this.array[index + 1] = y;
  5838. this.array[index + 2] = z;
  5839. this.array[index + 3] = w;
  5840. return this;
  5841. }
  5842. onUpload(callback) {
  5843. this.onUploadCallback = callback;
  5844. return this;
  5845. }
  5846. clone() {
  5847. return new this.constructor(this.array, this.itemSize).copy(this);
  5848. }
  5849. toJSON() {
  5850. const data = {
  5851. itemSize: this.itemSize,
  5852. type: this.array.constructor.name,
  5853. array: Array.prototype.slice.call(this.array),
  5854. normalized: this.normalized
  5855. };
  5856. if (this.name !== '') data.name = this.name;
  5857. if (this.usage !== StaticDrawUsage) data.usage = this.usage;
  5858. if (this.updateRange.offset !== 0 || this.updateRange.count !== -1) data.updateRange = this.updateRange;
  5859. return data;
  5860. }
  5861. }
  5862. BufferAttribute.prototype.isBufferAttribute = true; //
  5863. class Int8BufferAttribute extends BufferAttribute {
  5864. constructor(array, itemSize, normalized) {
  5865. super(new Int8Array(array), itemSize, normalized);
  5866. }
  5867. }
  5868. class Uint8BufferAttribute extends BufferAttribute {
  5869. constructor(array, itemSize, normalized) {
  5870. super(new Uint8Array(array), itemSize, normalized);
  5871. }
  5872. }
  5873. class Uint8ClampedBufferAttribute extends BufferAttribute {
  5874. constructor(array, itemSize, normalized) {
  5875. super(new Uint8ClampedArray(array), itemSize, normalized);
  5876. }
  5877. }
  5878. class Int16BufferAttribute extends BufferAttribute {
  5879. constructor(array, itemSize, normalized) {
  5880. super(new Int16Array(array), itemSize, normalized);
  5881. }
  5882. }
  5883. class Uint16BufferAttribute extends BufferAttribute {
  5884. constructor(array, itemSize, normalized) {
  5885. super(new Uint16Array(array), itemSize, normalized);
  5886. }
  5887. }
  5888. class Int32BufferAttribute extends BufferAttribute {
  5889. constructor(array, itemSize, normalized) {
  5890. super(new Int32Array(array), itemSize, normalized);
  5891. }
  5892. }
  5893. class Uint32BufferAttribute extends BufferAttribute {
  5894. constructor(array, itemSize, normalized) {
  5895. super(new Uint32Array(array), itemSize, normalized);
  5896. }
  5897. }
  5898. class Float16BufferAttribute extends BufferAttribute {
  5899. constructor(array, itemSize, normalized) {
  5900. super(new Uint16Array(array), itemSize, normalized);
  5901. }
  5902. }
  5903. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  5904. class Float32BufferAttribute extends BufferAttribute {
  5905. constructor(array, itemSize, normalized) {
  5906. super(new Float32Array(array), itemSize, normalized);
  5907. }
  5908. }
  5909. class Float64BufferAttribute extends BufferAttribute {
  5910. constructor(array, itemSize, normalized) {
  5911. super(new Float64Array(array), itemSize, normalized);
  5912. }
  5913. } //
  5914. function arrayMax(array) {
  5915. if (array.length === 0) return -Infinity;
  5916. let max = array[0];
  5917. for (let i = 1, l = array.length; i < l; ++i) {
  5918. if (array[i] > max) max = array[i];
  5919. }
  5920. return max;
  5921. }
  5922. const TYPED_ARRAYS = {
  5923. Int8Array: Int8Array,
  5924. Uint8Array: Uint8Array,
  5925. Uint8ClampedArray: Uint8ClampedArray,
  5926. Int16Array: Int16Array,
  5927. Uint16Array: Uint16Array,
  5928. Int32Array: Int32Array,
  5929. Uint32Array: Uint32Array,
  5930. Float32Array: Float32Array,
  5931. Float64Array: Float64Array
  5932. };
  5933. function getTypedArray(type, buffer) {
  5934. return new TYPED_ARRAYS[type](buffer);
  5935. }
  5936. let _id = 0;
  5937. const _m1 = /*@__PURE__*/new Matrix4();
  5938. const _obj = /*@__PURE__*/new Object3D();
  5939. const _offset = /*@__PURE__*/new Vector3();
  5940. const _box$1 = /*@__PURE__*/new Box3();
  5941. const _boxMorphTargets = /*@__PURE__*/new Box3();
  5942. const _vector$8 = /*@__PURE__*/new Vector3();
  5943. class BufferGeometry extends EventDispatcher {
  5944. constructor() {
  5945. super();
  5946. Object.defineProperty(this, 'id', {
  5947. value: _id++
  5948. });
  5949. this.uuid = generateUUID();
  5950. this.name = '';
  5951. this.type = 'BufferGeometry';
  5952. this.index = null;
  5953. this.attributes = {};
  5954. this.morphAttributes = {};
  5955. this.morphTargetsRelative = false;
  5956. this.groups = [];
  5957. this.boundingBox = null;
  5958. this.boundingSphere = null;
  5959. this.drawRange = {
  5960. start: 0,
  5961. count: Infinity
  5962. };
  5963. this.userData = {};
  5964. }
  5965. getIndex() {
  5966. return this.index;
  5967. }
  5968. setIndex(index) {
  5969. if (Array.isArray(index)) {
  5970. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  5971. } else {
  5972. this.index = index;
  5973. }
  5974. return this;
  5975. }
  5976. getAttribute(name) {
  5977. return this.attributes[name];
  5978. }
  5979. setAttribute(name, attribute) {
  5980. this.attributes[name] = attribute;
  5981. return this;
  5982. }
  5983. deleteAttribute(name) {
  5984. delete this.attributes[name];
  5985. return this;
  5986. }
  5987. hasAttribute(name) {
  5988. return this.attributes[name] !== undefined;
  5989. }
  5990. addGroup(start, count, materialIndex = 0) {
  5991. this.groups.push({
  5992. start: start,
  5993. count: count,
  5994. materialIndex: materialIndex
  5995. });
  5996. }
  5997. clearGroups() {
  5998. this.groups = [];
  5999. }
  6000. setDrawRange(start, count) {
  6001. this.drawRange.start = start;
  6002. this.drawRange.count = count;
  6003. }
  6004. applyMatrix4(matrix) {
  6005. const position = this.attributes.position;
  6006. if (position !== undefined) {
  6007. position.applyMatrix4(matrix);
  6008. position.needsUpdate = true;
  6009. }
  6010. const normal = this.attributes.normal;
  6011. if (normal !== undefined) {
  6012. const normalMatrix = new Matrix3().getNormalMatrix(matrix);
  6013. normal.applyNormalMatrix(normalMatrix);
  6014. normal.needsUpdate = true;
  6015. }
  6016. const tangent = this.attributes.tangent;
  6017. if (tangent !== undefined) {
  6018. tangent.transformDirection(matrix);
  6019. tangent.needsUpdate = true;
  6020. }
  6021. if (this.boundingBox !== null) {
  6022. this.computeBoundingBox();
  6023. }
  6024. if (this.boundingSphere !== null) {
  6025. this.computeBoundingSphere();
  6026. }
  6027. return this;
  6028. }
  6029. applyQuaternion(q) {
  6030. _m1.makeRotationFromQuaternion(q);
  6031. this.applyMatrix4(_m1);
  6032. return this;
  6033. }
  6034. rotateX(angle) {
  6035. // rotate geometry around world x-axis
  6036. _m1.makeRotationX(angle);
  6037. this.applyMatrix4(_m1);
  6038. return this;
  6039. }
  6040. rotateY(angle) {
  6041. // rotate geometry around world y-axis
  6042. _m1.makeRotationY(angle);
  6043. this.applyMatrix4(_m1);
  6044. return this;
  6045. }
  6046. rotateZ(angle) {
  6047. // rotate geometry around world z-axis
  6048. _m1.makeRotationZ(angle);
  6049. this.applyMatrix4(_m1);
  6050. return this;
  6051. }
  6052. translate(x, y, z) {
  6053. // translate geometry
  6054. _m1.makeTranslation(x, y, z);
  6055. this.applyMatrix4(_m1);
  6056. return this;
  6057. }
  6058. scale(x, y, z) {
  6059. // scale geometry
  6060. _m1.makeScale(x, y, z);
  6061. this.applyMatrix4(_m1);
  6062. return this;
  6063. }
  6064. lookAt(vector) {
  6065. _obj.lookAt(vector);
  6066. _obj.updateMatrix();
  6067. this.applyMatrix4(_obj.matrix);
  6068. return this;
  6069. }
  6070. center() {
  6071. this.computeBoundingBox();
  6072. this.boundingBox.getCenter(_offset).negate();
  6073. this.translate(_offset.x, _offset.y, _offset.z);
  6074. return this;
  6075. }
  6076. setFromPoints(points) {
  6077. const position = [];
  6078. for (let i = 0, l = points.length; i < l; i++) {
  6079. const point = points[i];
  6080. position.push(point.x, point.y, point.z || 0);
  6081. }
  6082. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  6083. return this;
  6084. }
  6085. computeBoundingBox() {
  6086. if (this.boundingBox === null) {
  6087. this.boundingBox = new Box3();
  6088. }
  6089. const position = this.attributes.position;
  6090. const morphAttributesPosition = this.morphAttributes.position;
  6091. if (position && position.isGLBufferAttribute) {
  6092. console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
  6093. this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
  6094. return;
  6095. }
  6096. if (position !== undefined) {
  6097. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  6098. if (morphAttributesPosition) {
  6099. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6100. const morphAttribute = morphAttributesPosition[i];
  6101. _box$1.setFromBufferAttribute(morphAttribute);
  6102. if (this.morphTargetsRelative) {
  6103. _vector$8.addVectors(this.boundingBox.min, _box$1.min);
  6104. this.boundingBox.expandByPoint(_vector$8);
  6105. _vector$8.addVectors(this.boundingBox.max, _box$1.max);
  6106. this.boundingBox.expandByPoint(_vector$8);
  6107. } else {
  6108. this.boundingBox.expandByPoint(_box$1.min);
  6109. this.boundingBox.expandByPoint(_box$1.max);
  6110. }
  6111. }
  6112. }
  6113. } else {
  6114. this.boundingBox.makeEmpty();
  6115. }
  6116. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  6117. console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  6118. }
  6119. }
  6120. computeBoundingSphere() {
  6121. if (this.boundingSphere === null) {
  6122. this.boundingSphere = new Sphere();
  6123. }
  6124. const position = this.attributes.position;
  6125. const morphAttributesPosition = this.morphAttributes.position;
  6126. if (position && position.isGLBufferAttribute) {
  6127. console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
  6128. this.boundingSphere.set(new Vector3(), Infinity);
  6129. return;
  6130. }
  6131. if (position) {
  6132. // first, find the center of the bounding sphere
  6133. const center = this.boundingSphere.center;
  6134. _box$1.setFromBufferAttribute(position); // process morph attributes if present
  6135. if (morphAttributesPosition) {
  6136. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6137. const morphAttribute = morphAttributesPosition[i];
  6138. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  6139. if (this.morphTargetsRelative) {
  6140. _vector$8.addVectors(_box$1.min, _boxMorphTargets.min);
  6141. _box$1.expandByPoint(_vector$8);
  6142. _vector$8.addVectors(_box$1.max, _boxMorphTargets.max);
  6143. _box$1.expandByPoint(_vector$8);
  6144. } else {
  6145. _box$1.expandByPoint(_boxMorphTargets.min);
  6146. _box$1.expandByPoint(_boxMorphTargets.max);
  6147. }
  6148. }
  6149. }
  6150. _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  6151. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6152. let maxRadiusSq = 0;
  6153. for (let i = 0, il = position.count; i < il; i++) {
  6154. _vector$8.fromBufferAttribute(position, i);
  6155. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6156. } // process morph attributes if present
  6157. if (morphAttributesPosition) {
  6158. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6159. const morphAttribute = morphAttributesPosition[i];
  6160. const morphTargetsRelative = this.morphTargetsRelative;
  6161. for (let j = 0, jl = morphAttribute.count; j < jl; j++) {
  6162. _vector$8.fromBufferAttribute(morphAttribute, j);
  6163. if (morphTargetsRelative) {
  6164. _offset.fromBufferAttribute(position, j);
  6165. _vector$8.add(_offset);
  6166. }
  6167. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6168. }
  6169. }
  6170. }
  6171. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  6172. if (isNaN(this.boundingSphere.radius)) {
  6173. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  6174. }
  6175. }
  6176. }
  6177. computeFaceNormals() {// backwards compatibility
  6178. }
  6179. computeTangents() {
  6180. const index = this.index;
  6181. const attributes = this.attributes; // based on http://www.terathon.com/code/tangent.html
  6182. // (per vertex tangents)
  6183. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  6184. console.error('THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)');
  6185. return;
  6186. }
  6187. const indices = index.array;
  6188. const positions = attributes.position.array;
  6189. const normals = attributes.normal.array;
  6190. const uvs = attributes.uv.array;
  6191. const nVertices = positions.length / 3;
  6192. if (attributes.tangent === undefined) {
  6193. this.setAttribute('tangent', new BufferAttribute(new Float32Array(4 * nVertices), 4));
  6194. }
  6195. const tangents = attributes.tangent.array;
  6196. const tan1 = [],
  6197. tan2 = [];
  6198. for (let i = 0; i < nVertices; i++) {
  6199. tan1[i] = new Vector3();
  6200. tan2[i] = new Vector3();
  6201. }
  6202. const vA = new Vector3(),
  6203. vB = new Vector3(),
  6204. vC = new Vector3(),
  6205. uvA = new Vector2(),
  6206. uvB = new Vector2(),
  6207. uvC = new Vector2(),
  6208. sdir = new Vector3(),
  6209. tdir = new Vector3();
  6210. function handleTriangle(a, b, c) {
  6211. vA.fromArray(positions, a * 3);
  6212. vB.fromArray(positions, b * 3);
  6213. vC.fromArray(positions, c * 3);
  6214. uvA.fromArray(uvs, a * 2);
  6215. uvB.fromArray(uvs, b * 2);
  6216. uvC.fromArray(uvs, c * 2);
  6217. vB.sub(vA);
  6218. vC.sub(vA);
  6219. uvB.sub(uvA);
  6220. uvC.sub(uvA);
  6221. const r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y); // silently ignore degenerate uv triangles having coincident or colinear vertices
  6222. if (!isFinite(r)) return;
  6223. sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
  6224. tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
  6225. tan1[a].add(sdir);
  6226. tan1[b].add(sdir);
  6227. tan1[c].add(sdir);
  6228. tan2[a].add(tdir);
  6229. tan2[b].add(tdir);
  6230. tan2[c].add(tdir);
  6231. }
  6232. let groups = this.groups;
  6233. if (groups.length === 0) {
  6234. groups = [{
  6235. start: 0,
  6236. count: indices.length
  6237. }];
  6238. }
  6239. for (let i = 0, il = groups.length; i < il; ++i) {
  6240. const group = groups[i];
  6241. const start = group.start;
  6242. const count = group.count;
  6243. for (let j = start, jl = start + count; j < jl; j += 3) {
  6244. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  6245. }
  6246. }
  6247. const tmp = new Vector3(),
  6248. tmp2 = new Vector3();
  6249. const n = new Vector3(),
  6250. n2 = new Vector3();
  6251. function handleVertex(v) {
  6252. n.fromArray(normals, v * 3);
  6253. n2.copy(n);
  6254. const t = tan1[v]; // Gram-Schmidt orthogonalize
  6255. tmp.copy(t);
  6256. tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
  6257. tmp2.crossVectors(n2, t);
  6258. const test = tmp2.dot(tan2[v]);
  6259. const w = test < 0.0 ? -1.0 : 1.0;
  6260. tangents[v * 4] = tmp.x;
  6261. tangents[v * 4 + 1] = tmp.y;
  6262. tangents[v * 4 + 2] = tmp.z;
  6263. tangents[v * 4 + 3] = w;
  6264. }
  6265. for (let i = 0, il = groups.length; i < il; ++i) {
  6266. const group = groups[i];
  6267. const start = group.start;
  6268. const count = group.count;
  6269. for (let j = start, jl = start + count; j < jl; j += 3) {
  6270. handleVertex(indices[j + 0]);
  6271. handleVertex(indices[j + 1]);
  6272. handleVertex(indices[j + 2]);
  6273. }
  6274. }
  6275. }
  6276. computeVertexNormals() {
  6277. const index = this.index;
  6278. const positionAttribute = this.getAttribute('position');
  6279. if (positionAttribute !== undefined) {
  6280. let normalAttribute = this.getAttribute('normal');
  6281. if (normalAttribute === undefined) {
  6282. normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
  6283. this.setAttribute('normal', normalAttribute);
  6284. } else {
  6285. // reset existing normals to zero
  6286. for (let i = 0, il = normalAttribute.count; i < il; i++) {
  6287. normalAttribute.setXYZ(i, 0, 0, 0);
  6288. }
  6289. }
  6290. const pA = new Vector3(),
  6291. pB = new Vector3(),
  6292. pC = new Vector3();
  6293. const nA = new Vector3(),
  6294. nB = new Vector3(),
  6295. nC = new Vector3();
  6296. const cb = new Vector3(),
  6297. ab = new Vector3(); // indexed elements
  6298. if (index) {
  6299. for (let i = 0, il = index.count; i < il; i += 3) {
  6300. const vA = index.getX(i + 0);
  6301. const vB = index.getX(i + 1);
  6302. const vC = index.getX(i + 2);
  6303. pA.fromBufferAttribute(positionAttribute, vA);
  6304. pB.fromBufferAttribute(positionAttribute, vB);
  6305. pC.fromBufferAttribute(positionAttribute, vC);
  6306. cb.subVectors(pC, pB);
  6307. ab.subVectors(pA, pB);
  6308. cb.cross(ab);
  6309. nA.fromBufferAttribute(normalAttribute, vA);
  6310. nB.fromBufferAttribute(normalAttribute, vB);
  6311. nC.fromBufferAttribute(normalAttribute, vC);
  6312. nA.add(cb);
  6313. nB.add(cb);
  6314. nC.add(cb);
  6315. normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
  6316. normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
  6317. normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
  6318. }
  6319. } else {
  6320. // non-indexed elements (unconnected triangle soup)
  6321. for (let i = 0, il = positionAttribute.count; i < il; i += 3) {
  6322. pA.fromBufferAttribute(positionAttribute, i + 0);
  6323. pB.fromBufferAttribute(positionAttribute, i + 1);
  6324. pC.fromBufferAttribute(positionAttribute, i + 2);
  6325. cb.subVectors(pC, pB);
  6326. ab.subVectors(pA, pB);
  6327. cb.cross(ab);
  6328. normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z);
  6329. normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z);
  6330. normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z);
  6331. }
  6332. }
  6333. this.normalizeNormals();
  6334. normalAttribute.needsUpdate = true;
  6335. }
  6336. }
  6337. merge(geometry, offset) {
  6338. if (!(geometry && geometry.isBufferGeometry)) {
  6339. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  6340. return;
  6341. }
  6342. if (offset === undefined) {
  6343. offset = 0;
  6344. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  6345. }
  6346. const attributes = this.attributes;
  6347. for (const key in attributes) {
  6348. if (geometry.attributes[key] === undefined) continue;
  6349. const attribute1 = attributes[key];
  6350. const attributeArray1 = attribute1.array;
  6351. const attribute2 = geometry.attributes[key];
  6352. const attributeArray2 = attribute2.array;
  6353. const attributeOffset = attribute2.itemSize * offset;
  6354. const length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  6355. for (let i = 0, j = attributeOffset; i < length; i++, j++) {
  6356. attributeArray1[j] = attributeArray2[i];
  6357. }
  6358. }
  6359. return this;
  6360. }
  6361. normalizeNormals() {
  6362. const normals = this.attributes.normal;
  6363. for (let i = 0, il = normals.count; i < il; i++) {
  6364. _vector$8.fromBufferAttribute(normals, i);
  6365. _vector$8.normalize();
  6366. normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z);
  6367. }
  6368. }
  6369. toNonIndexed() {
  6370. function convertBufferAttribute(attribute, indices) {
  6371. const array = attribute.array;
  6372. const itemSize = attribute.itemSize;
  6373. const normalized = attribute.normalized;
  6374. const array2 = new array.constructor(indices.length * itemSize);
  6375. let index = 0,
  6376. index2 = 0;
  6377. for (let i = 0, l = indices.length; i < l; i++) {
  6378. if (attribute.isInterleavedBufferAttribute) {
  6379. index = indices[i] * attribute.data.stride + attribute.offset;
  6380. } else {
  6381. index = indices[i] * itemSize;
  6382. }
  6383. for (let j = 0; j < itemSize; j++) {
  6384. array2[index2++] = array[index++];
  6385. }
  6386. }
  6387. return new BufferAttribute(array2, itemSize, normalized);
  6388. } //
  6389. if (this.index === null) {
  6390. console.warn('THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.');
  6391. return this;
  6392. }
  6393. const geometry2 = new BufferGeometry();
  6394. const indices = this.index.array;
  6395. const attributes = this.attributes; // attributes
  6396. for (const name in attributes) {
  6397. const attribute = attributes[name];
  6398. const newAttribute = convertBufferAttribute(attribute, indices);
  6399. geometry2.setAttribute(name, newAttribute);
  6400. } // morph attributes
  6401. const morphAttributes = this.morphAttributes;
  6402. for (const name in morphAttributes) {
  6403. const morphArray = [];
  6404. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6405. for (let i = 0, il = morphAttribute.length; i < il; i++) {
  6406. const attribute = morphAttribute[i];
  6407. const newAttribute = convertBufferAttribute(attribute, indices);
  6408. morphArray.push(newAttribute);
  6409. }
  6410. geometry2.morphAttributes[name] = morphArray;
  6411. }
  6412. geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
  6413. const groups = this.groups;
  6414. for (let i = 0, l = groups.length; i < l; i++) {
  6415. const group = groups[i];
  6416. geometry2.addGroup(group.start, group.count, group.materialIndex);
  6417. }
  6418. return geometry2;
  6419. }
  6420. toJSON() {
  6421. const data = {
  6422. metadata: {
  6423. version: 4.5,
  6424. type: 'BufferGeometry',
  6425. generator: 'BufferGeometry.toJSON'
  6426. }
  6427. }; // standard BufferGeometry serialization
  6428. data.uuid = this.uuid;
  6429. data.type = this.type;
  6430. if (this.name !== '') data.name = this.name;
  6431. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  6432. if (this.parameters !== undefined) {
  6433. const parameters = this.parameters;
  6434. for (const key in parameters) {
  6435. if (parameters[key] !== undefined) data[key] = parameters[key];
  6436. }
  6437. return data;
  6438. } // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6439. data.data = {
  6440. attributes: {}
  6441. };
  6442. const index = this.index;
  6443. if (index !== null) {
  6444. data.data.index = {
  6445. type: index.array.constructor.name,
  6446. array: Array.prototype.slice.call(index.array)
  6447. };
  6448. }
  6449. const attributes = this.attributes;
  6450. for (const key in attributes) {
  6451. const attribute = attributes[key];
  6452. data.data.attributes[key] = attribute.toJSON(data.data);
  6453. }
  6454. const morphAttributes = {};
  6455. let hasMorphAttributes = false;
  6456. for (const key in this.morphAttributes) {
  6457. const attributeArray = this.morphAttributes[key];
  6458. const array = [];
  6459. for (let i = 0, il = attributeArray.length; i < il; i++) {
  6460. const attribute = attributeArray[i];
  6461. array.push(attribute.toJSON(data.data));
  6462. }
  6463. if (array.length > 0) {
  6464. morphAttributes[key] = array;
  6465. hasMorphAttributes = true;
  6466. }
  6467. }
  6468. if (hasMorphAttributes) {
  6469. data.data.morphAttributes = morphAttributes;
  6470. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6471. }
  6472. const groups = this.groups;
  6473. if (groups.length > 0) {
  6474. data.data.groups = JSON.parse(JSON.stringify(groups));
  6475. }
  6476. const boundingSphere = this.boundingSphere;
  6477. if (boundingSphere !== null) {
  6478. data.data.boundingSphere = {
  6479. center: boundingSphere.center.toArray(),
  6480. radius: boundingSphere.radius
  6481. };
  6482. }
  6483. return data;
  6484. }
  6485. clone() {
  6486. /*
  6487. // Handle primitives
  6488. const parameters = this.parameters;
  6489. if ( parameters !== undefined ) {
  6490. const values = [];
  6491. for ( const key in parameters ) {
  6492. values.push( parameters[ key ] );
  6493. }
  6494. const geometry = Object.create( this.constructor.prototype );
  6495. this.constructor.apply( geometry, values );
  6496. return geometry;
  6497. }
  6498. return new this.constructor().copy( this );
  6499. */
  6500. return new BufferGeometry().copy(this);
  6501. }
  6502. copy(source) {
  6503. // reset
  6504. this.index = null;
  6505. this.attributes = {};
  6506. this.morphAttributes = {};
  6507. this.groups = [];
  6508. this.boundingBox = null;
  6509. this.boundingSphere = null; // used for storing cloned, shared data
  6510. const data = {}; // name
  6511. this.name = source.name; // index
  6512. const index = source.index;
  6513. if (index !== null) {
  6514. this.setIndex(index.clone(data));
  6515. } // attributes
  6516. const attributes = source.attributes;
  6517. for (const name in attributes) {
  6518. const attribute = attributes[name];
  6519. this.setAttribute(name, attribute.clone(data));
  6520. } // morph attributes
  6521. const morphAttributes = source.morphAttributes;
  6522. for (const name in morphAttributes) {
  6523. const array = [];
  6524. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6525. for (let i = 0, l = morphAttribute.length; i < l; i++) {
  6526. array.push(morphAttribute[i].clone(data));
  6527. }
  6528. this.morphAttributes[name] = array;
  6529. }
  6530. this.morphTargetsRelative = source.morphTargetsRelative; // groups
  6531. const groups = source.groups;
  6532. for (let i = 0, l = groups.length; i < l; i++) {
  6533. const group = groups[i];
  6534. this.addGroup(group.start, group.count, group.materialIndex);
  6535. } // bounding box
  6536. const boundingBox = source.boundingBox;
  6537. if (boundingBox !== null) {
  6538. this.boundingBox = boundingBox.clone();
  6539. } // bounding sphere
  6540. const boundingSphere = source.boundingSphere;
  6541. if (boundingSphere !== null) {
  6542. this.boundingSphere = boundingSphere.clone();
  6543. } // draw range
  6544. this.drawRange.start = source.drawRange.start;
  6545. this.drawRange.count = source.drawRange.count; // user data
  6546. this.userData = source.userData;
  6547. return this;
  6548. }
  6549. dispose() {
  6550. this.dispatchEvent({
  6551. type: 'dispose'
  6552. });
  6553. }
  6554. }
  6555. BufferGeometry.prototype.isBufferGeometry = true;
  6556. const _inverseMatrix$2 = /*@__PURE__*/new Matrix4();
  6557. const _ray$2 = /*@__PURE__*/new Ray();
  6558. const _sphere$3 = /*@__PURE__*/new Sphere();
  6559. const _vA$1 = /*@__PURE__*/new Vector3();
  6560. const _vB$1 = /*@__PURE__*/new Vector3();
  6561. const _vC$1 = /*@__PURE__*/new Vector3();
  6562. const _tempA = /*@__PURE__*/new Vector3();
  6563. const _tempB = /*@__PURE__*/new Vector3();
  6564. const _tempC = /*@__PURE__*/new Vector3();
  6565. const _morphA = /*@__PURE__*/new Vector3();
  6566. const _morphB = /*@__PURE__*/new Vector3();
  6567. const _morphC = /*@__PURE__*/new Vector3();
  6568. const _uvA$1 = /*@__PURE__*/new Vector2();
  6569. const _uvB$1 = /*@__PURE__*/new Vector2();
  6570. const _uvC$1 = /*@__PURE__*/new Vector2();
  6571. const _intersectionPoint = /*@__PURE__*/new Vector3();
  6572. const _intersectionPointWorld = /*@__PURE__*/new Vector3();
  6573. class Mesh extends Object3D {
  6574. constructor(geometry = new BufferGeometry(), material = new MeshBasicMaterial()) {
  6575. super();
  6576. this.type = 'Mesh';
  6577. this.geometry = geometry;
  6578. this.material = material;
  6579. this.updateMorphTargets();
  6580. }
  6581. copy(source) {
  6582. super.copy(source);
  6583. if (source.morphTargetInfluences !== undefined) {
  6584. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6585. }
  6586. if (source.morphTargetDictionary !== undefined) {
  6587. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  6588. }
  6589. this.material = source.material;
  6590. this.geometry = source.geometry;
  6591. return this;
  6592. }
  6593. updateMorphTargets() {
  6594. const geometry = this.geometry;
  6595. if (geometry.isBufferGeometry) {
  6596. const morphAttributes = geometry.morphAttributes;
  6597. const keys = Object.keys(morphAttributes);
  6598. if (keys.length > 0) {
  6599. const morphAttribute = morphAttributes[keys[0]];
  6600. if (morphAttribute !== undefined) {
  6601. this.morphTargetInfluences = [];
  6602. this.morphTargetDictionary = {};
  6603. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  6604. const name = morphAttribute[m].name || String(m);
  6605. this.morphTargetInfluences.push(0);
  6606. this.morphTargetDictionary[name] = m;
  6607. }
  6608. }
  6609. }
  6610. } else {
  6611. const morphTargets = geometry.morphTargets;
  6612. if (morphTargets !== undefined && morphTargets.length > 0) {
  6613. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6614. }
  6615. }
  6616. }
  6617. raycast(raycaster, intersects) {
  6618. const geometry = this.geometry;
  6619. const material = this.material;
  6620. const matrixWorld = this.matrixWorld;
  6621. if (material === undefined) return; // Checking boundingSphere distance to ray
  6622. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  6623. _sphere$3.copy(geometry.boundingSphere);
  6624. _sphere$3.applyMatrix4(matrixWorld);
  6625. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  6626. _inverseMatrix$2.copy(matrixWorld).invert();
  6627. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2); // Check boundingBox before continuing
  6628. if (geometry.boundingBox !== null) {
  6629. if (_ray$2.intersectsBox(geometry.boundingBox) === false) return;
  6630. }
  6631. let intersection;
  6632. if (geometry.isBufferGeometry) {
  6633. const index = geometry.index;
  6634. const position = geometry.attributes.position;
  6635. const morphPosition = geometry.morphAttributes.position;
  6636. const morphTargetsRelative = geometry.morphTargetsRelative;
  6637. const uv = geometry.attributes.uv;
  6638. const uv2 = geometry.attributes.uv2;
  6639. const groups = geometry.groups;
  6640. const drawRange = geometry.drawRange;
  6641. if (index !== null) {
  6642. // indexed buffer geometry
  6643. if (Array.isArray(material)) {
  6644. for (let i = 0, il = groups.length; i < il; i++) {
  6645. const group = groups[i];
  6646. const groupMaterial = material[group.materialIndex];
  6647. const start = Math.max(group.start, drawRange.start);
  6648. const end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  6649. for (let j = start, jl = end; j < jl; j += 3) {
  6650. const a = index.getX(j);
  6651. const b = index.getX(j + 1);
  6652. const c = index.getX(j + 2);
  6653. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6654. if (intersection) {
  6655. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  6656. intersection.face.materialIndex = group.materialIndex;
  6657. intersects.push(intersection);
  6658. }
  6659. }
  6660. }
  6661. } else {
  6662. const start = Math.max(0, drawRange.start);
  6663. const end = Math.min(index.count, drawRange.start + drawRange.count);
  6664. for (let i = start, il = end; i < il; i += 3) {
  6665. const a = index.getX(i);
  6666. const b = index.getX(i + 1);
  6667. const c = index.getX(i + 2);
  6668. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6669. if (intersection) {
  6670. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  6671. intersects.push(intersection);
  6672. }
  6673. }
  6674. }
  6675. } else if (position !== undefined) {
  6676. // non-indexed buffer geometry
  6677. if (Array.isArray(material)) {
  6678. for (let i = 0, il = groups.length; i < il; i++) {
  6679. const group = groups[i];
  6680. const groupMaterial = material[group.materialIndex];
  6681. const start = Math.max(group.start, drawRange.start);
  6682. const end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  6683. for (let j = start, jl = end; j < jl; j += 3) {
  6684. const a = j;
  6685. const b = j + 1;
  6686. const c = j + 2;
  6687. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6688. if (intersection) {
  6689. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  6690. intersection.face.materialIndex = group.materialIndex;
  6691. intersects.push(intersection);
  6692. }
  6693. }
  6694. }
  6695. } else {
  6696. const start = Math.max(0, drawRange.start);
  6697. const end = Math.min(position.count, drawRange.start + drawRange.count);
  6698. for (let i = start, il = end; i < il; i += 3) {
  6699. const a = i;
  6700. const b = i + 1;
  6701. const c = i + 2;
  6702. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6703. if (intersection) {
  6704. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  6705. intersects.push(intersection);
  6706. }
  6707. }
  6708. }
  6709. }
  6710. } else if (geometry.isGeometry) {
  6711. console.error('THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6712. }
  6713. }
  6714. }
  6715. Mesh.prototype.isMesh = true;
  6716. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  6717. let intersect;
  6718. if (material.side === BackSide) {
  6719. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  6720. } else {
  6721. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  6722. }
  6723. if (intersect === null) return null;
  6724. _intersectionPointWorld.copy(point);
  6725. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  6726. const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  6727. if (distance < raycaster.near || distance > raycaster.far) return null;
  6728. return {
  6729. distance: distance,
  6730. point: _intersectionPointWorld.clone(),
  6731. object: object
  6732. };
  6733. }
  6734. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  6735. _vA$1.fromBufferAttribute(position, a);
  6736. _vB$1.fromBufferAttribute(position, b);
  6737. _vC$1.fromBufferAttribute(position, c);
  6738. const morphInfluences = object.morphTargetInfluences;
  6739. if (morphPosition && morphInfluences) {
  6740. _morphA.set(0, 0, 0);
  6741. _morphB.set(0, 0, 0);
  6742. _morphC.set(0, 0, 0);
  6743. for (let i = 0, il = morphPosition.length; i < il; i++) {
  6744. const influence = morphInfluences[i];
  6745. const morphAttribute = morphPosition[i];
  6746. if (influence === 0) continue;
  6747. _tempA.fromBufferAttribute(morphAttribute, a);
  6748. _tempB.fromBufferAttribute(morphAttribute, b);
  6749. _tempC.fromBufferAttribute(morphAttribute, c);
  6750. if (morphTargetsRelative) {
  6751. _morphA.addScaledVector(_tempA, influence);
  6752. _morphB.addScaledVector(_tempB, influence);
  6753. _morphC.addScaledVector(_tempC, influence);
  6754. } else {
  6755. _morphA.addScaledVector(_tempA.sub(_vA$1), influence);
  6756. _morphB.addScaledVector(_tempB.sub(_vB$1), influence);
  6757. _morphC.addScaledVector(_tempC.sub(_vC$1), influence);
  6758. }
  6759. }
  6760. _vA$1.add(_morphA);
  6761. _vB$1.add(_morphB);
  6762. _vC$1.add(_morphC);
  6763. }
  6764. if (object.isSkinnedMesh) {
  6765. object.boneTransform(a, _vA$1);
  6766. object.boneTransform(b, _vB$1);
  6767. object.boneTransform(c, _vC$1);
  6768. }
  6769. const intersection = checkIntersection(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint);
  6770. if (intersection) {
  6771. if (uv) {
  6772. _uvA$1.fromBufferAttribute(uv, a);
  6773. _uvB$1.fromBufferAttribute(uv, b);
  6774. _uvC$1.fromBufferAttribute(uv, c);
  6775. intersection.uv = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6776. }
  6777. if (uv2) {
  6778. _uvA$1.fromBufferAttribute(uv2, a);
  6779. _uvB$1.fromBufferAttribute(uv2, b);
  6780. _uvC$1.fromBufferAttribute(uv2, c);
  6781. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6782. }
  6783. const face = {
  6784. a: a,
  6785. b: b,
  6786. c: c,
  6787. normal: new Vector3(),
  6788. materialIndex: 0
  6789. };
  6790. Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal);
  6791. intersection.face = face;
  6792. }
  6793. return intersection;
  6794. }
  6795. class BoxGeometry extends BufferGeometry {
  6796. constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
  6797. super();
  6798. this.type = 'BoxGeometry';
  6799. this.parameters = {
  6800. width: width,
  6801. height: height,
  6802. depth: depth,
  6803. widthSegments: widthSegments,
  6804. heightSegments: heightSegments,
  6805. depthSegments: depthSegments
  6806. };
  6807. const scope = this; // segments
  6808. widthSegments = Math.floor(widthSegments);
  6809. heightSegments = Math.floor(heightSegments);
  6810. depthSegments = Math.floor(depthSegments); // buffers
  6811. const indices = [];
  6812. const vertices = [];
  6813. const normals = [];
  6814. const uvs = []; // helper variables
  6815. let numberOfVertices = 0;
  6816. let groupStart = 0; // build each side of the box geometry
  6817. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  6818. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  6819. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  6820. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  6821. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  6822. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  6823. // build geometry
  6824. this.setIndex(indices);
  6825. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  6826. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  6827. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  6828. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  6829. const segmentWidth = width / gridX;
  6830. const segmentHeight = height / gridY;
  6831. const widthHalf = width / 2;
  6832. const heightHalf = height / 2;
  6833. const depthHalf = depth / 2;
  6834. const gridX1 = gridX + 1;
  6835. const gridY1 = gridY + 1;
  6836. let vertexCounter = 0;
  6837. let groupCount = 0;
  6838. const vector = new Vector3(); // generate vertices, normals and uvs
  6839. for (let iy = 0; iy < gridY1; iy++) {
  6840. const y = iy * segmentHeight - heightHalf;
  6841. for (let ix = 0; ix < gridX1; ix++) {
  6842. const x = ix * segmentWidth - widthHalf; // set values to correct vector component
  6843. vector[u] = x * udir;
  6844. vector[v] = y * vdir;
  6845. vector[w] = depthHalf; // now apply vector to vertex buffer
  6846. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  6847. vector[u] = 0;
  6848. vector[v] = 0;
  6849. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  6850. normals.push(vector.x, vector.y, vector.z); // uvs
  6851. uvs.push(ix / gridX);
  6852. uvs.push(1 - iy / gridY); // counters
  6853. vertexCounter += 1;
  6854. }
  6855. } // indices
  6856. // 1. you need three indices to draw a single face
  6857. // 2. a single segment consists of two faces
  6858. // 3. so we need to generate six (2*3) indices per segment
  6859. for (let iy = 0; iy < gridY; iy++) {
  6860. for (let ix = 0; ix < gridX; ix++) {
  6861. const a = numberOfVertices + ix + gridX1 * iy;
  6862. const b = numberOfVertices + ix + gridX1 * (iy + 1);
  6863. const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  6864. const d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  6865. indices.push(a, b, d);
  6866. indices.push(b, c, d); // increase counter
  6867. groupCount += 6;
  6868. }
  6869. } // add a group to the geometry. this will ensure multi material support
  6870. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  6871. groupStart += groupCount; // update total number of vertices
  6872. numberOfVertices += vertexCounter;
  6873. }
  6874. }
  6875. static fromJSON(data) {
  6876. return new BoxGeometry(data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  6877. }
  6878. }
  6879. /**
  6880. * Uniform Utilities
  6881. */
  6882. function cloneUniforms(src) {
  6883. const dst = {};
  6884. for (const u in src) {
  6885. dst[u] = {};
  6886. for (const p in src[u]) {
  6887. const property = src[u][p];
  6888. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion)) {
  6889. dst[u][p] = property.clone();
  6890. } else if (Array.isArray(property)) {
  6891. dst[u][p] = property.slice();
  6892. } else {
  6893. dst[u][p] = property;
  6894. }
  6895. }
  6896. }
  6897. return dst;
  6898. }
  6899. function mergeUniforms(uniforms) {
  6900. const merged = {};
  6901. for (let u = 0; u < uniforms.length; u++) {
  6902. const tmp = cloneUniforms(uniforms[u]);
  6903. for (const p in tmp) {
  6904. merged[p] = tmp[p];
  6905. }
  6906. }
  6907. return merged;
  6908. } // Legacy
  6909. const UniformsUtils = {
  6910. clone: cloneUniforms,
  6911. merge: mergeUniforms
  6912. };
  6913. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  6914. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  6915. /**
  6916. * parameters = {
  6917. * defines: { "label" : "value" },
  6918. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  6919. *
  6920. * fragmentShader: <string>,
  6921. * vertexShader: <string>,
  6922. *
  6923. * wireframe: <boolean>,
  6924. * wireframeLinewidth: <float>,
  6925. *
  6926. * lights: <bool>
  6927. * }
  6928. */
  6929. class ShaderMaterial extends Material {
  6930. constructor(parameters) {
  6931. super();
  6932. this.type = 'ShaderMaterial';
  6933. this.defines = {};
  6934. this.uniforms = {};
  6935. this.vertexShader = default_vertex;
  6936. this.fragmentShader = default_fragment;
  6937. this.linewidth = 1;
  6938. this.wireframe = false;
  6939. this.wireframeLinewidth = 1;
  6940. this.fog = false; // set to use scene fog
  6941. this.lights = false; // set to use scene lights
  6942. this.clipping = false; // set to use user-defined clipping planes
  6943. this.extensions = {
  6944. derivatives: false,
  6945. // set to use derivatives
  6946. fragDepth: false,
  6947. // set to use fragment depth values
  6948. drawBuffers: false,
  6949. // set to use draw buffers
  6950. shaderTextureLOD: false // set to use shader texture LOD
  6951. }; // When rendered geometry doesn't include these attributes but the material does,
  6952. // use these default values in WebGL. This avoids errors when buffer data is missing.
  6953. this.defaultAttributeValues = {
  6954. 'color': [1, 1, 1],
  6955. 'uv': [0, 0],
  6956. 'uv2': [0, 0]
  6957. };
  6958. this.index0AttributeName = undefined;
  6959. this.uniformsNeedUpdate = false;
  6960. this.glslVersion = null;
  6961. if (parameters !== undefined) {
  6962. if (parameters.attributes !== undefined) {
  6963. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  6964. }
  6965. this.setValues(parameters);
  6966. }
  6967. }
  6968. copy(source) {
  6969. super.copy(source);
  6970. this.fragmentShader = source.fragmentShader;
  6971. this.vertexShader = source.vertexShader;
  6972. this.uniforms = cloneUniforms(source.uniforms);
  6973. this.defines = Object.assign({}, source.defines);
  6974. this.wireframe = source.wireframe;
  6975. this.wireframeLinewidth = source.wireframeLinewidth;
  6976. this.lights = source.lights;
  6977. this.clipping = source.clipping;
  6978. this.extensions = Object.assign({}, source.extensions);
  6979. this.glslVersion = source.glslVersion;
  6980. return this;
  6981. }
  6982. toJSON(meta) {
  6983. const data = super.toJSON(meta);
  6984. data.glslVersion = this.glslVersion;
  6985. data.uniforms = {};
  6986. for (const name in this.uniforms) {
  6987. const uniform = this.uniforms[name];
  6988. const value = uniform.value;
  6989. if (value && value.isTexture) {
  6990. data.uniforms[name] = {
  6991. type: 't',
  6992. value: value.toJSON(meta).uuid
  6993. };
  6994. } else if (value && value.isColor) {
  6995. data.uniforms[name] = {
  6996. type: 'c',
  6997. value: value.getHex()
  6998. };
  6999. } else if (value && value.isVector2) {
  7000. data.uniforms[name] = {
  7001. type: 'v2',
  7002. value: value.toArray()
  7003. };
  7004. } else if (value && value.isVector3) {
  7005. data.uniforms[name] = {
  7006. type: 'v3',
  7007. value: value.toArray()
  7008. };
  7009. } else if (value && value.isVector4) {
  7010. data.uniforms[name] = {
  7011. type: 'v4',
  7012. value: value.toArray()
  7013. };
  7014. } else if (value && value.isMatrix3) {
  7015. data.uniforms[name] = {
  7016. type: 'm3',
  7017. value: value.toArray()
  7018. };
  7019. } else if (value && value.isMatrix4) {
  7020. data.uniforms[name] = {
  7021. type: 'm4',
  7022. value: value.toArray()
  7023. };
  7024. } else {
  7025. data.uniforms[name] = {
  7026. value: value
  7027. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7028. }
  7029. }
  7030. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  7031. data.vertexShader = this.vertexShader;
  7032. data.fragmentShader = this.fragmentShader;
  7033. const extensions = {};
  7034. for (const key in this.extensions) {
  7035. if (this.extensions[key] === true) extensions[key] = true;
  7036. }
  7037. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  7038. return data;
  7039. }
  7040. }
  7041. ShaderMaterial.prototype.isShaderMaterial = true;
  7042. class Camera extends Object3D {
  7043. constructor() {
  7044. super();
  7045. this.type = 'Camera';
  7046. this.matrixWorldInverse = new Matrix4();
  7047. this.projectionMatrix = new Matrix4();
  7048. this.projectionMatrixInverse = new Matrix4();
  7049. }
  7050. copy(source, recursive) {
  7051. super.copy(source, recursive);
  7052. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  7053. this.projectionMatrix.copy(source.projectionMatrix);
  7054. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  7055. return this;
  7056. }
  7057. getWorldDirection(target) {
  7058. this.updateWorldMatrix(true, false);
  7059. const e = this.matrixWorld.elements;
  7060. return target.set(-e[8], -e[9], -e[10]).normalize();
  7061. }
  7062. updateMatrixWorld(force) {
  7063. super.updateMatrixWorld(force);
  7064. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7065. }
  7066. updateWorldMatrix(updateParents, updateChildren) {
  7067. super.updateWorldMatrix(updateParents, updateChildren);
  7068. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7069. }
  7070. clone() {
  7071. return new this.constructor().copy(this);
  7072. }
  7073. }
  7074. Camera.prototype.isCamera = true;
  7075. class PerspectiveCamera extends Camera {
  7076. constructor(fov = 50, aspect = 1, near = 0.1, far = 2000) {
  7077. super();
  7078. this.type = 'PerspectiveCamera';
  7079. this.fov = fov;
  7080. this.zoom = 1;
  7081. this.near = near;
  7082. this.far = far;
  7083. this.focus = 10;
  7084. this.aspect = aspect;
  7085. this.view = null;
  7086. this.filmGauge = 35; // width of the film (default in millimeters)
  7087. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7088. this.updateProjectionMatrix();
  7089. }
  7090. copy(source, recursive) {
  7091. super.copy(source, recursive);
  7092. this.fov = source.fov;
  7093. this.zoom = source.zoom;
  7094. this.near = source.near;
  7095. this.far = source.far;
  7096. this.focus = source.focus;
  7097. this.aspect = source.aspect;
  7098. this.view = source.view === null ? null : Object.assign({}, source.view);
  7099. this.filmGauge = source.filmGauge;
  7100. this.filmOffset = source.filmOffset;
  7101. return this;
  7102. }
  7103. /**
  7104. * Sets the FOV by focal length in respect to the current .filmGauge.
  7105. *
  7106. * The default film gauge is 35, so that the focal length can be specified for
  7107. * a 35mm (full frame) camera.
  7108. *
  7109. * Values for focal length and film gauge must have the same unit.
  7110. */
  7111. setFocalLength(focalLength) {
  7112. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7113. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7114. this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope);
  7115. this.updateProjectionMatrix();
  7116. }
  7117. /**
  7118. * Calculates the focal length from the current .fov and .filmGauge.
  7119. */
  7120. getFocalLength() {
  7121. const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov);
  7122. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7123. }
  7124. getEffectiveFOV() {
  7125. return RAD2DEG * 2 * Math.atan(Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom);
  7126. }
  7127. getFilmWidth() {
  7128. // film not completely covered in portrait format (aspect < 1)
  7129. return this.filmGauge * Math.min(this.aspect, 1);
  7130. }
  7131. getFilmHeight() {
  7132. // film not completely covered in landscape format (aspect > 1)
  7133. return this.filmGauge / Math.max(this.aspect, 1);
  7134. }
  7135. /**
  7136. * Sets an offset in a larger frustum. This is useful for multi-window or
  7137. * multi-monitor/multi-machine setups.
  7138. *
  7139. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7140. * the monitors are in grid like this
  7141. *
  7142. * +---+---+---+
  7143. * | A | B | C |
  7144. * +---+---+---+
  7145. * | D | E | F |
  7146. * +---+---+---+
  7147. *
  7148. * then for each monitor you would call it like this
  7149. *
  7150. * const w = 1920;
  7151. * const h = 1080;
  7152. * const fullWidth = w * 3;
  7153. * const fullHeight = h * 2;
  7154. *
  7155. * --A--
  7156. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7157. * --B--
  7158. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7159. * --C--
  7160. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7161. * --D--
  7162. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7163. * --E--
  7164. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7165. * --F--
  7166. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7167. *
  7168. * Note there is no reason monitors have to be the same size or in a grid.
  7169. */
  7170. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  7171. this.aspect = fullWidth / fullHeight;
  7172. if (this.view === null) {
  7173. this.view = {
  7174. enabled: true,
  7175. fullWidth: 1,
  7176. fullHeight: 1,
  7177. offsetX: 0,
  7178. offsetY: 0,
  7179. width: 1,
  7180. height: 1
  7181. };
  7182. }
  7183. this.view.enabled = true;
  7184. this.view.fullWidth = fullWidth;
  7185. this.view.fullHeight = fullHeight;
  7186. this.view.offsetX = x;
  7187. this.view.offsetY = y;
  7188. this.view.width = width;
  7189. this.view.height = height;
  7190. this.updateProjectionMatrix();
  7191. }
  7192. clearViewOffset() {
  7193. if (this.view !== null) {
  7194. this.view.enabled = false;
  7195. }
  7196. this.updateProjectionMatrix();
  7197. }
  7198. updateProjectionMatrix() {
  7199. const near = this.near;
  7200. let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom;
  7201. let height = 2 * top;
  7202. let width = this.aspect * height;
  7203. let left = -0.5 * width;
  7204. const view = this.view;
  7205. if (this.view !== null && this.view.enabled) {
  7206. const fullWidth = view.fullWidth,
  7207. fullHeight = view.fullHeight;
  7208. left += view.offsetX * width / fullWidth;
  7209. top -= view.offsetY * height / fullHeight;
  7210. width *= view.width / fullWidth;
  7211. height *= view.height / fullHeight;
  7212. }
  7213. const skew = this.filmOffset;
  7214. if (skew !== 0) left += near * skew / this.getFilmWidth();
  7215. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  7216. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  7217. }
  7218. toJSON(meta) {
  7219. const data = super.toJSON(meta);
  7220. data.object.fov = this.fov;
  7221. data.object.zoom = this.zoom;
  7222. data.object.near = this.near;
  7223. data.object.far = this.far;
  7224. data.object.focus = this.focus;
  7225. data.object.aspect = this.aspect;
  7226. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  7227. data.object.filmGauge = this.filmGauge;
  7228. data.object.filmOffset = this.filmOffset;
  7229. return data;
  7230. }
  7231. }
  7232. PerspectiveCamera.prototype.isPerspectiveCamera = true;
  7233. const fov = 90,
  7234. aspect = 1;
  7235. class CubeCamera extends Object3D {
  7236. constructor(near, far, renderTarget) {
  7237. super();
  7238. this.type = 'CubeCamera';
  7239. if (renderTarget.isWebGLCubeRenderTarget !== true) {
  7240. console.error('THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.');
  7241. return;
  7242. }
  7243. this.renderTarget = renderTarget;
  7244. const cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  7245. cameraPX.layers = this.layers;
  7246. cameraPX.up.set(0, -1, 0);
  7247. cameraPX.lookAt(new Vector3(1, 0, 0));
  7248. this.add(cameraPX);
  7249. const cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  7250. cameraNX.layers = this.layers;
  7251. cameraNX.up.set(0, -1, 0);
  7252. cameraNX.lookAt(new Vector3(-1, 0, 0));
  7253. this.add(cameraNX);
  7254. const cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  7255. cameraPY.layers = this.layers;
  7256. cameraPY.up.set(0, 0, 1);
  7257. cameraPY.lookAt(new Vector3(0, 1, 0));
  7258. this.add(cameraPY);
  7259. const cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  7260. cameraNY.layers = this.layers;
  7261. cameraNY.up.set(0, 0, -1);
  7262. cameraNY.lookAt(new Vector3(0, -1, 0));
  7263. this.add(cameraNY);
  7264. const cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  7265. cameraPZ.layers = this.layers;
  7266. cameraPZ.up.set(0, -1, 0);
  7267. cameraPZ.lookAt(new Vector3(0, 0, 1));
  7268. this.add(cameraPZ);
  7269. const cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  7270. cameraNZ.layers = this.layers;
  7271. cameraNZ.up.set(0, -1, 0);
  7272. cameraNZ.lookAt(new Vector3(0, 0, -1));
  7273. this.add(cameraNZ);
  7274. }
  7275. update(renderer, scene) {
  7276. if (this.parent === null) this.updateMatrixWorld();
  7277. const renderTarget = this.renderTarget;
  7278. const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children;
  7279. const currentXrEnabled = renderer.xr.enabled;
  7280. const currentRenderTarget = renderer.getRenderTarget();
  7281. renderer.xr.enabled = false;
  7282. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7283. renderTarget.texture.generateMipmaps = false;
  7284. renderer.setRenderTarget(renderTarget, 0);
  7285. renderer.render(scene, cameraPX);
  7286. renderer.setRenderTarget(renderTarget, 1);
  7287. renderer.render(scene, cameraNX);
  7288. renderer.setRenderTarget(renderTarget, 2);
  7289. renderer.render(scene, cameraPY);
  7290. renderer.setRenderTarget(renderTarget, 3);
  7291. renderer.render(scene, cameraNY);
  7292. renderer.setRenderTarget(renderTarget, 4);
  7293. renderer.render(scene, cameraPZ);
  7294. renderTarget.texture.generateMipmaps = generateMipmaps;
  7295. renderer.setRenderTarget(renderTarget, 5);
  7296. renderer.render(scene, cameraNZ);
  7297. renderer.setRenderTarget(currentRenderTarget);
  7298. renderer.xr.enabled = currentXrEnabled;
  7299. }
  7300. }
  7301. class CubeTexture extends Texture {
  7302. constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  7303. images = images !== undefined ? images : [];
  7304. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7305. format = format !== undefined ? format : RGBFormat;
  7306. super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  7307. this.flipY = false;
  7308. }
  7309. get images() {
  7310. return this.image;
  7311. }
  7312. set images(value) {
  7313. this.image = value;
  7314. }
  7315. }
  7316. CubeTexture.prototype.isCubeTexture = true;
  7317. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7318. constructor(size, options, dummy) {
  7319. if (Number.isInteger(options)) {
  7320. console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');
  7321. options = dummy;
  7322. }
  7323. super(size, size, options);
  7324. options = options || {}; // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7325. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7326. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7327. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7328. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7329. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7330. this.texture = new CubeTexture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  7331. this.texture.isRenderTargetTexture = true;
  7332. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7333. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7334. this.texture._needsFlipEnvMap = false;
  7335. }
  7336. fromEquirectangularTexture(renderer, texture) {
  7337. this.texture.type = texture.type;
  7338. this.texture.format = RGBAFormat; // see #18859
  7339. this.texture.encoding = texture.encoding;
  7340. this.texture.generateMipmaps = texture.generateMipmaps;
  7341. this.texture.minFilter = texture.minFilter;
  7342. this.texture.magFilter = texture.magFilter;
  7343. const shader = {
  7344. uniforms: {
  7345. tEquirect: {
  7346. value: null
  7347. }
  7348. },
  7349. vertexShader:
  7350. /* glsl */
  7351. `
  7352. varying vec3 vWorldDirection;
  7353. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7354. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7355. }
  7356. void main() {
  7357. vWorldDirection = transformDirection( position, modelMatrix );
  7358. #include <begin_vertex>
  7359. #include <project_vertex>
  7360. }
  7361. `,
  7362. fragmentShader:
  7363. /* glsl */
  7364. `
  7365. uniform sampler2D tEquirect;
  7366. varying vec3 vWorldDirection;
  7367. #include <common>
  7368. void main() {
  7369. vec3 direction = normalize( vWorldDirection );
  7370. vec2 sampleUV = equirectUv( direction );
  7371. gl_FragColor = texture2D( tEquirect, sampleUV );
  7372. }
  7373. `
  7374. };
  7375. const geometry = new BoxGeometry(5, 5, 5);
  7376. const material = new ShaderMaterial({
  7377. name: 'CubemapFromEquirect',
  7378. uniforms: cloneUniforms(shader.uniforms),
  7379. vertexShader: shader.vertexShader,
  7380. fragmentShader: shader.fragmentShader,
  7381. side: BackSide,
  7382. blending: NoBlending
  7383. });
  7384. material.uniforms.tEquirect.value = texture;
  7385. const mesh = new Mesh(geometry, material);
  7386. const currentMinFilter = texture.minFilter; // Avoid blurred poles
  7387. if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
  7388. const camera = new CubeCamera(1, 10, this);
  7389. camera.update(renderer, mesh);
  7390. texture.minFilter = currentMinFilter;
  7391. mesh.geometry.dispose();
  7392. mesh.material.dispose();
  7393. return this;
  7394. }
  7395. clear(renderer, color, depth, stencil) {
  7396. const currentRenderTarget = renderer.getRenderTarget();
  7397. for (let i = 0; i < 6; i++) {
  7398. renderer.setRenderTarget(this, i);
  7399. renderer.clear(color, depth, stencil);
  7400. }
  7401. renderer.setRenderTarget(currentRenderTarget);
  7402. }
  7403. }
  7404. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  7405. const _vector1 = /*@__PURE__*/new Vector3();
  7406. const _vector2 = /*@__PURE__*/new Vector3();
  7407. const _normalMatrix = /*@__PURE__*/new Matrix3();
  7408. class Plane {
  7409. constructor(normal = new Vector3(1, 0, 0), constant = 0) {
  7410. // normal is assumed to be normalized
  7411. this.normal = normal;
  7412. this.constant = constant;
  7413. }
  7414. set(normal, constant) {
  7415. this.normal.copy(normal);
  7416. this.constant = constant;
  7417. return this;
  7418. }
  7419. setComponents(x, y, z, w) {
  7420. this.normal.set(x, y, z);
  7421. this.constant = w;
  7422. return this;
  7423. }
  7424. setFromNormalAndCoplanarPoint(normal, point) {
  7425. this.normal.copy(normal);
  7426. this.constant = -point.dot(this.normal);
  7427. return this;
  7428. }
  7429. setFromCoplanarPoints(a, b, c) {
  7430. 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)?
  7431. this.setFromNormalAndCoplanarPoint(normal, a);
  7432. return this;
  7433. }
  7434. copy(plane) {
  7435. this.normal.copy(plane.normal);
  7436. this.constant = plane.constant;
  7437. return this;
  7438. }
  7439. normalize() {
  7440. // Note: will lead to a divide by zero if the plane is invalid.
  7441. const inverseNormalLength = 1.0 / this.normal.length();
  7442. this.normal.multiplyScalar(inverseNormalLength);
  7443. this.constant *= inverseNormalLength;
  7444. return this;
  7445. }
  7446. negate() {
  7447. this.constant *= -1;
  7448. this.normal.negate();
  7449. return this;
  7450. }
  7451. distanceToPoint(point) {
  7452. return this.normal.dot(point) + this.constant;
  7453. }
  7454. distanceToSphere(sphere) {
  7455. return this.distanceToPoint(sphere.center) - sphere.radius;
  7456. }
  7457. projectPoint(point, target) {
  7458. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  7459. }
  7460. intersectLine(line, target) {
  7461. const direction = line.delta(_vector1);
  7462. const denominator = this.normal.dot(direction);
  7463. if (denominator === 0) {
  7464. // line is coplanar, return origin
  7465. if (this.distanceToPoint(line.start) === 0) {
  7466. return target.copy(line.start);
  7467. } // Unsure if this is the correct method to handle this case.
  7468. return null;
  7469. }
  7470. const t = -(line.start.dot(this.normal) + this.constant) / denominator;
  7471. if (t < 0 || t > 1) {
  7472. return null;
  7473. }
  7474. return target.copy(direction).multiplyScalar(t).add(line.start);
  7475. }
  7476. intersectsLine(line) {
  7477. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7478. const startSign = this.distanceToPoint(line.start);
  7479. const endSign = this.distanceToPoint(line.end);
  7480. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  7481. }
  7482. intersectsBox(box) {
  7483. return box.intersectsPlane(this);
  7484. }
  7485. intersectsSphere(sphere) {
  7486. return sphere.intersectsPlane(this);
  7487. }
  7488. coplanarPoint(target) {
  7489. return target.copy(this.normal).multiplyScalar(-this.constant);
  7490. }
  7491. applyMatrix4(matrix, optionalNormalMatrix) {
  7492. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  7493. const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  7494. const normal = this.normal.applyMatrix3(normalMatrix).normalize();
  7495. this.constant = -referencePoint.dot(normal);
  7496. return this;
  7497. }
  7498. translate(offset) {
  7499. this.constant -= offset.dot(this.normal);
  7500. return this;
  7501. }
  7502. equals(plane) {
  7503. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  7504. }
  7505. clone() {
  7506. return new this.constructor().copy(this);
  7507. }
  7508. }
  7509. Plane.prototype.isPlane = true;
  7510. const _sphere$2 = /*@__PURE__*/new Sphere();
  7511. const _vector$7 = /*@__PURE__*/new Vector3();
  7512. class Frustum {
  7513. constructor(p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane()) {
  7514. this.planes = [p0, p1, p2, p3, p4, p5];
  7515. }
  7516. set(p0, p1, p2, p3, p4, p5) {
  7517. const planes = this.planes;
  7518. planes[0].copy(p0);
  7519. planes[1].copy(p1);
  7520. planes[2].copy(p2);
  7521. planes[3].copy(p3);
  7522. planes[4].copy(p4);
  7523. planes[5].copy(p5);
  7524. return this;
  7525. }
  7526. copy(frustum) {
  7527. const planes = this.planes;
  7528. for (let i = 0; i < 6; i++) {
  7529. planes[i].copy(frustum.planes[i]);
  7530. }
  7531. return this;
  7532. }
  7533. setFromProjectionMatrix(m) {
  7534. const planes = this.planes;
  7535. const me = m.elements;
  7536. const me0 = me[0],
  7537. me1 = me[1],
  7538. me2 = me[2],
  7539. me3 = me[3];
  7540. const me4 = me[4],
  7541. me5 = me[5],
  7542. me6 = me[6],
  7543. me7 = me[7];
  7544. const me8 = me[8],
  7545. me9 = me[9],
  7546. me10 = me[10],
  7547. me11 = me[11];
  7548. const me12 = me[12],
  7549. me13 = me[13],
  7550. me14 = me[14],
  7551. me15 = me[15];
  7552. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  7553. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  7554. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  7555. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  7556. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  7557. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  7558. return this;
  7559. }
  7560. intersectsObject(object) {
  7561. const geometry = object.geometry;
  7562. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  7563. _sphere$2.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  7564. return this.intersectsSphere(_sphere$2);
  7565. }
  7566. intersectsSprite(sprite) {
  7567. _sphere$2.center.set(0, 0, 0);
  7568. _sphere$2.radius = 0.7071067811865476;
  7569. _sphere$2.applyMatrix4(sprite.matrixWorld);
  7570. return this.intersectsSphere(_sphere$2);
  7571. }
  7572. intersectsSphere(sphere) {
  7573. const planes = this.planes;
  7574. const center = sphere.center;
  7575. const negRadius = -sphere.radius;
  7576. for (let i = 0; i < 6; i++) {
  7577. const distance = planes[i].distanceToPoint(center);
  7578. if (distance < negRadius) {
  7579. return false;
  7580. }
  7581. }
  7582. return true;
  7583. }
  7584. intersectsBox(box) {
  7585. const planes = this.planes;
  7586. for (let i = 0; i < 6; i++) {
  7587. const plane = planes[i]; // corner at max distance
  7588. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7589. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7590. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7591. if (plane.distanceToPoint(_vector$7) < 0) {
  7592. return false;
  7593. }
  7594. }
  7595. return true;
  7596. }
  7597. containsPoint(point) {
  7598. const planes = this.planes;
  7599. for (let i = 0; i < 6; i++) {
  7600. if (planes[i].distanceToPoint(point) < 0) {
  7601. return false;
  7602. }
  7603. }
  7604. return true;
  7605. }
  7606. clone() {
  7607. return new this.constructor().copy(this);
  7608. }
  7609. }
  7610. function WebGLAnimation() {
  7611. let context = null;
  7612. let isAnimating = false;
  7613. let animationLoop = null;
  7614. let requestId = null;
  7615. function onAnimationFrame(time, frame) {
  7616. animationLoop(time, frame);
  7617. requestId = context.requestAnimationFrame(onAnimationFrame);
  7618. }
  7619. return {
  7620. start: function () {
  7621. if (isAnimating === true) return;
  7622. if (animationLoop === null) return;
  7623. requestId = context.requestAnimationFrame(onAnimationFrame);
  7624. isAnimating = true;
  7625. },
  7626. stop: function () {
  7627. context.cancelAnimationFrame(requestId);
  7628. isAnimating = false;
  7629. },
  7630. setAnimationLoop: function (callback) {
  7631. animationLoop = callback;
  7632. },
  7633. setContext: function (value) {
  7634. context = value;
  7635. }
  7636. };
  7637. }
  7638. function WebGLAttributes(gl, capabilities) {
  7639. const isWebGL2 = capabilities.isWebGL2;
  7640. const buffers = new WeakMap();
  7641. function createBuffer(attribute, bufferType) {
  7642. const array = attribute.array;
  7643. const usage = attribute.usage;
  7644. const buffer = gl.createBuffer();
  7645. gl.bindBuffer(bufferType, buffer);
  7646. gl.bufferData(bufferType, array, usage);
  7647. attribute.onUploadCallback();
  7648. let type = gl.FLOAT;
  7649. if (array instanceof Float32Array) {
  7650. type = gl.FLOAT;
  7651. } else if (array instanceof Float64Array) {
  7652. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  7653. } else if (array instanceof Uint16Array) {
  7654. if (attribute.isFloat16BufferAttribute) {
  7655. if (isWebGL2) {
  7656. type = gl.HALF_FLOAT;
  7657. } else {
  7658. console.warn('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
  7659. }
  7660. } else {
  7661. type = gl.UNSIGNED_SHORT;
  7662. }
  7663. } else if (array instanceof Int16Array) {
  7664. type = gl.SHORT;
  7665. } else if (array instanceof Uint32Array) {
  7666. type = gl.UNSIGNED_INT;
  7667. } else if (array instanceof Int32Array) {
  7668. type = gl.INT;
  7669. } else if (array instanceof Int8Array) {
  7670. type = gl.BYTE;
  7671. } else if (array instanceof Uint8Array) {
  7672. type = gl.UNSIGNED_BYTE;
  7673. } else if (array instanceof Uint8ClampedArray) {
  7674. type = gl.UNSIGNED_BYTE;
  7675. }
  7676. return {
  7677. buffer: buffer,
  7678. type: type,
  7679. bytesPerElement: array.BYTES_PER_ELEMENT,
  7680. version: attribute.version
  7681. };
  7682. }
  7683. function updateBuffer(buffer, attribute, bufferType) {
  7684. const array = attribute.array;
  7685. const updateRange = attribute.updateRange;
  7686. gl.bindBuffer(bufferType, buffer);
  7687. if (updateRange.count === -1) {
  7688. // Not using update ranges
  7689. gl.bufferSubData(bufferType, 0, array);
  7690. } else {
  7691. if (isWebGL2) {
  7692. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  7693. } else {
  7694. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  7695. }
  7696. updateRange.count = -1; // reset range
  7697. }
  7698. } //
  7699. function get(attribute) {
  7700. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7701. return buffers.get(attribute);
  7702. }
  7703. function remove(attribute) {
  7704. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7705. const data = buffers.get(attribute);
  7706. if (data) {
  7707. gl.deleteBuffer(data.buffer);
  7708. buffers.delete(attribute);
  7709. }
  7710. }
  7711. function update(attribute, bufferType) {
  7712. if (attribute.isGLBufferAttribute) {
  7713. const cached = buffers.get(attribute);
  7714. if (!cached || cached.version < attribute.version) {
  7715. buffers.set(attribute, {
  7716. buffer: attribute.buffer,
  7717. type: attribute.type,
  7718. bytesPerElement: attribute.elementSize,
  7719. version: attribute.version
  7720. });
  7721. }
  7722. return;
  7723. }
  7724. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7725. const data = buffers.get(attribute);
  7726. if (data === undefined) {
  7727. buffers.set(attribute, createBuffer(attribute, bufferType));
  7728. } else if (data.version < attribute.version) {
  7729. updateBuffer(data.buffer, attribute, bufferType);
  7730. data.version = attribute.version;
  7731. }
  7732. }
  7733. return {
  7734. get: get,
  7735. remove: remove,
  7736. update: update
  7737. };
  7738. }
  7739. class PlaneGeometry extends BufferGeometry {
  7740. constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) {
  7741. super();
  7742. this.type = 'PlaneGeometry';
  7743. this.parameters = {
  7744. width: width,
  7745. height: height,
  7746. widthSegments: widthSegments,
  7747. heightSegments: heightSegments
  7748. };
  7749. const width_half = width / 2;
  7750. const height_half = height / 2;
  7751. const gridX = Math.floor(widthSegments);
  7752. const gridY = Math.floor(heightSegments);
  7753. const gridX1 = gridX + 1;
  7754. const gridY1 = gridY + 1;
  7755. const segment_width = width / gridX;
  7756. const segment_height = height / gridY; //
  7757. const indices = [];
  7758. const vertices = [];
  7759. const normals = [];
  7760. const uvs = [];
  7761. for (let iy = 0; iy < gridY1; iy++) {
  7762. const y = iy * segment_height - height_half;
  7763. for (let ix = 0; ix < gridX1; ix++) {
  7764. const x = ix * segment_width - width_half;
  7765. vertices.push(x, -y, 0);
  7766. normals.push(0, 0, 1);
  7767. uvs.push(ix / gridX);
  7768. uvs.push(1 - iy / gridY);
  7769. }
  7770. }
  7771. for (let iy = 0; iy < gridY; iy++) {
  7772. for (let ix = 0; ix < gridX; ix++) {
  7773. const a = ix + gridX1 * iy;
  7774. const b = ix + gridX1 * (iy + 1);
  7775. const c = ix + 1 + gridX1 * (iy + 1);
  7776. const d = ix + 1 + gridX1 * iy;
  7777. indices.push(a, b, d);
  7778. indices.push(b, c, d);
  7779. }
  7780. }
  7781. this.setIndex(indices);
  7782. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  7783. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  7784. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  7785. }
  7786. static fromJSON(data) {
  7787. return new PlaneGeometry(data.width, data.height, data.widthSegments, data.heightSegments);
  7788. }
  7789. }
  7790. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7791. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7792. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  7793. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif";
  7794. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7795. var begin_vertex = "vec3 transformed = vec3( position );";
  7796. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7797. var bsdfs = "vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in vec3 f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn ( f90 - f0 ) * fresnel + f0;\n}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in vec3 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 dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, vec3( 1.0 ), dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif";
  7798. 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";
  7799. 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";
  7800. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7801. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7802. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7803. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7804. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7805. 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";
  7806. 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";
  7807. var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat max3( vec3 v ) { return max( max( v.x, v.y ), v.z ); }\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}";
  7808. 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";
  7809. 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";
  7810. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7811. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7812. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7813. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7814. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7815. 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}";
  7816. 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";
  7817. 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";
  7818. 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";
  7819. 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";
  7820. 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";
  7821. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  7822. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  7823. 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";
  7824. 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";
  7825. 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}";
  7826. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";
  7827. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7828. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";
  7829. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif";
  7830. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\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 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\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";
  7831. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7832. 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\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)";
  7833. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7834. 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\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";
  7835. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.specularRoughness = max( roughnessFactor, 0.0525 );material.specularRoughness += geometryRoughness;\nmaterial.specularRoughness = min( material.specularRoughness, 1.0 );\n#ifdef IOR\n\t#ifdef SPECULAR\n\t\tvec3 specularIntensityFactor = vec3( 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.specularColorF90 = mix( specularIntensityFactor, vec3( 1.0 ), metalnessFactor );\n\t#else\n\t\tvec3 specularIntensityFactor = vec3( 1.0 );\n\t\tvec3 specularTintFactor = vec3( 1.0 );\n\t\tmaterial.specularColorF90 = vec3( 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( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularColorF90 = vec3( 1.0 );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheen;\n#endif";
  7836. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat specularRoughness;\n\tvec3 specularColor;\n\tvec3 specularColorF90;\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\n#endif\n};\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearcoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tccIrradiance *= PI;\n\t\t#endif\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), vec3( 1.0 ), material.clearcoatRoughness );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(\n\t\t\tmaterial.specularRoughness,\n\t\t\tdirectLight.direction,\n\t\t\tgeometry,\n\t\t\tmaterial.sheenColor\n\t\t);\n\t#else\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularColorF90, material.specularRoughness);\n\t#endif\n\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += clearcoatInv * radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  7837. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  7838. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\t#ifdef CLEARCOAT\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\t#endif\n#endif";
  7839. 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";
  7840. 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";
  7841. 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";
  7842. 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";
  7843. 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";
  7844. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  7845. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7846. 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";
  7847. 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";
  7848. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7849. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7850. 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";
  7851. 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";
  7852. 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";
  7853. 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;";
  7854. 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";
  7855. 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";
  7856. 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";
  7857. 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";
  7858. 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";
  7859. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7860. 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";
  7861. 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";
  7862. 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}";
  7863. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7864. 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;";
  7865. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7866. 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";
  7867. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7868. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7869. 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";
  7870. 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";
  7871. 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";
  7872. 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}";
  7873. 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";
  7874. 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";
  7875. 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";
  7876. 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";
  7877. 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";
  7878. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7879. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7880. 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; }";
  7881. var transmission_fragment = "#ifdef USE_TRANSMISSION\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.xyz / vWorldPosition.w;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec3 transmission = transmissionFactor * getIBLVolumeRefraction(\n\t\tn, v, roughnessFactor, material.diffuseColor, material.specularColor,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, ior, thicknessFactor,\n\t\tattenuationTint, attenuationDistance );\n\ttotalDiffuse = mix( totalDiffuse, transmission, transmissionFactor );\n#endif";
  7882. var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\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 vec4 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\tvec3 getTransmissionSample(vec2 fragCoord, float roughness, float ior) {\n\t\tfloat framebufferLod = log2(transmissionSamplerSize.x) * applyIorToRoughness(roughness, ior);\n\t\treturn texture2DLodEXT(transmissionSamplerMap, fragCoord.xy, framebufferLod).rgb;\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\tvec3 getIBLVolumeRefraction(vec3 n, vec3 v, float perceptualRoughness, vec3 baseColor, vec3 specularColor,\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\tvec3 transmittedLight = getTransmissionSample(refractionCoords, perceptualRoughness, ior);\n\t\tvec3 attenuatedColor = applyVolumeAttenuation(transmittedLight, length(transmissionRay), attenuationColor, attenuationDistance);\n\t\treturn (1.0 - specularColor) * attenuatedColor * baseColor;\n\t}\n#endif";
  7883. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7884. 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";
  7885. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7886. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7887. 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";
  7888. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7889. 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";
  7890. 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}";
  7891. 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}";
  7892. 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}";
  7893. 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}";
  7894. var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
  7895. 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}";
  7896. var distanceRGBA_frag = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  7897. 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}";
  7898. 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}";
  7899. 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}";
  7900. var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7901. 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}";
  7902. var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7903. 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}";
  7904. var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7905. 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}";
  7906. 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 <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\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7907. 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}";
  7908. var meshtoon_frag = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <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\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7909. 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}";
  7910. var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <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\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7911. 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}";
  7912. var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define CLEARCOAT\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationTint;\n#endif\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 CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <transmission_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <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\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7913. var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec4 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;\n#endif\n}";
  7914. var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#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}";
  7915. var normal_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}";
  7916. var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  7917. 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}";
  7918. 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}";
  7919. 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}";
  7920. var sprite_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  7921. 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}";
  7922. const ShaderChunk = {
  7923. alphamap_fragment: alphamap_fragment,
  7924. alphamap_pars_fragment: alphamap_pars_fragment,
  7925. alphatest_fragment: alphatest_fragment,
  7926. aomap_fragment: aomap_fragment,
  7927. aomap_pars_fragment: aomap_pars_fragment,
  7928. begin_vertex: begin_vertex,
  7929. beginnormal_vertex: beginnormal_vertex,
  7930. bsdfs: bsdfs,
  7931. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7932. clipping_planes_fragment: clipping_planes_fragment,
  7933. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7934. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7935. clipping_planes_vertex: clipping_planes_vertex,
  7936. color_fragment: color_fragment,
  7937. color_pars_fragment: color_pars_fragment,
  7938. color_pars_vertex: color_pars_vertex,
  7939. color_vertex: color_vertex,
  7940. common: common,
  7941. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7942. defaultnormal_vertex: defaultnormal_vertex,
  7943. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7944. displacementmap_vertex: displacementmap_vertex,
  7945. emissivemap_fragment: emissivemap_fragment,
  7946. emissivemap_pars_fragment: emissivemap_pars_fragment,
  7947. encodings_fragment: encodings_fragment,
  7948. encodings_pars_fragment: encodings_pars_fragment,
  7949. envmap_fragment: envmap_fragment,
  7950. envmap_common_pars_fragment: envmap_common_pars_fragment,
  7951. envmap_pars_fragment: envmap_pars_fragment,
  7952. envmap_pars_vertex: envmap_pars_vertex,
  7953. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  7954. envmap_vertex: envmap_vertex,
  7955. fog_vertex: fog_vertex,
  7956. fog_pars_vertex: fog_pars_vertex,
  7957. fog_fragment: fog_fragment,
  7958. fog_pars_fragment: fog_pars_fragment,
  7959. gradientmap_pars_fragment: gradientmap_pars_fragment,
  7960. lightmap_fragment: lightmap_fragment,
  7961. lightmap_pars_fragment: lightmap_pars_fragment,
  7962. lights_lambert_vertex: lights_lambert_vertex,
  7963. lights_pars_begin: lights_pars_begin,
  7964. lights_toon_fragment: lights_toon_fragment,
  7965. lights_toon_pars_fragment: lights_toon_pars_fragment,
  7966. lights_phong_fragment: lights_phong_fragment,
  7967. lights_phong_pars_fragment: lights_phong_pars_fragment,
  7968. lights_physical_fragment: lights_physical_fragment,
  7969. lights_physical_pars_fragment: lights_physical_pars_fragment,
  7970. lights_fragment_begin: lights_fragment_begin,
  7971. lights_fragment_maps: lights_fragment_maps,
  7972. lights_fragment_end: lights_fragment_end,
  7973. logdepthbuf_fragment: logdepthbuf_fragment,
  7974. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  7975. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  7976. logdepthbuf_vertex: logdepthbuf_vertex,
  7977. map_fragment: map_fragment,
  7978. map_pars_fragment: map_pars_fragment,
  7979. map_particle_fragment: map_particle_fragment,
  7980. map_particle_pars_fragment: map_particle_pars_fragment,
  7981. metalnessmap_fragment: metalnessmap_fragment,
  7982. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  7983. morphnormal_vertex: morphnormal_vertex,
  7984. morphtarget_pars_vertex: morphtarget_pars_vertex,
  7985. morphtarget_vertex: morphtarget_vertex,
  7986. normal_fragment_begin: normal_fragment_begin,
  7987. normal_fragment_maps: normal_fragment_maps,
  7988. normal_pars_fragment: normal_pars_fragment,
  7989. normal_pars_vertex: normal_pars_vertex,
  7990. normal_vertex: normal_vertex,
  7991. normalmap_pars_fragment: normalmap_pars_fragment,
  7992. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  7993. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  7994. clearcoat_pars_fragment: clearcoat_pars_fragment,
  7995. packing: packing,
  7996. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  7997. project_vertex: project_vertex,
  7998. dithering_fragment: dithering_fragment,
  7999. dithering_pars_fragment: dithering_pars_fragment,
  8000. roughnessmap_fragment: roughnessmap_fragment,
  8001. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8002. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8003. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8004. shadowmap_vertex: shadowmap_vertex,
  8005. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8006. skinbase_vertex: skinbase_vertex,
  8007. skinning_pars_vertex: skinning_pars_vertex,
  8008. skinning_vertex: skinning_vertex,
  8009. skinnormal_vertex: skinnormal_vertex,
  8010. specularmap_fragment: specularmap_fragment,
  8011. specularmap_pars_fragment: specularmap_pars_fragment,
  8012. tonemapping_fragment: tonemapping_fragment,
  8013. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8014. transmission_fragment: transmission_fragment,
  8015. transmission_pars_fragment: transmission_pars_fragment,
  8016. uv_pars_fragment: uv_pars_fragment,
  8017. uv_pars_vertex: uv_pars_vertex,
  8018. uv_vertex: uv_vertex,
  8019. uv2_pars_fragment: uv2_pars_fragment,
  8020. uv2_pars_vertex: uv2_pars_vertex,
  8021. uv2_vertex: uv2_vertex,
  8022. worldpos_vertex: worldpos_vertex,
  8023. background_frag: background_frag,
  8024. background_vert: background_vert,
  8025. cube_frag: cube_frag,
  8026. cube_vert: cube_vert,
  8027. depth_frag: depth_frag,
  8028. depth_vert: depth_vert,
  8029. distanceRGBA_frag: distanceRGBA_frag,
  8030. distanceRGBA_vert: distanceRGBA_vert,
  8031. equirect_frag: equirect_frag,
  8032. equirect_vert: equirect_vert,
  8033. linedashed_frag: linedashed_frag,
  8034. linedashed_vert: linedashed_vert,
  8035. meshbasic_frag: meshbasic_frag,
  8036. meshbasic_vert: meshbasic_vert,
  8037. meshlambert_frag: meshlambert_frag,
  8038. meshlambert_vert: meshlambert_vert,
  8039. meshmatcap_frag: meshmatcap_frag,
  8040. meshmatcap_vert: meshmatcap_vert,
  8041. meshtoon_frag: meshtoon_frag,
  8042. meshtoon_vert: meshtoon_vert,
  8043. meshphong_frag: meshphong_frag,
  8044. meshphong_vert: meshphong_vert,
  8045. meshphysical_frag: meshphysical_frag,
  8046. meshphysical_vert: meshphysical_vert,
  8047. normal_frag: normal_frag,
  8048. normal_vert: normal_vert,
  8049. points_frag: points_frag,
  8050. points_vert: points_vert,
  8051. shadow_frag: shadow_frag,
  8052. shadow_vert: shadow_vert,
  8053. sprite_frag: sprite_frag,
  8054. sprite_vert: sprite_vert
  8055. };
  8056. /**
  8057. * Uniforms library for shared webgl shaders
  8058. */
  8059. const UniformsLib = {
  8060. common: {
  8061. diffuse: {
  8062. value: new Color(0xffffff)
  8063. },
  8064. opacity: {
  8065. value: 1.0
  8066. },
  8067. map: {
  8068. value: null
  8069. },
  8070. uvTransform: {
  8071. value: new Matrix3()
  8072. },
  8073. uv2Transform: {
  8074. value: new Matrix3()
  8075. },
  8076. alphaMap: {
  8077. value: null
  8078. }
  8079. },
  8080. specularmap: {
  8081. specularMap: {
  8082. value: null
  8083. }
  8084. },
  8085. envmap: {
  8086. envMap: {
  8087. value: null
  8088. },
  8089. flipEnvMap: {
  8090. value: -1
  8091. },
  8092. reflectivity: {
  8093. value: 1.0
  8094. },
  8095. // basic, lambert, phong
  8096. ior: {
  8097. value: 1.5
  8098. },
  8099. // standard, physical
  8100. refractionRatio: {
  8101. value: 0.98
  8102. },
  8103. maxMipLevel: {
  8104. value: 0
  8105. }
  8106. },
  8107. aomap: {
  8108. aoMap: {
  8109. value: null
  8110. },
  8111. aoMapIntensity: {
  8112. value: 1
  8113. }
  8114. },
  8115. lightmap: {
  8116. lightMap: {
  8117. value: null
  8118. },
  8119. lightMapIntensity: {
  8120. value: 1
  8121. }
  8122. },
  8123. emissivemap: {
  8124. emissiveMap: {
  8125. value: null
  8126. }
  8127. },
  8128. bumpmap: {
  8129. bumpMap: {
  8130. value: null
  8131. },
  8132. bumpScale: {
  8133. value: 1
  8134. }
  8135. },
  8136. normalmap: {
  8137. normalMap: {
  8138. value: null
  8139. },
  8140. normalScale: {
  8141. value: new Vector2(1, 1)
  8142. }
  8143. },
  8144. displacementmap: {
  8145. displacementMap: {
  8146. value: null
  8147. },
  8148. displacementScale: {
  8149. value: 1
  8150. },
  8151. displacementBias: {
  8152. value: 0
  8153. }
  8154. },
  8155. roughnessmap: {
  8156. roughnessMap: {
  8157. value: null
  8158. }
  8159. },
  8160. metalnessmap: {
  8161. metalnessMap: {
  8162. value: null
  8163. }
  8164. },
  8165. gradientmap: {
  8166. gradientMap: {
  8167. value: null
  8168. }
  8169. },
  8170. fog: {
  8171. fogDensity: {
  8172. value: 0.00025
  8173. },
  8174. fogNear: {
  8175. value: 1
  8176. },
  8177. fogFar: {
  8178. value: 2000
  8179. },
  8180. fogColor: {
  8181. value: new Color(0xffffff)
  8182. }
  8183. },
  8184. lights: {
  8185. ambientLightColor: {
  8186. value: []
  8187. },
  8188. lightProbe: {
  8189. value: []
  8190. },
  8191. directionalLights: {
  8192. value: [],
  8193. properties: {
  8194. direction: {},
  8195. color: {}
  8196. }
  8197. },
  8198. directionalLightShadows: {
  8199. value: [],
  8200. properties: {
  8201. shadowBias: {},
  8202. shadowNormalBias: {},
  8203. shadowRadius: {},
  8204. shadowMapSize: {}
  8205. }
  8206. },
  8207. directionalShadowMap: {
  8208. value: []
  8209. },
  8210. directionalShadowMatrix: {
  8211. value: []
  8212. },
  8213. spotLights: {
  8214. value: [],
  8215. properties: {
  8216. color: {},
  8217. position: {},
  8218. direction: {},
  8219. distance: {},
  8220. coneCos: {},
  8221. penumbraCos: {},
  8222. decay: {}
  8223. }
  8224. },
  8225. spotLightShadows: {
  8226. value: [],
  8227. properties: {
  8228. shadowBias: {},
  8229. shadowNormalBias: {},
  8230. shadowRadius: {},
  8231. shadowMapSize: {}
  8232. }
  8233. },
  8234. spotShadowMap: {
  8235. value: []
  8236. },
  8237. spotShadowMatrix: {
  8238. value: []
  8239. },
  8240. pointLights: {
  8241. value: [],
  8242. properties: {
  8243. color: {},
  8244. position: {},
  8245. decay: {},
  8246. distance: {}
  8247. }
  8248. },
  8249. pointLightShadows: {
  8250. value: [],
  8251. properties: {
  8252. shadowBias: {},
  8253. shadowNormalBias: {},
  8254. shadowRadius: {},
  8255. shadowMapSize: {},
  8256. shadowCameraNear: {},
  8257. shadowCameraFar: {}
  8258. }
  8259. },
  8260. pointShadowMap: {
  8261. value: []
  8262. },
  8263. pointShadowMatrix: {
  8264. value: []
  8265. },
  8266. hemisphereLights: {
  8267. value: [],
  8268. properties: {
  8269. direction: {},
  8270. skyColor: {},
  8271. groundColor: {}
  8272. }
  8273. },
  8274. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8275. rectAreaLights: {
  8276. value: [],
  8277. properties: {
  8278. color: {},
  8279. position: {},
  8280. width: {},
  8281. height: {}
  8282. }
  8283. },
  8284. ltc_1: {
  8285. value: null
  8286. },
  8287. ltc_2: {
  8288. value: null
  8289. }
  8290. },
  8291. points: {
  8292. diffuse: {
  8293. value: new Color(0xffffff)
  8294. },
  8295. opacity: {
  8296. value: 1.0
  8297. },
  8298. size: {
  8299. value: 1.0
  8300. },
  8301. scale: {
  8302. value: 1.0
  8303. },
  8304. map: {
  8305. value: null
  8306. },
  8307. alphaMap: {
  8308. value: null
  8309. },
  8310. uvTransform: {
  8311. value: new Matrix3()
  8312. }
  8313. },
  8314. sprite: {
  8315. diffuse: {
  8316. value: new Color(0xffffff)
  8317. },
  8318. opacity: {
  8319. value: 1.0
  8320. },
  8321. center: {
  8322. value: new Vector2(0.5, 0.5)
  8323. },
  8324. rotation: {
  8325. value: 0.0
  8326. },
  8327. map: {
  8328. value: null
  8329. },
  8330. alphaMap: {
  8331. value: null
  8332. },
  8333. uvTransform: {
  8334. value: new Matrix3()
  8335. }
  8336. }
  8337. };
  8338. const ShaderLib = {
  8339. basic: {
  8340. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  8341. vertexShader: ShaderChunk.meshbasic_vert,
  8342. fragmentShader: ShaderChunk.meshbasic_frag
  8343. },
  8344. lambert: {
  8345. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  8346. emissive: {
  8347. value: new Color(0x000000)
  8348. }
  8349. }]),
  8350. vertexShader: ShaderChunk.meshlambert_vert,
  8351. fragmentShader: ShaderChunk.meshlambert_frag
  8352. },
  8353. phong: {
  8354. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  8355. emissive: {
  8356. value: new Color(0x000000)
  8357. },
  8358. specular: {
  8359. value: new Color(0x111111)
  8360. },
  8361. shininess: {
  8362. value: 30
  8363. }
  8364. }]),
  8365. vertexShader: ShaderChunk.meshphong_vert,
  8366. fragmentShader: ShaderChunk.meshphong_frag
  8367. },
  8368. standard: {
  8369. 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, {
  8370. emissive: {
  8371. value: new Color(0x000000)
  8372. },
  8373. roughness: {
  8374. value: 1.0
  8375. },
  8376. metalness: {
  8377. value: 0.0
  8378. },
  8379. envMapIntensity: {
  8380. value: 1
  8381. } // temporary
  8382. }]),
  8383. vertexShader: ShaderChunk.meshphysical_vert,
  8384. fragmentShader: ShaderChunk.meshphysical_frag
  8385. },
  8386. toon: {
  8387. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  8388. emissive: {
  8389. value: new Color(0x000000)
  8390. }
  8391. }]),
  8392. vertexShader: ShaderChunk.meshtoon_vert,
  8393. fragmentShader: ShaderChunk.meshtoon_frag
  8394. },
  8395. matcap: {
  8396. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  8397. matcap: {
  8398. value: null
  8399. }
  8400. }]),
  8401. vertexShader: ShaderChunk.meshmatcap_vert,
  8402. fragmentShader: ShaderChunk.meshmatcap_frag
  8403. },
  8404. points: {
  8405. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  8406. vertexShader: ShaderChunk.points_vert,
  8407. fragmentShader: ShaderChunk.points_frag
  8408. },
  8409. dashed: {
  8410. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  8411. scale: {
  8412. value: 1
  8413. },
  8414. dashSize: {
  8415. value: 1
  8416. },
  8417. totalSize: {
  8418. value: 2
  8419. }
  8420. }]),
  8421. vertexShader: ShaderChunk.linedashed_vert,
  8422. fragmentShader: ShaderChunk.linedashed_frag
  8423. },
  8424. depth: {
  8425. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  8426. vertexShader: ShaderChunk.depth_vert,
  8427. fragmentShader: ShaderChunk.depth_frag
  8428. },
  8429. normal: {
  8430. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  8431. opacity: {
  8432. value: 1.0
  8433. }
  8434. }]),
  8435. vertexShader: ShaderChunk.normal_vert,
  8436. fragmentShader: ShaderChunk.normal_frag
  8437. },
  8438. sprite: {
  8439. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  8440. vertexShader: ShaderChunk.sprite_vert,
  8441. fragmentShader: ShaderChunk.sprite_frag
  8442. },
  8443. background: {
  8444. uniforms: {
  8445. uvTransform: {
  8446. value: new Matrix3()
  8447. },
  8448. t2D: {
  8449. value: null
  8450. }
  8451. },
  8452. vertexShader: ShaderChunk.background_vert,
  8453. fragmentShader: ShaderChunk.background_frag
  8454. },
  8455. /* -------------------------------------------------------------------------
  8456. // Cube map shader
  8457. ------------------------------------------------------------------------- */
  8458. cube: {
  8459. uniforms: mergeUniforms([UniformsLib.envmap, {
  8460. opacity: {
  8461. value: 1.0
  8462. }
  8463. }]),
  8464. vertexShader: ShaderChunk.cube_vert,
  8465. fragmentShader: ShaderChunk.cube_frag
  8466. },
  8467. equirect: {
  8468. uniforms: {
  8469. tEquirect: {
  8470. value: null
  8471. }
  8472. },
  8473. vertexShader: ShaderChunk.equirect_vert,
  8474. fragmentShader: ShaderChunk.equirect_frag
  8475. },
  8476. distanceRGBA: {
  8477. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  8478. referencePosition: {
  8479. value: new Vector3()
  8480. },
  8481. nearDistance: {
  8482. value: 1
  8483. },
  8484. farDistance: {
  8485. value: 1000
  8486. }
  8487. }]),
  8488. vertexShader: ShaderChunk.distanceRGBA_vert,
  8489. fragmentShader: ShaderChunk.distanceRGBA_frag
  8490. },
  8491. shadow: {
  8492. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  8493. color: {
  8494. value: new Color(0x00000)
  8495. },
  8496. opacity: {
  8497. value: 1.0
  8498. }
  8499. }]),
  8500. vertexShader: ShaderChunk.shadow_vert,
  8501. fragmentShader: ShaderChunk.shadow_frag
  8502. }
  8503. };
  8504. ShaderLib.physical = {
  8505. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  8506. clearcoat: {
  8507. value: 0
  8508. },
  8509. clearcoatMap: {
  8510. value: null
  8511. },
  8512. clearcoatRoughness: {
  8513. value: 0
  8514. },
  8515. clearcoatRoughnessMap: {
  8516. value: null
  8517. },
  8518. clearcoatNormalScale: {
  8519. value: new Vector2(1, 1)
  8520. },
  8521. clearcoatNormalMap: {
  8522. value: null
  8523. },
  8524. sheen: {
  8525. value: new Color(0x000000)
  8526. },
  8527. transmission: {
  8528. value: 0
  8529. },
  8530. transmissionMap: {
  8531. value: null
  8532. },
  8533. transmissionSamplerSize: {
  8534. value: new Vector2()
  8535. },
  8536. transmissionSamplerMap: {
  8537. value: null
  8538. },
  8539. thickness: {
  8540. value: 0
  8541. },
  8542. thicknessMap: {
  8543. value: null
  8544. },
  8545. attenuationDistance: {
  8546. value: 0
  8547. },
  8548. attenuationTint: {
  8549. value: new Color(0x000000)
  8550. },
  8551. specularIntensity: {
  8552. value: 0
  8553. },
  8554. specularIntensityMap: {
  8555. value: null
  8556. },
  8557. specularTint: {
  8558. value: new Color(1, 1, 1)
  8559. },
  8560. specularTintMap: {
  8561. value: null
  8562. }
  8563. }]),
  8564. vertexShader: ShaderChunk.meshphysical_vert,
  8565. fragmentShader: ShaderChunk.meshphysical_frag
  8566. };
  8567. function WebGLBackground(renderer, cubemaps, state, objects, premultipliedAlpha) {
  8568. const clearColor = new Color(0x000000);
  8569. let clearAlpha = 0;
  8570. let planeMesh;
  8571. let boxMesh;
  8572. let currentBackground = null;
  8573. let currentBackgroundVersion = 0;
  8574. let currentTonemapping = null;
  8575. function render(renderList, scene) {
  8576. let forceClear = false;
  8577. let background = scene.isScene === true ? scene.background : null;
  8578. if (background && background.isTexture) {
  8579. background = cubemaps.get(background);
  8580. } // Ignore background in AR
  8581. // TODO: Reconsider this.
  8582. const xr = renderer.xr;
  8583. const session = xr.getSession && xr.getSession();
  8584. if (session && session.environmentBlendMode === 'additive') {
  8585. background = null;
  8586. }
  8587. if (background === null) {
  8588. setClear(clearColor, clearAlpha);
  8589. } else if (background && background.isColor) {
  8590. setClear(background, 1);
  8591. forceClear = true;
  8592. }
  8593. if (renderer.autoClear || forceClear) {
  8594. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  8595. }
  8596. if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) {
  8597. if (boxMesh === undefined) {
  8598. boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({
  8599. name: 'BackgroundCubeMaterial',
  8600. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  8601. vertexShader: ShaderLib.cube.vertexShader,
  8602. fragmentShader: ShaderLib.cube.fragmentShader,
  8603. side: BackSide,
  8604. depthTest: false,
  8605. depthWrite: false,
  8606. fog: false
  8607. }));
  8608. boxMesh.geometry.deleteAttribute('normal');
  8609. boxMesh.geometry.deleteAttribute('uv');
  8610. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  8611. this.matrixWorld.copyPosition(camera.matrixWorld);
  8612. }; // enable code injection for non-built-in material
  8613. Object.defineProperty(boxMesh.material, 'envMap', {
  8614. get: function () {
  8615. return this.uniforms.envMap.value;
  8616. }
  8617. });
  8618. objects.update(boxMesh);
  8619. }
  8620. boxMesh.material.uniforms.envMap.value = background;
  8621. boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background.isRenderTargetTexture === false ? -1 : 1;
  8622. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8623. boxMesh.material.needsUpdate = true;
  8624. currentBackground = background;
  8625. currentBackgroundVersion = background.version;
  8626. currentTonemapping = renderer.toneMapping;
  8627. } // push to the pre-sorted opaque render list
  8628. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  8629. } else if (background && background.isTexture) {
  8630. if (planeMesh === undefined) {
  8631. planeMesh = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({
  8632. name: 'BackgroundMaterial',
  8633. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  8634. vertexShader: ShaderLib.background.vertexShader,
  8635. fragmentShader: ShaderLib.background.fragmentShader,
  8636. side: FrontSide,
  8637. depthTest: false,
  8638. depthWrite: false,
  8639. fog: false
  8640. }));
  8641. planeMesh.geometry.deleteAttribute('normal'); // enable code injection for non-built-in material
  8642. Object.defineProperty(planeMesh.material, 'map', {
  8643. get: function () {
  8644. return this.uniforms.t2D.value;
  8645. }
  8646. });
  8647. objects.update(planeMesh);
  8648. }
  8649. planeMesh.material.uniforms.t2D.value = background;
  8650. if (background.matrixAutoUpdate === true) {
  8651. background.updateMatrix();
  8652. }
  8653. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  8654. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8655. planeMesh.material.needsUpdate = true;
  8656. currentBackground = background;
  8657. currentBackgroundVersion = background.version;
  8658. currentTonemapping = renderer.toneMapping;
  8659. } // push to the pre-sorted opaque render list
  8660. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  8661. }
  8662. }
  8663. function setClear(color, alpha) {
  8664. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  8665. }
  8666. return {
  8667. getClearColor: function () {
  8668. return clearColor;
  8669. },
  8670. setClearColor: function (color, alpha = 1) {
  8671. clearColor.set(color);
  8672. clearAlpha = alpha;
  8673. setClear(clearColor, clearAlpha);
  8674. },
  8675. getClearAlpha: function () {
  8676. return clearAlpha;
  8677. },
  8678. setClearAlpha: function (alpha) {
  8679. clearAlpha = alpha;
  8680. setClear(clearColor, clearAlpha);
  8681. },
  8682. render: render
  8683. };
  8684. }
  8685. function WebGLBindingStates(gl, extensions, attributes, capabilities) {
  8686. const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  8687. const extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
  8688. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8689. const bindingStates = {};
  8690. const defaultState = createBindingState(null);
  8691. let currentState = defaultState;
  8692. function setup(object, material, program, geometry, index) {
  8693. let updateBuffers = false;
  8694. if (vaoAvailable) {
  8695. const state = getBindingState(geometry, program, material);
  8696. if (currentState !== state) {
  8697. currentState = state;
  8698. bindVertexArrayObject(currentState.object);
  8699. }
  8700. updateBuffers = needsUpdate(geometry, index);
  8701. if (updateBuffers) saveCache(geometry, index);
  8702. } else {
  8703. const wireframe = material.wireframe === true;
  8704. if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
  8705. currentState.geometry = geometry.id;
  8706. currentState.program = program.id;
  8707. currentState.wireframe = wireframe;
  8708. updateBuffers = true;
  8709. }
  8710. }
  8711. if (object.isInstancedMesh === true) {
  8712. updateBuffers = true;
  8713. }
  8714. if (index !== null) {
  8715. attributes.update(index, gl.ELEMENT_ARRAY_BUFFER);
  8716. }
  8717. if (updateBuffers) {
  8718. setupVertexAttributes(object, material, program, geometry);
  8719. if (index !== null) {
  8720. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index).buffer);
  8721. }
  8722. }
  8723. }
  8724. function createVertexArrayObject() {
  8725. if (capabilities.isWebGL2) return gl.createVertexArray();
  8726. return extension.createVertexArrayOES();
  8727. }
  8728. function bindVertexArrayObject(vao) {
  8729. if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
  8730. return extension.bindVertexArrayOES(vao);
  8731. }
  8732. function deleteVertexArrayObject(vao) {
  8733. if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
  8734. return extension.deleteVertexArrayOES(vao);
  8735. }
  8736. function getBindingState(geometry, program, material) {
  8737. const wireframe = material.wireframe === true;
  8738. let programMap = bindingStates[geometry.id];
  8739. if (programMap === undefined) {
  8740. programMap = {};
  8741. bindingStates[geometry.id] = programMap;
  8742. }
  8743. let stateMap = programMap[program.id];
  8744. if (stateMap === undefined) {
  8745. stateMap = {};
  8746. programMap[program.id] = stateMap;
  8747. }
  8748. let state = stateMap[wireframe];
  8749. if (state === undefined) {
  8750. state = createBindingState(createVertexArrayObject());
  8751. stateMap[wireframe] = state;
  8752. }
  8753. return state;
  8754. }
  8755. function createBindingState(vao) {
  8756. const newAttributes = [];
  8757. const enabledAttributes = [];
  8758. const attributeDivisors = [];
  8759. for (let i = 0; i < maxVertexAttributes; i++) {
  8760. newAttributes[i] = 0;
  8761. enabledAttributes[i] = 0;
  8762. attributeDivisors[i] = 0;
  8763. }
  8764. return {
  8765. // for backward compatibility on non-VAO support browser
  8766. geometry: null,
  8767. program: null,
  8768. wireframe: false,
  8769. newAttributes: newAttributes,
  8770. enabledAttributes: enabledAttributes,
  8771. attributeDivisors: attributeDivisors,
  8772. object: vao,
  8773. attributes: {},
  8774. index: null
  8775. };
  8776. }
  8777. function needsUpdate(geometry, index) {
  8778. const cachedAttributes = currentState.attributes;
  8779. const geometryAttributes = geometry.attributes;
  8780. let attributesNum = 0;
  8781. for (const key in geometryAttributes) {
  8782. const cachedAttribute = cachedAttributes[key];
  8783. const geometryAttribute = geometryAttributes[key];
  8784. if (cachedAttribute === undefined) return true;
  8785. if (cachedAttribute.attribute !== geometryAttribute) return true;
  8786. if (cachedAttribute.data !== geometryAttribute.data) return true;
  8787. attributesNum++;
  8788. }
  8789. if (currentState.attributesNum !== attributesNum) return true;
  8790. if (currentState.index !== index) return true;
  8791. return false;
  8792. }
  8793. function saveCache(geometry, index) {
  8794. const cache = {};
  8795. const attributes = geometry.attributes;
  8796. let attributesNum = 0;
  8797. for (const key in attributes) {
  8798. const attribute = attributes[key];
  8799. const data = {};
  8800. data.attribute = attribute;
  8801. if (attribute.data) {
  8802. data.data = attribute.data;
  8803. }
  8804. cache[key] = data;
  8805. attributesNum++;
  8806. }
  8807. currentState.attributes = cache;
  8808. currentState.attributesNum = attributesNum;
  8809. currentState.index = index;
  8810. }
  8811. function initAttributes() {
  8812. const newAttributes = currentState.newAttributes;
  8813. for (let i = 0, il = newAttributes.length; i < il; i++) {
  8814. newAttributes[i] = 0;
  8815. }
  8816. }
  8817. function enableAttribute(attribute) {
  8818. enableAttributeAndDivisor(attribute, 0);
  8819. }
  8820. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  8821. const newAttributes = currentState.newAttributes;
  8822. const enabledAttributes = currentState.enabledAttributes;
  8823. const attributeDivisors = currentState.attributeDivisors;
  8824. newAttributes[attribute] = 1;
  8825. if (enabledAttributes[attribute] === 0) {
  8826. gl.enableVertexAttribArray(attribute);
  8827. enabledAttributes[attribute] = 1;
  8828. }
  8829. if (attributeDivisors[attribute] !== meshPerAttribute) {
  8830. const extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  8831. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  8832. attributeDivisors[attribute] = meshPerAttribute;
  8833. }
  8834. }
  8835. function disableUnusedAttributes() {
  8836. const newAttributes = currentState.newAttributes;
  8837. const enabledAttributes = currentState.enabledAttributes;
  8838. for (let i = 0, il = enabledAttributes.length; i < il; i++) {
  8839. if (enabledAttributes[i] !== newAttributes[i]) {
  8840. gl.disableVertexAttribArray(i);
  8841. enabledAttributes[i] = 0;
  8842. }
  8843. }
  8844. }
  8845. function vertexAttribPointer(index, size, type, normalized, stride, offset) {
  8846. if (capabilities.isWebGL2 === true && (type === gl.INT || type === gl.UNSIGNED_INT)) {
  8847. gl.vertexAttribIPointer(index, size, type, stride, offset);
  8848. } else {
  8849. gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
  8850. }
  8851. }
  8852. function setupVertexAttributes(object, material, program, geometry) {
  8853. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  8854. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  8855. }
  8856. initAttributes();
  8857. const geometryAttributes = geometry.attributes;
  8858. const programAttributes = program.getAttributes();
  8859. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8860. for (const name in programAttributes) {
  8861. const programAttribute = programAttributes[name];
  8862. if (programAttribute >= 0) {
  8863. const geometryAttribute = geometryAttributes[name];
  8864. if (geometryAttribute !== undefined) {
  8865. const normalized = geometryAttribute.normalized;
  8866. const size = geometryAttribute.itemSize;
  8867. const attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  8868. if (attribute === undefined) continue;
  8869. const buffer = attribute.buffer;
  8870. const type = attribute.type;
  8871. const bytesPerElement = attribute.bytesPerElement;
  8872. if (geometryAttribute.isInterleavedBufferAttribute) {
  8873. const data = geometryAttribute.data;
  8874. const stride = data.stride;
  8875. const offset = geometryAttribute.offset;
  8876. if (data && data.isInstancedInterleavedBuffer) {
  8877. enableAttributeAndDivisor(programAttribute, data.meshPerAttribute);
  8878. if (geometry._maxInstanceCount === undefined) {
  8879. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8880. }
  8881. } else {
  8882. enableAttribute(programAttribute);
  8883. }
  8884. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8885. vertexAttribPointer(programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement);
  8886. } else {
  8887. if (geometryAttribute.isInstancedBufferAttribute) {
  8888. enableAttributeAndDivisor(programAttribute, geometryAttribute.meshPerAttribute);
  8889. if (geometry._maxInstanceCount === undefined) {
  8890. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8891. }
  8892. } else {
  8893. enableAttribute(programAttribute);
  8894. }
  8895. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8896. vertexAttribPointer(programAttribute, size, type, normalized, 0, 0);
  8897. }
  8898. } else if (name === 'instanceMatrix') {
  8899. const attribute = attributes.get(object.instanceMatrix); // TODO Attribute may not be available on context restore
  8900. if (attribute === undefined) continue;
  8901. const buffer = attribute.buffer;
  8902. const type = attribute.type;
  8903. enableAttributeAndDivisor(programAttribute + 0, 1);
  8904. enableAttributeAndDivisor(programAttribute + 1, 1);
  8905. enableAttributeAndDivisor(programAttribute + 2, 1);
  8906. enableAttributeAndDivisor(programAttribute + 3, 1);
  8907. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8908. gl.vertexAttribPointer(programAttribute + 0, 4, type, false, 64, 0);
  8909. gl.vertexAttribPointer(programAttribute + 1, 4, type, false, 64, 16);
  8910. gl.vertexAttribPointer(programAttribute + 2, 4, type, false, 64, 32);
  8911. gl.vertexAttribPointer(programAttribute + 3, 4, type, false, 64, 48);
  8912. } else if (name === 'instanceColor') {
  8913. const attribute = attributes.get(object.instanceColor); // TODO Attribute may not be available on context restore
  8914. if (attribute === undefined) continue;
  8915. const buffer = attribute.buffer;
  8916. const type = attribute.type;
  8917. enableAttributeAndDivisor(programAttribute, 1);
  8918. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8919. gl.vertexAttribPointer(programAttribute, 3, type, false, 12, 0);
  8920. } else if (materialDefaultAttributeValues !== undefined) {
  8921. const value = materialDefaultAttributeValues[name];
  8922. if (value !== undefined) {
  8923. switch (value.length) {
  8924. case 2:
  8925. gl.vertexAttrib2fv(programAttribute, value);
  8926. break;
  8927. case 3:
  8928. gl.vertexAttrib3fv(programAttribute, value);
  8929. break;
  8930. case 4:
  8931. gl.vertexAttrib4fv(programAttribute, value);
  8932. break;
  8933. default:
  8934. gl.vertexAttrib1fv(programAttribute, value);
  8935. }
  8936. }
  8937. }
  8938. }
  8939. }
  8940. disableUnusedAttributes();
  8941. }
  8942. function dispose() {
  8943. reset();
  8944. for (const geometryId in bindingStates) {
  8945. const programMap = bindingStates[geometryId];
  8946. for (const programId in programMap) {
  8947. const stateMap = programMap[programId];
  8948. for (const wireframe in stateMap) {
  8949. deleteVertexArrayObject(stateMap[wireframe].object);
  8950. delete stateMap[wireframe];
  8951. }
  8952. delete programMap[programId];
  8953. }
  8954. delete bindingStates[geometryId];
  8955. }
  8956. }
  8957. function releaseStatesOfGeometry(geometry) {
  8958. if (bindingStates[geometry.id] === undefined) return;
  8959. const programMap = bindingStates[geometry.id];
  8960. for (const programId in programMap) {
  8961. const stateMap = programMap[programId];
  8962. for (const wireframe in stateMap) {
  8963. deleteVertexArrayObject(stateMap[wireframe].object);
  8964. delete stateMap[wireframe];
  8965. }
  8966. delete programMap[programId];
  8967. }
  8968. delete bindingStates[geometry.id];
  8969. }
  8970. function releaseStatesOfProgram(program) {
  8971. for (const geometryId in bindingStates) {
  8972. const programMap = bindingStates[geometryId];
  8973. if (programMap[program.id] === undefined) continue;
  8974. const stateMap = programMap[program.id];
  8975. for (const wireframe in stateMap) {
  8976. deleteVertexArrayObject(stateMap[wireframe].object);
  8977. delete stateMap[wireframe];
  8978. }
  8979. delete programMap[program.id];
  8980. }
  8981. }
  8982. function reset() {
  8983. resetDefaultState();
  8984. if (currentState === defaultState) return;
  8985. currentState = defaultState;
  8986. bindVertexArrayObject(currentState.object);
  8987. } // for backward-compatilibity
  8988. function resetDefaultState() {
  8989. defaultState.geometry = null;
  8990. defaultState.program = null;
  8991. defaultState.wireframe = false;
  8992. }
  8993. return {
  8994. setup: setup,
  8995. reset: reset,
  8996. resetDefaultState: resetDefaultState,
  8997. dispose: dispose,
  8998. releaseStatesOfGeometry: releaseStatesOfGeometry,
  8999. releaseStatesOfProgram: releaseStatesOfProgram,
  9000. initAttributes: initAttributes,
  9001. enableAttribute: enableAttribute,
  9002. disableUnusedAttributes: disableUnusedAttributes
  9003. };
  9004. }
  9005. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  9006. const isWebGL2 = capabilities.isWebGL2;
  9007. let mode;
  9008. function setMode(value) {
  9009. mode = value;
  9010. }
  9011. function render(start, count) {
  9012. gl.drawArrays(mode, start, count);
  9013. info.update(count, mode, 1);
  9014. }
  9015. function renderInstances(start, count, primcount) {
  9016. if (primcount === 0) return;
  9017. let extension, methodName;
  9018. if (isWebGL2) {
  9019. extension = gl;
  9020. methodName = 'drawArraysInstanced';
  9021. } else {
  9022. extension = extensions.get('ANGLE_instanced_arrays');
  9023. methodName = 'drawArraysInstancedANGLE';
  9024. if (extension === null) {
  9025. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9026. return;
  9027. }
  9028. }
  9029. extension[methodName](mode, start, count, primcount);
  9030. info.update(count, mode, primcount);
  9031. } //
  9032. this.setMode = setMode;
  9033. this.render = render;
  9034. this.renderInstances = renderInstances;
  9035. }
  9036. function WebGLCapabilities(gl, extensions, parameters) {
  9037. let maxAnisotropy;
  9038. function getMaxAnisotropy() {
  9039. if (maxAnisotropy !== undefined) return maxAnisotropy;
  9040. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  9041. const extension = extensions.get('EXT_texture_filter_anisotropic');
  9042. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  9043. } else {
  9044. maxAnisotropy = 0;
  9045. }
  9046. return maxAnisotropy;
  9047. }
  9048. function getMaxPrecision(precision) {
  9049. if (precision === 'highp') {
  9050. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) {
  9051. return 'highp';
  9052. }
  9053. precision = 'mediump';
  9054. }
  9055. if (precision === 'mediump') {
  9056. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) {
  9057. return 'mediump';
  9058. }
  9059. }
  9060. return 'lowp';
  9061. }
  9062. /* eslint-disable no-undef */
  9063. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  9064. /* eslint-enable no-undef */
  9065. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9066. const maxPrecision = getMaxPrecision(precision);
  9067. if (maxPrecision !== precision) {
  9068. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  9069. precision = maxPrecision;
  9070. }
  9071. const drawBuffers = isWebGL2 || extensions.has('WEBGL_draw_buffers');
  9072. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9073. const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
  9074. const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9075. const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
  9076. const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9077. const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  9078. const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
  9079. const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS);
  9080. const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9081. const vertexTextures = maxVertexTextures > 0;
  9082. const floatFragmentTextures = isWebGL2 || extensions.has('OES_texture_float');
  9083. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9084. const maxSamples = isWebGL2 ? gl.getParameter(gl.MAX_SAMPLES) : 0;
  9085. return {
  9086. isWebGL2: isWebGL2,
  9087. drawBuffers: drawBuffers,
  9088. getMaxAnisotropy: getMaxAnisotropy,
  9089. getMaxPrecision: getMaxPrecision,
  9090. precision: precision,
  9091. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9092. maxTextures: maxTextures,
  9093. maxVertexTextures: maxVertexTextures,
  9094. maxTextureSize: maxTextureSize,
  9095. maxCubemapSize: maxCubemapSize,
  9096. maxAttributes: maxAttributes,
  9097. maxVertexUniforms: maxVertexUniforms,
  9098. maxVaryings: maxVaryings,
  9099. maxFragmentUniforms: maxFragmentUniforms,
  9100. vertexTextures: vertexTextures,
  9101. floatFragmentTextures: floatFragmentTextures,
  9102. floatVertexTextures: floatVertexTextures,
  9103. maxSamples: maxSamples
  9104. };
  9105. }
  9106. function WebGLClipping(properties) {
  9107. const scope = this;
  9108. let globalState = null,
  9109. numGlobalPlanes = 0,
  9110. localClippingEnabled = false,
  9111. renderingShadows = false;
  9112. const plane = new Plane(),
  9113. viewNormalMatrix = new Matrix3(),
  9114. uniform = {
  9115. value: null,
  9116. needsUpdate: false
  9117. };
  9118. this.uniform = uniform;
  9119. this.numPlanes = 0;
  9120. this.numIntersection = 0;
  9121. this.init = function (planes, enableLocalClipping, camera) {
  9122. const enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  9123. // run another frame in order to reset the state:
  9124. numGlobalPlanes !== 0 || localClippingEnabled;
  9125. localClippingEnabled = enableLocalClipping;
  9126. globalState = projectPlanes(planes, camera, 0);
  9127. numGlobalPlanes = planes.length;
  9128. return enabled;
  9129. };
  9130. this.beginShadows = function () {
  9131. renderingShadows = true;
  9132. projectPlanes(null);
  9133. };
  9134. this.endShadows = function () {
  9135. renderingShadows = false;
  9136. resetGlobalState();
  9137. };
  9138. this.setState = function (material, camera, useCache) {
  9139. const planes = material.clippingPlanes,
  9140. clipIntersection = material.clipIntersection,
  9141. clipShadows = material.clipShadows;
  9142. const materialProperties = properties.get(material);
  9143. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  9144. // there's no local clipping
  9145. if (renderingShadows) {
  9146. // there's no global clipping
  9147. projectPlanes(null);
  9148. } else {
  9149. resetGlobalState();
  9150. }
  9151. } else {
  9152. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9153. lGlobal = nGlobal * 4;
  9154. let dstArray = materialProperties.clippingState || null;
  9155. uniform.value = dstArray; // ensure unique state
  9156. dstArray = projectPlanes(planes, camera, lGlobal, useCache);
  9157. for (let i = 0; i !== lGlobal; ++i) {
  9158. dstArray[i] = globalState[i];
  9159. }
  9160. materialProperties.clippingState = dstArray;
  9161. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9162. this.numPlanes += nGlobal;
  9163. }
  9164. };
  9165. function resetGlobalState() {
  9166. if (uniform.value !== globalState) {
  9167. uniform.value = globalState;
  9168. uniform.needsUpdate = numGlobalPlanes > 0;
  9169. }
  9170. scope.numPlanes = numGlobalPlanes;
  9171. scope.numIntersection = 0;
  9172. }
  9173. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  9174. const nPlanes = planes !== null ? planes.length : 0;
  9175. let dstArray = null;
  9176. if (nPlanes !== 0) {
  9177. dstArray = uniform.value;
  9178. if (skipTransform !== true || dstArray === null) {
  9179. const flatSize = dstOffset + nPlanes * 4,
  9180. viewMatrix = camera.matrixWorldInverse;
  9181. viewNormalMatrix.getNormalMatrix(viewMatrix);
  9182. if (dstArray === null || dstArray.length < flatSize) {
  9183. dstArray = new Float32Array(flatSize);
  9184. }
  9185. for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  9186. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  9187. plane.normal.toArray(dstArray, i4);
  9188. dstArray[i4 + 3] = plane.constant;
  9189. }
  9190. }
  9191. uniform.value = dstArray;
  9192. uniform.needsUpdate = true;
  9193. }
  9194. scope.numPlanes = nPlanes;
  9195. scope.numIntersection = 0;
  9196. return dstArray;
  9197. }
  9198. }
  9199. function WebGLCubeMaps(renderer) {
  9200. let cubemaps = new WeakMap();
  9201. function mapTextureMapping(texture, mapping) {
  9202. if (mapping === EquirectangularReflectionMapping) {
  9203. texture.mapping = CubeReflectionMapping;
  9204. } else if (mapping === EquirectangularRefractionMapping) {
  9205. texture.mapping = CubeRefractionMapping;
  9206. }
  9207. return texture;
  9208. }
  9209. function get(texture) {
  9210. if (texture && texture.isTexture && texture.isRenderTargetTexture === false) {
  9211. const mapping = texture.mapping;
  9212. if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
  9213. if (cubemaps.has(texture)) {
  9214. const cubemap = cubemaps.get(texture).texture;
  9215. return mapTextureMapping(cubemap, texture.mapping);
  9216. } else {
  9217. const image = texture.image;
  9218. if (image && image.height > 0) {
  9219. const currentRenderTarget = renderer.getRenderTarget();
  9220. const renderTarget = new WebGLCubeRenderTarget(image.height / 2);
  9221. renderTarget.fromEquirectangularTexture(renderer, texture);
  9222. cubemaps.set(texture, renderTarget);
  9223. renderer.setRenderTarget(currentRenderTarget);
  9224. texture.addEventListener('dispose', onTextureDispose);
  9225. return mapTextureMapping(renderTarget.texture, texture.mapping);
  9226. } else {
  9227. // image not yet ready. try the conversion next frame
  9228. return null;
  9229. }
  9230. }
  9231. }
  9232. }
  9233. return texture;
  9234. }
  9235. function onTextureDispose(event) {
  9236. const texture = event.target;
  9237. texture.removeEventListener('dispose', onTextureDispose);
  9238. const cubemap = cubemaps.get(texture);
  9239. if (cubemap !== undefined) {
  9240. cubemaps.delete(texture);
  9241. cubemap.dispose();
  9242. }
  9243. }
  9244. function dispose() {
  9245. cubemaps = new WeakMap();
  9246. }
  9247. return {
  9248. get: get,
  9249. dispose: dispose
  9250. };
  9251. }
  9252. class OrthographicCamera extends Camera {
  9253. constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) {
  9254. super();
  9255. this.type = 'OrthographicCamera';
  9256. this.zoom = 1;
  9257. this.view = null;
  9258. this.left = left;
  9259. this.right = right;
  9260. this.top = top;
  9261. this.bottom = bottom;
  9262. this.near = near;
  9263. this.far = far;
  9264. this.updateProjectionMatrix();
  9265. }
  9266. copy(source, recursive) {
  9267. super.copy(source, recursive);
  9268. this.left = source.left;
  9269. this.right = source.right;
  9270. this.top = source.top;
  9271. this.bottom = source.bottom;
  9272. this.near = source.near;
  9273. this.far = source.far;
  9274. this.zoom = source.zoom;
  9275. this.view = source.view === null ? null : Object.assign({}, source.view);
  9276. return this;
  9277. }
  9278. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  9279. if (this.view === null) {
  9280. this.view = {
  9281. enabled: true,
  9282. fullWidth: 1,
  9283. fullHeight: 1,
  9284. offsetX: 0,
  9285. offsetY: 0,
  9286. width: 1,
  9287. height: 1
  9288. };
  9289. }
  9290. this.view.enabled = true;
  9291. this.view.fullWidth = fullWidth;
  9292. this.view.fullHeight = fullHeight;
  9293. this.view.offsetX = x;
  9294. this.view.offsetY = y;
  9295. this.view.width = width;
  9296. this.view.height = height;
  9297. this.updateProjectionMatrix();
  9298. }
  9299. clearViewOffset() {
  9300. if (this.view !== null) {
  9301. this.view.enabled = false;
  9302. }
  9303. this.updateProjectionMatrix();
  9304. }
  9305. updateProjectionMatrix() {
  9306. const dx = (this.right - this.left) / (2 * this.zoom);
  9307. const dy = (this.top - this.bottom) / (2 * this.zoom);
  9308. const cx = (this.right + this.left) / 2;
  9309. const cy = (this.top + this.bottom) / 2;
  9310. let left = cx - dx;
  9311. let right = cx + dx;
  9312. let top = cy + dy;
  9313. let bottom = cy - dy;
  9314. if (this.view !== null && this.view.enabled) {
  9315. const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  9316. const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  9317. left += scaleW * this.view.offsetX;
  9318. right = left + scaleW * this.view.width;
  9319. top -= scaleH * this.view.offsetY;
  9320. bottom = top - scaleH * this.view.height;
  9321. }
  9322. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  9323. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  9324. }
  9325. toJSON(meta) {
  9326. const data = super.toJSON(meta);
  9327. data.object.zoom = this.zoom;
  9328. data.object.left = this.left;
  9329. data.object.right = this.right;
  9330. data.object.top = this.top;
  9331. data.object.bottom = this.bottom;
  9332. data.object.near = this.near;
  9333. data.object.far = this.far;
  9334. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  9335. return data;
  9336. }
  9337. }
  9338. OrthographicCamera.prototype.isOrthographicCamera = true;
  9339. class RawShaderMaterial extends ShaderMaterial {
  9340. constructor(parameters) {
  9341. super(parameters);
  9342. this.type = 'RawShaderMaterial';
  9343. }
  9344. }
  9345. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  9346. const LOD_MIN = 4;
  9347. const LOD_MAX = 8;
  9348. const SIZE_MAX = Math.pow(2, LOD_MAX); // The standard deviations (radians) associated with the extra mips. These are
  9349. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9350. // geometric shadowing function. These sigma values squared must match the
  9351. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9352. const EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
  9353. 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
  9354. // samples and exit early, but not recompile the shader.
  9355. const MAX_SAMPLES = 20;
  9356. const ENCODINGS = {
  9357. [LinearEncoding]: 0,
  9358. [sRGBEncoding]: 1,
  9359. [RGBEEncoding]: 2,
  9360. [RGBM7Encoding]: 3,
  9361. [RGBM16Encoding]: 4,
  9362. [RGBDEncoding]: 5,
  9363. [GammaEncoding]: 6
  9364. };
  9365. const backgroundMaterial = new MeshBasicMaterial({
  9366. side: BackSide,
  9367. depthWrite: false,
  9368. depthTest: false
  9369. });
  9370. const backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial);
  9371. const _flatCamera = /*@__PURE__*/new OrthographicCamera();
  9372. const {
  9373. _lodPlanes,
  9374. _sizeLods,
  9375. _sigmas
  9376. } = /*@__PURE__*/_createPlanes();
  9377. const _clearColor = /*@__PURE__*/new Color();
  9378. let _oldTarget = null; // Golden Ratio
  9379. const PHI = (1 + Math.sqrt(5)) / 2;
  9380. const INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
  9381. // same axis), used as axis directions evenly spread on a sphere.
  9382. 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)];
  9383. /**
  9384. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9385. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9386. * blur to be quickly accessed based on material roughness. It is packed into a
  9387. * special CubeUV format that allows us to perform custom interpolation so that
  9388. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9389. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9390. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9391. * higher roughness levels. In this way we maintain resolution to smoothly
  9392. * interpolate diffuse lighting while limiting sampling computation.
  9393. *
  9394. * Paper: Fast, Accurate Image-Based Lighting
  9395. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9396. */
  9397. function convertLinearToRGBE(color) {
  9398. const maxComponent = Math.max(color.r, color.g, color.b);
  9399. const fExp = Math.min(Math.max(Math.ceil(Math.log2(maxComponent)), -128.0), 127.0);
  9400. color.multiplyScalar(Math.pow(2.0, -fExp));
  9401. const alpha = (fExp + 128.0) / 255.0;
  9402. return alpha;
  9403. }
  9404. class PMREMGenerator {
  9405. constructor(renderer) {
  9406. this._renderer = renderer;
  9407. this._pingPongRenderTarget = null;
  9408. this._blurMaterial = _getBlurShader(MAX_SAMPLES);
  9409. this._equirectShader = null;
  9410. this._cubemapShader = null;
  9411. this._compileMaterial(this._blurMaterial);
  9412. }
  9413. /**
  9414. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9415. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9416. * in radians to be applied to the scene before PMREM generation. Optional near
  9417. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9418. * is placed at the origin).
  9419. */
  9420. fromScene(scene, sigma = 0, near = 0.1, far = 100) {
  9421. _oldTarget = this._renderer.getRenderTarget();
  9422. const cubeUVRenderTarget = this._allocateTargets();
  9423. this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  9424. if (sigma > 0) {
  9425. this._blur(cubeUVRenderTarget, 0, 0, sigma);
  9426. }
  9427. this._applyPMREM(cubeUVRenderTarget);
  9428. this._cleanup(cubeUVRenderTarget);
  9429. return cubeUVRenderTarget;
  9430. }
  9431. /**
  9432. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9433. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  9434. * as this matches best with the 256 x 256 cubemap output.
  9435. */
  9436. fromEquirectangular(equirectangular) {
  9437. return this._fromTexture(equirectangular);
  9438. }
  9439. /**
  9440. * Generates a PMREM from an cubemap texture, which can be either LDR
  9441. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  9442. * as this matches best with the 256 x 256 cubemap output.
  9443. */
  9444. fromCubemap(cubemap) {
  9445. return this._fromTexture(cubemap);
  9446. }
  9447. /**
  9448. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9449. * your texture's network fetch for increased concurrency.
  9450. */
  9451. compileCubemapShader() {
  9452. if (this._cubemapShader === null) {
  9453. this._cubemapShader = _getCubemapShader();
  9454. this._compileMaterial(this._cubemapShader);
  9455. }
  9456. }
  9457. /**
  9458. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9459. * your texture's network fetch for increased concurrency.
  9460. */
  9461. compileEquirectangularShader() {
  9462. if (this._equirectShader === null) {
  9463. this._equirectShader = _getEquirectShader();
  9464. this._compileMaterial(this._equirectShader);
  9465. }
  9466. }
  9467. /**
  9468. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9469. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9470. * one of them will cause any others to also become unusable.
  9471. */
  9472. dispose() {
  9473. this._blurMaterial.dispose();
  9474. if (this._cubemapShader !== null) this._cubemapShader.dispose();
  9475. if (this._equirectShader !== null) this._equirectShader.dispose();
  9476. for (let i = 0; i < _lodPlanes.length; i++) {
  9477. _lodPlanes[i].dispose();
  9478. }
  9479. } // private interface
  9480. _cleanup(outputTarget) {
  9481. this._pingPongRenderTarget.dispose();
  9482. this._renderer.setRenderTarget(_oldTarget);
  9483. outputTarget.scissorTest = false;
  9484. _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
  9485. }
  9486. _fromTexture(texture) {
  9487. _oldTarget = this._renderer.getRenderTarget();
  9488. const cubeUVRenderTarget = this._allocateTargets(texture);
  9489. this._textureToCubeUV(texture, cubeUVRenderTarget);
  9490. this._applyPMREM(cubeUVRenderTarget);
  9491. this._cleanup(cubeUVRenderTarget);
  9492. return cubeUVRenderTarget;
  9493. }
  9494. _allocateTargets(texture) {
  9495. // warning: null texture is valid
  9496. const params = {
  9497. magFilter: NearestFilter,
  9498. minFilter: NearestFilter,
  9499. generateMipmaps: false,
  9500. type: UnsignedByteType,
  9501. format: RGBEFormat,
  9502. encoding: _isLDR(texture) ? texture.encoding : RGBEEncoding,
  9503. depthBuffer: false
  9504. };
  9505. const cubeUVRenderTarget = _createRenderTarget(params);
  9506. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  9507. this._pingPongRenderTarget = _createRenderTarget(params);
  9508. return cubeUVRenderTarget;
  9509. }
  9510. _compileMaterial(material) {
  9511. const tmpMesh = new Mesh(_lodPlanes[0], material);
  9512. this._renderer.compile(tmpMesh, _flatCamera);
  9513. }
  9514. _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  9515. const fov = 90;
  9516. const aspect = 1;
  9517. const cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  9518. const upSign = [1, -1, 1, 1, 1, 1];
  9519. const forwardSign = [1, 1, 1, -1, -1, -1];
  9520. const renderer = this._renderer;
  9521. const originalAutoClear = renderer.autoClear;
  9522. const outputEncoding = renderer.outputEncoding;
  9523. const toneMapping = renderer.toneMapping;
  9524. renderer.getClearColor(_clearColor);
  9525. renderer.toneMapping = NoToneMapping;
  9526. renderer.outputEncoding = LinearEncoding;
  9527. renderer.autoClear = false;
  9528. let useSolidColor = false;
  9529. const background = scene.background;
  9530. if (background) {
  9531. if (background.isColor) {
  9532. backgroundMaterial.color.copy(background).convertSRGBToLinear();
  9533. scene.background = null;
  9534. const alpha = convertLinearToRGBE(backgroundMaterial.color);
  9535. backgroundMaterial.opacity = alpha;
  9536. useSolidColor = true;
  9537. }
  9538. } else {
  9539. backgroundMaterial.color.copy(_clearColor).convertSRGBToLinear();
  9540. const alpha = convertLinearToRGBE(backgroundMaterial.color);
  9541. backgroundMaterial.opacity = alpha;
  9542. useSolidColor = true;
  9543. }
  9544. for (let i = 0; i < 6; i++) {
  9545. const col = i % 3;
  9546. if (col == 0) {
  9547. cubeCamera.up.set(0, upSign[i], 0);
  9548. cubeCamera.lookAt(forwardSign[i], 0, 0);
  9549. } else if (col == 1) {
  9550. cubeCamera.up.set(0, 0, upSign[i]);
  9551. cubeCamera.lookAt(0, forwardSign[i], 0);
  9552. } else {
  9553. cubeCamera.up.set(0, upSign[i], 0);
  9554. cubeCamera.lookAt(0, 0, forwardSign[i]);
  9555. }
  9556. _setViewport(cubeUVRenderTarget, col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX);
  9557. renderer.setRenderTarget(cubeUVRenderTarget);
  9558. if (useSolidColor) {
  9559. renderer.render(backgroundBox, cubeCamera);
  9560. }
  9561. renderer.render(scene, cubeCamera);
  9562. }
  9563. renderer.toneMapping = toneMapping;
  9564. renderer.outputEncoding = outputEncoding;
  9565. renderer.autoClear = originalAutoClear;
  9566. }
  9567. _textureToCubeUV(texture, cubeUVRenderTarget) {
  9568. const renderer = this._renderer;
  9569. if (texture.isCubeTexture) {
  9570. if (this._cubemapShader == null) {
  9571. this._cubemapShader = _getCubemapShader();
  9572. }
  9573. } else {
  9574. if (this._equirectShader == null) {
  9575. this._equirectShader = _getEquirectShader();
  9576. }
  9577. }
  9578. const material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  9579. const mesh = new Mesh(_lodPlanes[0], material);
  9580. const uniforms = material.uniforms;
  9581. uniforms['envMap'].value = texture;
  9582. if (!texture.isCubeTexture) {
  9583. uniforms['texelSize'].value.set(1.0 / texture.image.width, 1.0 / texture.image.height);
  9584. }
  9585. uniforms['inputEncoding'].value = ENCODINGS[texture.encoding];
  9586. uniforms['outputEncoding'].value = ENCODINGS[cubeUVRenderTarget.texture.encoding];
  9587. _setViewport(cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX);
  9588. renderer.setRenderTarget(cubeUVRenderTarget);
  9589. renderer.render(mesh, _flatCamera);
  9590. }
  9591. _applyPMREM(cubeUVRenderTarget) {
  9592. const renderer = this._renderer;
  9593. const autoClear = renderer.autoClear;
  9594. renderer.autoClear = false;
  9595. for (let i = 1; i < TOTAL_LODS; i++) {
  9596. const sigma = Math.sqrt(_sigmas[i] * _sigmas[i] - _sigmas[i - 1] * _sigmas[i - 1]);
  9597. const poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  9598. this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  9599. }
  9600. renderer.autoClear = autoClear;
  9601. }
  9602. /**
  9603. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9604. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9605. * the blur latitudinally (around the poles), and then longitudinally (towards
  9606. * the poles) to approximate the orthogonally-separable blur. It is least
  9607. * accurate at the poles, but still does a decent job.
  9608. */
  9609. _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  9610. const pingPongRenderTarget = this._pingPongRenderTarget;
  9611. this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  9612. this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  9613. }
  9614. _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  9615. const renderer = this._renderer;
  9616. const blurMaterial = this._blurMaterial;
  9617. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  9618. console.error('blur direction must be either latitudinal or longitudinal!');
  9619. } // Number of standard deviations at which to cut off the discrete approximation.
  9620. const STANDARD_DEVIATIONS = 3;
  9621. const blurMesh = new Mesh(_lodPlanes[lodOut], blurMaterial);
  9622. const blurUniforms = blurMaterial.uniforms;
  9623. const pixels = _sizeLods[lodIn] - 1;
  9624. const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  9625. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9626. const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  9627. if (samples > MAX_SAMPLES) {
  9628. console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
  9629. }
  9630. const weights = [];
  9631. let sum = 0;
  9632. for (let i = 0; i < MAX_SAMPLES; ++i) {
  9633. const x = i / sigmaPixels;
  9634. const weight = Math.exp(-x * x / 2);
  9635. weights.push(weight);
  9636. if (i == 0) {
  9637. sum += weight;
  9638. } else if (i < samples) {
  9639. sum += 2 * weight;
  9640. }
  9641. }
  9642. for (let i = 0; i < weights.length; i++) {
  9643. weights[i] = weights[i] / sum;
  9644. }
  9645. blurUniforms['envMap'].value = targetIn.texture;
  9646. blurUniforms['samples'].value = samples;
  9647. blurUniforms['weights'].value = weights;
  9648. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  9649. if (poleAxis) {
  9650. blurUniforms['poleAxis'].value = poleAxis;
  9651. }
  9652. blurUniforms['dTheta'].value = radiansPerPixel;
  9653. blurUniforms['mipInt'].value = LOD_MAX - lodIn;
  9654. blurUniforms['inputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  9655. blurUniforms['outputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  9656. const outputSize = _sizeLods[lodOut];
  9657. const x = 3 * Math.max(0, SIZE_MAX - 2 * outputSize);
  9658. const y = (lodOut === 0 ? 0 : 2 * SIZE_MAX) + 2 * outputSize * (lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0);
  9659. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  9660. renderer.setRenderTarget(targetOut);
  9661. renderer.render(blurMesh, _flatCamera);
  9662. }
  9663. }
  9664. function _isLDR(texture) {
  9665. if (texture === undefined || texture.type !== UnsignedByteType) return false;
  9666. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  9667. }
  9668. function _createPlanes() {
  9669. const _lodPlanes = [];
  9670. const _sizeLods = [];
  9671. const _sigmas = [];
  9672. let lod = LOD_MAX;
  9673. for (let i = 0; i < TOTAL_LODS; i++) {
  9674. const sizeLod = Math.pow(2, lod);
  9675. _sizeLods.push(sizeLod);
  9676. let sigma = 1.0 / sizeLod;
  9677. if (i > LOD_MAX - LOD_MIN) {
  9678. sigma = EXTRA_LOD_SIGMA[i - LOD_MAX + LOD_MIN - 1];
  9679. } else if (i == 0) {
  9680. sigma = 0;
  9681. }
  9682. _sigmas.push(sigma);
  9683. const texelSize = 1.0 / (sizeLod - 1);
  9684. const min = -texelSize / 2;
  9685. const max = 1 + texelSize / 2;
  9686. const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  9687. const cubeFaces = 6;
  9688. const vertices = 6;
  9689. const positionSize = 3;
  9690. const uvSize = 2;
  9691. const faceIndexSize = 1;
  9692. const position = new Float32Array(positionSize * vertices * cubeFaces);
  9693. const uv = new Float32Array(uvSize * vertices * cubeFaces);
  9694. const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  9695. for (let face = 0; face < cubeFaces; face++) {
  9696. const x = face % 3 * 2 / 3 - 1;
  9697. const y = face > 2 ? 0 : -1;
  9698. 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];
  9699. position.set(coordinates, positionSize * vertices * face);
  9700. uv.set(uv1, uvSize * vertices * face);
  9701. const fill = [face, face, face, face, face, face];
  9702. faceIndex.set(fill, faceIndexSize * vertices * face);
  9703. }
  9704. const planes = new BufferGeometry();
  9705. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  9706. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  9707. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  9708. _lodPlanes.push(planes);
  9709. if (lod > LOD_MIN) {
  9710. lod--;
  9711. }
  9712. }
  9713. return {
  9714. _lodPlanes,
  9715. _sizeLods,
  9716. _sigmas
  9717. };
  9718. }
  9719. function _createRenderTarget(params) {
  9720. const cubeUVRenderTarget = new WebGLRenderTarget(3 * SIZE_MAX, 3 * SIZE_MAX, params);
  9721. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9722. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9723. cubeUVRenderTarget.scissorTest = true;
  9724. return cubeUVRenderTarget;
  9725. }
  9726. function _setViewport(target, x, y, width, height) {
  9727. target.viewport.set(x, y, width, height);
  9728. target.scissor.set(x, y, width, height);
  9729. }
  9730. function _getBlurShader(maxSamples) {
  9731. const weights = new Float32Array(maxSamples);
  9732. const poleAxis = new Vector3(0, 1, 0);
  9733. const shaderMaterial = new RawShaderMaterial({
  9734. name: 'SphericalGaussianBlur',
  9735. defines: {
  9736. 'n': maxSamples
  9737. },
  9738. uniforms: {
  9739. 'envMap': {
  9740. value: null
  9741. },
  9742. 'samples': {
  9743. value: 1
  9744. },
  9745. 'weights': {
  9746. value: weights
  9747. },
  9748. 'latitudinal': {
  9749. value: false
  9750. },
  9751. 'dTheta': {
  9752. value: 0
  9753. },
  9754. 'mipInt': {
  9755. value: 0
  9756. },
  9757. 'poleAxis': {
  9758. value: poleAxis
  9759. },
  9760. 'inputEncoding': {
  9761. value: ENCODINGS[LinearEncoding]
  9762. },
  9763. 'outputEncoding': {
  9764. value: ENCODINGS[LinearEncoding]
  9765. }
  9766. },
  9767. vertexShader: _getCommonVertexShader(),
  9768. fragmentShader:
  9769. /* glsl */
  9770. `
  9771. precision mediump float;
  9772. precision mediump int;
  9773. varying vec3 vOutputDirection;
  9774. uniform sampler2D envMap;
  9775. uniform int samples;
  9776. uniform float weights[ n ];
  9777. uniform bool latitudinal;
  9778. uniform float dTheta;
  9779. uniform float mipInt;
  9780. uniform vec3 poleAxis;
  9781. ${_getEncodings()}
  9782. #define ENVMAP_TYPE_CUBE_UV
  9783. #include <cube_uv_reflection_fragment>
  9784. vec3 getSample( float theta, vec3 axis ) {
  9785. float cosTheta = cos( theta );
  9786. // Rodrigues' axis-angle rotation
  9787. vec3 sampleDirection = vOutputDirection * cosTheta
  9788. + cross( axis, vOutputDirection ) * sin( theta )
  9789. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9790. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  9791. }
  9792. void main() {
  9793. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  9794. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  9795. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  9796. }
  9797. axis = normalize( axis );
  9798. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9799. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  9800. for ( int i = 1; i < n; i++ ) {
  9801. if ( i >= samples ) {
  9802. break;
  9803. }
  9804. float theta = dTheta * float( i );
  9805. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  9806. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  9807. }
  9808. gl_FragColor = linearToOutputTexel( gl_FragColor );
  9809. }
  9810. `,
  9811. blending: NoBlending,
  9812. depthTest: false,
  9813. depthWrite: false
  9814. });
  9815. return shaderMaterial;
  9816. }
  9817. function _getEquirectShader() {
  9818. const texelSize = new Vector2(1, 1);
  9819. const shaderMaterial = new RawShaderMaterial({
  9820. name: 'EquirectangularToCubeUV',
  9821. uniforms: {
  9822. 'envMap': {
  9823. value: null
  9824. },
  9825. 'texelSize': {
  9826. value: texelSize
  9827. },
  9828. 'inputEncoding': {
  9829. value: ENCODINGS[LinearEncoding]
  9830. },
  9831. 'outputEncoding': {
  9832. value: ENCODINGS[LinearEncoding]
  9833. }
  9834. },
  9835. vertexShader: _getCommonVertexShader(),
  9836. fragmentShader:
  9837. /* glsl */
  9838. `
  9839. precision mediump float;
  9840. precision mediump int;
  9841. varying vec3 vOutputDirection;
  9842. uniform sampler2D envMap;
  9843. uniform vec2 texelSize;
  9844. ${_getEncodings()}
  9845. #include <common>
  9846. void main() {
  9847. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9848. vec3 outputDirection = normalize( vOutputDirection );
  9849. vec2 uv = equirectUv( outputDirection );
  9850. vec2 f = fract( uv / texelSize - 0.5 );
  9851. uv -= f * texelSize;
  9852. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9853. uv.x += texelSize.x;
  9854. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9855. uv.y += texelSize.y;
  9856. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9857. uv.x -= texelSize.x;
  9858. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9859. vec3 tm = mix( tl, tr, f.x );
  9860. vec3 bm = mix( bl, br, f.x );
  9861. gl_FragColor.rgb = mix( tm, bm, f.y );
  9862. gl_FragColor = linearToOutputTexel( gl_FragColor );
  9863. }
  9864. `,
  9865. blending: NoBlending,
  9866. depthTest: false,
  9867. depthWrite: false
  9868. });
  9869. return shaderMaterial;
  9870. }
  9871. function _getCubemapShader() {
  9872. const shaderMaterial = new RawShaderMaterial({
  9873. name: 'CubemapToCubeUV',
  9874. uniforms: {
  9875. 'envMap': {
  9876. value: null
  9877. },
  9878. 'inputEncoding': {
  9879. value: ENCODINGS[LinearEncoding]
  9880. },
  9881. 'outputEncoding': {
  9882. value: ENCODINGS[LinearEncoding]
  9883. }
  9884. },
  9885. vertexShader: _getCommonVertexShader(),
  9886. fragmentShader:
  9887. /* glsl */
  9888. `
  9889. precision mediump float;
  9890. precision mediump int;
  9891. varying vec3 vOutputDirection;
  9892. uniform samplerCube envMap;
  9893. ${_getEncodings()}
  9894. void main() {
  9895. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9896. gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;
  9897. gl_FragColor = linearToOutputTexel( gl_FragColor );
  9898. }
  9899. `,
  9900. blending: NoBlending,
  9901. depthTest: false,
  9902. depthWrite: false
  9903. });
  9904. return shaderMaterial;
  9905. }
  9906. function _getCommonVertexShader() {
  9907. return (
  9908. /* glsl */
  9909. `
  9910. precision mediump float;
  9911. precision mediump int;
  9912. attribute vec3 position;
  9913. attribute vec2 uv;
  9914. attribute float faceIndex;
  9915. varying vec3 vOutputDirection;
  9916. // RH coordinate system; PMREM face-indexing convention
  9917. vec3 getDirection( vec2 uv, float face ) {
  9918. uv = 2.0 * uv - 1.0;
  9919. vec3 direction = vec3( uv, 1.0 );
  9920. if ( face == 0.0 ) {
  9921. direction = direction.zyx; // ( 1, v, u ) pos x
  9922. } else if ( face == 1.0 ) {
  9923. direction = direction.xzy;
  9924. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  9925. } else if ( face == 2.0 ) {
  9926. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  9927. } else if ( face == 3.0 ) {
  9928. direction = direction.zyx;
  9929. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  9930. } else if ( face == 4.0 ) {
  9931. direction = direction.xzy;
  9932. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  9933. } else if ( face == 5.0 ) {
  9934. direction.z *= -1.0; // ( u, v, -1 ) neg z
  9935. }
  9936. return direction;
  9937. }
  9938. void main() {
  9939. vOutputDirection = getDirection( uv, faceIndex );
  9940. gl_Position = vec4( position, 1.0 );
  9941. }
  9942. `
  9943. );
  9944. }
  9945. function _getEncodings() {
  9946. return (
  9947. /* glsl */
  9948. `
  9949. uniform int inputEncoding;
  9950. uniform int outputEncoding;
  9951. #include <encodings_pars_fragment>
  9952. vec4 inputTexelToLinear( vec4 value ) {
  9953. if ( inputEncoding == 0 ) {
  9954. return value;
  9955. } else if ( inputEncoding == 1 ) {
  9956. return sRGBToLinear( value );
  9957. } else if ( inputEncoding == 2 ) {
  9958. return RGBEToLinear( value );
  9959. } else if ( inputEncoding == 3 ) {
  9960. return RGBMToLinear( value, 7.0 );
  9961. } else if ( inputEncoding == 4 ) {
  9962. return RGBMToLinear( value, 16.0 );
  9963. } else if ( inputEncoding == 5 ) {
  9964. return RGBDToLinear( value, 256.0 );
  9965. } else {
  9966. return GammaToLinear( value, 2.2 );
  9967. }
  9968. }
  9969. vec4 linearToOutputTexel( vec4 value ) {
  9970. if ( outputEncoding == 0 ) {
  9971. return value;
  9972. } else if ( outputEncoding == 1 ) {
  9973. return LinearTosRGB( value );
  9974. } else if ( outputEncoding == 2 ) {
  9975. return LinearToRGBE( value );
  9976. } else if ( outputEncoding == 3 ) {
  9977. return LinearToRGBM( value, 7.0 );
  9978. } else if ( outputEncoding == 4 ) {
  9979. return LinearToRGBM( value, 16.0 );
  9980. } else if ( outputEncoding == 5 ) {
  9981. return LinearToRGBD( value, 256.0 );
  9982. } else {
  9983. return LinearToGamma( value, 2.2 );
  9984. }
  9985. }
  9986. vec4 envMapTexelToLinear( vec4 color ) {
  9987. return inputTexelToLinear( color );
  9988. }
  9989. `
  9990. );
  9991. }
  9992. function WebGLCubeUVMaps(renderer) {
  9993. let cubeUVmaps = new WeakMap();
  9994. let pmremGenerator = null;
  9995. function get(texture) {
  9996. if (texture && texture.isTexture && texture.isRenderTargetTexture === false) {
  9997. const mapping = texture.mapping;
  9998. const isEquirectMap = mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping;
  9999. const isCubeMap = mapping === CubeReflectionMapping || mapping === CubeRefractionMapping;
  10000. if (isEquirectMap || isCubeMap) {
  10001. // equirect/cube map to cubeUV conversion
  10002. if (cubeUVmaps.has(texture)) {
  10003. return cubeUVmaps.get(texture).texture;
  10004. } else {
  10005. const image = texture.image;
  10006. if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) {
  10007. const currentRenderTarget = renderer.getRenderTarget();
  10008. if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer);
  10009. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture);
  10010. cubeUVmaps.set(texture, renderTarget);
  10011. renderer.setRenderTarget(currentRenderTarget);
  10012. texture.addEventListener('dispose', onTextureDispose);
  10013. return renderTarget.texture;
  10014. } else {
  10015. // image not yet ready. try the conversion next frame
  10016. return null;
  10017. }
  10018. }
  10019. }
  10020. }
  10021. return texture;
  10022. }
  10023. function isCubeTextureComplete(image) {
  10024. let count = 0;
  10025. const length = 6;
  10026. for (let i = 0; i < length; i++) {
  10027. if (image[i] !== undefined) count++;
  10028. }
  10029. return count === length;
  10030. }
  10031. function onTextureDispose(event) {
  10032. const texture = event.target;
  10033. texture.removeEventListener('dispose', onTextureDispose);
  10034. const cubemapUV = cubeUVmaps.get(texture);
  10035. if (cubemapUV !== undefined) {
  10036. cubemapUV.delete(texture);
  10037. cubemapUV.dispose();
  10038. }
  10039. }
  10040. function dispose() {
  10041. cubeUVmaps = new WeakMap();
  10042. if (pmremGenerator !== null) {
  10043. pmremGenerator.dispose();
  10044. pmremGenerator = null;
  10045. }
  10046. }
  10047. return {
  10048. get: get,
  10049. dispose: dispose
  10050. };
  10051. }
  10052. function WebGLExtensions(gl) {
  10053. const extensions = {};
  10054. function getExtension(name) {
  10055. if (extensions[name] !== undefined) {
  10056. return extensions[name];
  10057. }
  10058. let extension;
  10059. switch (name) {
  10060. case 'WEBGL_depth_texture':
  10061. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  10062. break;
  10063. case 'EXT_texture_filter_anisotropic':
  10064. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  10065. break;
  10066. case 'WEBGL_compressed_texture_s3tc':
  10067. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10068. break;
  10069. case 'WEBGL_compressed_texture_pvrtc':
  10070. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10071. break;
  10072. default:
  10073. extension = gl.getExtension(name);
  10074. }
  10075. extensions[name] = extension;
  10076. return extension;
  10077. }
  10078. return {
  10079. has: function (name) {
  10080. return getExtension(name) !== null;
  10081. },
  10082. init: function (capabilities) {
  10083. if (capabilities.isWebGL2) {
  10084. getExtension('EXT_color_buffer_float');
  10085. } else {
  10086. getExtension('WEBGL_depth_texture');
  10087. getExtension('OES_texture_float');
  10088. getExtension('OES_texture_half_float');
  10089. getExtension('OES_texture_half_float_linear');
  10090. getExtension('OES_standard_derivatives');
  10091. getExtension('OES_element_index_uint');
  10092. getExtension('OES_vertex_array_object');
  10093. getExtension('ANGLE_instanced_arrays');
  10094. }
  10095. getExtension('OES_texture_float_linear');
  10096. getExtension('EXT_color_buffer_half_float');
  10097. },
  10098. get: function (name) {
  10099. const extension = getExtension(name);
  10100. if (extension === null) {
  10101. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  10102. }
  10103. return extension;
  10104. }
  10105. };
  10106. }
  10107. function WebGLGeometries(gl, attributes, info, bindingStates) {
  10108. const geometries = {};
  10109. const wireframeAttributes = new WeakMap();
  10110. function onGeometryDispose(event) {
  10111. const geometry = event.target;
  10112. if (geometry.index !== null) {
  10113. attributes.remove(geometry.index);
  10114. }
  10115. for (const name in geometry.attributes) {
  10116. attributes.remove(geometry.attributes[name]);
  10117. }
  10118. geometry.removeEventListener('dispose', onGeometryDispose);
  10119. delete geometries[geometry.id];
  10120. const attribute = wireframeAttributes.get(geometry);
  10121. if (attribute) {
  10122. attributes.remove(attribute);
  10123. wireframeAttributes.delete(geometry);
  10124. }
  10125. bindingStates.releaseStatesOfGeometry(geometry);
  10126. if (geometry.isInstancedBufferGeometry === true) {
  10127. delete geometry._maxInstanceCount;
  10128. } //
  10129. info.memory.geometries--;
  10130. }
  10131. function get(object, geometry) {
  10132. if (geometries[geometry.id] === true) return geometry;
  10133. geometry.addEventListener('dispose', onGeometryDispose);
  10134. geometries[geometry.id] = true;
  10135. info.memory.geometries++;
  10136. return geometry;
  10137. }
  10138. function update(geometry) {
  10139. const geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates.
  10140. for (const name in geometryAttributes) {
  10141. attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER);
  10142. } // morph targets
  10143. const morphAttributes = geometry.morphAttributes;
  10144. for (const name in morphAttributes) {
  10145. const array = morphAttributes[name];
  10146. for (let i = 0, l = array.length; i < l; i++) {
  10147. attributes.update(array[i], gl.ARRAY_BUFFER);
  10148. }
  10149. }
  10150. }
  10151. function updateWireframeAttribute(geometry) {
  10152. const indices = [];
  10153. const geometryIndex = geometry.index;
  10154. const geometryPosition = geometry.attributes.position;
  10155. let version = 0;
  10156. if (geometryIndex !== null) {
  10157. const array = geometryIndex.array;
  10158. version = geometryIndex.version;
  10159. for (let i = 0, l = array.length; i < l; i += 3) {
  10160. const a = array[i + 0];
  10161. const b = array[i + 1];
  10162. const c = array[i + 2];
  10163. indices.push(a, b, b, c, c, a);
  10164. }
  10165. } else {
  10166. const array = geometryPosition.array;
  10167. version = geometryPosition.version;
  10168. for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  10169. const a = i + 0;
  10170. const b = i + 1;
  10171. const c = i + 2;
  10172. indices.push(a, b, b, c, c, a);
  10173. }
  10174. }
  10175. const attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  10176. attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
  10177. //
  10178. const previousAttribute = wireframeAttributes.get(geometry);
  10179. if (previousAttribute) attributes.remove(previousAttribute); //
  10180. wireframeAttributes.set(geometry, attribute);
  10181. }
  10182. function getWireframeAttribute(geometry) {
  10183. const currentAttribute = wireframeAttributes.get(geometry);
  10184. if (currentAttribute) {
  10185. const geometryIndex = geometry.index;
  10186. if (geometryIndex !== null) {
  10187. // if the attribute is obsolete, create a new one
  10188. if (currentAttribute.version < geometryIndex.version) {
  10189. updateWireframeAttribute(geometry);
  10190. }
  10191. }
  10192. } else {
  10193. updateWireframeAttribute(geometry);
  10194. }
  10195. return wireframeAttributes.get(geometry);
  10196. }
  10197. return {
  10198. get: get,
  10199. update: update,
  10200. getWireframeAttribute: getWireframeAttribute
  10201. };
  10202. }
  10203. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  10204. const isWebGL2 = capabilities.isWebGL2;
  10205. let mode;
  10206. function setMode(value) {
  10207. mode = value;
  10208. }
  10209. let type, bytesPerElement;
  10210. function setIndex(value) {
  10211. type = value.type;
  10212. bytesPerElement = value.bytesPerElement;
  10213. }
  10214. function render(start, count) {
  10215. gl.drawElements(mode, count, type, start * bytesPerElement);
  10216. info.update(count, mode, 1);
  10217. }
  10218. function renderInstances(start, count, primcount) {
  10219. if (primcount === 0) return;
  10220. let extension, methodName;
  10221. if (isWebGL2) {
  10222. extension = gl;
  10223. methodName = 'drawElementsInstanced';
  10224. } else {
  10225. extension = extensions.get('ANGLE_instanced_arrays');
  10226. methodName = 'drawElementsInstancedANGLE';
  10227. if (extension === null) {
  10228. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  10229. return;
  10230. }
  10231. }
  10232. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  10233. info.update(count, mode, primcount);
  10234. } //
  10235. this.setMode = setMode;
  10236. this.setIndex = setIndex;
  10237. this.render = render;
  10238. this.renderInstances = renderInstances;
  10239. }
  10240. function WebGLInfo(gl) {
  10241. const memory = {
  10242. geometries: 0,
  10243. textures: 0
  10244. };
  10245. const render = {
  10246. frame: 0,
  10247. calls: 0,
  10248. triangles: 0,
  10249. points: 0,
  10250. lines: 0
  10251. };
  10252. function update(count, mode, instanceCount) {
  10253. render.calls++;
  10254. switch (mode) {
  10255. case gl.TRIANGLES:
  10256. render.triangles += instanceCount * (count / 3);
  10257. break;
  10258. case gl.LINES:
  10259. render.lines += instanceCount * (count / 2);
  10260. break;
  10261. case gl.LINE_STRIP:
  10262. render.lines += instanceCount * (count - 1);
  10263. break;
  10264. case gl.LINE_LOOP:
  10265. render.lines += instanceCount * count;
  10266. break;
  10267. case gl.POINTS:
  10268. render.points += instanceCount * count;
  10269. break;
  10270. default:
  10271. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  10272. break;
  10273. }
  10274. }
  10275. function reset() {
  10276. render.frame++;
  10277. render.calls = 0;
  10278. render.triangles = 0;
  10279. render.points = 0;
  10280. render.lines = 0;
  10281. }
  10282. return {
  10283. memory: memory,
  10284. render: render,
  10285. programs: null,
  10286. autoReset: true,
  10287. reset: reset,
  10288. update: update
  10289. };
  10290. }
  10291. function numericalSort(a, b) {
  10292. return a[0] - b[0];
  10293. }
  10294. function absNumericalSort(a, b) {
  10295. return Math.abs(b[1]) - Math.abs(a[1]);
  10296. }
  10297. function WebGLMorphtargets(gl) {
  10298. const influencesList = {};
  10299. const morphInfluences = new Float32Array(8);
  10300. const workInfluences = [];
  10301. for (let i = 0; i < 8; i++) {
  10302. workInfluences[i] = [i, 0];
  10303. }
  10304. function update(object, geometry, material, program) {
  10305. const objectInfluences = object.morphTargetInfluences; // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10306. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10307. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10308. let influences = influencesList[geometry.id];
  10309. if (influences === undefined || influences.length !== length) {
  10310. // initialise list
  10311. influences = [];
  10312. for (let i = 0; i < length; i++) {
  10313. influences[i] = [i, 0];
  10314. }
  10315. influencesList[geometry.id] = influences;
  10316. } // Collect influences
  10317. for (let i = 0; i < length; i++) {
  10318. const influence = influences[i];
  10319. influence[0] = i;
  10320. influence[1] = objectInfluences[i];
  10321. }
  10322. influences.sort(absNumericalSort);
  10323. for (let i = 0; i < 8; i++) {
  10324. if (i < length && influences[i][1]) {
  10325. workInfluences[i][0] = influences[i][0];
  10326. workInfluences[i][1] = influences[i][1];
  10327. } else {
  10328. workInfluences[i][0] = Number.MAX_SAFE_INTEGER;
  10329. workInfluences[i][1] = 0;
  10330. }
  10331. }
  10332. workInfluences.sort(numericalSort);
  10333. const morphTargets = geometry.morphAttributes.position;
  10334. const morphNormals = geometry.morphAttributes.normal;
  10335. let morphInfluencesSum = 0;
  10336. for (let i = 0; i < 8; i++) {
  10337. const influence = workInfluences[i];
  10338. const index = influence[0];
  10339. const value = influence[1];
  10340. if (index !== Number.MAX_SAFE_INTEGER && value) {
  10341. if (morphTargets && geometry.getAttribute('morphTarget' + i) !== morphTargets[index]) {
  10342. geometry.setAttribute('morphTarget' + i, morphTargets[index]);
  10343. }
  10344. if (morphNormals && geometry.getAttribute('morphNormal' + i) !== morphNormals[index]) {
  10345. geometry.setAttribute('morphNormal' + i, morphNormals[index]);
  10346. }
  10347. morphInfluences[i] = value;
  10348. morphInfluencesSum += value;
  10349. } else {
  10350. if (morphTargets && geometry.hasAttribute('morphTarget' + i) === true) {
  10351. geometry.deleteAttribute('morphTarget' + i);
  10352. }
  10353. if (morphNormals && geometry.hasAttribute('morphNormal' + i) === true) {
  10354. geometry.deleteAttribute('morphNormal' + i);
  10355. }
  10356. morphInfluences[i] = 0;
  10357. }
  10358. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10359. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10360. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10361. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10362. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10363. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  10364. }
  10365. return {
  10366. update: update
  10367. };
  10368. }
  10369. function WebGLObjects(gl, geometries, attributes, info) {
  10370. let updateMap = new WeakMap();
  10371. function update(object) {
  10372. const frame = info.render.frame;
  10373. const geometry = object.geometry;
  10374. const buffergeometry = geometries.get(object, geometry); // Update once per frame
  10375. if (updateMap.get(buffergeometry) !== frame) {
  10376. geometries.update(buffergeometry);
  10377. updateMap.set(buffergeometry, frame);
  10378. }
  10379. if (object.isInstancedMesh) {
  10380. if (object.hasEventListener('dispose', onInstancedMeshDispose) === false) {
  10381. object.addEventListener('dispose', onInstancedMeshDispose);
  10382. }
  10383. attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER);
  10384. if (object.instanceColor !== null) {
  10385. attributes.update(object.instanceColor, gl.ARRAY_BUFFER);
  10386. }
  10387. }
  10388. return buffergeometry;
  10389. }
  10390. function dispose() {
  10391. updateMap = new WeakMap();
  10392. }
  10393. function onInstancedMeshDispose(event) {
  10394. const instancedMesh = event.target;
  10395. instancedMesh.removeEventListener('dispose', onInstancedMeshDispose);
  10396. attributes.remove(instancedMesh.instanceMatrix);
  10397. if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor);
  10398. }
  10399. return {
  10400. update: update,
  10401. dispose: dispose
  10402. };
  10403. }
  10404. class DataTexture2DArray extends Texture {
  10405. constructor(data = null, width = 1, height = 1, depth = 1) {
  10406. super(null);
  10407. this.image = {
  10408. data,
  10409. width,
  10410. height,
  10411. depth
  10412. };
  10413. this.magFilter = NearestFilter;
  10414. this.minFilter = NearestFilter;
  10415. this.wrapR = ClampToEdgeWrapping;
  10416. this.generateMipmaps = false;
  10417. this.flipY = false;
  10418. this.unpackAlignment = 1;
  10419. this.needsUpdate = true;
  10420. }
  10421. }
  10422. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  10423. class DataTexture3D extends Texture {
  10424. constructor(data = null, width = 1, height = 1, depth = 1) {
  10425. // We're going to add .setXXX() methods for setting properties later.
  10426. // Users can still set in DataTexture3D directly.
  10427. //
  10428. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  10429. // texture.anisotropy = 16;
  10430. //
  10431. // See #14839
  10432. super(null);
  10433. this.image = {
  10434. data,
  10435. width,
  10436. height,
  10437. depth
  10438. };
  10439. this.magFilter = NearestFilter;
  10440. this.minFilter = NearestFilter;
  10441. this.wrapR = ClampToEdgeWrapping;
  10442. this.generateMipmaps = false;
  10443. this.flipY = false;
  10444. this.unpackAlignment = 1;
  10445. this.needsUpdate = true;
  10446. }
  10447. }
  10448. DataTexture3D.prototype.isDataTexture3D = true;
  10449. /**
  10450. * Uniforms of a program.
  10451. * Those form a tree structure with a special top-level container for the root,
  10452. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10453. *
  10454. *
  10455. * Properties of inner nodes including the top-level container:
  10456. *
  10457. * .seq - array of nested uniforms
  10458. * .map - nested uniforms by name
  10459. *
  10460. *
  10461. * Methods of all nodes except the top-level container:
  10462. *
  10463. * .setValue( gl, value, [textures] )
  10464. *
  10465. * uploads a uniform value(s)
  10466. * the 'textures' parameter is needed for sampler uniforms
  10467. *
  10468. *
  10469. * Static methods of the top-level container (textures factorizations):
  10470. *
  10471. * .upload( gl, seq, values, textures )
  10472. *
  10473. * sets uniforms in 'seq' to 'values[id].value'
  10474. *
  10475. * .seqWithValue( seq, values ) : filteredSeq
  10476. *
  10477. * filters 'seq' entries with corresponding entry in values
  10478. *
  10479. *
  10480. * Methods of the top-level container (textures factorizations):
  10481. *
  10482. * .setValue( gl, name, value, textures )
  10483. *
  10484. * sets uniform with name 'name' to 'value'
  10485. *
  10486. * .setOptional( gl, obj, prop )
  10487. *
  10488. * like .set for an optional property of the object
  10489. *
  10490. */
  10491. const emptyTexture = new Texture();
  10492. const emptyTexture2dArray = new DataTexture2DArray();
  10493. const emptyTexture3d = new DataTexture3D();
  10494. const emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  10495. // Array Caches (provide typed arrays for temporary by size)
  10496. const arrayCacheF32 = [];
  10497. const arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  10498. const mat4array = new Float32Array(16);
  10499. const mat3array = new Float32Array(9);
  10500. const mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  10501. function flatten(array, nBlocks, blockSize) {
  10502. const firstElem = array[0];
  10503. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  10504. // see http://jacksondunstan.com/articles/983
  10505. const n = nBlocks * blockSize;
  10506. let r = arrayCacheF32[n];
  10507. if (r === undefined) {
  10508. r = new Float32Array(n);
  10509. arrayCacheF32[n] = r;
  10510. }
  10511. if (nBlocks !== 0) {
  10512. firstElem.toArray(r, 0);
  10513. for (let i = 1, offset = 0; i !== nBlocks; ++i) {
  10514. offset += blockSize;
  10515. array[i].toArray(r, offset);
  10516. }
  10517. }
  10518. return r;
  10519. }
  10520. function arraysEqual(a, b) {
  10521. if (a.length !== b.length) return false;
  10522. for (let i = 0, l = a.length; i < l; i++) {
  10523. if (a[i] !== b[i]) return false;
  10524. }
  10525. return true;
  10526. }
  10527. function copyArray(a, b) {
  10528. for (let i = 0, l = b.length; i < l; i++) {
  10529. a[i] = b[i];
  10530. }
  10531. } // Texture unit allocation
  10532. function allocTexUnits(textures, n) {
  10533. let r = arrayCacheI32[n];
  10534. if (r === undefined) {
  10535. r = new Int32Array(n);
  10536. arrayCacheI32[n] = r;
  10537. }
  10538. for (let i = 0; i !== n; ++i) {
  10539. r[i] = textures.allocateTextureUnit();
  10540. }
  10541. return r;
  10542. } // --- Setters ---
  10543. // Note: Defining these methods externally, because they come in a bunch
  10544. // and this way their names minify.
  10545. // Single scalar
  10546. function setValueV1f(gl, v) {
  10547. const cache = this.cache;
  10548. if (cache[0] === v) return;
  10549. gl.uniform1f(this.addr, v);
  10550. cache[0] = v;
  10551. } // Single float vector (from flat array or THREE.VectorN)
  10552. function setValueV2f(gl, v) {
  10553. const cache = this.cache;
  10554. if (v.x !== undefined) {
  10555. if (cache[0] !== v.x || cache[1] !== v.y) {
  10556. gl.uniform2f(this.addr, v.x, v.y);
  10557. cache[0] = v.x;
  10558. cache[1] = v.y;
  10559. }
  10560. } else {
  10561. if (arraysEqual(cache, v)) return;
  10562. gl.uniform2fv(this.addr, v);
  10563. copyArray(cache, v);
  10564. }
  10565. }
  10566. function setValueV3f(gl, v) {
  10567. const cache = this.cache;
  10568. if (v.x !== undefined) {
  10569. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  10570. gl.uniform3f(this.addr, v.x, v.y, v.z);
  10571. cache[0] = v.x;
  10572. cache[1] = v.y;
  10573. cache[2] = v.z;
  10574. }
  10575. } else if (v.r !== undefined) {
  10576. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  10577. gl.uniform3f(this.addr, v.r, v.g, v.b);
  10578. cache[0] = v.r;
  10579. cache[1] = v.g;
  10580. cache[2] = v.b;
  10581. }
  10582. } else {
  10583. if (arraysEqual(cache, v)) return;
  10584. gl.uniform3fv(this.addr, v);
  10585. copyArray(cache, v);
  10586. }
  10587. }
  10588. function setValueV4f(gl, v) {
  10589. const cache = this.cache;
  10590. if (v.x !== undefined) {
  10591. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  10592. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  10593. cache[0] = v.x;
  10594. cache[1] = v.y;
  10595. cache[2] = v.z;
  10596. cache[3] = v.w;
  10597. }
  10598. } else {
  10599. if (arraysEqual(cache, v)) return;
  10600. gl.uniform4fv(this.addr, v);
  10601. copyArray(cache, v);
  10602. }
  10603. } // Single matrix (from flat array or THREE.MatrixN)
  10604. function setValueM2(gl, v) {
  10605. const cache = this.cache;
  10606. const elements = v.elements;
  10607. if (elements === undefined) {
  10608. if (arraysEqual(cache, v)) return;
  10609. gl.uniformMatrix2fv(this.addr, false, v);
  10610. copyArray(cache, v);
  10611. } else {
  10612. if (arraysEqual(cache, elements)) return;
  10613. mat2array.set(elements);
  10614. gl.uniformMatrix2fv(this.addr, false, mat2array);
  10615. copyArray(cache, elements);
  10616. }
  10617. }
  10618. function setValueM3(gl, v) {
  10619. const cache = this.cache;
  10620. const elements = v.elements;
  10621. if (elements === undefined) {
  10622. if (arraysEqual(cache, v)) return;
  10623. gl.uniformMatrix3fv(this.addr, false, v);
  10624. copyArray(cache, v);
  10625. } else {
  10626. if (arraysEqual(cache, elements)) return;
  10627. mat3array.set(elements);
  10628. gl.uniformMatrix3fv(this.addr, false, mat3array);
  10629. copyArray(cache, elements);
  10630. }
  10631. }
  10632. function setValueM4(gl, v) {
  10633. const cache = this.cache;
  10634. const elements = v.elements;
  10635. if (elements === undefined) {
  10636. if (arraysEqual(cache, v)) return;
  10637. gl.uniformMatrix4fv(this.addr, false, v);
  10638. copyArray(cache, v);
  10639. } else {
  10640. if (arraysEqual(cache, elements)) return;
  10641. mat4array.set(elements);
  10642. gl.uniformMatrix4fv(this.addr, false, mat4array);
  10643. copyArray(cache, elements);
  10644. }
  10645. } // Single integer / boolean
  10646. function setValueV1i(gl, v) {
  10647. const cache = this.cache;
  10648. if (cache[0] === v) return;
  10649. gl.uniform1i(this.addr, v);
  10650. cache[0] = v;
  10651. } // Single integer / boolean vector (from flat array)
  10652. function setValueV2i(gl, v) {
  10653. const cache = this.cache;
  10654. if (arraysEqual(cache, v)) return;
  10655. gl.uniform2iv(this.addr, v);
  10656. copyArray(cache, v);
  10657. }
  10658. function setValueV3i(gl, v) {
  10659. const cache = this.cache;
  10660. if (arraysEqual(cache, v)) return;
  10661. gl.uniform3iv(this.addr, v);
  10662. copyArray(cache, v);
  10663. }
  10664. function setValueV4i(gl, v) {
  10665. const cache = this.cache;
  10666. if (arraysEqual(cache, v)) return;
  10667. gl.uniform4iv(this.addr, v);
  10668. copyArray(cache, v);
  10669. } // Single unsigned integer
  10670. function setValueV1ui(gl, v) {
  10671. const cache = this.cache;
  10672. if (cache[0] === v) return;
  10673. gl.uniform1ui(this.addr, v);
  10674. cache[0] = v;
  10675. } // Single unsigned integer vector (from flat array)
  10676. function setValueV2ui(gl, v) {
  10677. const cache = this.cache;
  10678. if (arraysEqual(cache, v)) return;
  10679. gl.uniform2uiv(this.addr, v);
  10680. copyArray(cache, v);
  10681. }
  10682. function setValueV3ui(gl, v) {
  10683. const cache = this.cache;
  10684. if (arraysEqual(cache, v)) return;
  10685. gl.uniform3uiv(this.addr, v);
  10686. copyArray(cache, v);
  10687. }
  10688. function setValueV4ui(gl, v) {
  10689. const cache = this.cache;
  10690. if (arraysEqual(cache, v)) return;
  10691. gl.uniform4uiv(this.addr, v);
  10692. copyArray(cache, v);
  10693. } // Single texture (2D / Cube)
  10694. function setValueT1(gl, v, textures) {
  10695. const cache = this.cache;
  10696. const unit = textures.allocateTextureUnit();
  10697. if (cache[0] !== unit) {
  10698. gl.uniform1i(this.addr, unit);
  10699. cache[0] = unit;
  10700. }
  10701. textures.safeSetTexture2D(v || emptyTexture, unit);
  10702. }
  10703. function setValueT3D1(gl, v, textures) {
  10704. const cache = this.cache;
  10705. const unit = textures.allocateTextureUnit();
  10706. if (cache[0] !== unit) {
  10707. gl.uniform1i(this.addr, unit);
  10708. cache[0] = unit;
  10709. }
  10710. textures.setTexture3D(v || emptyTexture3d, unit);
  10711. }
  10712. function setValueT6(gl, v, textures) {
  10713. const cache = this.cache;
  10714. const unit = textures.allocateTextureUnit();
  10715. if (cache[0] !== unit) {
  10716. gl.uniform1i(this.addr, unit);
  10717. cache[0] = unit;
  10718. }
  10719. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  10720. }
  10721. function setValueT2DArray1(gl, v, textures) {
  10722. const cache = this.cache;
  10723. const unit = textures.allocateTextureUnit();
  10724. if (cache[0] !== unit) {
  10725. gl.uniform1i(this.addr, unit);
  10726. cache[0] = unit;
  10727. }
  10728. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  10729. } // Helper to pick the right setter for the singular case
  10730. function getSingularSetter(type) {
  10731. switch (type) {
  10732. case 0x1406:
  10733. return setValueV1f;
  10734. // FLOAT
  10735. case 0x8b50:
  10736. return setValueV2f;
  10737. // _VEC2
  10738. case 0x8b51:
  10739. return setValueV3f;
  10740. // _VEC3
  10741. case 0x8b52:
  10742. return setValueV4f;
  10743. // _VEC4
  10744. case 0x8b5a:
  10745. return setValueM2;
  10746. // _MAT2
  10747. case 0x8b5b:
  10748. return setValueM3;
  10749. // _MAT3
  10750. case 0x8b5c:
  10751. return setValueM4;
  10752. // _MAT4
  10753. case 0x1404:
  10754. case 0x8b56:
  10755. return setValueV1i;
  10756. // INT, BOOL
  10757. case 0x8b53:
  10758. case 0x8b57:
  10759. return setValueV2i;
  10760. // _VEC2
  10761. case 0x8b54:
  10762. case 0x8b58:
  10763. return setValueV3i;
  10764. // _VEC3
  10765. case 0x8b55:
  10766. case 0x8b59:
  10767. return setValueV4i;
  10768. // _VEC4
  10769. case 0x1405:
  10770. return setValueV1ui;
  10771. // UINT
  10772. case 0x8dc6:
  10773. return setValueV2ui;
  10774. // _VEC2
  10775. case 0x8dc7:
  10776. return setValueV3ui;
  10777. // _VEC3
  10778. case 0x8dc8:
  10779. return setValueV4ui;
  10780. // _VEC4
  10781. case 0x8b5e: // SAMPLER_2D
  10782. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10783. case 0x8dca: // INT_SAMPLER_2D
  10784. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10785. case 0x8b62:
  10786. // SAMPLER_2D_SHADOW
  10787. return setValueT1;
  10788. case 0x8b5f: // SAMPLER_3D
  10789. case 0x8dcb: // INT_SAMPLER_3D
  10790. case 0x8dd3:
  10791. // UNSIGNED_INT_SAMPLER_3D
  10792. return setValueT3D1;
  10793. case 0x8b60: // SAMPLER_CUBE
  10794. case 0x8dcc: // INT_SAMPLER_CUBE
  10795. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10796. case 0x8dc5:
  10797. // SAMPLER_CUBE_SHADOW
  10798. return setValueT6;
  10799. case 0x8dc1: // SAMPLER_2D_ARRAY
  10800. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10801. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10802. case 0x8dc4:
  10803. // SAMPLER_2D_ARRAY_SHADOW
  10804. return setValueT2DArray1;
  10805. }
  10806. } // Array of scalars
  10807. function setValueV1fArray(gl, v) {
  10808. gl.uniform1fv(this.addr, v);
  10809. } // Array of vectors (from flat array or array of THREE.VectorN)
  10810. function setValueV2fArray(gl, v) {
  10811. const data = flatten(v, this.size, 2);
  10812. gl.uniform2fv(this.addr, data);
  10813. }
  10814. function setValueV3fArray(gl, v) {
  10815. const data = flatten(v, this.size, 3);
  10816. gl.uniform3fv(this.addr, data);
  10817. }
  10818. function setValueV4fArray(gl, v) {
  10819. const data = flatten(v, this.size, 4);
  10820. gl.uniform4fv(this.addr, data);
  10821. } // Array of matrices (from flat array or array of THREE.MatrixN)
  10822. function setValueM2Array(gl, v) {
  10823. const data = flatten(v, this.size, 4);
  10824. gl.uniformMatrix2fv(this.addr, false, data);
  10825. }
  10826. function setValueM3Array(gl, v) {
  10827. const data = flatten(v, this.size, 9);
  10828. gl.uniformMatrix3fv(this.addr, false, data);
  10829. }
  10830. function setValueM4Array(gl, v) {
  10831. const data = flatten(v, this.size, 16);
  10832. gl.uniformMatrix4fv(this.addr, false, data);
  10833. } // Array of integer / boolean
  10834. function setValueV1iArray(gl, v) {
  10835. gl.uniform1iv(this.addr, v);
  10836. } // Array of integer / boolean vectors (from flat array)
  10837. function setValueV2iArray(gl, v) {
  10838. gl.uniform2iv(this.addr, v);
  10839. }
  10840. function setValueV3iArray(gl, v) {
  10841. gl.uniform3iv(this.addr, v);
  10842. }
  10843. function setValueV4iArray(gl, v) {
  10844. gl.uniform4iv(this.addr, v);
  10845. } // Array of unsigned integer
  10846. function setValueV1uiArray(gl, v) {
  10847. gl.uniform1uiv(this.addr, v);
  10848. } // Array of unsigned integer vectors (from flat array)
  10849. function setValueV2uiArray(gl, v) {
  10850. gl.uniform2uiv(this.addr, v);
  10851. }
  10852. function setValueV3uiArray(gl, v) {
  10853. gl.uniform3uiv(this.addr, v);
  10854. }
  10855. function setValueV4uiArray(gl, v) {
  10856. gl.uniform4uiv(this.addr, v);
  10857. } // Array of textures (2D / Cube)
  10858. function setValueT1Array(gl, v, textures) {
  10859. const n = v.length;
  10860. const units = allocTexUnits(textures, n);
  10861. gl.uniform1iv(this.addr, units);
  10862. for (let i = 0; i !== n; ++i) {
  10863. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  10864. }
  10865. }
  10866. function setValueT6Array(gl, v, textures) {
  10867. const n = v.length;
  10868. const units = allocTexUnits(textures, n);
  10869. gl.uniform1iv(this.addr, units);
  10870. for (let i = 0; i !== n; ++i) {
  10871. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  10872. }
  10873. } // Helper to pick the right setter for a pure (bottom-level) array
  10874. function getPureArraySetter(type) {
  10875. switch (type) {
  10876. case 0x1406:
  10877. return setValueV1fArray;
  10878. // FLOAT
  10879. case 0x8b50:
  10880. return setValueV2fArray;
  10881. // _VEC2
  10882. case 0x8b51:
  10883. return setValueV3fArray;
  10884. // _VEC3
  10885. case 0x8b52:
  10886. return setValueV4fArray;
  10887. // _VEC4
  10888. case 0x8b5a:
  10889. return setValueM2Array;
  10890. // _MAT2
  10891. case 0x8b5b:
  10892. return setValueM3Array;
  10893. // _MAT3
  10894. case 0x8b5c:
  10895. return setValueM4Array;
  10896. // _MAT4
  10897. case 0x1404:
  10898. case 0x8b56:
  10899. return setValueV1iArray;
  10900. // INT, BOOL
  10901. case 0x8b53:
  10902. case 0x8b57:
  10903. return setValueV2iArray;
  10904. // _VEC2
  10905. case 0x8b54:
  10906. case 0x8b58:
  10907. return setValueV3iArray;
  10908. // _VEC3
  10909. case 0x8b55:
  10910. case 0x8b59:
  10911. return setValueV4iArray;
  10912. // _VEC4
  10913. case 0x1405:
  10914. return setValueV1uiArray;
  10915. // UINT
  10916. case 0x8dc6:
  10917. return setValueV2uiArray;
  10918. // _VEC2
  10919. case 0x8dc7:
  10920. return setValueV3uiArray;
  10921. // _VEC3
  10922. case 0x8dc8:
  10923. return setValueV4uiArray;
  10924. // _VEC4
  10925. case 0x8b5e: // SAMPLER_2D
  10926. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10927. case 0x8dca: // INT_SAMPLER_2D
  10928. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10929. case 0x8b62:
  10930. // SAMPLER_2D_SHADOW
  10931. return setValueT1Array;
  10932. case 0x8b60: // SAMPLER_CUBE
  10933. case 0x8dcc: // INT_SAMPLER_CUBE
  10934. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10935. case 0x8dc5:
  10936. // SAMPLER_CUBE_SHADOW
  10937. return setValueT6Array;
  10938. }
  10939. } // --- Uniform Classes ---
  10940. function SingleUniform(id, activeInfo, addr) {
  10941. this.id = id;
  10942. this.addr = addr;
  10943. this.cache = [];
  10944. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  10945. }
  10946. function PureArrayUniform(id, activeInfo, addr) {
  10947. this.id = id;
  10948. this.addr = addr;
  10949. this.cache = [];
  10950. this.size = activeInfo.size;
  10951. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  10952. }
  10953. PureArrayUniform.prototype.updateCache = function (data) {
  10954. const cache = this.cache;
  10955. if (data instanceof Float32Array && cache.length !== data.length) {
  10956. this.cache = new Float32Array(data.length);
  10957. }
  10958. copyArray(cache, data);
  10959. };
  10960. function StructuredUniform(id) {
  10961. this.id = id;
  10962. this.seq = [];
  10963. this.map = {};
  10964. }
  10965. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  10966. const seq = this.seq;
  10967. for (let i = 0, n = seq.length; i !== n; ++i) {
  10968. const u = seq[i];
  10969. u.setValue(gl, value[u.id], textures);
  10970. }
  10971. }; // --- Top-level ---
  10972. // Parser - builds up the property tree from the path strings
  10973. const RePathPart = /(\w+)(\])?(\[|\.)?/g; // extracts
  10974. // - the identifier (member name or array index)
  10975. // - followed by an optional right bracket (found when array index)
  10976. // - followed by an optional left bracket or dot (type of subscript)
  10977. //
  10978. // Note: These portions can be read in a non-overlapping fashion and
  10979. // allow straightforward parsing of the hierarchy that WebGL encodes
  10980. // in the uniform names.
  10981. function addUniform(container, uniformObject) {
  10982. container.seq.push(uniformObject);
  10983. container.map[uniformObject.id] = uniformObject;
  10984. }
  10985. function parseUniform(activeInfo, addr, container) {
  10986. const path = activeInfo.name,
  10987. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  10988. RePathPart.lastIndex = 0;
  10989. while (true) {
  10990. const match = RePathPart.exec(path),
  10991. matchEnd = RePathPart.lastIndex;
  10992. let id = match[1];
  10993. const idIsIndex = match[2] === ']',
  10994. subscript = match[3];
  10995. if (idIsIndex) id = id | 0; // convert to integer
  10996. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  10997. // bare name or "pure" bottom-level array "[0]" suffix
  10998. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  10999. break;
  11000. } else {
  11001. // step into inner node / create it in case it doesn't exist
  11002. const map = container.map;
  11003. let next = map[id];
  11004. if (next === undefined) {
  11005. next = new StructuredUniform(id);
  11006. addUniform(container, next);
  11007. }
  11008. container = next;
  11009. }
  11010. }
  11011. } // Root Container
  11012. function WebGLUniforms(gl, program) {
  11013. this.seq = [];
  11014. this.map = {};
  11015. const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  11016. for (let i = 0; i < n; ++i) {
  11017. const info = gl.getActiveUniform(program, i),
  11018. addr = gl.getUniformLocation(program, info.name);
  11019. parseUniform(info, addr, this);
  11020. }
  11021. }
  11022. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  11023. const u = this.map[name];
  11024. if (u !== undefined) u.setValue(gl, value, textures);
  11025. };
  11026. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  11027. const v = object[name];
  11028. if (v !== undefined) this.setValue(gl, name, v);
  11029. }; // Static interface
  11030. WebGLUniforms.upload = function (gl, seq, values, textures) {
  11031. for (let i = 0, n = seq.length; i !== n; ++i) {
  11032. const u = seq[i],
  11033. v = values[u.id];
  11034. if (v.needsUpdate !== false) {
  11035. // note: always updating when .needsUpdate is undefined
  11036. u.setValue(gl, v.value, textures);
  11037. }
  11038. }
  11039. };
  11040. WebGLUniforms.seqWithValue = function (seq, values) {
  11041. const r = [];
  11042. for (let i = 0, n = seq.length; i !== n; ++i) {
  11043. const u = seq[i];
  11044. if (u.id in values) r.push(u);
  11045. }
  11046. return r;
  11047. };
  11048. function WebGLShader(gl, type, string) {
  11049. const shader = gl.createShader(type);
  11050. gl.shaderSource(shader, string);
  11051. gl.compileShader(shader);
  11052. return shader;
  11053. }
  11054. let programIdCount = 0;
  11055. function addLineNumbers(string) {
  11056. const lines = string.split('\n');
  11057. for (let i = 0; i < lines.length; i++) {
  11058. lines[i] = i + 1 + ': ' + lines[i];
  11059. }
  11060. return lines.join('\n');
  11061. }
  11062. function getEncodingComponents(encoding) {
  11063. switch (encoding) {
  11064. case LinearEncoding:
  11065. return ['Linear', '( value )'];
  11066. case sRGBEncoding:
  11067. return ['sRGB', '( value )'];
  11068. case RGBEEncoding:
  11069. return ['RGBE', '( value )'];
  11070. case RGBM7Encoding:
  11071. return ['RGBM', '( value, 7.0 )'];
  11072. case RGBM16Encoding:
  11073. return ['RGBM', '( value, 16.0 )'];
  11074. case RGBDEncoding:
  11075. return ['RGBD', '( value, 256.0 )'];
  11076. case GammaEncoding:
  11077. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  11078. case LogLuvEncoding:
  11079. return ['LogLuv', '( value )'];
  11080. default:
  11081. console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
  11082. return ['Linear', '( value )'];
  11083. }
  11084. }
  11085. function getShaderErrors(gl, shader, type) {
  11086. const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  11087. const log = gl.getShaderInfoLog(shader).trim();
  11088. if (status && log === '') return ''; // --enable-privileged-webgl-extension
  11089. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11090. const source = gl.getShaderSource(shader);
  11091. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers(source);
  11092. }
  11093. function getTexelDecodingFunction(functionName, encoding) {
  11094. const components = getEncodingComponents(encoding);
  11095. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  11096. }
  11097. function getTexelEncodingFunction(functionName, encoding) {
  11098. const components = getEncodingComponents(encoding);
  11099. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  11100. }
  11101. function getToneMappingFunction(functionName, toneMapping) {
  11102. let toneMappingName;
  11103. switch (toneMapping) {
  11104. case LinearToneMapping:
  11105. toneMappingName = 'Linear';
  11106. break;
  11107. case ReinhardToneMapping:
  11108. toneMappingName = 'Reinhard';
  11109. break;
  11110. case CineonToneMapping:
  11111. toneMappingName = 'OptimizedCineon';
  11112. break;
  11113. case ACESFilmicToneMapping:
  11114. toneMappingName = 'ACESFilmic';
  11115. break;
  11116. case CustomToneMapping:
  11117. toneMappingName = 'Custom';
  11118. break;
  11119. default:
  11120. console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
  11121. toneMappingName = 'Linear';
  11122. }
  11123. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11124. }
  11125. function generateExtensions(parameters) {
  11126. 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 > 0.0) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''];
  11127. return chunks.filter(filterEmptyLine).join('\n');
  11128. }
  11129. function generateDefines(defines) {
  11130. const chunks = [];
  11131. for (const name in defines) {
  11132. const value = defines[name];
  11133. if (value === false) continue;
  11134. chunks.push('#define ' + name + ' ' + value);
  11135. }
  11136. return chunks.join('\n');
  11137. }
  11138. function fetchAttributeLocations(gl, program) {
  11139. const attributes = {};
  11140. const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  11141. for (let i = 0; i < n; i++) {
  11142. const info = gl.getActiveAttrib(program, i);
  11143. const name = info.name; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11144. attributes[name] = gl.getAttribLocation(program, name);
  11145. }
  11146. return attributes;
  11147. }
  11148. function filterEmptyLine(string) {
  11149. return string !== '';
  11150. }
  11151. function replaceLightNums(string, parameters) {
  11152. 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);
  11153. }
  11154. function replaceClippingPlaneNums(string, parameters) {
  11155. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  11156. } // Resolve Includes
  11157. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11158. function resolveIncludes(string) {
  11159. return string.replace(includePattern, includeReplacer);
  11160. }
  11161. function includeReplacer(match, include) {
  11162. const string = ShaderChunk[include];
  11163. if (string === undefined) {
  11164. throw new Error('Can not resolve #include <' + include + '>');
  11165. }
  11166. return resolveIncludes(string);
  11167. } // Unroll Loops
  11168. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  11169. 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;
  11170. function unrollLoops(string) {
  11171. return string.replace(unrollLoopPattern, loopReplacer).replace(deprecatedUnrollLoopPattern, deprecatedLoopReplacer);
  11172. }
  11173. function deprecatedLoopReplacer(match, start, end, snippet) {
  11174. console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');
  11175. return loopReplacer(match, start, end, snippet);
  11176. }
  11177. function loopReplacer(match, start, end, snippet) {
  11178. let string = '';
  11179. for (let i = parseInt(start); i < parseInt(end); i++) {
  11180. string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  11181. }
  11182. return string;
  11183. } //
  11184. function generatePrecision(parameters) {
  11185. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11186. if (parameters.precision === 'highp') {
  11187. precisionstring += '\n#define HIGH_PRECISION';
  11188. } else if (parameters.precision === 'mediump') {
  11189. precisionstring += '\n#define MEDIUM_PRECISION';
  11190. } else if (parameters.precision === 'lowp') {
  11191. precisionstring += '\n#define LOW_PRECISION';
  11192. }
  11193. return precisionstring;
  11194. }
  11195. function generateShadowMapTypeDefine(parameters) {
  11196. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11197. if (parameters.shadowMapType === PCFShadowMap) {
  11198. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11199. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  11200. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11201. } else if (parameters.shadowMapType === VSMShadowMap) {
  11202. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11203. }
  11204. return shadowMapTypeDefine;
  11205. }
  11206. function generateEnvMapTypeDefine(parameters) {
  11207. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11208. if (parameters.envMap) {
  11209. switch (parameters.envMapMode) {
  11210. case CubeReflectionMapping:
  11211. case CubeRefractionMapping:
  11212. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11213. break;
  11214. case CubeUVReflectionMapping:
  11215. case CubeUVRefractionMapping:
  11216. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11217. break;
  11218. }
  11219. }
  11220. return envMapTypeDefine;
  11221. }
  11222. function generateEnvMapModeDefine(parameters) {
  11223. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11224. if (parameters.envMap) {
  11225. switch (parameters.envMapMode) {
  11226. case CubeRefractionMapping:
  11227. case CubeUVRefractionMapping:
  11228. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11229. break;
  11230. }
  11231. }
  11232. return envMapModeDefine;
  11233. }
  11234. function generateEnvMapBlendingDefine(parameters) {
  11235. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11236. if (parameters.envMap) {
  11237. switch (parameters.combine) {
  11238. case MultiplyOperation:
  11239. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11240. break;
  11241. case MixOperation:
  11242. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11243. break;
  11244. case AddOperation:
  11245. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11246. break;
  11247. }
  11248. }
  11249. return envMapBlendingDefine;
  11250. }
  11251. function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
  11252. const gl = renderer.getContext();
  11253. const defines = parameters.defines;
  11254. let vertexShader = parameters.vertexShader;
  11255. let fragmentShader = parameters.fragmentShader;
  11256. const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  11257. const envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  11258. const envMapModeDefine = generateEnvMapModeDefine(parameters);
  11259. const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  11260. const gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  11261. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  11262. const customDefines = generateDefines(defines);
  11263. const program = gl.createProgram();
  11264. let prefixVertex, prefixFragment;
  11265. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11266. if (parameters.isRawShaderMaterial) {
  11267. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  11268. if (prefixVertex.length > 0) {
  11269. prefixVertex += '\n';
  11270. }
  11271. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  11272. if (prefixFragment.length > 0) {
  11273. prefixFragment += '\n';
  11274. }
  11275. } else {
  11276. 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');
  11277. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + (parameters.alphaTest % 1 ? '' : '.0') : '', // add '.0' if integer
  11278. '#define GAMMA_FACTOR ' + gammaFactorDefine, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.matcap ? '#define USE_MATCAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapTypeDefine : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.envMap ? '#define ' + envMapBlendingDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.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.sheen ? '#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
  11279. parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', ShaderChunk['encodings_pars_fragment'], // this code is required here because it is used by the various encoding/decoding function defined below
  11280. 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');
  11281. }
  11282. vertexShader = resolveIncludes(vertexShader);
  11283. vertexShader = replaceLightNums(vertexShader, parameters);
  11284. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  11285. fragmentShader = resolveIncludes(fragmentShader);
  11286. fragmentShader = replaceLightNums(fragmentShader, parameters);
  11287. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  11288. vertexShader = unrollLoops(vertexShader);
  11289. fragmentShader = unrollLoops(fragmentShader);
  11290. if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
  11291. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11292. versionString = '#version 300 es\n';
  11293. prefixVertex = ['#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  11294. 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;
  11295. }
  11296. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11297. const fragmentGlsl = versionString + prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  11298. // console.log( '*FRAGMENT*', fragmentGlsl );
  11299. const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl);
  11300. const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl);
  11301. gl.attachShader(program, glVertexShader);
  11302. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  11303. if (parameters.index0AttributeName !== undefined) {
  11304. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  11305. } else if (parameters.morphTargets === true) {
  11306. // programs with morphTargets displace position out of attribute 0
  11307. gl.bindAttribLocation(program, 0, 'position');
  11308. }
  11309. gl.linkProgram(program); // check for link errors
  11310. if (renderer.debug.checkShaderErrors) {
  11311. const programLog = gl.getProgramInfoLog(program).trim();
  11312. const vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  11313. const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  11314. let runnable = true;
  11315. let haveDiagnostics = true;
  11316. if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {
  11317. runnable = false;
  11318. const vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  11319. const fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  11320. console.error('THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors);
  11321. } else if (programLog !== '') {
  11322. console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()', programLog);
  11323. } else if (vertexLog === '' || fragmentLog === '') {
  11324. haveDiagnostics = false;
  11325. }
  11326. if (haveDiagnostics) {
  11327. this.diagnostics = {
  11328. runnable: runnable,
  11329. programLog: programLog,
  11330. vertexShader: {
  11331. log: vertexLog,
  11332. prefix: prefixVertex
  11333. },
  11334. fragmentShader: {
  11335. log: fragmentLog,
  11336. prefix: prefixFragment
  11337. }
  11338. };
  11339. }
  11340. } // Clean up
  11341. // Crashes in iOS9 and iOS10. #18402
  11342. // gl.detachShader( program, glVertexShader );
  11343. // gl.detachShader( program, glFragmentShader );
  11344. gl.deleteShader(glVertexShader);
  11345. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  11346. let cachedUniforms;
  11347. this.getUniforms = function () {
  11348. if (cachedUniforms === undefined) {
  11349. cachedUniforms = new WebGLUniforms(gl, program);
  11350. }
  11351. return cachedUniforms;
  11352. }; // set up caching for attribute locations
  11353. let cachedAttributes;
  11354. this.getAttributes = function () {
  11355. if (cachedAttributes === undefined) {
  11356. cachedAttributes = fetchAttributeLocations(gl, program);
  11357. }
  11358. return cachedAttributes;
  11359. }; // free resource
  11360. this.destroy = function () {
  11361. bindingStates.releaseStatesOfProgram(this);
  11362. gl.deleteProgram(program);
  11363. this.program = undefined;
  11364. }; //
  11365. this.name = parameters.shaderName;
  11366. this.id = programIdCount++;
  11367. this.cacheKey = cacheKey;
  11368. this.usedTimes = 1;
  11369. this.program = program;
  11370. this.vertexShader = glVertexShader;
  11371. this.fragmentShader = glFragmentShader;
  11372. return this;
  11373. }
  11374. function WebGLPrograms(renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping) {
  11375. const programs = [];
  11376. const isWebGL2 = capabilities.isWebGL2;
  11377. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11378. const floatVertexTextures = capabilities.floatVertexTextures;
  11379. const maxVertexUniforms = capabilities.maxVertexUniforms;
  11380. const vertexTextures = capabilities.vertexTextures;
  11381. let precision = capabilities.precision;
  11382. const shaderIDs = {
  11383. MeshDepthMaterial: 'depth',
  11384. MeshDistanceMaterial: 'distanceRGBA',
  11385. MeshNormalMaterial: 'normal',
  11386. MeshBasicMaterial: 'basic',
  11387. MeshLambertMaterial: 'lambert',
  11388. MeshPhongMaterial: 'phong',
  11389. MeshToonMaterial: 'toon',
  11390. MeshStandardMaterial: 'physical',
  11391. MeshPhysicalMaterial: 'physical',
  11392. MeshMatcapMaterial: 'matcap',
  11393. LineBasicMaterial: 'basic',
  11394. LineDashedMaterial: 'dashed',
  11395. PointsMaterial: 'points',
  11396. ShadowMaterial: 'shadow',
  11397. SpriteMaterial: 'sprite'
  11398. };
  11399. const parameterNames = ['precision', 'isWebGL2', 'supportsVertexTextures', 'outputEncoding', 'instancing', 'instancingColor', 'map', 'mapEncoding', 'matcap', 'matcapEncoding', 'envMap', 'envMapMode', 'envMapEncoding', 'envMapCubeUV', 'lightMap', 'lightMapEncoding', 'aoMap', 'emissiveMap', 'emissiveMapEncoding', 'bumpMap', 'normalMap', 'objectSpaceNormalMap', 'tangentSpaceNormalMap', 'clearcoatMap', 'clearcoatRoughnessMap', 'clearcoatNormalMap', 'displacementMap', 'specularMap', 'specularIntensityMap', 'specularTintMap', 'specularTintMapEncoding', 'roughnessMap', 'metalnessMap', 'gradientMap', 'alphaMap', 'combine', 'vertexColors', 'vertexAlphas', 'vertexTangents', 'vertexUvs', 'uvsVertexOnly', 'fog', 'useFog', 'fogExp2', 'flatShading', 'sizeAttenuation', 'logarithmicDepthBuffer', 'skinning', 'maxBones', 'useVertexTexture', 'morphTargets', 'morphNormals', 'premultipliedAlpha', 'numDirLights', 'numPointLights', 'numSpotLights', 'numHemiLights', 'numRectAreaLights', 'numDirLightShadows', 'numPointLightShadows', 'numSpotLightShadows', 'shadowMapEnabled', 'shadowMapType', 'toneMapping', 'physicallyCorrectLights', 'alphaTest', 'doubleSided', 'flipSided', 'numClippingPlanes', 'numClipIntersection', 'depthPacking', 'dithering', 'sheen', 'transmission', 'transmissionMap', 'thicknessMap'];
  11400. function getMaxBones(object) {
  11401. const skeleton = object.skeleton;
  11402. const bones = skeleton.bones;
  11403. if (floatVertexTextures) {
  11404. return 1024;
  11405. } else {
  11406. // default for when object is not specified
  11407. // ( for example when prebuilding shader to be used with multiple objects )
  11408. //
  11409. // - leave some extra space for other uniforms
  11410. // - limit here is ANGLE's 254 max uniform vectors
  11411. // (up to 54 should be safe)
  11412. const nVertexUniforms = maxVertexUniforms;
  11413. const nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  11414. const maxBones = Math.min(nVertexMatrices, bones.length);
  11415. if (maxBones < bones.length) {
  11416. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  11417. return 0;
  11418. }
  11419. return maxBones;
  11420. }
  11421. }
  11422. function getTextureEncodingFromMap(map) {
  11423. let encoding;
  11424. if (map && map.isTexture) {
  11425. encoding = map.encoding;
  11426. } else if (map && map.isWebGLRenderTarget) {
  11427. console.warn('THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.');
  11428. encoding = map.texture.encoding;
  11429. } else {
  11430. encoding = LinearEncoding;
  11431. }
  11432. return encoding;
  11433. }
  11434. function getParameters(material, lights, shadows, scene, object) {
  11435. const fog = scene.fog;
  11436. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11437. const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
  11438. const shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  11439. // (not to blow over maxLights budget)
  11440. const maxBones = object.isSkinnedMesh ? getMaxBones(object) : 0;
  11441. if (material.precision !== null) {
  11442. precision = capabilities.getMaxPrecision(material.precision);
  11443. if (precision !== material.precision) {
  11444. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  11445. }
  11446. }
  11447. let vertexShader, fragmentShader;
  11448. if (shaderID) {
  11449. const shader = ShaderLib[shaderID];
  11450. vertexShader = shader.vertexShader;
  11451. fragmentShader = shader.fragmentShader;
  11452. } else {
  11453. vertexShader = material.vertexShader;
  11454. fragmentShader = material.fragmentShader;
  11455. }
  11456. const currentRenderTarget = renderer.getRenderTarget();
  11457. const parameters = {
  11458. isWebGL2: isWebGL2,
  11459. shaderID: shaderID,
  11460. shaderName: material.type,
  11461. vertexShader: vertexShader,
  11462. fragmentShader: fragmentShader,
  11463. defines: material.defines,
  11464. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11465. glslVersion: material.glslVersion,
  11466. precision: precision,
  11467. instancing: object.isInstancedMesh === true,
  11468. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11469. supportsVertexTextures: vertexTextures,
  11470. outputEncoding: currentRenderTarget !== null ? getTextureEncodingFromMap(currentRenderTarget.texture) : renderer.outputEncoding,
  11471. map: !!material.map,
  11472. mapEncoding: getTextureEncodingFromMap(material.map),
  11473. matcap: !!material.matcap,
  11474. matcapEncoding: getTextureEncodingFromMap(material.matcap),
  11475. envMap: !!envMap,
  11476. envMapMode: envMap && envMap.mapping,
  11477. envMapEncoding: getTextureEncodingFromMap(envMap),
  11478. envMapCubeUV: !!envMap && (envMap.mapping === CubeUVReflectionMapping || envMap.mapping === CubeUVRefractionMapping),
  11479. lightMap: !!material.lightMap,
  11480. lightMapEncoding: getTextureEncodingFromMap(material.lightMap),
  11481. aoMap: !!material.aoMap,
  11482. emissiveMap: !!material.emissiveMap,
  11483. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap),
  11484. bumpMap: !!material.bumpMap,
  11485. normalMap: !!material.normalMap,
  11486. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11487. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11488. clearcoatMap: !!material.clearcoatMap,
  11489. clearcoatRoughnessMap: !!material.clearcoatRoughnessMap,
  11490. clearcoatNormalMap: !!material.clearcoatNormalMap,
  11491. displacementMap: !!material.displacementMap,
  11492. roughnessMap: !!material.roughnessMap,
  11493. metalnessMap: !!material.metalnessMap,
  11494. specularMap: !!material.specularMap,
  11495. specularIntensityMap: !!material.specularIntensityMap,
  11496. specularTintMap: !!material.specularTintMap,
  11497. specularTintMapEncoding: getTextureEncodingFromMap(material.specularTintMap),
  11498. alphaMap: !!material.alphaMap,
  11499. gradientMap: !!material.gradientMap,
  11500. sheen: !!material.sheen,
  11501. transmission: !!material.transmission,
  11502. transmissionMap: !!material.transmissionMap,
  11503. thicknessMap: !!material.thicknessMap,
  11504. combine: material.combine,
  11505. vertexTangents: !!material.normalMap && !!object.geometry && !!object.geometry.attributes.tangent,
  11506. vertexColors: material.vertexColors,
  11507. vertexAlphas: material.vertexColors === true && !!object.geometry && !!object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4,
  11508. 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,
  11509. uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap || !!material.transmission || !!material.transmissionMap || !!material.thicknessMap || !!material.specularIntensityMap || !!material.specularTintMap) && !!material.displacementMap,
  11510. fog: !!fog,
  11511. useFog: material.fog,
  11512. fogExp2: fog && fog.isFogExp2,
  11513. flatShading: !!material.flatShading,
  11514. sizeAttenuation: material.sizeAttenuation,
  11515. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11516. skinning: object.isSkinnedMesh === true && maxBones > 0,
  11517. maxBones: maxBones,
  11518. useVertexTexture: floatVertexTextures,
  11519. morphTargets: !!object.geometry && !!object.geometry.morphAttributes.position,
  11520. morphNormals: !!object.geometry && !!object.geometry.morphAttributes.normal,
  11521. numDirLights: lights.directional.length,
  11522. numPointLights: lights.point.length,
  11523. numSpotLights: lights.spot.length,
  11524. numRectAreaLights: lights.rectArea.length,
  11525. numHemiLights: lights.hemi.length,
  11526. numDirLightShadows: lights.directionalShadowMap.length,
  11527. numPointLightShadows: lights.pointShadowMap.length,
  11528. numSpotLightShadows: lights.spotShadowMap.length,
  11529. numClippingPlanes: clipping.numPlanes,
  11530. numClipIntersection: clipping.numIntersection,
  11531. dithering: material.dithering,
  11532. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11533. shadowMapType: renderer.shadowMap.type,
  11534. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11535. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11536. premultipliedAlpha: material.premultipliedAlpha,
  11537. alphaTest: material.alphaTest,
  11538. doubleSided: material.side === DoubleSide,
  11539. flipSided: material.side === BackSide,
  11540. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false,
  11541. index0AttributeName: material.index0AttributeName,
  11542. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11543. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11544. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11545. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11546. rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
  11547. rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
  11548. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
  11549. customProgramCacheKey: material.customProgramCacheKey()
  11550. };
  11551. return parameters;
  11552. }
  11553. function getProgramCacheKey(parameters) {
  11554. const array = [];
  11555. if (parameters.shaderID) {
  11556. array.push(parameters.shaderID);
  11557. } else {
  11558. array.push(parameters.fragmentShader);
  11559. array.push(parameters.vertexShader);
  11560. }
  11561. if (parameters.defines !== undefined) {
  11562. for (const name in parameters.defines) {
  11563. array.push(name);
  11564. array.push(parameters.defines[name]);
  11565. }
  11566. }
  11567. if (parameters.isRawShaderMaterial === false) {
  11568. for (let i = 0; i < parameterNames.length; i++) {
  11569. array.push(parameters[parameterNames[i]]);
  11570. }
  11571. array.push(renderer.outputEncoding);
  11572. array.push(renderer.gammaFactor);
  11573. }
  11574. array.push(parameters.customProgramCacheKey);
  11575. return array.join();
  11576. }
  11577. function getUniforms(material) {
  11578. const shaderID = shaderIDs[material.type];
  11579. let uniforms;
  11580. if (shaderID) {
  11581. const shader = ShaderLib[shaderID];
  11582. uniforms = UniformsUtils.clone(shader.uniforms);
  11583. } else {
  11584. uniforms = material.uniforms;
  11585. }
  11586. return uniforms;
  11587. }
  11588. function acquireProgram(parameters, cacheKey) {
  11589. let program; // Check if code has been already compiled
  11590. for (let p = 0, pl = programs.length; p < pl; p++) {
  11591. const preexistingProgram = programs[p];
  11592. if (preexistingProgram.cacheKey === cacheKey) {
  11593. program = preexistingProgram;
  11594. ++program.usedTimes;
  11595. break;
  11596. }
  11597. }
  11598. if (program === undefined) {
  11599. program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
  11600. programs.push(program);
  11601. }
  11602. return program;
  11603. }
  11604. function releaseProgram(program) {
  11605. if (--program.usedTimes === 0) {
  11606. // Remove from unordered set
  11607. const i = programs.indexOf(program);
  11608. programs[i] = programs[programs.length - 1];
  11609. programs.pop(); // Free WebGL resources
  11610. program.destroy();
  11611. }
  11612. }
  11613. return {
  11614. getParameters: getParameters,
  11615. getProgramCacheKey: getProgramCacheKey,
  11616. getUniforms: getUniforms,
  11617. acquireProgram: acquireProgram,
  11618. releaseProgram: releaseProgram,
  11619. // Exposed for resource monitoring & error feedback via renderer.info:
  11620. programs: programs
  11621. };
  11622. }
  11623. function WebGLProperties() {
  11624. let properties = new WeakMap();
  11625. function get(object) {
  11626. let map = properties.get(object);
  11627. if (map === undefined) {
  11628. map = {};
  11629. properties.set(object, map);
  11630. }
  11631. return map;
  11632. }
  11633. function remove(object) {
  11634. properties.delete(object);
  11635. }
  11636. function update(object, key, value) {
  11637. properties.get(object)[key] = value;
  11638. }
  11639. function dispose() {
  11640. properties = new WeakMap();
  11641. }
  11642. return {
  11643. get: get,
  11644. remove: remove,
  11645. update: update,
  11646. dispose: dispose
  11647. };
  11648. }
  11649. function painterSortStable(a, b) {
  11650. if (a.groupOrder !== b.groupOrder) {
  11651. return a.groupOrder - b.groupOrder;
  11652. } else if (a.renderOrder !== b.renderOrder) {
  11653. return a.renderOrder - b.renderOrder;
  11654. } else if (a.program !== b.program) {
  11655. return a.program.id - b.program.id;
  11656. } else if (a.material.id !== b.material.id) {
  11657. return a.material.id - b.material.id;
  11658. } else if (a.z !== b.z) {
  11659. return a.z - b.z;
  11660. } else {
  11661. return a.id - b.id;
  11662. }
  11663. }
  11664. function reversePainterSortStable(a, b) {
  11665. if (a.groupOrder !== b.groupOrder) {
  11666. return a.groupOrder - b.groupOrder;
  11667. } else if (a.renderOrder !== b.renderOrder) {
  11668. return a.renderOrder - b.renderOrder;
  11669. } else if (a.z !== b.z) {
  11670. return b.z - a.z;
  11671. } else {
  11672. return a.id - b.id;
  11673. }
  11674. }
  11675. function WebGLRenderList(properties) {
  11676. const renderItems = [];
  11677. let renderItemsIndex = 0;
  11678. const opaque = [];
  11679. const transmissive = [];
  11680. const transparent = [];
  11681. const defaultProgram = {
  11682. id: -1
  11683. };
  11684. function init() {
  11685. renderItemsIndex = 0;
  11686. opaque.length = 0;
  11687. transmissive.length = 0;
  11688. transparent.length = 0;
  11689. }
  11690. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  11691. let renderItem = renderItems[renderItemsIndex];
  11692. const materialProperties = properties.get(material);
  11693. if (renderItem === undefined) {
  11694. renderItem = {
  11695. id: object.id,
  11696. object: object,
  11697. geometry: geometry,
  11698. material: material,
  11699. program: materialProperties.program || defaultProgram,
  11700. groupOrder: groupOrder,
  11701. renderOrder: object.renderOrder,
  11702. z: z,
  11703. group: group
  11704. };
  11705. renderItems[renderItemsIndex] = renderItem;
  11706. } else {
  11707. renderItem.id = object.id;
  11708. renderItem.object = object;
  11709. renderItem.geometry = geometry;
  11710. renderItem.material = material;
  11711. renderItem.program = materialProperties.program || defaultProgram;
  11712. renderItem.groupOrder = groupOrder;
  11713. renderItem.renderOrder = object.renderOrder;
  11714. renderItem.z = z;
  11715. renderItem.group = group;
  11716. }
  11717. renderItemsIndex++;
  11718. return renderItem;
  11719. }
  11720. function push(object, geometry, material, groupOrder, z, group) {
  11721. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  11722. if (material.transmission > 0.0) {
  11723. transmissive.push(renderItem);
  11724. } else if (material.transparent === true) {
  11725. transparent.push(renderItem);
  11726. } else {
  11727. opaque.push(renderItem);
  11728. }
  11729. }
  11730. function unshift(object, geometry, material, groupOrder, z, group) {
  11731. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  11732. if (material.transmission > 0.0) {
  11733. transmissive.unshift(renderItem);
  11734. } else if (material.transparent === true) {
  11735. transparent.unshift(renderItem);
  11736. } else {
  11737. opaque.unshift(renderItem);
  11738. }
  11739. }
  11740. function sort(customOpaqueSort, customTransparentSort) {
  11741. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  11742. if (transmissive.length > 1) transmissive.sort(customTransparentSort || reversePainterSortStable);
  11743. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  11744. }
  11745. function finish() {
  11746. // Clear references from inactive renderItems in the list
  11747. for (let i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  11748. const renderItem = renderItems[i];
  11749. if (renderItem.id === null) break;
  11750. renderItem.id = null;
  11751. renderItem.object = null;
  11752. renderItem.geometry = null;
  11753. renderItem.material = null;
  11754. renderItem.program = null;
  11755. renderItem.group = null;
  11756. }
  11757. }
  11758. return {
  11759. opaque: opaque,
  11760. transmissive: transmissive,
  11761. transparent: transparent,
  11762. init: init,
  11763. push: push,
  11764. unshift: unshift,
  11765. finish: finish,
  11766. sort: sort
  11767. };
  11768. }
  11769. function WebGLRenderLists(properties) {
  11770. let lists = new WeakMap();
  11771. function get(scene, renderCallDepth) {
  11772. let list;
  11773. if (lists.has(scene) === false) {
  11774. list = new WebGLRenderList(properties);
  11775. lists.set(scene, [list]);
  11776. } else {
  11777. if (renderCallDepth >= lists.get(scene).length) {
  11778. list = new WebGLRenderList(properties);
  11779. lists.get(scene).push(list);
  11780. } else {
  11781. list = lists.get(scene)[renderCallDepth];
  11782. }
  11783. }
  11784. return list;
  11785. }
  11786. function dispose() {
  11787. lists = new WeakMap();
  11788. }
  11789. return {
  11790. get: get,
  11791. dispose: dispose
  11792. };
  11793. }
  11794. function UniformsCache() {
  11795. const lights = {};
  11796. return {
  11797. get: function (light) {
  11798. if (lights[light.id] !== undefined) {
  11799. return lights[light.id];
  11800. }
  11801. let uniforms;
  11802. switch (light.type) {
  11803. case 'DirectionalLight':
  11804. uniforms = {
  11805. direction: new Vector3(),
  11806. color: new Color()
  11807. };
  11808. break;
  11809. case 'SpotLight':
  11810. uniforms = {
  11811. position: new Vector3(),
  11812. direction: new Vector3(),
  11813. color: new Color(),
  11814. distance: 0,
  11815. coneCos: 0,
  11816. penumbraCos: 0,
  11817. decay: 0
  11818. };
  11819. break;
  11820. case 'PointLight':
  11821. uniforms = {
  11822. position: new Vector3(),
  11823. color: new Color(),
  11824. distance: 0,
  11825. decay: 0
  11826. };
  11827. break;
  11828. case 'HemisphereLight':
  11829. uniforms = {
  11830. direction: new Vector3(),
  11831. skyColor: new Color(),
  11832. groundColor: new Color()
  11833. };
  11834. break;
  11835. case 'RectAreaLight':
  11836. uniforms = {
  11837. color: new Color(),
  11838. position: new Vector3(),
  11839. halfWidth: new Vector3(),
  11840. halfHeight: new Vector3()
  11841. };
  11842. break;
  11843. }
  11844. lights[light.id] = uniforms;
  11845. return uniforms;
  11846. }
  11847. };
  11848. }
  11849. function ShadowUniformsCache() {
  11850. const lights = {};
  11851. return {
  11852. get: function (light) {
  11853. if (lights[light.id] !== undefined) {
  11854. return lights[light.id];
  11855. }
  11856. let uniforms;
  11857. switch (light.type) {
  11858. case 'DirectionalLight':
  11859. uniforms = {
  11860. shadowBias: 0,
  11861. shadowNormalBias: 0,
  11862. shadowRadius: 1,
  11863. shadowMapSize: new Vector2()
  11864. };
  11865. break;
  11866. case 'SpotLight':
  11867. uniforms = {
  11868. shadowBias: 0,
  11869. shadowNormalBias: 0,
  11870. shadowRadius: 1,
  11871. shadowMapSize: new Vector2()
  11872. };
  11873. break;
  11874. case 'PointLight':
  11875. uniforms = {
  11876. shadowBias: 0,
  11877. shadowNormalBias: 0,
  11878. shadowRadius: 1,
  11879. shadowMapSize: new Vector2(),
  11880. shadowCameraNear: 1,
  11881. shadowCameraFar: 1000
  11882. };
  11883. break;
  11884. // TODO (abelnation): set RectAreaLight shadow uniforms
  11885. }
  11886. lights[light.id] = uniforms;
  11887. return uniforms;
  11888. }
  11889. };
  11890. }
  11891. let nextVersion = 0;
  11892. function shadowCastingLightsFirst(lightA, lightB) {
  11893. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  11894. }
  11895. function WebGLLights(extensions, capabilities) {
  11896. const cache = new UniformsCache();
  11897. const shadowCache = ShadowUniformsCache();
  11898. const state = {
  11899. version: 0,
  11900. hash: {
  11901. directionalLength: -1,
  11902. pointLength: -1,
  11903. spotLength: -1,
  11904. rectAreaLength: -1,
  11905. hemiLength: -1,
  11906. numDirectionalShadows: -1,
  11907. numPointShadows: -1,
  11908. numSpotShadows: -1
  11909. },
  11910. ambient: [0, 0, 0],
  11911. probe: [],
  11912. directional: [],
  11913. directionalShadow: [],
  11914. directionalShadowMap: [],
  11915. directionalShadowMatrix: [],
  11916. spot: [],
  11917. spotShadow: [],
  11918. spotShadowMap: [],
  11919. spotShadowMatrix: [],
  11920. rectArea: [],
  11921. rectAreaLTC1: null,
  11922. rectAreaLTC2: null,
  11923. point: [],
  11924. pointShadow: [],
  11925. pointShadowMap: [],
  11926. pointShadowMatrix: [],
  11927. hemi: []
  11928. };
  11929. for (let i = 0; i < 9; i++) state.probe.push(new Vector3());
  11930. const vector3 = new Vector3();
  11931. const matrix4 = new Matrix4();
  11932. const matrix42 = new Matrix4();
  11933. function setup(lights) {
  11934. let r = 0,
  11935. g = 0,
  11936. b = 0;
  11937. for (let i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  11938. let directionalLength = 0;
  11939. let pointLength = 0;
  11940. let spotLength = 0;
  11941. let rectAreaLength = 0;
  11942. let hemiLength = 0;
  11943. let numDirectionalShadows = 0;
  11944. let numPointShadows = 0;
  11945. let numSpotShadows = 0;
  11946. lights.sort(shadowCastingLightsFirst);
  11947. for (let i = 0, l = lights.length; i < l; i++) {
  11948. const light = lights[i];
  11949. const color = light.color;
  11950. const intensity = light.intensity;
  11951. const distance = light.distance;
  11952. const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  11953. if (light.isAmbientLight) {
  11954. r += color.r * intensity;
  11955. g += color.g * intensity;
  11956. b += color.b * intensity;
  11957. } else if (light.isLightProbe) {
  11958. for (let j = 0; j < 9; j++) {
  11959. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  11960. }
  11961. } else if (light.isDirectionalLight) {
  11962. const uniforms = cache.get(light);
  11963. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  11964. if (light.castShadow) {
  11965. const shadow = light.shadow;
  11966. const shadowUniforms = shadowCache.get(light);
  11967. shadowUniforms.shadowBias = shadow.bias;
  11968. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11969. shadowUniforms.shadowRadius = shadow.radius;
  11970. shadowUniforms.shadowMapSize = shadow.mapSize;
  11971. state.directionalShadow[directionalLength] = shadowUniforms;
  11972. state.directionalShadowMap[directionalLength] = shadowMap;
  11973. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  11974. numDirectionalShadows++;
  11975. }
  11976. state.directional[directionalLength] = uniforms;
  11977. directionalLength++;
  11978. } else if (light.isSpotLight) {
  11979. const uniforms = cache.get(light);
  11980. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11981. uniforms.color.copy(color).multiplyScalar(intensity);
  11982. uniforms.distance = distance;
  11983. uniforms.coneCos = Math.cos(light.angle);
  11984. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  11985. uniforms.decay = light.decay;
  11986. if (light.castShadow) {
  11987. const shadow = light.shadow;
  11988. const shadowUniforms = shadowCache.get(light);
  11989. shadowUniforms.shadowBias = shadow.bias;
  11990. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11991. shadowUniforms.shadowRadius = shadow.radius;
  11992. shadowUniforms.shadowMapSize = shadow.mapSize;
  11993. state.spotShadow[spotLength] = shadowUniforms;
  11994. state.spotShadowMap[spotLength] = shadowMap;
  11995. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  11996. numSpotShadows++;
  11997. }
  11998. state.spot[spotLength] = uniforms;
  11999. spotLength++;
  12000. } else if (light.isRectAreaLight) {
  12001. const uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  12002. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  12003. // (b) intensity is the brightness of the light
  12004. uniforms.color.copy(color).multiplyScalar(intensity);
  12005. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12006. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12007. state.rectArea[rectAreaLength] = uniforms;
  12008. rectAreaLength++;
  12009. } else if (light.isPointLight) {
  12010. const uniforms = cache.get(light);
  12011. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  12012. uniforms.distance = light.distance;
  12013. uniforms.decay = light.decay;
  12014. if (light.castShadow) {
  12015. const shadow = light.shadow;
  12016. const shadowUniforms = shadowCache.get(light);
  12017. shadowUniforms.shadowBias = shadow.bias;
  12018. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12019. shadowUniforms.shadowRadius = shadow.radius;
  12020. shadowUniforms.shadowMapSize = shadow.mapSize;
  12021. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12022. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12023. state.pointShadow[pointLength] = shadowUniforms;
  12024. state.pointShadowMap[pointLength] = shadowMap;
  12025. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  12026. numPointShadows++;
  12027. }
  12028. state.point[pointLength] = uniforms;
  12029. pointLength++;
  12030. } else if (light.isHemisphereLight) {
  12031. const uniforms = cache.get(light);
  12032. uniforms.skyColor.copy(light.color).multiplyScalar(intensity);
  12033. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity);
  12034. state.hemi[hemiLength] = uniforms;
  12035. hemiLength++;
  12036. }
  12037. }
  12038. if (rectAreaLength > 0) {
  12039. if (capabilities.isWebGL2) {
  12040. // WebGL 2
  12041. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12042. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12043. } else {
  12044. // WebGL 1
  12045. if (extensions.has('OES_texture_float_linear') === true) {
  12046. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12047. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12048. } else if (extensions.has('OES_texture_half_float_linear') === true) {
  12049. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12050. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12051. } else {
  12052. console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
  12053. }
  12054. }
  12055. }
  12056. state.ambient[0] = r;
  12057. state.ambient[1] = g;
  12058. state.ambient[2] = b;
  12059. const hash = state.hash;
  12060. 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) {
  12061. state.directional.length = directionalLength;
  12062. state.spot.length = spotLength;
  12063. state.rectArea.length = rectAreaLength;
  12064. state.point.length = pointLength;
  12065. state.hemi.length = hemiLength;
  12066. state.directionalShadow.length = numDirectionalShadows;
  12067. state.directionalShadowMap.length = numDirectionalShadows;
  12068. state.pointShadow.length = numPointShadows;
  12069. state.pointShadowMap.length = numPointShadows;
  12070. state.spotShadow.length = numSpotShadows;
  12071. state.spotShadowMap.length = numSpotShadows;
  12072. state.directionalShadowMatrix.length = numDirectionalShadows;
  12073. state.pointShadowMatrix.length = numPointShadows;
  12074. state.spotShadowMatrix.length = numSpotShadows;
  12075. hash.directionalLength = directionalLength;
  12076. hash.pointLength = pointLength;
  12077. hash.spotLength = spotLength;
  12078. hash.rectAreaLength = rectAreaLength;
  12079. hash.hemiLength = hemiLength;
  12080. hash.numDirectionalShadows = numDirectionalShadows;
  12081. hash.numPointShadows = numPointShadows;
  12082. hash.numSpotShadows = numSpotShadows;
  12083. state.version = nextVersion++;
  12084. }
  12085. }
  12086. function setupView(lights, camera) {
  12087. let directionalLength = 0;
  12088. let pointLength = 0;
  12089. let spotLength = 0;
  12090. let rectAreaLength = 0;
  12091. let hemiLength = 0;
  12092. const viewMatrix = camera.matrixWorldInverse;
  12093. for (let i = 0, l = lights.length; i < l; i++) {
  12094. const light = lights[i];
  12095. if (light.isDirectionalLight) {
  12096. const uniforms = state.directional[directionalLength];
  12097. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12098. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12099. uniforms.direction.sub(vector3);
  12100. uniforms.direction.transformDirection(viewMatrix);
  12101. directionalLength++;
  12102. } else if (light.isSpotLight) {
  12103. const uniforms = state.spot[spotLength];
  12104. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12105. uniforms.position.applyMatrix4(viewMatrix);
  12106. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12107. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12108. uniforms.direction.sub(vector3);
  12109. uniforms.direction.transformDirection(viewMatrix);
  12110. spotLength++;
  12111. } else if (light.isRectAreaLight) {
  12112. const uniforms = state.rectArea[rectAreaLength];
  12113. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12114. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  12115. matrix42.identity();
  12116. matrix4.copy(light.matrixWorld);
  12117. matrix4.premultiply(viewMatrix);
  12118. matrix42.extractRotation(matrix4);
  12119. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12120. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12121. uniforms.halfWidth.applyMatrix4(matrix42);
  12122. uniforms.halfHeight.applyMatrix4(matrix42);
  12123. rectAreaLength++;
  12124. } else if (light.isPointLight) {
  12125. const uniforms = state.point[pointLength];
  12126. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12127. uniforms.position.applyMatrix4(viewMatrix);
  12128. pointLength++;
  12129. } else if (light.isHemisphereLight) {
  12130. const uniforms = state.hemi[hemiLength];
  12131. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12132. uniforms.direction.transformDirection(viewMatrix);
  12133. uniforms.direction.normalize();
  12134. hemiLength++;
  12135. }
  12136. }
  12137. }
  12138. return {
  12139. setup: setup,
  12140. setupView: setupView,
  12141. state: state
  12142. };
  12143. }
  12144. function WebGLRenderState(extensions, capabilities) {
  12145. const lights = new WebGLLights(extensions, capabilities);
  12146. const lightsArray = [];
  12147. const shadowsArray = [];
  12148. function init() {
  12149. lightsArray.length = 0;
  12150. shadowsArray.length = 0;
  12151. }
  12152. function pushLight(light) {
  12153. lightsArray.push(light);
  12154. }
  12155. function pushShadow(shadowLight) {
  12156. shadowsArray.push(shadowLight);
  12157. }
  12158. function setupLights() {
  12159. lights.setup(lightsArray);
  12160. }
  12161. function setupLightsView(camera) {
  12162. lights.setupView(lightsArray, camera);
  12163. }
  12164. const state = {
  12165. lightsArray: lightsArray,
  12166. shadowsArray: shadowsArray,
  12167. lights: lights
  12168. };
  12169. return {
  12170. init: init,
  12171. state: state,
  12172. setupLights: setupLights,
  12173. setupLightsView: setupLightsView,
  12174. pushLight: pushLight,
  12175. pushShadow: pushShadow
  12176. };
  12177. }
  12178. function WebGLRenderStates(extensions, capabilities) {
  12179. let renderStates = new WeakMap();
  12180. function get(scene, renderCallDepth = 0) {
  12181. let renderState;
  12182. if (renderStates.has(scene) === false) {
  12183. renderState = new WebGLRenderState(extensions, capabilities);
  12184. renderStates.set(scene, [renderState]);
  12185. } else {
  12186. if (renderCallDepth >= renderStates.get(scene).length) {
  12187. renderState = new WebGLRenderState(extensions, capabilities);
  12188. renderStates.get(scene).push(renderState);
  12189. } else {
  12190. renderState = renderStates.get(scene)[renderCallDepth];
  12191. }
  12192. }
  12193. return renderState;
  12194. }
  12195. function dispose() {
  12196. renderStates = new WeakMap();
  12197. }
  12198. return {
  12199. get: get,
  12200. dispose: dispose
  12201. };
  12202. }
  12203. /**
  12204. * parameters = {
  12205. *
  12206. * opacity: <float>,
  12207. *
  12208. * map: new THREE.Texture( <Image> ),
  12209. *
  12210. * alphaMap: new THREE.Texture( <Image> ),
  12211. *
  12212. * displacementMap: new THREE.Texture( <Image> ),
  12213. * displacementScale: <float>,
  12214. * displacementBias: <float>,
  12215. *
  12216. * wireframe: <boolean>,
  12217. * wireframeLinewidth: <float>
  12218. * }
  12219. */
  12220. class MeshDepthMaterial extends Material {
  12221. constructor(parameters) {
  12222. super();
  12223. this.type = 'MeshDepthMaterial';
  12224. this.depthPacking = BasicDepthPacking;
  12225. this.map = null;
  12226. this.alphaMap = null;
  12227. this.displacementMap = null;
  12228. this.displacementScale = 1;
  12229. this.displacementBias = 0;
  12230. this.wireframe = false;
  12231. this.wireframeLinewidth = 1;
  12232. this.fog = false;
  12233. this.setValues(parameters);
  12234. }
  12235. copy(source) {
  12236. super.copy(source);
  12237. this.depthPacking = source.depthPacking;
  12238. this.map = source.map;
  12239. this.alphaMap = source.alphaMap;
  12240. this.displacementMap = source.displacementMap;
  12241. this.displacementScale = source.displacementScale;
  12242. this.displacementBias = source.displacementBias;
  12243. this.wireframe = source.wireframe;
  12244. this.wireframeLinewidth = source.wireframeLinewidth;
  12245. return this;
  12246. }
  12247. }
  12248. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  12249. /**
  12250. * parameters = {
  12251. *
  12252. * referencePosition: <float>,
  12253. * nearDistance: <float>,
  12254. * farDistance: <float>,
  12255. *
  12256. * map: new THREE.Texture( <Image> ),
  12257. *
  12258. * alphaMap: new THREE.Texture( <Image> ),
  12259. *
  12260. * displacementMap: new THREE.Texture( <Image> ),
  12261. * displacementScale: <float>,
  12262. * displacementBias: <float>
  12263. *
  12264. * }
  12265. */
  12266. class MeshDistanceMaterial extends Material {
  12267. constructor(parameters) {
  12268. super();
  12269. this.type = 'MeshDistanceMaterial';
  12270. this.referencePosition = new Vector3();
  12271. this.nearDistance = 1;
  12272. this.farDistance = 1000;
  12273. this.map = null;
  12274. this.alphaMap = null;
  12275. this.displacementMap = null;
  12276. this.displacementScale = 1;
  12277. this.displacementBias = 0;
  12278. this.fog = false;
  12279. this.setValues(parameters);
  12280. }
  12281. copy(source) {
  12282. super.copy(source);
  12283. this.referencePosition.copy(source.referencePosition);
  12284. this.nearDistance = source.nearDistance;
  12285. this.farDistance = source.farDistance;
  12286. this.map = source.map;
  12287. this.alphaMap = source.alphaMap;
  12288. this.displacementMap = source.displacementMap;
  12289. this.displacementScale = source.displacementScale;
  12290. this.displacementBias = source.displacementBias;
  12291. return this;
  12292. }
  12293. }
  12294. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  12295. 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}";
  12296. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12297. function WebGLShadowMap(_renderer, _objects, _capabilities) {
  12298. let _frustum = new Frustum();
  12299. const _shadowMapSize = new Vector2(),
  12300. _viewportSize = new Vector2(),
  12301. _viewport = new Vector4(),
  12302. _depthMaterial = new MeshDepthMaterial({
  12303. depthPacking: RGBADepthPacking
  12304. }),
  12305. _distanceMaterial = new MeshDistanceMaterial(),
  12306. _materialCache = {},
  12307. _maxTextureSize = _capabilities.maxTextureSize;
  12308. const shadowSide = {
  12309. 0: BackSide,
  12310. 1: FrontSide,
  12311. 2: DoubleSide
  12312. };
  12313. const shadowMaterialVertical = new ShaderMaterial({
  12314. uniforms: {
  12315. shadow_pass: {
  12316. value: null
  12317. },
  12318. resolution: {
  12319. value: new Vector2()
  12320. },
  12321. radius: {
  12322. value: 4.0
  12323. },
  12324. samples: {
  12325. value: 8.0
  12326. }
  12327. },
  12328. vertexShader: vsm_vert,
  12329. fragmentShader: vsm_frag
  12330. });
  12331. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12332. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12333. const fullScreenTri = new BufferGeometry();
  12334. fullScreenTri.setAttribute('position', new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  12335. const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  12336. const scope = this;
  12337. this.enabled = false;
  12338. this.autoUpdate = true;
  12339. this.needsUpdate = false;
  12340. this.type = PCFShadowMap;
  12341. this.render = function (lights, scene, camera) {
  12342. if (scope.enabled === false) return;
  12343. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  12344. if (lights.length === 0) return;
  12345. const currentRenderTarget = _renderer.getRenderTarget();
  12346. const activeCubeFace = _renderer.getActiveCubeFace();
  12347. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12348. const _state = _renderer.state; // Set GL state for depth map.
  12349. _state.setBlending(NoBlending);
  12350. _state.buffers.color.setClear(1, 1, 1, 1);
  12351. _state.buffers.depth.setTest(true);
  12352. _state.setScissorTest(false); // render depth map
  12353. for (let i = 0, il = lights.length; i < il; i++) {
  12354. const light = lights[i];
  12355. const shadow = light.shadow;
  12356. if (shadow === undefined) {
  12357. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  12358. continue;
  12359. }
  12360. if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
  12361. _shadowMapSize.copy(shadow.mapSize);
  12362. const shadowFrameExtents = shadow.getFrameExtents();
  12363. _shadowMapSize.multiply(shadowFrameExtents);
  12364. _viewportSize.copy(shadow.mapSize);
  12365. if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) {
  12366. if (_shadowMapSize.x > _maxTextureSize) {
  12367. _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x);
  12368. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12369. shadow.mapSize.x = _viewportSize.x;
  12370. }
  12371. if (_shadowMapSize.y > _maxTextureSize) {
  12372. _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y);
  12373. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12374. shadow.mapSize.y = _viewportSize.y;
  12375. }
  12376. }
  12377. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12378. const pars = {
  12379. minFilter: LinearFilter,
  12380. magFilter: LinearFilter,
  12381. format: RGBAFormat
  12382. };
  12383. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12384. shadow.map.texture.name = light.name + '.shadowMap';
  12385. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12386. shadow.camera.updateProjectionMatrix();
  12387. }
  12388. if (shadow.map === null) {
  12389. const pars = {
  12390. minFilter: NearestFilter,
  12391. magFilter: NearestFilter,
  12392. format: RGBAFormat
  12393. };
  12394. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12395. shadow.map.texture.name = light.name + '.shadowMap';
  12396. shadow.camera.updateProjectionMatrix();
  12397. }
  12398. _renderer.setRenderTarget(shadow.map);
  12399. _renderer.clear();
  12400. const viewportCount = shadow.getViewportCount();
  12401. for (let vp = 0; vp < viewportCount; vp++) {
  12402. const viewport = shadow.getViewport(vp);
  12403. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  12404. _state.viewport(_viewport);
  12405. shadow.updateMatrices(light, vp);
  12406. _frustum = shadow.getFrustum();
  12407. renderObject(scene, camera, shadow.camera, light, this.type);
  12408. } // do blur pass for VSM
  12409. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12410. VSMPass(shadow, camera);
  12411. }
  12412. shadow.needsUpdate = false;
  12413. }
  12414. scope.needsUpdate = false;
  12415. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  12416. };
  12417. function VSMPass(shadow, camera) {
  12418. const geometry = _objects.update(fullScreenMesh); // vertical pass
  12419. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12420. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12421. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12422. shadowMaterialVertical.uniforms.samples.value = shadow.blurSamples;
  12423. _renderer.setRenderTarget(shadow.mapPass);
  12424. _renderer.clear();
  12425. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizontal pass
  12426. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12427. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12428. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12429. shadowMaterialHorizontal.uniforms.samples.value = shadow.blurSamples;
  12430. _renderer.setRenderTarget(shadow.map);
  12431. _renderer.clear();
  12432. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null);
  12433. }
  12434. function getDepthMaterial(object, geometry, material, light, shadowCameraNear, shadowCameraFar, type) {
  12435. let result = null;
  12436. const customMaterial = light.isPointLight === true ? object.customDistanceMaterial : object.customDepthMaterial;
  12437. if (customMaterial !== undefined) {
  12438. result = customMaterial;
  12439. } else {
  12440. result = light.isPointLight === true ? _distanceMaterial : _depthMaterial;
  12441. }
  12442. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0) {
  12443. // in this case we need a unique material instance reflecting the
  12444. // appropriate state
  12445. const keyA = result.uuid,
  12446. keyB = material.uuid;
  12447. let materialsForVariant = _materialCache[keyA];
  12448. if (materialsForVariant === undefined) {
  12449. materialsForVariant = {};
  12450. _materialCache[keyA] = materialsForVariant;
  12451. }
  12452. let cachedMaterial = materialsForVariant[keyB];
  12453. if (cachedMaterial === undefined) {
  12454. cachedMaterial = result.clone();
  12455. materialsForVariant[keyB] = cachedMaterial;
  12456. }
  12457. result = cachedMaterial;
  12458. }
  12459. result.visible = material.visible;
  12460. result.wireframe = material.wireframe;
  12461. if (type === VSMShadowMap) {
  12462. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  12463. } else {
  12464. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  12465. }
  12466. result.clipShadows = material.clipShadows;
  12467. result.clippingPlanes = material.clippingPlanes;
  12468. result.clipIntersection = material.clipIntersection;
  12469. result.wireframeLinewidth = material.wireframeLinewidth;
  12470. result.linewidth = material.linewidth;
  12471. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  12472. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  12473. result.nearDistance = shadowCameraNear;
  12474. result.farDistance = shadowCameraFar;
  12475. }
  12476. return result;
  12477. }
  12478. function renderObject(object, camera, shadowCamera, light, type) {
  12479. if (object.visible === false) return;
  12480. const visible = object.layers.test(camera.layers);
  12481. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  12482. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  12483. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  12484. const geometry = _objects.update(object);
  12485. const material = object.material;
  12486. if (Array.isArray(material)) {
  12487. const groups = geometry.groups;
  12488. for (let k = 0, kl = groups.length; k < kl; k++) {
  12489. const group = groups[k];
  12490. const groupMaterial = material[group.materialIndex];
  12491. if (groupMaterial && groupMaterial.visible) {
  12492. const depthMaterial = getDepthMaterial(object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  12493. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  12494. }
  12495. }
  12496. } else if (material.visible) {
  12497. const depthMaterial = getDepthMaterial(object, geometry, material, light, shadowCamera.near, shadowCamera.far, type);
  12498. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  12499. }
  12500. }
  12501. }
  12502. const children = object.children;
  12503. for (let i = 0, l = children.length; i < l; i++) {
  12504. renderObject(children[i], camera, shadowCamera, light, type);
  12505. }
  12506. }
  12507. }
  12508. function WebGLState(gl, extensions, capabilities) {
  12509. const isWebGL2 = capabilities.isWebGL2;
  12510. function ColorBuffer() {
  12511. let locked = false;
  12512. const color = new Vector4();
  12513. let currentColorMask = null;
  12514. const currentColorClear = new Vector4(0, 0, 0, 0);
  12515. return {
  12516. setMask: function (colorMask) {
  12517. if (currentColorMask !== colorMask && !locked) {
  12518. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  12519. currentColorMask = colorMask;
  12520. }
  12521. },
  12522. setLocked: function (lock) {
  12523. locked = lock;
  12524. },
  12525. setClear: function (r, g, b, a, premultipliedAlpha) {
  12526. if (premultipliedAlpha === true) {
  12527. r *= a;
  12528. g *= a;
  12529. b *= a;
  12530. }
  12531. color.set(r, g, b, a);
  12532. if (currentColorClear.equals(color) === false) {
  12533. gl.clearColor(r, g, b, a);
  12534. currentColorClear.copy(color);
  12535. }
  12536. },
  12537. reset: function () {
  12538. locked = false;
  12539. currentColorMask = null;
  12540. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  12541. }
  12542. };
  12543. }
  12544. function DepthBuffer() {
  12545. let locked = false;
  12546. let currentDepthMask = null;
  12547. let currentDepthFunc = null;
  12548. let currentDepthClear = null;
  12549. return {
  12550. setTest: function (depthTest) {
  12551. if (depthTest) {
  12552. enable(gl.DEPTH_TEST);
  12553. } else {
  12554. disable(gl.DEPTH_TEST);
  12555. }
  12556. },
  12557. setMask: function (depthMask) {
  12558. if (currentDepthMask !== depthMask && !locked) {
  12559. gl.depthMask(depthMask);
  12560. currentDepthMask = depthMask;
  12561. }
  12562. },
  12563. setFunc: function (depthFunc) {
  12564. if (currentDepthFunc !== depthFunc) {
  12565. if (depthFunc) {
  12566. switch (depthFunc) {
  12567. case NeverDepth:
  12568. gl.depthFunc(gl.NEVER);
  12569. break;
  12570. case AlwaysDepth:
  12571. gl.depthFunc(gl.ALWAYS);
  12572. break;
  12573. case LessDepth:
  12574. gl.depthFunc(gl.LESS);
  12575. break;
  12576. case LessEqualDepth:
  12577. gl.depthFunc(gl.LEQUAL);
  12578. break;
  12579. case EqualDepth:
  12580. gl.depthFunc(gl.EQUAL);
  12581. break;
  12582. case GreaterEqualDepth:
  12583. gl.depthFunc(gl.GEQUAL);
  12584. break;
  12585. case GreaterDepth:
  12586. gl.depthFunc(gl.GREATER);
  12587. break;
  12588. case NotEqualDepth:
  12589. gl.depthFunc(gl.NOTEQUAL);
  12590. break;
  12591. default:
  12592. gl.depthFunc(gl.LEQUAL);
  12593. }
  12594. } else {
  12595. gl.depthFunc(gl.LEQUAL);
  12596. }
  12597. currentDepthFunc = depthFunc;
  12598. }
  12599. },
  12600. setLocked: function (lock) {
  12601. locked = lock;
  12602. },
  12603. setClear: function (depth) {
  12604. if (currentDepthClear !== depth) {
  12605. gl.clearDepth(depth);
  12606. currentDepthClear = depth;
  12607. }
  12608. },
  12609. reset: function () {
  12610. locked = false;
  12611. currentDepthMask = null;
  12612. currentDepthFunc = null;
  12613. currentDepthClear = null;
  12614. }
  12615. };
  12616. }
  12617. function StencilBuffer() {
  12618. let locked = false;
  12619. let currentStencilMask = null;
  12620. let currentStencilFunc = null;
  12621. let currentStencilRef = null;
  12622. let currentStencilFuncMask = null;
  12623. let currentStencilFail = null;
  12624. let currentStencilZFail = null;
  12625. let currentStencilZPass = null;
  12626. let currentStencilClear = null;
  12627. return {
  12628. setTest: function (stencilTest) {
  12629. if (!locked) {
  12630. if (stencilTest) {
  12631. enable(gl.STENCIL_TEST);
  12632. } else {
  12633. disable(gl.STENCIL_TEST);
  12634. }
  12635. }
  12636. },
  12637. setMask: function (stencilMask) {
  12638. if (currentStencilMask !== stencilMask && !locked) {
  12639. gl.stencilMask(stencilMask);
  12640. currentStencilMask = stencilMask;
  12641. }
  12642. },
  12643. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  12644. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  12645. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  12646. currentStencilFunc = stencilFunc;
  12647. currentStencilRef = stencilRef;
  12648. currentStencilFuncMask = stencilMask;
  12649. }
  12650. },
  12651. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  12652. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  12653. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  12654. currentStencilFail = stencilFail;
  12655. currentStencilZFail = stencilZFail;
  12656. currentStencilZPass = stencilZPass;
  12657. }
  12658. },
  12659. setLocked: function (lock) {
  12660. locked = lock;
  12661. },
  12662. setClear: function (stencil) {
  12663. if (currentStencilClear !== stencil) {
  12664. gl.clearStencil(stencil);
  12665. currentStencilClear = stencil;
  12666. }
  12667. },
  12668. reset: function () {
  12669. locked = false;
  12670. currentStencilMask = null;
  12671. currentStencilFunc = null;
  12672. currentStencilRef = null;
  12673. currentStencilFuncMask = null;
  12674. currentStencilFail = null;
  12675. currentStencilZFail = null;
  12676. currentStencilZPass = null;
  12677. currentStencilClear = null;
  12678. }
  12679. };
  12680. } //
  12681. const colorBuffer = new ColorBuffer();
  12682. const depthBuffer = new DepthBuffer();
  12683. const stencilBuffer = new StencilBuffer();
  12684. let enabledCapabilities = {};
  12685. let xrFramebuffer = null;
  12686. let currentBoundFramebuffers = {};
  12687. let currentProgram = null;
  12688. let currentBlendingEnabled = false;
  12689. let currentBlending = null;
  12690. let currentBlendEquation = null;
  12691. let currentBlendSrc = null;
  12692. let currentBlendDst = null;
  12693. let currentBlendEquationAlpha = null;
  12694. let currentBlendSrcAlpha = null;
  12695. let currentBlendDstAlpha = null;
  12696. let currentPremultipledAlpha = false;
  12697. let currentFlipSided = null;
  12698. let currentCullFace = null;
  12699. let currentLineWidth = null;
  12700. let currentPolygonOffsetFactor = null;
  12701. let currentPolygonOffsetUnits = null;
  12702. const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12703. let lineWidthAvailable = false;
  12704. let version = 0;
  12705. const glVersion = gl.getParameter(gl.VERSION);
  12706. if (glVersion.indexOf('WebGL') !== -1) {
  12707. version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]);
  12708. lineWidthAvailable = version >= 1.0;
  12709. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  12710. version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);
  12711. lineWidthAvailable = version >= 2.0;
  12712. }
  12713. let currentTextureSlot = null;
  12714. let currentBoundTextures = {};
  12715. const scissorParam = gl.getParameter(gl.SCISSOR_BOX);
  12716. const viewportParam = gl.getParameter(gl.VIEWPORT);
  12717. const currentScissor = new Vector4().fromArray(scissorParam);
  12718. const currentViewport = new Vector4().fromArray(viewportParam);
  12719. function createTexture(type, target, count) {
  12720. const data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  12721. const texture = gl.createTexture();
  12722. gl.bindTexture(type, texture);
  12723. gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12724. gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12725. for (let i = 0; i < count; i++) {
  12726. gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
  12727. }
  12728. return texture;
  12729. }
  12730. const emptyTextures = {};
  12731. emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1);
  12732. emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); // init
  12733. colorBuffer.setClear(0, 0, 0, 1);
  12734. depthBuffer.setClear(1);
  12735. stencilBuffer.setClear(0);
  12736. enable(gl.DEPTH_TEST);
  12737. depthBuffer.setFunc(LessEqualDepth);
  12738. setFlipSided(false);
  12739. setCullFace(CullFaceBack);
  12740. enable(gl.CULL_FACE);
  12741. setBlending(NoBlending); //
  12742. function enable(id) {
  12743. if (enabledCapabilities[id] !== true) {
  12744. gl.enable(id);
  12745. enabledCapabilities[id] = true;
  12746. }
  12747. }
  12748. function disable(id) {
  12749. if (enabledCapabilities[id] !== false) {
  12750. gl.disable(id);
  12751. enabledCapabilities[id] = false;
  12752. }
  12753. }
  12754. function bindXRFramebuffer(framebuffer) {
  12755. if (framebuffer !== xrFramebuffer) {
  12756. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  12757. xrFramebuffer = framebuffer;
  12758. }
  12759. }
  12760. function bindFramebuffer(target, framebuffer) {
  12761. if (framebuffer === null && xrFramebuffer !== null) framebuffer = xrFramebuffer; // use active XR framebuffer if available
  12762. if (currentBoundFramebuffers[target] !== framebuffer) {
  12763. gl.bindFramebuffer(target, framebuffer);
  12764. currentBoundFramebuffers[target] = framebuffer;
  12765. if (isWebGL2) {
  12766. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  12767. if (target === gl.DRAW_FRAMEBUFFER) {
  12768. currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer;
  12769. }
  12770. if (target === gl.FRAMEBUFFER) {
  12771. currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer;
  12772. }
  12773. }
  12774. return true;
  12775. }
  12776. return false;
  12777. }
  12778. function useProgram(program) {
  12779. if (currentProgram !== program) {
  12780. gl.useProgram(program);
  12781. currentProgram = program;
  12782. return true;
  12783. }
  12784. return false;
  12785. }
  12786. const equationToGL = {
  12787. [AddEquation]: gl.FUNC_ADD,
  12788. [SubtractEquation]: gl.FUNC_SUBTRACT,
  12789. [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT
  12790. };
  12791. if (isWebGL2) {
  12792. equationToGL[MinEquation] = gl.MIN;
  12793. equationToGL[MaxEquation] = gl.MAX;
  12794. } else {
  12795. const extension = extensions.get('EXT_blend_minmax');
  12796. if (extension !== null) {
  12797. equationToGL[MinEquation] = extension.MIN_EXT;
  12798. equationToGL[MaxEquation] = extension.MAX_EXT;
  12799. }
  12800. }
  12801. const factorToGL = {
  12802. [ZeroFactor]: gl.ZERO,
  12803. [OneFactor]: gl.ONE,
  12804. [SrcColorFactor]: gl.SRC_COLOR,
  12805. [SrcAlphaFactor]: gl.SRC_ALPHA,
  12806. [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE,
  12807. [DstColorFactor]: gl.DST_COLOR,
  12808. [DstAlphaFactor]: gl.DST_ALPHA,
  12809. [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR,
  12810. [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA,
  12811. [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR,
  12812. [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA
  12813. };
  12814. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  12815. if (blending === NoBlending) {
  12816. if (currentBlendingEnabled === true) {
  12817. disable(gl.BLEND);
  12818. currentBlendingEnabled = false;
  12819. }
  12820. return;
  12821. }
  12822. if (currentBlendingEnabled === false) {
  12823. enable(gl.BLEND);
  12824. currentBlendingEnabled = true;
  12825. }
  12826. if (blending !== CustomBlending) {
  12827. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  12828. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  12829. gl.blendEquation(gl.FUNC_ADD);
  12830. currentBlendEquation = AddEquation;
  12831. currentBlendEquationAlpha = AddEquation;
  12832. }
  12833. if (premultipliedAlpha) {
  12834. switch (blending) {
  12835. case NormalBlending:
  12836. gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  12837. break;
  12838. case AdditiveBlending:
  12839. gl.blendFunc(gl.ONE, gl.ONE);
  12840. break;
  12841. case SubtractiveBlending:
  12842. gl.blendFuncSeparate(gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA);
  12843. break;
  12844. case MultiplyBlending:
  12845. gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA);
  12846. break;
  12847. default:
  12848. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12849. break;
  12850. }
  12851. } else {
  12852. switch (blending) {
  12853. case NormalBlending:
  12854. gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  12855. break;
  12856. case AdditiveBlending:
  12857. gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  12858. break;
  12859. case SubtractiveBlending:
  12860. gl.blendFunc(gl.ZERO, gl.ONE_MINUS_SRC_COLOR);
  12861. break;
  12862. case MultiplyBlending:
  12863. gl.blendFunc(gl.ZERO, gl.SRC_COLOR);
  12864. break;
  12865. default:
  12866. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12867. break;
  12868. }
  12869. }
  12870. currentBlendSrc = null;
  12871. currentBlendDst = null;
  12872. currentBlendSrcAlpha = null;
  12873. currentBlendDstAlpha = null;
  12874. currentBlending = blending;
  12875. currentPremultipledAlpha = premultipliedAlpha;
  12876. }
  12877. return;
  12878. } // custom blending
  12879. blendEquationAlpha = blendEquationAlpha || blendEquation;
  12880. blendSrcAlpha = blendSrcAlpha || blendSrc;
  12881. blendDstAlpha = blendDstAlpha || blendDst;
  12882. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  12883. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  12884. currentBlendEquation = blendEquation;
  12885. currentBlendEquationAlpha = blendEquationAlpha;
  12886. }
  12887. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  12888. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  12889. currentBlendSrc = blendSrc;
  12890. currentBlendDst = blendDst;
  12891. currentBlendSrcAlpha = blendSrcAlpha;
  12892. currentBlendDstAlpha = blendDstAlpha;
  12893. }
  12894. currentBlending = blending;
  12895. currentPremultipledAlpha = null;
  12896. }
  12897. function setMaterial(material, frontFaceCW) {
  12898. material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE);
  12899. let flipSided = material.side === BackSide;
  12900. if (frontFaceCW) flipSided = !flipSided;
  12901. setFlipSided(flipSided);
  12902. 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);
  12903. depthBuffer.setFunc(material.depthFunc);
  12904. depthBuffer.setTest(material.depthTest);
  12905. depthBuffer.setMask(material.depthWrite);
  12906. colorBuffer.setMask(material.colorWrite);
  12907. const stencilWrite = material.stencilWrite;
  12908. stencilBuffer.setTest(stencilWrite);
  12909. if (stencilWrite) {
  12910. stencilBuffer.setMask(material.stencilWriteMask);
  12911. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  12912. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  12913. }
  12914. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  12915. material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  12916. } //
  12917. function setFlipSided(flipSided) {
  12918. if (currentFlipSided !== flipSided) {
  12919. if (flipSided) {
  12920. gl.frontFace(gl.CW);
  12921. } else {
  12922. gl.frontFace(gl.CCW);
  12923. }
  12924. currentFlipSided = flipSided;
  12925. }
  12926. }
  12927. function setCullFace(cullFace) {
  12928. if (cullFace !== CullFaceNone) {
  12929. enable(gl.CULL_FACE);
  12930. if (cullFace !== currentCullFace) {
  12931. if (cullFace === CullFaceBack) {
  12932. gl.cullFace(gl.BACK);
  12933. } else if (cullFace === CullFaceFront) {
  12934. gl.cullFace(gl.FRONT);
  12935. } else {
  12936. gl.cullFace(gl.FRONT_AND_BACK);
  12937. }
  12938. }
  12939. } else {
  12940. disable(gl.CULL_FACE);
  12941. }
  12942. currentCullFace = cullFace;
  12943. }
  12944. function setLineWidth(width) {
  12945. if (width !== currentLineWidth) {
  12946. if (lineWidthAvailable) gl.lineWidth(width);
  12947. currentLineWidth = width;
  12948. }
  12949. }
  12950. function setPolygonOffset(polygonOffset, factor, units) {
  12951. if (polygonOffset) {
  12952. enable(gl.POLYGON_OFFSET_FILL);
  12953. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  12954. gl.polygonOffset(factor, units);
  12955. currentPolygonOffsetFactor = factor;
  12956. currentPolygonOffsetUnits = units;
  12957. }
  12958. } else {
  12959. disable(gl.POLYGON_OFFSET_FILL);
  12960. }
  12961. }
  12962. function setScissorTest(scissorTest) {
  12963. if (scissorTest) {
  12964. enable(gl.SCISSOR_TEST);
  12965. } else {
  12966. disable(gl.SCISSOR_TEST);
  12967. }
  12968. } // texture
  12969. function activeTexture(webglSlot) {
  12970. if (webglSlot === undefined) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  12971. if (currentTextureSlot !== webglSlot) {
  12972. gl.activeTexture(webglSlot);
  12973. currentTextureSlot = webglSlot;
  12974. }
  12975. }
  12976. function bindTexture(webglType, webglTexture) {
  12977. if (currentTextureSlot === null) {
  12978. activeTexture();
  12979. }
  12980. let boundTexture = currentBoundTextures[currentTextureSlot];
  12981. if (boundTexture === undefined) {
  12982. boundTexture = {
  12983. type: undefined,
  12984. texture: undefined
  12985. };
  12986. currentBoundTextures[currentTextureSlot] = boundTexture;
  12987. }
  12988. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  12989. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  12990. boundTexture.type = webglType;
  12991. boundTexture.texture = webglTexture;
  12992. }
  12993. }
  12994. function unbindTexture() {
  12995. const boundTexture = currentBoundTextures[currentTextureSlot];
  12996. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  12997. gl.bindTexture(boundTexture.type, null);
  12998. boundTexture.type = undefined;
  12999. boundTexture.texture = undefined;
  13000. }
  13001. }
  13002. function compressedTexImage2D() {
  13003. try {
  13004. gl.compressedTexImage2D.apply(gl, arguments);
  13005. } catch (error) {
  13006. console.error('THREE.WebGLState:', error);
  13007. }
  13008. }
  13009. function texImage2D() {
  13010. try {
  13011. gl.texImage2D.apply(gl, arguments);
  13012. } catch (error) {
  13013. console.error('THREE.WebGLState:', error);
  13014. }
  13015. }
  13016. function texImage3D() {
  13017. try {
  13018. gl.texImage3D.apply(gl, arguments);
  13019. } catch (error) {
  13020. console.error('THREE.WebGLState:', error);
  13021. }
  13022. } //
  13023. function scissor(scissor) {
  13024. if (currentScissor.equals(scissor) === false) {
  13025. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  13026. currentScissor.copy(scissor);
  13027. }
  13028. }
  13029. function viewport(viewport) {
  13030. if (currentViewport.equals(viewport) === false) {
  13031. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  13032. currentViewport.copy(viewport);
  13033. }
  13034. } //
  13035. function reset() {
  13036. // reset state
  13037. gl.disable(gl.BLEND);
  13038. gl.disable(gl.CULL_FACE);
  13039. gl.disable(gl.DEPTH_TEST);
  13040. gl.disable(gl.POLYGON_OFFSET_FILL);
  13041. gl.disable(gl.SCISSOR_TEST);
  13042. gl.disable(gl.STENCIL_TEST);
  13043. gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  13044. gl.blendEquation(gl.FUNC_ADD);
  13045. gl.blendFunc(gl.ONE, gl.ZERO);
  13046. gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO);
  13047. gl.colorMask(true, true, true, true);
  13048. gl.clearColor(0, 0, 0, 0);
  13049. gl.depthMask(true);
  13050. gl.depthFunc(gl.LESS);
  13051. gl.clearDepth(1);
  13052. gl.stencilMask(0xffffffff);
  13053. gl.stencilFunc(gl.ALWAYS, 0, 0xffffffff);
  13054. gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
  13055. gl.clearStencil(0);
  13056. gl.cullFace(gl.BACK);
  13057. gl.frontFace(gl.CCW);
  13058. gl.polygonOffset(0, 0);
  13059. gl.activeTexture(gl.TEXTURE0);
  13060. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13061. if (isWebGL2 === true) {
  13062. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
  13063. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  13064. }
  13065. gl.useProgram(null);
  13066. gl.lineWidth(1);
  13067. gl.scissor(0, 0, gl.canvas.width, gl.canvas.height);
  13068. gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); // reset internals
  13069. enabledCapabilities = {};
  13070. currentTextureSlot = null;
  13071. currentBoundTextures = {};
  13072. xrFramebuffer = null;
  13073. currentBoundFramebuffers = {};
  13074. currentProgram = null;
  13075. currentBlendingEnabled = false;
  13076. currentBlending = null;
  13077. currentBlendEquation = null;
  13078. currentBlendSrc = null;
  13079. currentBlendDst = null;
  13080. currentBlendEquationAlpha = null;
  13081. currentBlendSrcAlpha = null;
  13082. currentBlendDstAlpha = null;
  13083. currentPremultipledAlpha = false;
  13084. currentFlipSided = null;
  13085. currentCullFace = null;
  13086. currentLineWidth = null;
  13087. currentPolygonOffsetFactor = null;
  13088. currentPolygonOffsetUnits = null;
  13089. currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height);
  13090. currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height);
  13091. colorBuffer.reset();
  13092. depthBuffer.reset();
  13093. stencilBuffer.reset();
  13094. }
  13095. return {
  13096. buffers: {
  13097. color: colorBuffer,
  13098. depth: depthBuffer,
  13099. stencil: stencilBuffer
  13100. },
  13101. enable: enable,
  13102. disable: disable,
  13103. bindFramebuffer: bindFramebuffer,
  13104. bindXRFramebuffer: bindXRFramebuffer,
  13105. useProgram: useProgram,
  13106. setBlending: setBlending,
  13107. setMaterial: setMaterial,
  13108. setFlipSided: setFlipSided,
  13109. setCullFace: setCullFace,
  13110. setLineWidth: setLineWidth,
  13111. setPolygonOffset: setPolygonOffset,
  13112. setScissorTest: setScissorTest,
  13113. activeTexture: activeTexture,
  13114. bindTexture: bindTexture,
  13115. unbindTexture: unbindTexture,
  13116. compressedTexImage2D: compressedTexImage2D,
  13117. texImage2D: texImage2D,
  13118. texImage3D: texImage3D,
  13119. scissor: scissor,
  13120. viewport: viewport,
  13121. reset: reset
  13122. };
  13123. }
  13124. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  13125. const isWebGL2 = capabilities.isWebGL2;
  13126. const maxTextures = capabilities.maxTextures;
  13127. const maxCubemapSize = capabilities.maxCubemapSize;
  13128. const maxTextureSize = capabilities.maxTextureSize;
  13129. const maxSamples = capabilities.maxSamples;
  13130. const _videoTextures = new WeakMap();
  13131. let _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13132. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13133. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13134. let useOffscreenCanvas = false;
  13135. try {
  13136. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext('2d') !== null;
  13137. } catch (err) {// Ignore any errors
  13138. }
  13139. function createCanvas(width, height) {
  13140. // Use OffscreenCanvas when available. Specially needed in web workers
  13141. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  13142. }
  13143. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  13144. let scale = 1; // handle case if texture exceeds max size
  13145. if (image.width > maxSize || image.height > maxSize) {
  13146. scale = maxSize / Math.max(image.width, image.height);
  13147. } // only perform resize if necessary
  13148. if (scale < 1 || needsPowerOfTwo === true) {
  13149. // only perform resize for certain image types
  13150. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  13151. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13152. const width = floor(scale * image.width);
  13153. const height = floor(scale * image.height);
  13154. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  13155. const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  13156. canvas.width = width;
  13157. canvas.height = height;
  13158. const context = canvas.getContext('2d');
  13159. context.drawImage(image, 0, 0, width, height);
  13160. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  13161. return canvas;
  13162. } else {
  13163. if ('data' in image) {
  13164. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  13165. }
  13166. return image;
  13167. }
  13168. }
  13169. return image;
  13170. }
  13171. function isPowerOfTwo$1(image) {
  13172. return isPowerOfTwo(image.width) && isPowerOfTwo(image.height);
  13173. }
  13174. function textureNeedsPowerOfTwo(texture) {
  13175. if (isWebGL2) return false;
  13176. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13177. }
  13178. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  13179. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13180. }
  13181. function generateMipmap(target, texture, width, height, depth = 1) {
  13182. _gl.generateMipmap(target);
  13183. const textureProperties = properties.get(texture);
  13184. textureProperties.__maxMipLevel = Math.log2(Math.max(width, height, depth));
  13185. }
  13186. function getInternalFormat(internalFormatName, glFormat, glType) {
  13187. if (isWebGL2 === false) return glFormat;
  13188. if (internalFormatName !== null) {
  13189. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  13190. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  13191. }
  13192. let internalFormat = glFormat;
  13193. if (glFormat === _gl.RED) {
  13194. if (glType === _gl.FLOAT) internalFormat = _gl.R32F;
  13195. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.R16F;
  13196. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8;
  13197. }
  13198. if (glFormat === _gl.RGB) {
  13199. if (glType === _gl.FLOAT) internalFormat = _gl.RGB32F;
  13200. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGB16F;
  13201. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGB8;
  13202. }
  13203. if (glFormat === _gl.RGBA) {
  13204. if (glType === _gl.FLOAT) internalFormat = _gl.RGBA32F;
  13205. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGBA16F;
  13206. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGBA8;
  13207. }
  13208. if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) {
  13209. extensions.get('EXT_color_buffer_float');
  13210. }
  13211. return internalFormat;
  13212. } // Fallback filters for non-power-of-2 textures
  13213. function filterFallback(f) {
  13214. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  13215. return _gl.NEAREST;
  13216. }
  13217. return _gl.LINEAR;
  13218. } //
  13219. function onTextureDispose(event) {
  13220. const texture = event.target;
  13221. texture.removeEventListener('dispose', onTextureDispose);
  13222. deallocateTexture(texture);
  13223. if (texture.isVideoTexture) {
  13224. _videoTextures.delete(texture);
  13225. }
  13226. info.memory.textures--;
  13227. }
  13228. function onRenderTargetDispose(event) {
  13229. const renderTarget = event.target;
  13230. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  13231. deallocateRenderTarget(renderTarget);
  13232. } //
  13233. function deallocateTexture(texture) {
  13234. const textureProperties = properties.get(texture);
  13235. if (textureProperties.__webglInit === undefined) return;
  13236. _gl.deleteTexture(textureProperties.__webglTexture);
  13237. properties.remove(texture);
  13238. }
  13239. function deallocateRenderTarget(renderTarget) {
  13240. const texture = renderTarget.texture;
  13241. const renderTargetProperties = properties.get(renderTarget);
  13242. const textureProperties = properties.get(texture);
  13243. if (!renderTarget) return;
  13244. if (textureProperties.__webglTexture !== undefined) {
  13245. _gl.deleteTexture(textureProperties.__webglTexture);
  13246. info.memory.textures--;
  13247. }
  13248. if (renderTarget.depthTexture) {
  13249. renderTarget.depthTexture.dispose();
  13250. }
  13251. if (renderTarget.isWebGLCubeRenderTarget) {
  13252. for (let i = 0; i < 6; i++) {
  13253. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  13254. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  13255. }
  13256. } else {
  13257. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  13258. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  13259. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  13260. if (renderTargetProperties.__webglColorRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);
  13261. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  13262. }
  13263. if (renderTarget.isWebGLMultipleRenderTargets) {
  13264. for (let i = 0, il = texture.length; i < il; i++) {
  13265. const attachmentProperties = properties.get(texture[i]);
  13266. if (attachmentProperties.__webglTexture) {
  13267. _gl.deleteTexture(attachmentProperties.__webglTexture);
  13268. info.memory.textures--;
  13269. }
  13270. properties.remove(texture[i]);
  13271. }
  13272. }
  13273. properties.remove(texture);
  13274. properties.remove(renderTarget);
  13275. } //
  13276. let textureUnits = 0;
  13277. function resetTextureUnits() {
  13278. textureUnits = 0;
  13279. }
  13280. function allocateTextureUnit() {
  13281. const textureUnit = textureUnits;
  13282. if (textureUnit >= maxTextures) {
  13283. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  13284. }
  13285. textureUnits += 1;
  13286. return textureUnit;
  13287. } //
  13288. function setTexture2D(texture, slot) {
  13289. const textureProperties = properties.get(texture);
  13290. if (texture.isVideoTexture) updateVideoTexture(texture);
  13291. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13292. const image = texture.image;
  13293. if (image === undefined) {
  13294. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  13295. } else if (image.complete === false) {
  13296. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  13297. } else {
  13298. uploadTexture(textureProperties, texture, slot);
  13299. return;
  13300. }
  13301. }
  13302. state.activeTexture(_gl.TEXTURE0 + slot);
  13303. state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture);
  13304. }
  13305. function setTexture2DArray(texture, slot) {
  13306. const textureProperties = properties.get(texture);
  13307. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13308. uploadTexture(textureProperties, texture, slot);
  13309. return;
  13310. }
  13311. state.activeTexture(_gl.TEXTURE0 + slot);
  13312. state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture);
  13313. }
  13314. function setTexture3D(texture, slot) {
  13315. const textureProperties = properties.get(texture);
  13316. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13317. uploadTexture(textureProperties, texture, slot);
  13318. return;
  13319. }
  13320. state.activeTexture(_gl.TEXTURE0 + slot);
  13321. state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture);
  13322. }
  13323. function setTextureCube(texture, slot) {
  13324. const textureProperties = properties.get(texture);
  13325. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13326. uploadCubeTexture(textureProperties, texture, slot);
  13327. return;
  13328. }
  13329. state.activeTexture(_gl.TEXTURE0 + slot);
  13330. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  13331. }
  13332. const wrappingToGL = {
  13333. [RepeatWrapping]: _gl.REPEAT,
  13334. [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE,
  13335. [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT
  13336. };
  13337. const filterToGL = {
  13338. [NearestFilter]: _gl.NEAREST,
  13339. [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST,
  13340. [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR,
  13341. [LinearFilter]: _gl.LINEAR,
  13342. [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST,
  13343. [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR
  13344. };
  13345. function setTextureParameters(textureType, texture, supportsMips) {
  13346. if (supportsMips) {
  13347. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]);
  13348. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]);
  13349. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  13350. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]);
  13351. }
  13352. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]);
  13353. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]);
  13354. } else {
  13355. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE);
  13356. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE);
  13357. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  13358. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE);
  13359. }
  13360. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  13361. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  13362. }
  13363. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterFallback(texture.magFilter));
  13364. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterFallback(texture.minFilter));
  13365. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13366. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  13367. }
  13368. }
  13369. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  13370. const extension = extensions.get('EXT_texture_filter_anisotropic');
  13371. if (texture.type === FloatType && extensions.has('OES_texture_float_linear') === false) return; // verify extension for WebGL 1 and WebGL 2
  13372. if (isWebGL2 === false && texture.type === HalfFloatType && extensions.has('OES_texture_half_float_linear') === false) return; // verify extension for WebGL 1 only
  13373. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  13374. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  13375. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  13376. }
  13377. }
  13378. }
  13379. function initTexture(textureProperties, texture) {
  13380. if (textureProperties.__webglInit === undefined) {
  13381. textureProperties.__webglInit = true;
  13382. texture.addEventListener('dispose', onTextureDispose);
  13383. textureProperties.__webglTexture = _gl.createTexture();
  13384. info.memory.textures++;
  13385. }
  13386. }
  13387. function uploadTexture(textureProperties, texture, slot) {
  13388. let textureType = _gl.TEXTURE_2D;
  13389. if (texture.isDataTexture2DArray) textureType = _gl.TEXTURE_2D_ARRAY;
  13390. if (texture.isDataTexture3D) textureType = _gl.TEXTURE_3D;
  13391. initTexture(textureProperties, texture);
  13392. state.activeTexture(_gl.TEXTURE0 + slot);
  13393. state.bindTexture(textureType, textureProperties.__webglTexture);
  13394. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  13395. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  13396. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  13397. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  13398. const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo$1(texture.image) === false;
  13399. const image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  13400. const supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  13401. glFormat = utils.convert(texture.format);
  13402. let glType = utils.convert(texture.type),
  13403. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13404. setTextureParameters(textureType, texture, supportsMips);
  13405. let mipmap;
  13406. const mipmaps = texture.mipmaps;
  13407. if (texture.isDepthTexture) {
  13408. // populate depth texture with dummy data
  13409. glInternalFormat = _gl.DEPTH_COMPONENT;
  13410. if (isWebGL2) {
  13411. if (texture.type === FloatType) {
  13412. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  13413. } else if (texture.type === UnsignedIntType) {
  13414. glInternalFormat = _gl.DEPTH_COMPONENT24;
  13415. } else if (texture.type === UnsignedInt248Type) {
  13416. glInternalFormat = _gl.DEPTH24_STENCIL8;
  13417. } else {
  13418. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  13419. }
  13420. } else {
  13421. if (texture.type === FloatType) {
  13422. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  13423. }
  13424. } // validation checks for WebGL 1
  13425. if (texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  13426. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13427. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13428. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13429. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  13430. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  13431. texture.type = UnsignedShortType;
  13432. glType = utils.convert(texture.type);
  13433. }
  13434. }
  13435. if (texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  13436. // Depth stencil textures need the DEPTH_STENCIL internal format
  13437. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13438. glInternalFormat = _gl.DEPTH_STENCIL; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13439. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13440. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13441. if (texture.type !== UnsignedInt248Type) {
  13442. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  13443. texture.type = UnsignedInt248Type;
  13444. glType = utils.convert(texture.type);
  13445. }
  13446. } //
  13447. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  13448. } else if (texture.isDataTexture) {
  13449. // use manually created mipmaps if available
  13450. // if there are no manual mipmaps
  13451. // set 0 level mipmap and then use GL to generate other mipmap levels
  13452. if (mipmaps.length > 0 && supportsMips) {
  13453. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13454. mipmap = mipmaps[i];
  13455. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13456. }
  13457. texture.generateMipmaps = false;
  13458. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13459. } else {
  13460. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  13461. textureProperties.__maxMipLevel = 0;
  13462. }
  13463. } else if (texture.isCompressedTexture) {
  13464. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13465. mipmap = mipmaps[i];
  13466. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13467. if (glFormat !== null) {
  13468. state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13469. } else {
  13470. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  13471. }
  13472. } else {
  13473. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13474. }
  13475. }
  13476. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13477. } else if (texture.isDataTexture2DArray) {
  13478. state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13479. textureProperties.__maxMipLevel = 0;
  13480. } else if (texture.isDataTexture3D) {
  13481. state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13482. textureProperties.__maxMipLevel = 0;
  13483. } else {
  13484. // regular Texture (image, video, canvas)
  13485. // use manually created mipmaps if available
  13486. // if there are no manual mipmaps
  13487. // set 0 level mipmap and then use GL to generate other mipmap levels
  13488. if (mipmaps.length > 0 && supportsMips) {
  13489. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13490. mipmap = mipmaps[i];
  13491. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap);
  13492. }
  13493. texture.generateMipmaps = false;
  13494. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13495. } else {
  13496. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image);
  13497. textureProperties.__maxMipLevel = 0;
  13498. }
  13499. }
  13500. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13501. generateMipmap(textureType, texture, image.width, image.height);
  13502. }
  13503. textureProperties.__version = texture.version;
  13504. if (texture.onUpdate) texture.onUpdate(texture);
  13505. }
  13506. function uploadCubeTexture(textureProperties, texture, slot) {
  13507. if (texture.image.length !== 6) return;
  13508. initTexture(textureProperties, texture);
  13509. state.activeTexture(_gl.TEXTURE0 + slot);
  13510. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  13511. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  13512. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  13513. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  13514. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  13515. const isCompressed = texture && (texture.isCompressedTexture || texture.image[0].isCompressedTexture);
  13516. const isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  13517. const cubeImage = [];
  13518. for (let i = 0; i < 6; i++) {
  13519. if (!isCompressed && !isDataTexture) {
  13520. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  13521. } else {
  13522. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  13523. }
  13524. }
  13525. const image = cubeImage[0],
  13526. supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  13527. glFormat = utils.convert(texture.format),
  13528. glType = utils.convert(texture.type),
  13529. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13530. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  13531. let mipmaps;
  13532. if (isCompressed) {
  13533. for (let i = 0; i < 6; i++) {
  13534. mipmaps = cubeImage[i].mipmaps;
  13535. for (let j = 0; j < mipmaps.length; j++) {
  13536. const mipmap = mipmaps[j];
  13537. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13538. if (glFormat !== null) {
  13539. state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13540. } else {
  13541. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  13542. }
  13543. } else {
  13544. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13545. }
  13546. }
  13547. }
  13548. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13549. } else {
  13550. mipmaps = texture.mipmaps;
  13551. for (let i = 0; i < 6; i++) {
  13552. if (isDataTexture) {
  13553. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  13554. for (let j = 0; j < mipmaps.length; j++) {
  13555. const mipmap = mipmaps[j];
  13556. const mipmapImage = mipmap.image[i].image;
  13557. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  13558. }
  13559. } else {
  13560. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  13561. for (let j = 0; j < mipmaps.length; j++) {
  13562. const mipmap = mipmaps[j];
  13563. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  13564. }
  13565. }
  13566. }
  13567. textureProperties.__maxMipLevel = mipmaps.length;
  13568. }
  13569. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13570. // We assume images for cube map have the same size.
  13571. generateMipmap(_gl.TEXTURE_CUBE_MAP, texture, image.width, image.height);
  13572. }
  13573. textureProperties.__version = texture.version;
  13574. if (texture.onUpdate) texture.onUpdate(texture);
  13575. } // Render targets
  13576. // Setup storage for target texture and bind it to correct framebuffer
  13577. function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget) {
  13578. const glFormat = utils.convert(texture.format);
  13579. const glType = utils.convert(texture.type);
  13580. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13581. if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) {
  13582. state.texImage3D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null);
  13583. } else {
  13584. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  13585. }
  13586. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  13587. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0);
  13588. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  13589. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  13590. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  13591. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer);
  13592. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  13593. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  13594. if (isMultisample) {
  13595. const depthTexture = renderTarget.depthTexture;
  13596. if (depthTexture && depthTexture.isDepthTexture) {
  13597. if (depthTexture.type === FloatType) {
  13598. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  13599. } else if (depthTexture.type === UnsignedIntType) {
  13600. glInternalFormat = _gl.DEPTH_COMPONENT24;
  13601. }
  13602. }
  13603. const samples = getRenderTargetSamples(renderTarget);
  13604. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13605. } else {
  13606. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  13607. }
  13608. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  13609. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  13610. if (isMultisample) {
  13611. const samples = getRenderTargetSamples(renderTarget);
  13612. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  13613. } else {
  13614. _gl.renderbufferStorage(_gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height);
  13615. }
  13616. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  13617. } else {
  13618. // Use the first texture for MRT so far
  13619. const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[0] : renderTarget.texture;
  13620. const glFormat = utils.convert(texture.format);
  13621. const glType = utils.convert(texture.type);
  13622. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13623. if (isMultisample) {
  13624. const samples = getRenderTargetSamples(renderTarget);
  13625. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13626. } else {
  13627. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  13628. }
  13629. }
  13630. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  13631. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  13632. function setupDepthTexture(framebuffer, renderTarget) {
  13633. const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  13634. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  13635. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  13636. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  13637. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  13638. } // upload an empty depth texture with framebuffer size
  13639. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  13640. renderTarget.depthTexture.image.width = renderTarget.width;
  13641. renderTarget.depthTexture.image.height = renderTarget.height;
  13642. renderTarget.depthTexture.needsUpdate = true;
  13643. }
  13644. setTexture2D(renderTarget.depthTexture, 0);
  13645. const webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  13646. if (renderTarget.depthTexture.format === DepthFormat) {
  13647. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  13648. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  13649. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  13650. } else {
  13651. throw new Error('Unknown depthTexture format');
  13652. }
  13653. } // Setup GL resources for a non-texture depth buffer
  13654. function setupDepthRenderbuffer(renderTarget) {
  13655. const renderTargetProperties = properties.get(renderTarget);
  13656. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  13657. if (renderTarget.depthTexture) {
  13658. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  13659. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  13660. } else {
  13661. if (isCube) {
  13662. renderTargetProperties.__webglDepthbuffer = [];
  13663. for (let i = 0; i < 6; i++) {
  13664. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]);
  13665. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  13666. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  13667. }
  13668. } else {
  13669. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  13670. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  13671. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  13672. }
  13673. }
  13674. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  13675. } // Set up GL resources for the render target
  13676. function setupRenderTarget(renderTarget) {
  13677. const texture = renderTarget.texture;
  13678. const renderTargetProperties = properties.get(renderTarget);
  13679. const textureProperties = properties.get(texture);
  13680. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  13681. if (renderTarget.isWebGLMultipleRenderTargets !== true) {
  13682. textureProperties.__webglTexture = _gl.createTexture();
  13683. textureProperties.__version = texture.version;
  13684. info.memory.textures++;
  13685. }
  13686. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  13687. const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true;
  13688. const isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
  13689. const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray;
  13690. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2; // Handles WebGL2 RGBFormat fallback - #18858
  13691. if (isWebGL2 && texture.format === RGBFormat && (texture.type === FloatType || texture.type === HalfFloatType)) {
  13692. texture.format = RGBAFormat;
  13693. console.warn('THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.');
  13694. } // Setup framebuffer
  13695. if (isCube) {
  13696. renderTargetProperties.__webglFramebuffer = [];
  13697. for (let i = 0; i < 6; i++) {
  13698. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  13699. }
  13700. } else {
  13701. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  13702. if (isMultipleRenderTargets) {
  13703. if (capabilities.drawBuffers) {
  13704. const textures = renderTarget.texture;
  13705. for (let i = 0, il = textures.length; i < il; i++) {
  13706. const attachmentProperties = properties.get(textures[i]);
  13707. if (attachmentProperties.__webglTexture === undefined) {
  13708. attachmentProperties.__webglTexture = _gl.createTexture();
  13709. info.memory.textures++;
  13710. }
  13711. }
  13712. } else {
  13713. console.warn('THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.');
  13714. }
  13715. } else if (isMultisample) {
  13716. if (isWebGL2) {
  13717. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  13718. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  13719. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  13720. const glFormat = utils.convert(texture.format);
  13721. const glType = utils.convert(texture.type);
  13722. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13723. const samples = getRenderTargetSamples(renderTarget);
  13724. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13725. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  13726. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  13727. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  13728. if (renderTarget.depthBuffer) {
  13729. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  13730. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  13731. }
  13732. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  13733. } else {
  13734. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  13735. }
  13736. }
  13737. } // Setup color buffer
  13738. if (isCube) {
  13739. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  13740. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  13741. for (let i = 0; i < 6; i++) {
  13742. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i);
  13743. }
  13744. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13745. generateMipmap(_gl.TEXTURE_CUBE_MAP, texture, renderTarget.width, renderTarget.height);
  13746. }
  13747. state.bindTexture(_gl.TEXTURE_CUBE_MAP, null);
  13748. } else if (isMultipleRenderTargets) {
  13749. const textures = renderTarget.texture;
  13750. for (let i = 0, il = textures.length; i < il; i++) {
  13751. const attachment = textures[i];
  13752. const attachmentProperties = properties.get(attachment);
  13753. state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture);
  13754. setTextureParameters(_gl.TEXTURE_2D, attachment, supportsMips);
  13755. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D);
  13756. if (textureNeedsGenerateMipmaps(attachment, supportsMips)) {
  13757. generateMipmap(_gl.TEXTURE_2D, attachment, renderTarget.width, renderTarget.height);
  13758. }
  13759. }
  13760. state.bindTexture(_gl.TEXTURE_2D, null);
  13761. } else {
  13762. let glTextureType = _gl.TEXTURE_2D;
  13763. if (isRenderTarget3D) {
  13764. // Render targets containing layers, i.e: Texture 3D and 2d arrays
  13765. if (isWebGL2) {
  13766. const isTexture3D = texture.isDataTexture3D;
  13767. glTextureType = isTexture3D ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  13768. } else {
  13769. console.warn('THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.');
  13770. }
  13771. }
  13772. state.bindTexture(glTextureType, textureProperties.__webglTexture);
  13773. setTextureParameters(glTextureType, texture, supportsMips);
  13774. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType);
  13775. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13776. generateMipmap(glTextureType, texture, renderTarget.width, renderTarget.height, renderTarget.depth);
  13777. }
  13778. state.bindTexture(glTextureType, null);
  13779. } // Setup depth and stencil buffers
  13780. if (renderTarget.depthBuffer) {
  13781. setupDepthRenderbuffer(renderTarget);
  13782. }
  13783. }
  13784. function updateRenderTargetMipmap(renderTarget) {
  13785. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2;
  13786. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture];
  13787. for (let i = 0, il = textures.length; i < il; i++) {
  13788. const texture = textures[i];
  13789. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13790. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  13791. const webglTexture = properties.get(texture).__webglTexture;
  13792. state.bindTexture(target, webglTexture);
  13793. generateMipmap(target, texture, renderTarget.width, renderTarget.height);
  13794. state.bindTexture(target, null);
  13795. }
  13796. }
  13797. }
  13798. function updateMultisampleRenderTarget(renderTarget) {
  13799. if (renderTarget.isWebGLMultisampleRenderTarget) {
  13800. if (isWebGL2) {
  13801. const width = renderTarget.width;
  13802. const height = renderTarget.height;
  13803. let mask = _gl.COLOR_BUFFER_BIT;
  13804. if (renderTarget.depthBuffer) mask |= _gl.DEPTH_BUFFER_BIT;
  13805. if (renderTarget.stencilBuffer) mask |= _gl.STENCIL_BUFFER_BIT;
  13806. const renderTargetProperties = properties.get(renderTarget);
  13807. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  13808. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  13809. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST);
  13810. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null);
  13811. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  13812. } else {
  13813. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  13814. }
  13815. }
  13816. }
  13817. function getRenderTargetSamples(renderTarget) {
  13818. return isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(maxSamples, renderTarget.samples) : 0;
  13819. }
  13820. function updateVideoTexture(texture) {
  13821. const frame = info.render.frame; // Check the last frame we updated the VideoTexture
  13822. if (_videoTextures.get(texture) !== frame) {
  13823. _videoTextures.set(texture, frame);
  13824. texture.update();
  13825. }
  13826. } // backwards compatibility
  13827. let warnedTexture2D = false;
  13828. let warnedTextureCube = false;
  13829. function safeSetTexture2D(texture, slot) {
  13830. if (texture && texture.isWebGLRenderTarget) {
  13831. if (warnedTexture2D === false) {
  13832. console.warn('THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.');
  13833. warnedTexture2D = true;
  13834. }
  13835. texture = texture.texture;
  13836. }
  13837. setTexture2D(texture, slot);
  13838. }
  13839. function safeSetTextureCube(texture, slot) {
  13840. if (texture && texture.isWebGLCubeRenderTarget) {
  13841. if (warnedTextureCube === false) {
  13842. console.warn('THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.');
  13843. warnedTextureCube = true;
  13844. }
  13845. texture = texture.texture;
  13846. }
  13847. setTextureCube(texture, slot);
  13848. } //
  13849. this.allocateTextureUnit = allocateTextureUnit;
  13850. this.resetTextureUnits = resetTextureUnits;
  13851. this.setTexture2D = setTexture2D;
  13852. this.setTexture2DArray = setTexture2DArray;
  13853. this.setTexture3D = setTexture3D;
  13854. this.setTextureCube = setTextureCube;
  13855. this.setupRenderTarget = setupRenderTarget;
  13856. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  13857. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  13858. this.safeSetTexture2D = safeSetTexture2D;
  13859. this.safeSetTextureCube = safeSetTextureCube;
  13860. }
  13861. function WebGLUtils(gl, extensions, capabilities) {
  13862. const isWebGL2 = capabilities.isWebGL2;
  13863. function convert(p) {
  13864. let extension;
  13865. if (p === UnsignedByteType) return gl.UNSIGNED_BYTE;
  13866. if (p === UnsignedShort4444Type) return gl.UNSIGNED_SHORT_4_4_4_4;
  13867. if (p === UnsignedShort5551Type) return gl.UNSIGNED_SHORT_5_5_5_1;
  13868. if (p === UnsignedShort565Type) return gl.UNSIGNED_SHORT_5_6_5;
  13869. if (p === ByteType) return gl.BYTE;
  13870. if (p === ShortType) return gl.SHORT;
  13871. if (p === UnsignedShortType) return gl.UNSIGNED_SHORT;
  13872. if (p === IntType) return gl.INT;
  13873. if (p === UnsignedIntType) return gl.UNSIGNED_INT;
  13874. if (p === FloatType) return gl.FLOAT;
  13875. if (p === HalfFloatType) {
  13876. if (isWebGL2) return gl.HALF_FLOAT;
  13877. extension = extensions.get('OES_texture_half_float');
  13878. if (extension !== null) {
  13879. return extension.HALF_FLOAT_OES;
  13880. } else {
  13881. return null;
  13882. }
  13883. }
  13884. if (p === AlphaFormat) return gl.ALPHA;
  13885. if (p === RGBFormat) return gl.RGB;
  13886. if (p === RGBAFormat) return gl.RGBA;
  13887. if (p === LuminanceFormat) return gl.LUMINANCE;
  13888. if (p === LuminanceAlphaFormat) return gl.LUMINANCE_ALPHA;
  13889. if (p === DepthFormat) return gl.DEPTH_COMPONENT;
  13890. if (p === DepthStencilFormat) return gl.DEPTH_STENCIL;
  13891. if (p === RedFormat) return gl.RED; // WebGL2 formats.
  13892. if (p === RedIntegerFormat) return gl.RED_INTEGER;
  13893. if (p === RGFormat) return gl.RG;
  13894. if (p === RGIntegerFormat) return gl.RG_INTEGER;
  13895. if (p === RGBIntegerFormat) return gl.RGB_INTEGER;
  13896. if (p === RGBAIntegerFormat) return gl.RGBA_INTEGER;
  13897. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  13898. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  13899. if (extension !== null) {
  13900. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13901. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13902. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13903. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13904. } else {
  13905. return null;
  13906. }
  13907. }
  13908. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  13909. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  13910. if (extension !== null) {
  13911. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13912. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13913. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13914. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13915. } else {
  13916. return null;
  13917. }
  13918. }
  13919. if (p === RGB_ETC1_Format) {
  13920. extension = extensions.get('WEBGL_compressed_texture_etc1');
  13921. if (extension !== null) {
  13922. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13923. } else {
  13924. return null;
  13925. }
  13926. }
  13927. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  13928. extension = extensions.get('WEBGL_compressed_texture_etc');
  13929. if (extension !== null) {
  13930. if (p === RGB_ETC2_Format) return extension.COMPRESSED_RGB8_ETC2;
  13931. if (p === RGBA_ETC2_EAC_Format) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  13932. }
  13933. }
  13934. 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) {
  13935. extension = extensions.get('WEBGL_compressed_texture_astc');
  13936. if (extension !== null) {
  13937. // TODO Complete?
  13938. return p;
  13939. } else {
  13940. return null;
  13941. }
  13942. }
  13943. if (p === RGBA_BPTC_Format) {
  13944. extension = extensions.get('EXT_texture_compression_bptc');
  13945. if (extension !== null) {
  13946. // TODO Complete?
  13947. return p;
  13948. } else {
  13949. return null;
  13950. }
  13951. }
  13952. if (p === UnsignedInt248Type) {
  13953. if (isWebGL2) return gl.UNSIGNED_INT_24_8;
  13954. extension = extensions.get('WEBGL_depth_texture');
  13955. if (extension !== null) {
  13956. return extension.UNSIGNED_INT_24_8_WEBGL;
  13957. } else {
  13958. return null;
  13959. }
  13960. }
  13961. }
  13962. return {
  13963. convert: convert
  13964. };
  13965. }
  13966. class ArrayCamera extends PerspectiveCamera {
  13967. constructor(array = []) {
  13968. super();
  13969. this.cameras = array;
  13970. }
  13971. }
  13972. ArrayCamera.prototype.isArrayCamera = true;
  13973. class Group extends Object3D {
  13974. constructor() {
  13975. super();
  13976. this.type = 'Group';
  13977. }
  13978. }
  13979. Group.prototype.isGroup = true;
  13980. const _moveEvent = {
  13981. type: 'move'
  13982. };
  13983. class WebXRController {
  13984. constructor() {
  13985. this._targetRay = null;
  13986. this._grip = null;
  13987. this._hand = null;
  13988. }
  13989. getHandSpace() {
  13990. if (this._hand === null) {
  13991. this._hand = new Group();
  13992. this._hand.matrixAutoUpdate = false;
  13993. this._hand.visible = false;
  13994. this._hand.joints = {};
  13995. this._hand.inputState = {
  13996. pinching: false
  13997. };
  13998. }
  13999. return this._hand;
  14000. }
  14001. getTargetRaySpace() {
  14002. if (this._targetRay === null) {
  14003. this._targetRay = new Group();
  14004. this._targetRay.matrixAutoUpdate = false;
  14005. this._targetRay.visible = false;
  14006. this._targetRay.hasLinearVelocity = false;
  14007. this._targetRay.linearVelocity = new Vector3();
  14008. this._targetRay.hasAngularVelocity = false;
  14009. this._targetRay.angularVelocity = new Vector3();
  14010. }
  14011. return this._targetRay;
  14012. }
  14013. getGripSpace() {
  14014. if (this._grip === null) {
  14015. this._grip = new Group();
  14016. this._grip.matrixAutoUpdate = false;
  14017. this._grip.visible = false;
  14018. this._grip.hasLinearVelocity = false;
  14019. this._grip.linearVelocity = new Vector3();
  14020. this._grip.hasAngularVelocity = false;
  14021. this._grip.angularVelocity = new Vector3();
  14022. }
  14023. return this._grip;
  14024. }
  14025. dispatchEvent(event) {
  14026. if (this._targetRay !== null) {
  14027. this._targetRay.dispatchEvent(event);
  14028. }
  14029. if (this._grip !== null) {
  14030. this._grip.dispatchEvent(event);
  14031. }
  14032. if (this._hand !== null) {
  14033. this._hand.dispatchEvent(event);
  14034. }
  14035. return this;
  14036. }
  14037. disconnect(inputSource) {
  14038. this.dispatchEvent({
  14039. type: 'disconnected',
  14040. data: inputSource
  14041. });
  14042. if (this._targetRay !== null) {
  14043. this._targetRay.visible = false;
  14044. }
  14045. if (this._grip !== null) {
  14046. this._grip.visible = false;
  14047. }
  14048. if (this._hand !== null) {
  14049. this._hand.visible = false;
  14050. }
  14051. return this;
  14052. }
  14053. update(inputSource, frame, referenceSpace) {
  14054. let inputPose = null;
  14055. let gripPose = null;
  14056. let handPose = null;
  14057. const targetRay = this._targetRay;
  14058. const grip = this._grip;
  14059. const hand = this._hand;
  14060. if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
  14061. if (targetRay !== null) {
  14062. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  14063. if (inputPose !== null) {
  14064. targetRay.matrix.fromArray(inputPose.transform.matrix);
  14065. targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
  14066. if (inputPose.linearVelocity) {
  14067. targetRay.hasLinearVelocity = true;
  14068. targetRay.linearVelocity.copy(inputPose.linearVelocity);
  14069. } else {
  14070. targetRay.hasLinearVelocity = false;
  14071. }
  14072. if (inputPose.angularVelocity) {
  14073. targetRay.hasAngularVelocity = true;
  14074. targetRay.angularVelocity.copy(inputPose.angularVelocity);
  14075. } else {
  14076. targetRay.hasAngularVelocity = false;
  14077. }
  14078. this.dispatchEvent(_moveEvent);
  14079. }
  14080. }
  14081. if (hand && inputSource.hand) {
  14082. handPose = true;
  14083. for (const inputjoint of inputSource.hand.values()) {
  14084. // Update the joints groups with the XRJoint poses
  14085. const jointPose = frame.getJointPose(inputjoint, referenceSpace);
  14086. if (hand.joints[inputjoint.jointName] === undefined) {
  14087. // The transform of this joint will be updated with the joint pose on each frame
  14088. const joint = new Group();
  14089. joint.matrixAutoUpdate = false;
  14090. joint.visible = false;
  14091. hand.joints[inputjoint.jointName] = joint; // ??
  14092. hand.add(joint);
  14093. }
  14094. const joint = hand.joints[inputjoint.jointName];
  14095. if (jointPose !== null) {
  14096. joint.matrix.fromArray(jointPose.transform.matrix);
  14097. joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
  14098. joint.jointRadius = jointPose.radius;
  14099. }
  14100. joint.visible = jointPose !== null;
  14101. } // Custom events
  14102. // Check pinchz
  14103. const indexTip = hand.joints['index-finger-tip'];
  14104. const thumbTip = hand.joints['thumb-tip'];
  14105. const distance = indexTip.position.distanceTo(thumbTip.position);
  14106. const distanceToPinch = 0.02;
  14107. const threshold = 0.005;
  14108. if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
  14109. hand.inputState.pinching = false;
  14110. this.dispatchEvent({
  14111. type: 'pinchend',
  14112. handedness: inputSource.handedness,
  14113. target: this
  14114. });
  14115. } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
  14116. hand.inputState.pinching = true;
  14117. this.dispatchEvent({
  14118. type: 'pinchstart',
  14119. handedness: inputSource.handedness,
  14120. target: this
  14121. });
  14122. }
  14123. } else {
  14124. if (grip !== null && inputSource.gripSpace) {
  14125. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  14126. if (gripPose !== null) {
  14127. grip.matrix.fromArray(gripPose.transform.matrix);
  14128. grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
  14129. if (gripPose.linearVelocity) {
  14130. grip.hasLinearVelocity = true;
  14131. grip.linearVelocity.copy(gripPose.linearVelocity);
  14132. } else {
  14133. grip.hasLinearVelocity = false;
  14134. }
  14135. if (gripPose.angularVelocity) {
  14136. grip.hasAngularVelocity = true;
  14137. grip.angularVelocity.copy(gripPose.angularVelocity);
  14138. } else {
  14139. grip.hasAngularVelocity = false;
  14140. }
  14141. }
  14142. }
  14143. }
  14144. }
  14145. if (targetRay !== null) {
  14146. targetRay.visible = inputPose !== null;
  14147. }
  14148. if (grip !== null) {
  14149. grip.visible = gripPose !== null;
  14150. }
  14151. if (hand !== null) {
  14152. hand.visible = handPose !== null;
  14153. }
  14154. return this;
  14155. }
  14156. }
  14157. class WebXRManager extends EventDispatcher {
  14158. constructor(renderer, gl) {
  14159. super();
  14160. const scope = this;
  14161. const state = renderer.state;
  14162. let session = null;
  14163. let framebufferScaleFactor = 1.0;
  14164. let referenceSpace = null;
  14165. let referenceSpaceType = 'local-floor';
  14166. let pose = null;
  14167. let glBinding = null;
  14168. let glFramebuffer = null;
  14169. let glProjLayer = null;
  14170. let glBaseLayer = null;
  14171. let isMultisample = false;
  14172. let glMultisampledFramebuffer = null;
  14173. let glColorRenderbuffer = null;
  14174. let glDepthRenderbuffer = null;
  14175. let xrFrame = null;
  14176. let depthStyle = null;
  14177. let clearStyle = null;
  14178. const controllers = [];
  14179. const inputSourcesMap = new Map(); //
  14180. const cameraL = new PerspectiveCamera();
  14181. cameraL.layers.enable(1);
  14182. cameraL.viewport = new Vector4();
  14183. const cameraR = new PerspectiveCamera();
  14184. cameraR.layers.enable(2);
  14185. cameraR.viewport = new Vector4();
  14186. const cameras = [cameraL, cameraR];
  14187. const cameraVR = new ArrayCamera();
  14188. cameraVR.layers.enable(1);
  14189. cameraVR.layers.enable(2);
  14190. let _currentDepthNear = null;
  14191. let _currentDepthFar = null; //
  14192. this.cameraAutoUpdate = true;
  14193. this.enabled = false;
  14194. this.isPresenting = false;
  14195. this.getController = function (index) {
  14196. let controller = controllers[index];
  14197. if (controller === undefined) {
  14198. controller = new WebXRController();
  14199. controllers[index] = controller;
  14200. }
  14201. return controller.getTargetRaySpace();
  14202. };
  14203. this.getControllerGrip = function (index) {
  14204. let controller = controllers[index];
  14205. if (controller === undefined) {
  14206. controller = new WebXRController();
  14207. controllers[index] = controller;
  14208. }
  14209. return controller.getGripSpace();
  14210. };
  14211. this.getHand = function (index) {
  14212. let controller = controllers[index];
  14213. if (controller === undefined) {
  14214. controller = new WebXRController();
  14215. controllers[index] = controller;
  14216. }
  14217. return controller.getHandSpace();
  14218. }; //
  14219. function onSessionEvent(event) {
  14220. const controller = inputSourcesMap.get(event.inputSource);
  14221. if (controller) {
  14222. controller.dispatchEvent({
  14223. type: event.type,
  14224. data: event.inputSource
  14225. });
  14226. }
  14227. }
  14228. function onSessionEnd() {
  14229. inputSourcesMap.forEach(function (controller, inputSource) {
  14230. controller.disconnect(inputSource);
  14231. });
  14232. inputSourcesMap.clear();
  14233. _currentDepthNear = null;
  14234. _currentDepthFar = null; // restore framebuffer/rendering state
  14235. state.bindXRFramebuffer(null);
  14236. renderer.setRenderTarget(renderer.getRenderTarget());
  14237. if (glFramebuffer) gl.deleteFramebuffer(glFramebuffer);
  14238. if (glMultisampledFramebuffer) gl.deleteFramebuffer(glMultisampledFramebuffer);
  14239. if (glColorRenderbuffer) gl.deleteRenderbuffer(glColorRenderbuffer);
  14240. if (glDepthRenderbuffer) gl.deleteRenderbuffer(glDepthRenderbuffer);
  14241. glFramebuffer = null;
  14242. glMultisampledFramebuffer = null;
  14243. glColorRenderbuffer = null;
  14244. glDepthRenderbuffer = null;
  14245. glBaseLayer = null;
  14246. glProjLayer = null;
  14247. glBinding = null;
  14248. session = null; //
  14249. animation.stop();
  14250. scope.isPresenting = false;
  14251. scope.dispatchEvent({
  14252. type: 'sessionend'
  14253. });
  14254. }
  14255. this.setFramebufferScaleFactor = function (value) {
  14256. framebufferScaleFactor = value;
  14257. if (scope.isPresenting === true) {
  14258. console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
  14259. }
  14260. };
  14261. this.setReferenceSpaceType = function (value) {
  14262. referenceSpaceType = value;
  14263. if (scope.isPresenting === true) {
  14264. console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
  14265. }
  14266. };
  14267. this.getReferenceSpace = function () {
  14268. return referenceSpace;
  14269. };
  14270. this.getBaseLayer = function () {
  14271. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  14272. };
  14273. this.getBinding = function () {
  14274. return glBinding;
  14275. };
  14276. this.getFrame = function () {
  14277. return xrFrame;
  14278. };
  14279. this.getSession = function () {
  14280. return session;
  14281. };
  14282. this.setSession = async function (value) {
  14283. session = value;
  14284. if (session !== null) {
  14285. session.addEventListener('select', onSessionEvent);
  14286. session.addEventListener('selectstart', onSessionEvent);
  14287. session.addEventListener('selectend', onSessionEvent);
  14288. session.addEventListener('squeeze', onSessionEvent);
  14289. session.addEventListener('squeezestart', onSessionEvent);
  14290. session.addEventListener('squeezeend', onSessionEvent);
  14291. session.addEventListener('end', onSessionEnd);
  14292. session.addEventListener('inputsourceschange', onInputSourcesChange);
  14293. const attributes = gl.getContextAttributes();
  14294. if (attributes.xrCompatible !== true) {
  14295. await gl.makeXRCompatible();
  14296. }
  14297. if (session.renderState.layers === undefined) {
  14298. const layerInit = {
  14299. antialias: attributes.antialias,
  14300. alpha: attributes.alpha,
  14301. depth: attributes.depth,
  14302. stencil: attributes.stencil,
  14303. framebufferScaleFactor: framebufferScaleFactor
  14304. };
  14305. glBaseLayer = new XRWebGLLayer(session, gl, layerInit);
  14306. session.updateRenderState({
  14307. baseLayer: glBaseLayer
  14308. });
  14309. } else if (gl instanceof WebGLRenderingContext) {
  14310. // Use old style webgl layer because we can't use MSAA
  14311. // WebGL2 support.
  14312. const layerInit = {
  14313. antialias: true,
  14314. alpha: attributes.alpha,
  14315. depth: attributes.depth,
  14316. stencil: attributes.stencil,
  14317. framebufferScaleFactor: framebufferScaleFactor
  14318. };
  14319. glBaseLayer = new XRWebGLLayer(session, gl, layerInit);
  14320. session.updateRenderState({
  14321. layers: [glBaseLayer]
  14322. });
  14323. } else {
  14324. isMultisample = attributes.antialias;
  14325. let depthFormat = null;
  14326. if (attributes.depth) {
  14327. clearStyle = gl.DEPTH_BUFFER_BIT;
  14328. if (attributes.stencil) clearStyle |= gl.STENCIL_BUFFER_BIT;
  14329. depthStyle = attributes.stencil ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  14330. depthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  14331. }
  14332. const projectionlayerInit = {
  14333. colorFormat: attributes.alpha ? gl.RGBA8 : gl.RGB8,
  14334. depthFormat: depthFormat,
  14335. scaleFactor: framebufferScaleFactor
  14336. };
  14337. glBinding = new XRWebGLBinding(session, gl);
  14338. glProjLayer = glBinding.createProjectionLayer(projectionlayerInit);
  14339. glFramebuffer = gl.createFramebuffer();
  14340. session.updateRenderState({
  14341. layers: [glProjLayer]
  14342. });
  14343. if (isMultisample) {
  14344. glMultisampledFramebuffer = gl.createFramebuffer();
  14345. glColorRenderbuffer = gl.createRenderbuffer();
  14346. gl.bindRenderbuffer(gl.RENDERBUFFER, glColorRenderbuffer);
  14347. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, 4, gl.RGBA8, glProjLayer.textureWidth, glProjLayer.textureHeight);
  14348. state.bindFramebuffer(gl.FRAMEBUFFER, glMultisampledFramebuffer);
  14349. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, glColorRenderbuffer);
  14350. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14351. if (depthFormat !== null) {
  14352. glDepthRenderbuffer = gl.createRenderbuffer();
  14353. gl.bindRenderbuffer(gl.RENDERBUFFER, glDepthRenderbuffer);
  14354. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, 4, depthFormat, glProjLayer.textureWidth, glProjLayer.textureHeight);
  14355. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, glDepthRenderbuffer);
  14356. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14357. }
  14358. state.bindFramebuffer(gl.FRAMEBUFFER, null);
  14359. }
  14360. }
  14361. referenceSpace = await session.requestReferenceSpace(referenceSpaceType);
  14362. animation.setContext(session);
  14363. animation.start();
  14364. scope.isPresenting = true;
  14365. scope.dispatchEvent({
  14366. type: 'sessionstart'
  14367. });
  14368. }
  14369. };
  14370. function onInputSourcesChange(event) {
  14371. const inputSources = session.inputSources; // Assign inputSources to available controllers
  14372. for (let i = 0; i < controllers.length; i++) {
  14373. inputSourcesMap.set(inputSources[i], controllers[i]);
  14374. } // Notify disconnected
  14375. for (let i = 0; i < event.removed.length; i++) {
  14376. const inputSource = event.removed[i];
  14377. const controller = inputSourcesMap.get(inputSource);
  14378. if (controller) {
  14379. controller.dispatchEvent({
  14380. type: 'disconnected',
  14381. data: inputSource
  14382. });
  14383. inputSourcesMap.delete(inputSource);
  14384. }
  14385. } // Notify connected
  14386. for (let i = 0; i < event.added.length; i++) {
  14387. const inputSource = event.added[i];
  14388. const controller = inputSourcesMap.get(inputSource);
  14389. if (controller) {
  14390. controller.dispatchEvent({
  14391. type: 'connected',
  14392. data: inputSource
  14393. });
  14394. }
  14395. }
  14396. } //
  14397. const cameraLPos = new Vector3();
  14398. const cameraRPos = new Vector3();
  14399. /**
  14400. * Assumes 2 cameras that are parallel and share an X-axis, and that
  14401. * the cameras' projection and world matrices have already been set.
  14402. * And that near and far planes are identical for both cameras.
  14403. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  14404. */
  14405. function setProjectionFromUnion(camera, cameraL, cameraR) {
  14406. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  14407. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  14408. const ipd = cameraLPos.distanceTo(cameraRPos);
  14409. const projL = cameraL.projectionMatrix.elements;
  14410. const projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  14411. // most likely identical top and bottom frustum extents.
  14412. // Use the left camera for these values.
  14413. const near = projL[14] / (projL[10] - 1);
  14414. const far = projL[14] / (projL[10] + 1);
  14415. const topFov = (projL[9] + 1) / projL[5];
  14416. const bottomFov = (projL[9] - 1) / projL[5];
  14417. const leftFov = (projL[8] - 1) / projL[0];
  14418. const rightFov = (projR[8] + 1) / projR[0];
  14419. const left = near * leftFov;
  14420. const right = near * rightFov; // Calculate the new camera's position offset from the
  14421. // left camera. xOffset should be roughly half `ipd`.
  14422. const zOffset = ipd / (-leftFov + rightFov);
  14423. const xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  14424. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  14425. camera.translateX(xOffset);
  14426. camera.translateZ(zOffset);
  14427. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  14428. camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); // Find the union of the frustum values of the cameras and scale
  14429. // the values so that the near plane's position does not change in world space,
  14430. // although must now be relative to the new union camera.
  14431. const near2 = near + zOffset;
  14432. const far2 = far + zOffset;
  14433. const left2 = left - xOffset;
  14434. const right2 = right + (ipd - xOffset);
  14435. const top2 = topFov * far / far2 * near2;
  14436. const bottom2 = bottomFov * far / far2 * near2;
  14437. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  14438. }
  14439. function updateCamera(camera, parent) {
  14440. if (parent === null) {
  14441. camera.matrixWorld.copy(camera.matrix);
  14442. } else {
  14443. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  14444. }
  14445. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  14446. }
  14447. this.updateCamera = function (camera) {
  14448. if (session === null) return;
  14449. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  14450. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  14451. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  14452. // Note that the new renderState won't apply until the next frame. See #18320
  14453. session.updateRenderState({
  14454. depthNear: cameraVR.near,
  14455. depthFar: cameraVR.far
  14456. });
  14457. _currentDepthNear = cameraVR.near;
  14458. _currentDepthFar = cameraVR.far;
  14459. }
  14460. const parent = camera.parent;
  14461. const cameras = cameraVR.cameras;
  14462. updateCamera(cameraVR, parent);
  14463. for (let i = 0; i < cameras.length; i++) {
  14464. updateCamera(cameras[i], parent);
  14465. }
  14466. cameraVR.matrixWorld.decompose(cameraVR.position, cameraVR.quaternion, cameraVR.scale); // update user camera and its children
  14467. camera.position.copy(cameraVR.position);
  14468. camera.quaternion.copy(cameraVR.quaternion);
  14469. camera.scale.copy(cameraVR.scale);
  14470. camera.matrix.copy(cameraVR.matrix);
  14471. camera.matrixWorld.copy(cameraVR.matrixWorld);
  14472. const children = camera.children;
  14473. for (let i = 0, l = children.length; i < l; i++) {
  14474. children[i].updateMatrixWorld(true);
  14475. } // update projection matrix for proper view frustum culling
  14476. if (cameras.length === 2) {
  14477. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  14478. } else {
  14479. // assume single camera setup (AR)
  14480. cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
  14481. }
  14482. };
  14483. this.getCamera = function () {
  14484. return cameraVR;
  14485. };
  14486. this.getFoveation = function () {
  14487. if (glProjLayer !== null) {
  14488. return glProjLayer.fixedFoveation;
  14489. }
  14490. if (glBaseLayer !== null) {
  14491. return glBaseLayer.fixedFoveation;
  14492. }
  14493. return undefined;
  14494. };
  14495. this.setFoveation = function (foveation) {
  14496. // 0 = no foveation = full resolution
  14497. // 1 = maximum foveation = the edges render at lower resolution
  14498. if (glProjLayer !== null) {
  14499. glProjLayer.fixedFoveation = foveation;
  14500. }
  14501. if (glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined) {
  14502. glBaseLayer.fixedFoveation = foveation;
  14503. }
  14504. }; // Animation Loop
  14505. let onAnimationFrameCallback = null;
  14506. function onAnimationFrame(time, frame) {
  14507. pose = frame.getViewerPose(referenceSpace);
  14508. xrFrame = frame;
  14509. if (pose !== null) {
  14510. const views = pose.views;
  14511. if (glBaseLayer !== null) {
  14512. state.bindXRFramebuffer(glBaseLayer.framebuffer);
  14513. }
  14514. let cameraVRNeedsUpdate = false; // check if it's necessary to rebuild cameraVR's camera list
  14515. if (views.length !== cameraVR.cameras.length) {
  14516. cameraVR.cameras.length = 0;
  14517. cameraVRNeedsUpdate = true;
  14518. }
  14519. for (let i = 0; i < views.length; i++) {
  14520. const view = views[i];
  14521. let viewport = null;
  14522. if (glBaseLayer !== null) {
  14523. viewport = glBaseLayer.getViewport(view);
  14524. } else {
  14525. const glSubImage = glBinding.getViewSubImage(glProjLayer, view);
  14526. state.bindXRFramebuffer(glFramebuffer);
  14527. if (glSubImage.depthStencilTexture !== undefined) {
  14528. gl.framebufferTexture2D(gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, glSubImage.depthStencilTexture, 0);
  14529. }
  14530. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, glSubImage.colorTexture, 0);
  14531. viewport = glSubImage.viewport;
  14532. }
  14533. const camera = cameras[i];
  14534. camera.matrix.fromArray(view.transform.matrix);
  14535. camera.projectionMatrix.fromArray(view.projectionMatrix);
  14536. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  14537. if (i === 0) {
  14538. cameraVR.matrix.copy(camera.matrix);
  14539. }
  14540. if (cameraVRNeedsUpdate === true) {
  14541. cameraVR.cameras.push(camera);
  14542. }
  14543. }
  14544. if (isMultisample) {
  14545. state.bindXRFramebuffer(glMultisampledFramebuffer);
  14546. if (clearStyle !== null) gl.clear(clearStyle);
  14547. }
  14548. } //
  14549. const inputSources = session.inputSources;
  14550. for (let i = 0; i < controllers.length; i++) {
  14551. const controller = controllers[i];
  14552. const inputSource = inputSources[i];
  14553. controller.update(inputSource, frame, referenceSpace);
  14554. }
  14555. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  14556. if (isMultisample) {
  14557. const width = glProjLayer.textureWidth;
  14558. const height = glProjLayer.textureHeight;
  14559. state.bindFramebuffer(gl.READ_FRAMEBUFFER, glMultisampledFramebuffer);
  14560. state.bindFramebuffer(gl.DRAW_FRAMEBUFFER, glFramebuffer); // Invalidate the depth here to avoid flush of the depth data to main memory.
  14561. gl.invalidateFramebuffer(gl.READ_FRAMEBUFFER, [depthStyle]);
  14562. gl.invalidateFramebuffer(gl.DRAW_FRAMEBUFFER, [depthStyle]);
  14563. 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.
  14564. gl.invalidateFramebuffer(gl.READ_FRAMEBUFFER, [gl.COLOR_ATTACHMENT0]);
  14565. state.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  14566. state.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
  14567. state.bindFramebuffer(gl.FRAMEBUFFER, glMultisampledFramebuffer);
  14568. }
  14569. xrFrame = null;
  14570. }
  14571. const animation = new WebGLAnimation();
  14572. animation.setAnimationLoop(onAnimationFrame);
  14573. this.setAnimationLoop = function (callback) {
  14574. onAnimationFrameCallback = callback;
  14575. };
  14576. this.dispose = function () {};
  14577. }
  14578. }
  14579. function WebGLMaterials(properties) {
  14580. function refreshFogUniforms(uniforms, fog) {
  14581. uniforms.fogColor.value.copy(fog.color);
  14582. if (fog.isFog) {
  14583. uniforms.fogNear.value = fog.near;
  14584. uniforms.fogFar.value = fog.far;
  14585. } else if (fog.isFogExp2) {
  14586. uniforms.fogDensity.value = fog.density;
  14587. }
  14588. }
  14589. function refreshMaterialUniforms(uniforms, material, pixelRatio, height, transmissionRenderTarget) {
  14590. if (material.isMeshBasicMaterial) {
  14591. refreshUniformsCommon(uniforms, material);
  14592. } else if (material.isMeshLambertMaterial) {
  14593. refreshUniformsCommon(uniforms, material);
  14594. refreshUniformsLambert(uniforms, material);
  14595. } else if (material.isMeshToonMaterial) {
  14596. refreshUniformsCommon(uniforms, material);
  14597. refreshUniformsToon(uniforms, material);
  14598. } else if (material.isMeshPhongMaterial) {
  14599. refreshUniformsCommon(uniforms, material);
  14600. refreshUniformsPhong(uniforms, material);
  14601. } else if (material.isMeshStandardMaterial) {
  14602. refreshUniformsCommon(uniforms, material);
  14603. if (material.isMeshPhysicalMaterial) {
  14604. refreshUniformsPhysical(uniforms, material, transmissionRenderTarget);
  14605. } else {
  14606. refreshUniformsStandard(uniforms, material);
  14607. }
  14608. } else if (material.isMeshMatcapMaterial) {
  14609. refreshUniformsCommon(uniforms, material);
  14610. refreshUniformsMatcap(uniforms, material);
  14611. } else if (material.isMeshDepthMaterial) {
  14612. refreshUniformsCommon(uniforms, material);
  14613. refreshUniformsDepth(uniforms, material);
  14614. } else if (material.isMeshDistanceMaterial) {
  14615. refreshUniformsCommon(uniforms, material);
  14616. refreshUniformsDistance(uniforms, material);
  14617. } else if (material.isMeshNormalMaterial) {
  14618. refreshUniformsCommon(uniforms, material);
  14619. refreshUniformsNormal(uniforms, material);
  14620. } else if (material.isLineBasicMaterial) {
  14621. refreshUniformsLine(uniforms, material);
  14622. if (material.isLineDashedMaterial) {
  14623. refreshUniformsDash(uniforms, material);
  14624. }
  14625. } else if (material.isPointsMaterial) {
  14626. refreshUniformsPoints(uniforms, material, pixelRatio, height);
  14627. } else if (material.isSpriteMaterial) {
  14628. refreshUniformsSprites(uniforms, material);
  14629. } else if (material.isShadowMaterial) {
  14630. uniforms.color.value.copy(material.color);
  14631. uniforms.opacity.value = material.opacity;
  14632. } else if (material.isShaderMaterial) {
  14633. material.uniformsNeedUpdate = false; // #15581
  14634. }
  14635. }
  14636. function refreshUniformsCommon(uniforms, material) {
  14637. uniforms.opacity.value = material.opacity;
  14638. if (material.color) {
  14639. uniforms.diffuse.value.copy(material.color);
  14640. }
  14641. if (material.emissive) {
  14642. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  14643. }
  14644. if (material.map) {
  14645. uniforms.map.value = material.map;
  14646. }
  14647. if (material.alphaMap) {
  14648. uniforms.alphaMap.value = material.alphaMap;
  14649. }
  14650. if (material.specularMap) {
  14651. uniforms.specularMap.value = material.specularMap;
  14652. }
  14653. const envMap = properties.get(material).envMap;
  14654. if (envMap) {
  14655. uniforms.envMap.value = envMap;
  14656. uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1;
  14657. uniforms.reflectivity.value = material.reflectivity;
  14658. uniforms.ior.value = material.ior;
  14659. uniforms.refractionRatio.value = material.refractionRatio;
  14660. const maxMipLevel = properties.get(envMap).__maxMipLevel;
  14661. if (maxMipLevel !== undefined) {
  14662. uniforms.maxMipLevel.value = maxMipLevel;
  14663. }
  14664. }
  14665. if (material.lightMap) {
  14666. uniforms.lightMap.value = material.lightMap;
  14667. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  14668. }
  14669. if (material.aoMap) {
  14670. uniforms.aoMap.value = material.aoMap;
  14671. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  14672. } // uv repeat and offset setting priorities
  14673. // 1. color map
  14674. // 2. specular map
  14675. // 3. displacementMap map
  14676. // 4. normal map
  14677. // 5. bump map
  14678. // 6. roughnessMap map
  14679. // 7. metalnessMap map
  14680. // 8. alphaMap map
  14681. // 9. emissiveMap map
  14682. // 10. clearcoat map
  14683. // 11. clearcoat normal map
  14684. // 12. clearcoat roughnessMap map
  14685. // 13. specular intensity map
  14686. // 14. specular tint map
  14687. let uvScaleMap;
  14688. if (material.map) {
  14689. uvScaleMap = material.map;
  14690. } else if (material.specularMap) {
  14691. uvScaleMap = material.specularMap;
  14692. } else if (material.displacementMap) {
  14693. uvScaleMap = material.displacementMap;
  14694. } else if (material.normalMap) {
  14695. uvScaleMap = material.normalMap;
  14696. } else if (material.bumpMap) {
  14697. uvScaleMap = material.bumpMap;
  14698. } else if (material.roughnessMap) {
  14699. uvScaleMap = material.roughnessMap;
  14700. } else if (material.metalnessMap) {
  14701. uvScaleMap = material.metalnessMap;
  14702. } else if (material.alphaMap) {
  14703. uvScaleMap = material.alphaMap;
  14704. } else if (material.emissiveMap) {
  14705. uvScaleMap = material.emissiveMap;
  14706. } else if (material.clearcoatMap) {
  14707. uvScaleMap = material.clearcoatMap;
  14708. } else if (material.clearcoatNormalMap) {
  14709. uvScaleMap = material.clearcoatNormalMap;
  14710. } else if (material.clearcoatRoughnessMap) {
  14711. uvScaleMap = material.clearcoatRoughnessMap;
  14712. } else if (material.specularIntensityMap) {
  14713. uvScaleMap = material.specularIntensityMap;
  14714. } else if (material.specularTintMap) {
  14715. uvScaleMap = material.specularTintMap;
  14716. }
  14717. if (uvScaleMap !== undefined) {
  14718. // backwards compatibility
  14719. if (uvScaleMap.isWebGLRenderTarget) {
  14720. uvScaleMap = uvScaleMap.texture;
  14721. }
  14722. if (uvScaleMap.matrixAutoUpdate === true) {
  14723. uvScaleMap.updateMatrix();
  14724. }
  14725. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  14726. } // uv repeat and offset setting priorities for uv2
  14727. // 1. ao map
  14728. // 2. light map
  14729. let uv2ScaleMap;
  14730. if (material.aoMap) {
  14731. uv2ScaleMap = material.aoMap;
  14732. } else if (material.lightMap) {
  14733. uv2ScaleMap = material.lightMap;
  14734. }
  14735. if (uv2ScaleMap !== undefined) {
  14736. // backwards compatibility
  14737. if (uv2ScaleMap.isWebGLRenderTarget) {
  14738. uv2ScaleMap = uv2ScaleMap.texture;
  14739. }
  14740. if (uv2ScaleMap.matrixAutoUpdate === true) {
  14741. uv2ScaleMap.updateMatrix();
  14742. }
  14743. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  14744. }
  14745. }
  14746. function refreshUniformsLine(uniforms, material) {
  14747. uniforms.diffuse.value.copy(material.color);
  14748. uniforms.opacity.value = material.opacity;
  14749. }
  14750. function refreshUniformsDash(uniforms, material) {
  14751. uniforms.dashSize.value = material.dashSize;
  14752. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14753. uniforms.scale.value = material.scale;
  14754. }
  14755. function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
  14756. uniforms.diffuse.value.copy(material.color);
  14757. uniforms.opacity.value = material.opacity;
  14758. uniforms.size.value = material.size * pixelRatio;
  14759. uniforms.scale.value = height * 0.5;
  14760. if (material.map) {
  14761. uniforms.map.value = material.map;
  14762. }
  14763. if (material.alphaMap) {
  14764. uniforms.alphaMap.value = material.alphaMap;
  14765. } // uv repeat and offset setting priorities
  14766. // 1. color map
  14767. // 2. alpha map
  14768. let uvScaleMap;
  14769. if (material.map) {
  14770. uvScaleMap = material.map;
  14771. } else if (material.alphaMap) {
  14772. uvScaleMap = material.alphaMap;
  14773. }
  14774. if (uvScaleMap !== undefined) {
  14775. if (uvScaleMap.matrixAutoUpdate === true) {
  14776. uvScaleMap.updateMatrix();
  14777. }
  14778. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  14779. }
  14780. }
  14781. function refreshUniformsSprites(uniforms, material) {
  14782. uniforms.diffuse.value.copy(material.color);
  14783. uniforms.opacity.value = material.opacity;
  14784. uniforms.rotation.value = material.rotation;
  14785. if (material.map) {
  14786. uniforms.map.value = material.map;
  14787. }
  14788. if (material.alphaMap) {
  14789. uniforms.alphaMap.value = material.alphaMap;
  14790. } // uv repeat and offset setting priorities
  14791. // 1. color map
  14792. // 2. alpha map
  14793. let uvScaleMap;
  14794. if (material.map) {
  14795. uvScaleMap = material.map;
  14796. } else if (material.alphaMap) {
  14797. uvScaleMap = material.alphaMap;
  14798. }
  14799. if (uvScaleMap !== undefined) {
  14800. if (uvScaleMap.matrixAutoUpdate === true) {
  14801. uvScaleMap.updateMatrix();
  14802. }
  14803. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  14804. }
  14805. }
  14806. function refreshUniformsLambert(uniforms, material) {
  14807. if (material.emissiveMap) {
  14808. uniforms.emissiveMap.value = material.emissiveMap;
  14809. }
  14810. }
  14811. function refreshUniformsPhong(uniforms, material) {
  14812. uniforms.specular.value.copy(material.specular);
  14813. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  14814. if (material.emissiveMap) {
  14815. uniforms.emissiveMap.value = material.emissiveMap;
  14816. }
  14817. if (material.bumpMap) {
  14818. uniforms.bumpMap.value = material.bumpMap;
  14819. uniforms.bumpScale.value = material.bumpScale;
  14820. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14821. }
  14822. if (material.normalMap) {
  14823. uniforms.normalMap.value = material.normalMap;
  14824. uniforms.normalScale.value.copy(material.normalScale);
  14825. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14826. }
  14827. if (material.displacementMap) {
  14828. uniforms.displacementMap.value = material.displacementMap;
  14829. uniforms.displacementScale.value = material.displacementScale;
  14830. uniforms.displacementBias.value = material.displacementBias;
  14831. }
  14832. }
  14833. function refreshUniformsToon(uniforms, material) {
  14834. if (material.gradientMap) {
  14835. uniforms.gradientMap.value = material.gradientMap;
  14836. }
  14837. if (material.emissiveMap) {
  14838. uniforms.emissiveMap.value = material.emissiveMap;
  14839. }
  14840. if (material.bumpMap) {
  14841. uniforms.bumpMap.value = material.bumpMap;
  14842. uniforms.bumpScale.value = material.bumpScale;
  14843. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14844. }
  14845. if (material.normalMap) {
  14846. uniforms.normalMap.value = material.normalMap;
  14847. uniforms.normalScale.value.copy(material.normalScale);
  14848. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14849. }
  14850. if (material.displacementMap) {
  14851. uniforms.displacementMap.value = material.displacementMap;
  14852. uniforms.displacementScale.value = material.displacementScale;
  14853. uniforms.displacementBias.value = material.displacementBias;
  14854. }
  14855. }
  14856. function refreshUniformsStandard(uniforms, material) {
  14857. uniforms.roughness.value = material.roughness;
  14858. uniforms.metalness.value = material.metalness;
  14859. if (material.roughnessMap) {
  14860. uniforms.roughnessMap.value = material.roughnessMap;
  14861. }
  14862. if (material.metalnessMap) {
  14863. uniforms.metalnessMap.value = material.metalnessMap;
  14864. }
  14865. if (material.emissiveMap) {
  14866. uniforms.emissiveMap.value = material.emissiveMap;
  14867. }
  14868. if (material.bumpMap) {
  14869. uniforms.bumpMap.value = material.bumpMap;
  14870. uniforms.bumpScale.value = material.bumpScale;
  14871. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14872. }
  14873. if (material.normalMap) {
  14874. uniforms.normalMap.value = material.normalMap;
  14875. uniforms.normalScale.value.copy(material.normalScale);
  14876. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14877. }
  14878. if (material.displacementMap) {
  14879. uniforms.displacementMap.value = material.displacementMap;
  14880. uniforms.displacementScale.value = material.displacementScale;
  14881. uniforms.displacementBias.value = material.displacementBias;
  14882. }
  14883. const envMap = properties.get(material).envMap;
  14884. if (envMap) {
  14885. //uniforms.envMap.value = material.envMap; // part of uniforms common
  14886. uniforms.envMapIntensity.value = material.envMapIntensity;
  14887. }
  14888. }
  14889. function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) {
  14890. refreshUniformsStandard(uniforms, material);
  14891. uniforms.ior.value = material.ior; // also part of uniforms common
  14892. uniforms.clearcoat.value = material.clearcoat;
  14893. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  14894. if (material.sheen) uniforms.sheen.value.copy(material.sheen);
  14895. if (material.clearcoatMap) {
  14896. uniforms.clearcoatMap.value = material.clearcoatMap;
  14897. }
  14898. if (material.clearcoatRoughnessMap) {
  14899. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  14900. }
  14901. if (material.clearcoatNormalMap) {
  14902. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  14903. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  14904. if (material.side === BackSide) {
  14905. uniforms.clearcoatNormalScale.value.negate();
  14906. }
  14907. }
  14908. uniforms.transmission.value = material.transmission;
  14909. if (material.transmissionMap) {
  14910. uniforms.transmissionMap.value = material.transmissionMap;
  14911. }
  14912. if (material.transmission > 0.0) {
  14913. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  14914. uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height);
  14915. }
  14916. uniforms.thickness.value = material.thickness;
  14917. if (material.thicknessMap) {
  14918. uniforms.thicknessMap.value = material.thicknessMap;
  14919. }
  14920. uniforms.attenuationDistance.value = material.attenuationDistance;
  14921. uniforms.attenuationTint.value.copy(material.attenuationTint);
  14922. uniforms.specularIntensity.value = material.specularIntensity;
  14923. uniforms.specularTint.value.copy(material.specularTint);
  14924. if (material.specularIntensityMap) {
  14925. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  14926. }
  14927. if (material.specularTintMap) {
  14928. uniforms.specularTintMap.value = material.specularTintMap;
  14929. }
  14930. }
  14931. function refreshUniformsMatcap(uniforms, material) {
  14932. if (material.matcap) {
  14933. uniforms.matcap.value = material.matcap;
  14934. }
  14935. if (material.bumpMap) {
  14936. uniforms.bumpMap.value = material.bumpMap;
  14937. uniforms.bumpScale.value = material.bumpScale;
  14938. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14939. }
  14940. if (material.normalMap) {
  14941. uniforms.normalMap.value = material.normalMap;
  14942. uniforms.normalScale.value.copy(material.normalScale);
  14943. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14944. }
  14945. if (material.displacementMap) {
  14946. uniforms.displacementMap.value = material.displacementMap;
  14947. uniforms.displacementScale.value = material.displacementScale;
  14948. uniforms.displacementBias.value = material.displacementBias;
  14949. }
  14950. }
  14951. function refreshUniformsDepth(uniforms, material) {
  14952. if (material.displacementMap) {
  14953. uniforms.displacementMap.value = material.displacementMap;
  14954. uniforms.displacementScale.value = material.displacementScale;
  14955. uniforms.displacementBias.value = material.displacementBias;
  14956. }
  14957. }
  14958. function refreshUniformsDistance(uniforms, material) {
  14959. if (material.displacementMap) {
  14960. uniforms.displacementMap.value = material.displacementMap;
  14961. uniforms.displacementScale.value = material.displacementScale;
  14962. uniforms.displacementBias.value = material.displacementBias;
  14963. }
  14964. uniforms.referencePosition.value.copy(material.referencePosition);
  14965. uniforms.nearDistance.value = material.nearDistance;
  14966. uniforms.farDistance.value = material.farDistance;
  14967. }
  14968. function refreshUniformsNormal(uniforms, material) {
  14969. if (material.bumpMap) {
  14970. uniforms.bumpMap.value = material.bumpMap;
  14971. uniforms.bumpScale.value = material.bumpScale;
  14972. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14973. }
  14974. if (material.normalMap) {
  14975. uniforms.normalMap.value = material.normalMap;
  14976. uniforms.normalScale.value.copy(material.normalScale);
  14977. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14978. }
  14979. if (material.displacementMap) {
  14980. uniforms.displacementMap.value = material.displacementMap;
  14981. uniforms.displacementScale.value = material.displacementScale;
  14982. uniforms.displacementBias.value = material.displacementBias;
  14983. }
  14984. }
  14985. return {
  14986. refreshFogUniforms: refreshFogUniforms,
  14987. refreshMaterialUniforms: refreshMaterialUniforms
  14988. };
  14989. }
  14990. function createCanvasElement() {
  14991. const canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  14992. canvas.style.display = 'block';
  14993. return canvas;
  14994. }
  14995. function WebGLRenderer(parameters = {}) {
  14996. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  14997. _context = parameters.context !== undefined ? parameters.context : null,
  14998. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14999. _depth = parameters.depth !== undefined ? parameters.depth : true,
  15000. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  15001. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  15002. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  15003. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  15004. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  15005. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  15006. let currentRenderList = null;
  15007. let currentRenderState = null; // render() can be called from within a callback triggered by another render.
  15008. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  15009. const renderListStack = [];
  15010. const renderStateStack = []; // public properties
  15011. this.domElement = _canvas; // Debug configuration container
  15012. this.debug = {
  15013. /**
  15014. * Enables error checking and reporting when shader programs are being compiled
  15015. * @type {boolean}
  15016. */
  15017. checkShaderErrors: true
  15018. }; // clearing
  15019. this.autoClear = true;
  15020. this.autoClearColor = true;
  15021. this.autoClearDepth = true;
  15022. this.autoClearStencil = true; // scene graph
  15023. this.sortObjects = true; // user-defined clipping
  15024. this.clippingPlanes = [];
  15025. this.localClippingEnabled = false; // physically based shading
  15026. this.gammaFactor = 2.0; // for backwards compatibility
  15027. this.outputEncoding = LinearEncoding; // physical lights
  15028. this.physicallyCorrectLights = false; // tone mapping
  15029. this.toneMapping = NoToneMapping;
  15030. this.toneMappingExposure = 1.0; // internal properties
  15031. const _this = this;
  15032. let _isContextLost = false; // internal state cache
  15033. let _currentActiveCubeFace = 0;
  15034. let _currentActiveMipmapLevel = 0;
  15035. let _currentRenderTarget = null;
  15036. let _currentMaterialId = -1;
  15037. let _currentCamera = null;
  15038. const _currentViewport = new Vector4();
  15039. const _currentScissor = new Vector4();
  15040. let _currentScissorTest = null; //
  15041. let _width = _canvas.width;
  15042. let _height = _canvas.height;
  15043. let _pixelRatio = 1;
  15044. let _opaqueSort = null;
  15045. let _transparentSort = null;
  15046. const _viewport = new Vector4(0, 0, _width, _height);
  15047. const _scissor = new Vector4(0, 0, _width, _height);
  15048. let _scissorTest = false; //
  15049. const _currentDrawBuffers = []; // frustum
  15050. const _frustum = new Frustum(); // clipping
  15051. let _clippingEnabled = false;
  15052. let _localClippingEnabled = false; // transmission
  15053. let _transmissionRenderTarget = null; // camera matrices cache
  15054. const _projScreenMatrix = new Matrix4();
  15055. const _vector3 = new Vector3();
  15056. const _emptyScene = {
  15057. background: null,
  15058. fog: null,
  15059. environment: null,
  15060. overrideMaterial: null,
  15061. isScene: true
  15062. };
  15063. function getTargetPixelRatio() {
  15064. return _currentRenderTarget === null ? _pixelRatio : 1;
  15065. } // initialize
  15066. let _gl = _context;
  15067. function getContext(contextNames, contextAttributes) {
  15068. for (let i = 0; i < contextNames.length; i++) {
  15069. const contextName = contextNames[i];
  15070. const context = _canvas.getContext(contextName, contextAttributes);
  15071. if (context !== null) return context;
  15072. }
  15073. return null;
  15074. }
  15075. try {
  15076. const contextAttributes = {
  15077. alpha: _alpha,
  15078. depth: _depth,
  15079. stencil: _stencil,
  15080. antialias: _antialias,
  15081. premultipliedAlpha: _premultipliedAlpha,
  15082. preserveDrawingBuffer: _preserveDrawingBuffer,
  15083. powerPreference: _powerPreference,
  15084. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  15085. }; // event listeners must be registered before WebGL context is created, see #12753
  15086. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  15087. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  15088. if (_gl === null) {
  15089. const contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
  15090. if (_this.isWebGL1Renderer === true) {
  15091. contextNames.shift();
  15092. }
  15093. _gl = getContext(contextNames, contextAttributes);
  15094. if (_gl === null) {
  15095. if (getContext(contextNames)) {
  15096. throw new Error('Error creating WebGL context with your selected attributes.');
  15097. } else {
  15098. throw new Error('Error creating WebGL context.');
  15099. }
  15100. }
  15101. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  15102. if (_gl.getShaderPrecisionFormat === undefined) {
  15103. _gl.getShaderPrecisionFormat = function () {
  15104. return {
  15105. 'rangeMin': 1,
  15106. 'rangeMax': 1,
  15107. 'precision': 1
  15108. };
  15109. };
  15110. }
  15111. } catch (error) {
  15112. console.error('THREE.WebGLRenderer: ' + error.message);
  15113. throw error;
  15114. }
  15115. let extensions, capabilities, state, info;
  15116. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  15117. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  15118. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  15119. let utils, bindingStates;
  15120. function initGLContext() {
  15121. extensions = new WebGLExtensions(_gl);
  15122. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  15123. extensions.init(capabilities);
  15124. utils = new WebGLUtils(_gl, extensions, capabilities);
  15125. state = new WebGLState(_gl, extensions, capabilities);
  15126. _currentDrawBuffers[0] = _gl.BACK;
  15127. info = new WebGLInfo(_gl);
  15128. properties = new WebGLProperties();
  15129. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  15130. cubemaps = new WebGLCubeMaps(_this);
  15131. cubeuvmaps = new WebGLCubeUVMaps(_this);
  15132. attributes = new WebGLAttributes(_gl, capabilities);
  15133. bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
  15134. geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
  15135. objects = new WebGLObjects(_gl, geometries, attributes, info);
  15136. morphtargets = new WebGLMorphtargets(_gl);
  15137. clipping = new WebGLClipping(properties);
  15138. programCache = new WebGLPrograms(_this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping);
  15139. materials = new WebGLMaterials(properties);
  15140. renderLists = new WebGLRenderLists(properties);
  15141. renderStates = new WebGLRenderStates(extensions, capabilities);
  15142. background = new WebGLBackground(_this, cubemaps, state, objects, _premultipliedAlpha);
  15143. shadowMap = new WebGLShadowMap(_this, objects, capabilities);
  15144. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  15145. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  15146. info.programs = programCache.programs;
  15147. _this.capabilities = capabilities;
  15148. _this.extensions = extensions;
  15149. _this.properties = properties;
  15150. _this.renderLists = renderLists;
  15151. _this.shadowMap = shadowMap;
  15152. _this.state = state;
  15153. _this.info = info;
  15154. }
  15155. initGLContext(); // xr
  15156. const xr = new WebXRManager(_this, _gl);
  15157. this.xr = xr; // API
  15158. this.getContext = function () {
  15159. return _gl;
  15160. };
  15161. this.getContextAttributes = function () {
  15162. return _gl.getContextAttributes();
  15163. };
  15164. this.forceContextLoss = function () {
  15165. const extension = extensions.get('WEBGL_lose_context');
  15166. if (extension) extension.loseContext();
  15167. };
  15168. this.forceContextRestore = function () {
  15169. const extension = extensions.get('WEBGL_lose_context');
  15170. if (extension) extension.restoreContext();
  15171. };
  15172. this.getPixelRatio = function () {
  15173. return _pixelRatio;
  15174. };
  15175. this.setPixelRatio = function (value) {
  15176. if (value === undefined) return;
  15177. _pixelRatio = value;
  15178. this.setSize(_width, _height, false);
  15179. };
  15180. this.getSize = function (target) {
  15181. return target.set(_width, _height);
  15182. };
  15183. this.setSize = function (width, height, updateStyle) {
  15184. if (xr.isPresenting) {
  15185. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  15186. return;
  15187. }
  15188. _width = width;
  15189. _height = height;
  15190. _canvas.width = Math.floor(width * _pixelRatio);
  15191. _canvas.height = Math.floor(height * _pixelRatio);
  15192. if (updateStyle !== false) {
  15193. _canvas.style.width = width + 'px';
  15194. _canvas.style.height = height + 'px';
  15195. }
  15196. this.setViewport(0, 0, width, height);
  15197. };
  15198. this.getDrawingBufferSize = function (target) {
  15199. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  15200. };
  15201. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  15202. _width = width;
  15203. _height = height;
  15204. _pixelRatio = pixelRatio;
  15205. _canvas.width = Math.floor(width * pixelRatio);
  15206. _canvas.height = Math.floor(height * pixelRatio);
  15207. this.setViewport(0, 0, width, height);
  15208. };
  15209. this.getCurrentViewport = function (target) {
  15210. return target.copy(_currentViewport);
  15211. };
  15212. this.getViewport = function (target) {
  15213. return target.copy(_viewport);
  15214. };
  15215. this.setViewport = function (x, y, width, height) {
  15216. if (x.isVector4) {
  15217. _viewport.set(x.x, x.y, x.z, x.w);
  15218. } else {
  15219. _viewport.set(x, y, width, height);
  15220. }
  15221. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  15222. };
  15223. this.getScissor = function (target) {
  15224. return target.copy(_scissor);
  15225. };
  15226. this.setScissor = function (x, y, width, height) {
  15227. if (x.isVector4) {
  15228. _scissor.set(x.x, x.y, x.z, x.w);
  15229. } else {
  15230. _scissor.set(x, y, width, height);
  15231. }
  15232. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  15233. };
  15234. this.getScissorTest = function () {
  15235. return _scissorTest;
  15236. };
  15237. this.setScissorTest = function (boolean) {
  15238. state.setScissorTest(_scissorTest = boolean);
  15239. };
  15240. this.setOpaqueSort = function (method) {
  15241. _opaqueSort = method;
  15242. };
  15243. this.setTransparentSort = function (method) {
  15244. _transparentSort = method;
  15245. }; // Clearing
  15246. this.getClearColor = function (target) {
  15247. return target.copy(background.getClearColor());
  15248. };
  15249. this.setClearColor = function () {
  15250. background.setClearColor.apply(background, arguments);
  15251. };
  15252. this.getClearAlpha = function () {
  15253. return background.getClearAlpha();
  15254. };
  15255. this.setClearAlpha = function () {
  15256. background.setClearAlpha.apply(background, arguments);
  15257. };
  15258. this.clear = function (color, depth, stencil) {
  15259. let bits = 0;
  15260. if (color === undefined || color) bits |= _gl.COLOR_BUFFER_BIT;
  15261. if (depth === undefined || depth) bits |= _gl.DEPTH_BUFFER_BIT;
  15262. if (stencil === undefined || stencil) bits |= _gl.STENCIL_BUFFER_BIT;
  15263. _gl.clear(bits);
  15264. };
  15265. this.clearColor = function () {
  15266. this.clear(true, false, false);
  15267. };
  15268. this.clearDepth = function () {
  15269. this.clear(false, true, false);
  15270. };
  15271. this.clearStencil = function () {
  15272. this.clear(false, false, true);
  15273. }; //
  15274. this.dispose = function () {
  15275. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  15276. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  15277. renderLists.dispose();
  15278. renderStates.dispose();
  15279. properties.dispose();
  15280. cubemaps.dispose();
  15281. cubeuvmaps.dispose();
  15282. objects.dispose();
  15283. bindingStates.dispose();
  15284. xr.dispose();
  15285. xr.removeEventListener('sessionstart', onXRSessionStart);
  15286. xr.removeEventListener('sessionend', onXRSessionEnd);
  15287. if (_transmissionRenderTarget) {
  15288. _transmissionRenderTarget.dispose();
  15289. _transmissionRenderTarget = null;
  15290. }
  15291. animation.stop();
  15292. }; // Events
  15293. function onContextLost(event) {
  15294. event.preventDefault();
  15295. console.log('THREE.WebGLRenderer: Context Lost.');
  15296. _isContextLost = true;
  15297. }
  15298. function onContextRestore() {
  15299. console.log('THREE.WebGLRenderer: Context Restored.');
  15300. _isContextLost = false;
  15301. const infoAutoReset = info.autoReset;
  15302. const shadowMapEnabled = shadowMap.enabled;
  15303. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  15304. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  15305. const shadowMapType = shadowMap.type;
  15306. initGLContext();
  15307. info.autoReset = infoAutoReset;
  15308. shadowMap.enabled = shadowMapEnabled;
  15309. shadowMap.autoUpdate = shadowMapAutoUpdate;
  15310. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  15311. shadowMap.type = shadowMapType;
  15312. }
  15313. function onMaterialDispose(event) {
  15314. const material = event.target;
  15315. material.removeEventListener('dispose', onMaterialDispose);
  15316. deallocateMaterial(material);
  15317. } // Buffer deallocation
  15318. function deallocateMaterial(material) {
  15319. releaseMaterialProgramReferences(material);
  15320. properties.remove(material);
  15321. }
  15322. function releaseMaterialProgramReferences(material) {
  15323. const programs = properties.get(material).programs;
  15324. if (programs !== undefined) {
  15325. programs.forEach(function (program) {
  15326. programCache.releaseProgram(program);
  15327. });
  15328. }
  15329. } // Buffer rendering
  15330. function renderObjectImmediate(object, program) {
  15331. object.render(function (object) {
  15332. _this.renderBufferImmediate(object, program);
  15333. });
  15334. }
  15335. this.renderBufferImmediate = function (object, program) {
  15336. bindingStates.initAttributes();
  15337. const buffers = properties.get(object);
  15338. if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
  15339. if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
  15340. if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
  15341. if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
  15342. const programAttributes = program.getAttributes();
  15343. if (object.hasPositions) {
  15344. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.position);
  15345. _gl.bufferData(_gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW);
  15346. bindingStates.enableAttribute(programAttributes.position);
  15347. _gl.vertexAttribPointer(programAttributes.position, 3, _gl.FLOAT, false, 0, 0);
  15348. }
  15349. if (object.hasNormals) {
  15350. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.normal);
  15351. _gl.bufferData(_gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW);
  15352. bindingStates.enableAttribute(programAttributes.normal);
  15353. _gl.vertexAttribPointer(programAttributes.normal, 3, _gl.FLOAT, false, 0, 0);
  15354. }
  15355. if (object.hasUvs) {
  15356. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.uv);
  15357. _gl.bufferData(_gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW);
  15358. bindingStates.enableAttribute(programAttributes.uv);
  15359. _gl.vertexAttribPointer(programAttributes.uv, 2, _gl.FLOAT, false, 0, 0);
  15360. }
  15361. if (object.hasColors) {
  15362. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.color);
  15363. _gl.bufferData(_gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW);
  15364. bindingStates.enableAttribute(programAttributes.color);
  15365. _gl.vertexAttribPointer(programAttributes.color, 3, _gl.FLOAT, false, 0, 0);
  15366. }
  15367. bindingStates.disableUnusedAttributes();
  15368. _gl.drawArrays(_gl.TRIANGLES, 0, object.count);
  15369. object.count = 0;
  15370. };
  15371. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  15372. if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  15373. const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  15374. const program = setProgram(camera, scene, material, object);
  15375. state.setMaterial(material, frontFaceCW); //
  15376. let index = geometry.index;
  15377. const position = geometry.attributes.position; //
  15378. if (index === null) {
  15379. if (position === undefined || position.count === 0) return;
  15380. } else if (index.count === 0) {
  15381. return;
  15382. } //
  15383. let rangeFactor = 1;
  15384. if (material.wireframe === true) {
  15385. index = geometries.getWireframeAttribute(geometry);
  15386. rangeFactor = 2;
  15387. }
  15388. if (geometry.morphAttributes.position !== undefined || geometry.morphAttributes.normal !== undefined) {
  15389. morphtargets.update(object, geometry, material, program);
  15390. }
  15391. bindingStates.setup(object, material, program, geometry, index);
  15392. let attribute;
  15393. let renderer = bufferRenderer;
  15394. if (index !== null) {
  15395. attribute = attributes.get(index);
  15396. renderer = indexedBufferRenderer;
  15397. renderer.setIndex(attribute);
  15398. } //
  15399. const dataCount = index !== null ? index.count : position.count;
  15400. const rangeStart = geometry.drawRange.start * rangeFactor;
  15401. const rangeCount = geometry.drawRange.count * rangeFactor;
  15402. const groupStart = group !== null ? group.start * rangeFactor : 0;
  15403. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  15404. const drawStart = Math.max(rangeStart, groupStart);
  15405. const drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  15406. const drawCount = Math.max(0, drawEnd - drawStart + 1);
  15407. if (drawCount === 0) return; //
  15408. if (object.isMesh) {
  15409. if (material.wireframe === true) {
  15410. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  15411. renderer.setMode(_gl.LINES);
  15412. } else {
  15413. renderer.setMode(_gl.TRIANGLES);
  15414. }
  15415. } else if (object.isLine) {
  15416. let lineWidth = material.linewidth;
  15417. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  15418. state.setLineWidth(lineWidth * getTargetPixelRatio());
  15419. if (object.isLineSegments) {
  15420. renderer.setMode(_gl.LINES);
  15421. } else if (object.isLineLoop) {
  15422. renderer.setMode(_gl.LINE_LOOP);
  15423. } else {
  15424. renderer.setMode(_gl.LINE_STRIP);
  15425. }
  15426. } else if (object.isPoints) {
  15427. renderer.setMode(_gl.POINTS);
  15428. } else if (object.isSprite) {
  15429. renderer.setMode(_gl.TRIANGLES);
  15430. }
  15431. if (object.isInstancedMesh) {
  15432. renderer.renderInstances(drawStart, drawCount, object.count);
  15433. } else if (geometry.isInstancedBufferGeometry) {
  15434. const instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount);
  15435. renderer.renderInstances(drawStart, drawCount, instanceCount);
  15436. } else {
  15437. renderer.render(drawStart, drawCount);
  15438. }
  15439. }; // Compile
  15440. this.compile = function (scene, camera) {
  15441. currentRenderState = renderStates.get(scene);
  15442. currentRenderState.init();
  15443. renderStateStack.push(currentRenderState);
  15444. scene.traverseVisible(function (object) {
  15445. if (object.isLight && object.layers.test(camera.layers)) {
  15446. currentRenderState.pushLight(object);
  15447. if (object.castShadow) {
  15448. currentRenderState.pushShadow(object);
  15449. }
  15450. }
  15451. });
  15452. currentRenderState.setupLights();
  15453. scene.traverse(function (object) {
  15454. const material = object.material;
  15455. if (material) {
  15456. if (Array.isArray(material)) {
  15457. for (let i = 0; i < material.length; i++) {
  15458. const material2 = material[i];
  15459. getProgram(material2, scene, object);
  15460. }
  15461. } else {
  15462. getProgram(material, scene, object);
  15463. }
  15464. }
  15465. });
  15466. renderStateStack.pop();
  15467. currentRenderState = null;
  15468. }; // Animation Loop
  15469. let onAnimationFrameCallback = null;
  15470. function onAnimationFrame(time) {
  15471. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  15472. }
  15473. function onXRSessionStart() {
  15474. animation.stop();
  15475. }
  15476. function onXRSessionEnd() {
  15477. animation.start();
  15478. }
  15479. const animation = new WebGLAnimation();
  15480. animation.setAnimationLoop(onAnimationFrame);
  15481. if (typeof window !== 'undefined') animation.setContext(window);
  15482. this.setAnimationLoop = function (callback) {
  15483. onAnimationFrameCallback = callback;
  15484. xr.setAnimationLoop(callback);
  15485. callback === null ? animation.stop() : animation.start();
  15486. };
  15487. xr.addEventListener('sessionstart', onXRSessionStart);
  15488. xr.addEventListener('sessionend', onXRSessionEnd); // Rendering
  15489. this.render = function (scene, camera) {
  15490. if (camera !== undefined && camera.isCamera !== true) {
  15491. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  15492. return;
  15493. }
  15494. if (_isContextLost === true) return; // update scene graph
  15495. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  15496. if (camera.parent === null) camera.updateMatrixWorld();
  15497. if (xr.enabled === true && xr.isPresenting === true) {
  15498. if (xr.cameraAutoUpdate === true) xr.updateCamera(camera);
  15499. camera = xr.getCamera(); // use XR camera for rendering
  15500. } //
  15501. if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, _currentRenderTarget);
  15502. currentRenderState = renderStates.get(scene, renderStateStack.length);
  15503. currentRenderState.init();
  15504. renderStateStack.push(currentRenderState);
  15505. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  15506. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  15507. _localClippingEnabled = this.localClippingEnabled;
  15508. _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  15509. currentRenderList = renderLists.get(scene, renderListStack.length);
  15510. currentRenderList.init();
  15511. renderListStack.push(currentRenderList);
  15512. projectObject(scene, camera, 0, _this.sortObjects);
  15513. currentRenderList.finish();
  15514. if (_this.sortObjects === true) {
  15515. currentRenderList.sort(_opaqueSort, _transparentSort);
  15516. } //
  15517. if (_clippingEnabled === true) clipping.beginShadows();
  15518. const shadowsArray = currentRenderState.state.shadowsArray;
  15519. shadowMap.render(shadowsArray, scene, camera);
  15520. currentRenderState.setupLights();
  15521. currentRenderState.setupLightsView(camera);
  15522. if (_clippingEnabled === true) clipping.endShadows(); //
  15523. if (this.info.autoReset === true) this.info.reset(); //
  15524. background.render(currentRenderList, scene); // render scene
  15525. const opaqueObjects = currentRenderList.opaque;
  15526. const transmissiveObjects = currentRenderList.transmissive;
  15527. const transparentObjects = currentRenderList.transparent;
  15528. if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
  15529. if (transmissiveObjects.length > 0) renderTransmissiveObjects(opaqueObjects, transmissiveObjects, scene, camera);
  15530. if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera); //
  15531. if (_currentRenderTarget !== null) {
  15532. // resolve multisample renderbuffers to a single-sample texture if necessary
  15533. textures.updateMultisampleRenderTarget(_currentRenderTarget); // Generate mipmap if we're using any kind of mipmap filtering
  15534. textures.updateRenderTargetMipmap(_currentRenderTarget);
  15535. } //
  15536. if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); // Ensure depth buffer writing is enabled so it can be cleared on next render
  15537. state.buffers.depth.setTest(true);
  15538. state.buffers.depth.setMask(true);
  15539. state.buffers.color.setMask(true);
  15540. state.setPolygonOffset(false); // _gl.finish();
  15541. bindingStates.resetDefaultState();
  15542. _currentMaterialId = -1;
  15543. _currentCamera = null;
  15544. renderStateStack.pop();
  15545. if (renderStateStack.length > 0) {
  15546. currentRenderState = renderStateStack[renderStateStack.length - 1];
  15547. } else {
  15548. currentRenderState = null;
  15549. }
  15550. renderListStack.pop();
  15551. if (renderListStack.length > 0) {
  15552. currentRenderList = renderListStack[renderListStack.length - 1];
  15553. } else {
  15554. currentRenderList = null;
  15555. }
  15556. };
  15557. function projectObject(object, camera, groupOrder, sortObjects) {
  15558. if (object.visible === false) return;
  15559. const visible = object.layers.test(camera.layers);
  15560. if (visible) {
  15561. if (object.isGroup) {
  15562. groupOrder = object.renderOrder;
  15563. } else if (object.isLOD) {
  15564. if (object.autoUpdate === true) object.update(camera);
  15565. } else if (object.isLight) {
  15566. currentRenderState.pushLight(object);
  15567. if (object.castShadow) {
  15568. currentRenderState.pushShadow(object);
  15569. }
  15570. } else if (object.isSprite) {
  15571. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  15572. if (sortObjects) {
  15573. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15574. }
  15575. const geometry = objects.update(object);
  15576. const material = object.material;
  15577. if (material.visible) {
  15578. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  15579. }
  15580. }
  15581. } else if (object.isImmediateRenderObject) {
  15582. if (sortObjects) {
  15583. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15584. }
  15585. currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
  15586. } else if (object.isMesh || object.isLine || object.isPoints) {
  15587. if (object.isSkinnedMesh) {
  15588. // update skeleton only once in a frame
  15589. if (object.skeleton.frame !== info.render.frame) {
  15590. object.skeleton.update();
  15591. object.skeleton.frame = info.render.frame;
  15592. }
  15593. }
  15594. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  15595. if (sortObjects) {
  15596. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15597. }
  15598. const geometry = objects.update(object);
  15599. const material = object.material;
  15600. if (Array.isArray(material)) {
  15601. const groups = geometry.groups;
  15602. for (let i = 0, l = groups.length; i < l; i++) {
  15603. const group = groups[i];
  15604. const groupMaterial = material[group.materialIndex];
  15605. if (groupMaterial && groupMaterial.visible) {
  15606. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  15607. }
  15608. }
  15609. } else if (material.visible) {
  15610. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  15611. }
  15612. }
  15613. }
  15614. }
  15615. const children = object.children;
  15616. for (let i = 0, l = children.length; i < l; i++) {
  15617. projectObject(children[i], camera, groupOrder, sortObjects);
  15618. }
  15619. }
  15620. function renderTransmissiveObjects(opaqueObjects, transmissiveObjects, scene, camera) {
  15621. if (_transmissionRenderTarget === null) {
  15622. const needsAntialias = _antialias === true && capabilities.isWebGL2 === true;
  15623. const renderTargetType = needsAntialias ? WebGLMultisampleRenderTarget : WebGLRenderTarget;
  15624. _transmissionRenderTarget = new renderTargetType(1024, 1024, {
  15625. generateMipmaps: true,
  15626. type: utils.convert(HalfFloatType) !== null ? HalfFloatType : UnsignedByteType,
  15627. minFilter: LinearMipmapLinearFilter,
  15628. magFilter: NearestFilter,
  15629. wrapS: ClampToEdgeWrapping,
  15630. wrapT: ClampToEdgeWrapping
  15631. });
  15632. }
  15633. const currentRenderTarget = _this.getRenderTarget();
  15634. _this.setRenderTarget(_transmissionRenderTarget);
  15635. _this.clear(); // Turn off the features which can affect the frag color for opaque objects pass.
  15636. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  15637. const currentToneMapping = _this.toneMapping;
  15638. _this.toneMapping = NoToneMapping;
  15639. renderObjects(opaqueObjects, scene, camera);
  15640. _this.toneMapping = currentToneMapping;
  15641. textures.updateMultisampleRenderTarget(_transmissionRenderTarget);
  15642. textures.updateRenderTargetMipmap(_transmissionRenderTarget);
  15643. _this.setRenderTarget(currentRenderTarget);
  15644. renderObjects(transmissiveObjects, scene, camera);
  15645. }
  15646. function renderObjects(renderList, scene, camera) {
  15647. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  15648. if (camera.isArrayCamera) {
  15649. const cameras = camera.cameras;
  15650. for (let i = 0, l = cameras.length; i < l; i++) {
  15651. const camera2 = cameras[i];
  15652. state.viewport(_currentViewport.copy(camera2.viewport));
  15653. currentRenderState.setupLightsView(camera2);
  15654. for (let j = 0, jl = renderList.length; j < jl; j++) {
  15655. const renderItem = renderList[j];
  15656. const object = renderItem.object;
  15657. const geometry = renderItem.geometry;
  15658. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  15659. const group = renderItem.group;
  15660. if (object.layers.test(camera2.layers)) {
  15661. renderObject(object, scene, camera2, geometry, material, group);
  15662. }
  15663. }
  15664. }
  15665. } else {
  15666. for (let j = 0, jl = renderList.length; j < jl; j++) {
  15667. const renderItem = renderList[j];
  15668. const object = renderItem.object;
  15669. const geometry = renderItem.geometry;
  15670. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  15671. const group = renderItem.group;
  15672. renderObject(object, scene, camera, geometry, material, group);
  15673. }
  15674. }
  15675. }
  15676. function renderObject(object, scene, camera, geometry, material, group) {
  15677. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  15678. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  15679. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  15680. if (object.isImmediateRenderObject) {
  15681. const program = setProgram(camera, scene, material, object);
  15682. state.setMaterial(material);
  15683. bindingStates.reset();
  15684. renderObjectImmediate(object, program);
  15685. } else {
  15686. if (material.transparent === true && material.side === DoubleSide) {
  15687. material.side = BackSide;
  15688. material.needsUpdate = true;
  15689. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  15690. material.side = FrontSide;
  15691. material.needsUpdate = true;
  15692. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  15693. material.side = DoubleSide;
  15694. } else {
  15695. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  15696. }
  15697. }
  15698. object.onAfterRender(_this, scene, camera, geometry, material, group);
  15699. }
  15700. function getProgram(material, scene, object) {
  15701. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  15702. const materialProperties = properties.get(material);
  15703. const lights = currentRenderState.state.lights;
  15704. const shadowsArray = currentRenderState.state.shadowsArray;
  15705. const lightsStateVersion = lights.state.version;
  15706. const parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
  15707. const programCacheKey = programCache.getProgramCacheKey(parameters);
  15708. 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
  15709. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  15710. materialProperties.fog = scene.fog;
  15711. materialProperties.envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || materialProperties.environment);
  15712. if (programs === undefined) {
  15713. // new material
  15714. material.addEventListener('dispose', onMaterialDispose);
  15715. programs = new Map();
  15716. materialProperties.programs = programs;
  15717. }
  15718. let program = programs.get(programCacheKey);
  15719. if (program !== undefined) {
  15720. // early out if program and light state is identical
  15721. if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) {
  15722. updateCommonMaterialProperties(material, parameters);
  15723. return program;
  15724. }
  15725. } else {
  15726. parameters.uniforms = programCache.getUniforms(material);
  15727. material.onBuild(parameters, _this);
  15728. material.onBeforeCompile(parameters, _this);
  15729. program = programCache.acquireProgram(parameters, programCacheKey);
  15730. programs.set(programCacheKey, program);
  15731. materialProperties.uniforms = parameters.uniforms;
  15732. }
  15733. const uniforms = materialProperties.uniforms;
  15734. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  15735. uniforms.clippingPlanes = clipping.uniform;
  15736. }
  15737. updateCommonMaterialProperties(material, parameters); // store the light setup it was created for
  15738. materialProperties.needsLights = materialNeedsLights(material);
  15739. materialProperties.lightsStateVersion = lightsStateVersion;
  15740. if (materialProperties.needsLights) {
  15741. // wire up the material to this renderer's lighting state
  15742. uniforms.ambientLightColor.value = lights.state.ambient;
  15743. uniforms.lightProbe.value = lights.state.probe;
  15744. uniforms.directionalLights.value = lights.state.directional;
  15745. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  15746. uniforms.spotLights.value = lights.state.spot;
  15747. uniforms.spotLightShadows.value = lights.state.spotShadow;
  15748. uniforms.rectAreaLights.value = lights.state.rectArea;
  15749. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  15750. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  15751. uniforms.pointLights.value = lights.state.point;
  15752. uniforms.pointLightShadows.value = lights.state.pointShadow;
  15753. uniforms.hemisphereLights.value = lights.state.hemi;
  15754. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  15755. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  15756. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  15757. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  15758. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  15759. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  15760. }
  15761. const progUniforms = program.getUniforms();
  15762. const uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  15763. materialProperties.currentProgram = program;
  15764. materialProperties.uniformsList = uniformsList;
  15765. return program;
  15766. }
  15767. function updateCommonMaterialProperties(material, parameters) {
  15768. const materialProperties = properties.get(material);
  15769. materialProperties.outputEncoding = parameters.outputEncoding;
  15770. materialProperties.instancing = parameters.instancing;
  15771. materialProperties.skinning = parameters.skinning;
  15772. materialProperties.morphTargets = parameters.morphTargets;
  15773. materialProperties.morphNormals = parameters.morphNormals;
  15774. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  15775. materialProperties.numIntersection = parameters.numClipIntersection;
  15776. materialProperties.vertexAlphas = parameters.vertexAlphas;
  15777. materialProperties.vertexTangents = parameters.vertexTangents;
  15778. }
  15779. function setProgram(camera, scene, material, object) {
  15780. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  15781. textures.resetTextureUnits();
  15782. const fog = scene.fog;
  15783. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  15784. const encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  15785. const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
  15786. const vertexAlphas = material.vertexColors === true && !!object.geometry && !!object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4;
  15787. const vertexTangents = !!object.geometry && !!object.geometry.attributes.tangent;
  15788. const morphTargets = !!object.geometry && !!object.geometry.morphAttributes.position;
  15789. const morphNormals = !!object.geometry && !!object.geometry.morphAttributes.normal;
  15790. const materialProperties = properties.get(material);
  15791. const lights = currentRenderState.state.lights;
  15792. if (_clippingEnabled === true) {
  15793. if (_localClippingEnabled === true || camera !== _currentCamera) {
  15794. const useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  15795. // object instead of the material, once it becomes feasible
  15796. // (#8465, #8379)
  15797. clipping.setState(material, camera, useCache);
  15798. }
  15799. } //
  15800. let needsProgramChange = false;
  15801. if (material.version === materialProperties.__version) {
  15802. if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  15803. needsProgramChange = true;
  15804. } else if (materialProperties.outputEncoding !== encoding) {
  15805. needsProgramChange = true;
  15806. } else if (object.isInstancedMesh && materialProperties.instancing === false) {
  15807. needsProgramChange = true;
  15808. } else if (!object.isInstancedMesh && materialProperties.instancing === true) {
  15809. needsProgramChange = true;
  15810. } else if (object.isSkinnedMesh && materialProperties.skinning === false) {
  15811. needsProgramChange = true;
  15812. } else if (!object.isSkinnedMesh && materialProperties.skinning === true) {
  15813. needsProgramChange = true;
  15814. } else if (materialProperties.envMap !== envMap) {
  15815. needsProgramChange = true;
  15816. } else if (material.fog && materialProperties.fog !== fog) {
  15817. needsProgramChange = true;
  15818. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
  15819. needsProgramChange = true;
  15820. } else if (materialProperties.vertexAlphas !== vertexAlphas) {
  15821. needsProgramChange = true;
  15822. } else if (materialProperties.vertexTangents !== vertexTangents) {
  15823. needsProgramChange = true;
  15824. } else if (materialProperties.morphTargets !== morphTargets) {
  15825. needsProgramChange = true;
  15826. } else if (materialProperties.morphNormals !== morphNormals) {
  15827. needsProgramChange = true;
  15828. }
  15829. } else {
  15830. needsProgramChange = true;
  15831. materialProperties.__version = material.version;
  15832. } //
  15833. let program = materialProperties.currentProgram;
  15834. if (needsProgramChange === true) {
  15835. program = getProgram(material, scene, object);
  15836. }
  15837. let refreshProgram = false;
  15838. let refreshMaterial = false;
  15839. let refreshLights = false;
  15840. const p_uniforms = program.getUniforms(),
  15841. m_uniforms = materialProperties.uniforms;
  15842. if (state.useProgram(program.program)) {
  15843. refreshProgram = true;
  15844. refreshMaterial = true;
  15845. refreshLights = true;
  15846. }
  15847. if (material.id !== _currentMaterialId) {
  15848. _currentMaterialId = material.id;
  15849. refreshMaterial = true;
  15850. }
  15851. if (refreshProgram || _currentCamera !== camera) {
  15852. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  15853. if (capabilities.logarithmicDepthBuffer) {
  15854. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  15855. }
  15856. if (_currentCamera !== camera) {
  15857. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  15858. // now, in case this material supports lights - or later, when
  15859. // the next material that does gets activated:
  15860. refreshMaterial = true; // set to true on material change
  15861. refreshLights = true; // remains set until update done
  15862. } // load material specific uniforms
  15863. // (shader material also gets them for the sake of genericity)
  15864. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  15865. const uCamPos = p_uniforms.map.cameraPosition;
  15866. if (uCamPos !== undefined) {
  15867. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  15868. }
  15869. }
  15870. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  15871. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  15872. }
  15873. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || object.isSkinnedMesh) {
  15874. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  15875. }
  15876. } // skinning uniforms must be set even if material didn't change
  15877. // auto-setting of texture unit for bone texture must go before other textures
  15878. // otherwise textures used for skinning can take over texture units reserved for other material textures
  15879. if (object.isSkinnedMesh) {
  15880. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  15881. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  15882. const skeleton = object.skeleton;
  15883. if (skeleton) {
  15884. if (capabilities.floatVertexTextures) {
  15885. if (skeleton.boneTexture === null) skeleton.computeBoneTexture();
  15886. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  15887. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  15888. } else {
  15889. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  15890. }
  15891. }
  15892. }
  15893. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  15894. materialProperties.receiveShadow = object.receiveShadow;
  15895. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  15896. }
  15897. if (refreshMaterial) {
  15898. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  15899. if (materialProperties.needsLights) {
  15900. // the current material requires lighting info
  15901. // note: all lighting uniforms are always set correctly
  15902. // they simply reference the renderer's state for their
  15903. // values
  15904. //
  15905. // use the current material's .needsUpdate flags to set
  15906. // the GL state when required
  15907. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  15908. } // refresh uniforms common to several materials
  15909. if (fog && material.fog) {
  15910. materials.refreshFogUniforms(m_uniforms, fog);
  15911. }
  15912. materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget);
  15913. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  15914. }
  15915. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  15916. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  15917. material.uniformsNeedUpdate = false;
  15918. }
  15919. if (material.isSpriteMaterial) {
  15920. p_uniforms.setValue(_gl, 'center', object.center);
  15921. } // common matrices
  15922. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  15923. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  15924. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  15925. return program;
  15926. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  15927. function markUniformsLightsNeedsUpdate(uniforms, value) {
  15928. uniforms.ambientLightColor.needsUpdate = value;
  15929. uniforms.lightProbe.needsUpdate = value;
  15930. uniforms.directionalLights.needsUpdate = value;
  15931. uniforms.directionalLightShadows.needsUpdate = value;
  15932. uniforms.pointLights.needsUpdate = value;
  15933. uniforms.pointLightShadows.needsUpdate = value;
  15934. uniforms.spotLights.needsUpdate = value;
  15935. uniforms.spotLightShadows.needsUpdate = value;
  15936. uniforms.rectAreaLights.needsUpdate = value;
  15937. uniforms.hemisphereLights.needsUpdate = value;
  15938. }
  15939. function materialNeedsLights(material) {
  15940. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  15941. }
  15942. this.getActiveCubeFace = function () {
  15943. return _currentActiveCubeFace;
  15944. };
  15945. this.getActiveMipmapLevel = function () {
  15946. return _currentActiveMipmapLevel;
  15947. };
  15948. this.getRenderTarget = function () {
  15949. return _currentRenderTarget;
  15950. };
  15951. this.setRenderTarget = function (renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) {
  15952. _currentRenderTarget = renderTarget;
  15953. _currentActiveCubeFace = activeCubeFace;
  15954. _currentActiveMipmapLevel = activeMipmapLevel;
  15955. if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
  15956. textures.setupRenderTarget(renderTarget);
  15957. }
  15958. let framebuffer = null;
  15959. let isCube = false;
  15960. let isRenderTarget3D = false;
  15961. if (renderTarget) {
  15962. const texture = renderTarget.texture;
  15963. if (texture.isDataTexture3D || texture.isDataTexture2DArray) {
  15964. isRenderTarget3D = true;
  15965. }
  15966. const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  15967. if (renderTarget.isWebGLCubeRenderTarget) {
  15968. framebuffer = __webglFramebuffer[activeCubeFace];
  15969. isCube = true;
  15970. } else if (renderTarget.isWebGLMultisampleRenderTarget) {
  15971. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  15972. } else {
  15973. framebuffer = __webglFramebuffer;
  15974. }
  15975. _currentViewport.copy(renderTarget.viewport);
  15976. _currentScissor.copy(renderTarget.scissor);
  15977. _currentScissorTest = renderTarget.scissorTest;
  15978. } else {
  15979. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  15980. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  15981. _currentScissorTest = _scissorTest;
  15982. }
  15983. const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  15984. if (framebufferBound && capabilities.drawBuffers) {
  15985. let needsUpdate = false;
  15986. if (renderTarget) {
  15987. if (renderTarget.isWebGLMultipleRenderTargets) {
  15988. const textures = renderTarget.texture;
  15989. if (_currentDrawBuffers.length !== textures.length || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
  15990. for (let i = 0, il = textures.length; i < il; i++) {
  15991. _currentDrawBuffers[i] = _gl.COLOR_ATTACHMENT0 + i;
  15992. }
  15993. _currentDrawBuffers.length = textures.length;
  15994. needsUpdate = true;
  15995. }
  15996. } else {
  15997. if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
  15998. _currentDrawBuffers[0] = _gl.COLOR_ATTACHMENT0;
  15999. _currentDrawBuffers.length = 1;
  16000. needsUpdate = true;
  16001. }
  16002. }
  16003. } else {
  16004. if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.BACK) {
  16005. _currentDrawBuffers[0] = _gl.BACK;
  16006. _currentDrawBuffers.length = 1;
  16007. needsUpdate = true;
  16008. }
  16009. }
  16010. if (needsUpdate) {
  16011. if (capabilities.isWebGL2) {
  16012. _gl.drawBuffers(_currentDrawBuffers);
  16013. } else {
  16014. extensions.get('WEBGL_draw_buffers').drawBuffersWEBGL(_currentDrawBuffers);
  16015. }
  16016. }
  16017. }
  16018. state.viewport(_currentViewport);
  16019. state.scissor(_currentScissor);
  16020. state.setScissorTest(_currentScissorTest);
  16021. if (isCube) {
  16022. const textureProperties = properties.get(renderTarget.texture);
  16023. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
  16024. } else if (isRenderTarget3D) {
  16025. const textureProperties = properties.get(renderTarget.texture);
  16026. const layer = activeCubeFace || 0;
  16027. _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer);
  16028. }
  16029. };
  16030. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  16031. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  16032. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  16033. return;
  16034. }
  16035. let framebuffer = properties.get(renderTarget).__webglFramebuffer;
  16036. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  16037. framebuffer = framebuffer[activeCubeFaceIndex];
  16038. }
  16039. if (framebuffer) {
  16040. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16041. try {
  16042. const texture = renderTarget.texture;
  16043. const textureFormat = texture.format;
  16044. const textureType = texture.type;
  16045. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_FORMAT)) {
  16046. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  16047. return;
  16048. }
  16049. const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has('EXT_color_buffer_half_float') || capabilities.isWebGL2 && extensions.has('EXT_color_buffer_float'));
  16050. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513)
  16051. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.has('OES_texture_float') || extensions.has('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  16052. !halfFloatSupportedByExt) {
  16053. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  16054. return;
  16055. }
  16056. if (_gl.checkFramebufferStatus(_gl.FRAMEBUFFER) === _gl.FRAMEBUFFER_COMPLETE) {
  16057. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  16058. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  16059. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  16060. }
  16061. } else {
  16062. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  16063. }
  16064. } finally {
  16065. // restore framebuffer of current render target if necessary
  16066. const framebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null;
  16067. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16068. }
  16069. }
  16070. };
  16071. this.copyFramebufferToTexture = function (position, texture, level = 0) {
  16072. const levelScale = Math.pow(2, -level);
  16073. const width = Math.floor(texture.image.width * levelScale);
  16074. const height = Math.floor(texture.image.height * levelScale);
  16075. let glFormat = utils.convert(texture.format);
  16076. if (capabilities.isWebGL2) {
  16077. // Workaround for https://bugs.chromium.org/p/chromium/issues/detail?id=1120100
  16078. // Not needed in Chrome 93+
  16079. if (glFormat === _gl.RGB) glFormat = _gl.RGB8;
  16080. if (glFormat === _gl.RGBA) glFormat = _gl.RGBA8;
  16081. }
  16082. textures.setTexture2D(texture, 0);
  16083. _gl.copyTexImage2D(_gl.TEXTURE_2D, level, glFormat, position.x, position.y, width, height, 0);
  16084. state.unbindTexture();
  16085. };
  16086. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level = 0) {
  16087. const width = srcTexture.image.width;
  16088. const height = srcTexture.image.height;
  16089. const glFormat = utils.convert(dstTexture.format);
  16090. const glType = utils.convert(dstTexture.type);
  16091. textures.setTexture2D(dstTexture, 0); // As another texture upload may have changed pixelStorei
  16092. // parameters, make sure they are correct for the dstTexture
  16093. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  16094. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  16095. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  16096. if (srcTexture.isDataTexture) {
  16097. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  16098. } else {
  16099. if (srcTexture.isCompressedTexture) {
  16100. _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
  16101. } else {
  16102. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image);
  16103. }
  16104. } // Generate mipmaps only when copying level 0
  16105. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(_gl.TEXTURE_2D);
  16106. state.unbindTexture();
  16107. };
  16108. this.copyTextureToTexture3D = function (sourceBox, position, srcTexture, dstTexture, level = 0) {
  16109. if (_this.isWebGL1Renderer) {
  16110. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.');
  16111. return;
  16112. }
  16113. const width = sourceBox.max.x - sourceBox.min.x + 1;
  16114. const height = sourceBox.max.y - sourceBox.min.y + 1;
  16115. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  16116. const glFormat = utils.convert(dstTexture.format);
  16117. const glType = utils.convert(dstTexture.type);
  16118. let glTarget;
  16119. if (dstTexture.isDataTexture3D) {
  16120. textures.setTexture3D(dstTexture, 0);
  16121. glTarget = _gl.TEXTURE_3D;
  16122. } else if (dstTexture.isDataTexture2DArray) {
  16123. textures.setTexture2DArray(dstTexture, 0);
  16124. glTarget = _gl.TEXTURE_2D_ARRAY;
  16125. } else {
  16126. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.');
  16127. return;
  16128. }
  16129. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  16130. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  16131. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  16132. const unpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH);
  16133. const unpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT);
  16134. const unpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS);
  16135. const unpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS);
  16136. const unpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES);
  16137. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[0] : srcTexture.image;
  16138. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width);
  16139. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, image.height);
  16140. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, sourceBox.min.x);
  16141. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, sourceBox.min.y);
  16142. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, sourceBox.min.z);
  16143. if (srcTexture.isDataTexture || srcTexture.isDataTexture3D) {
  16144. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data);
  16145. } else {
  16146. if (srcTexture.isCompressedTexture) {
  16147. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.');
  16148. _gl.compressedTexSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data);
  16149. } else {
  16150. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image);
  16151. }
  16152. }
  16153. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, unpackRowLen);
  16154. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight);
  16155. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, unpackSkipPixels);
  16156. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, unpackSkipRows);
  16157. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, unpackSkipImages); // Generate mipmaps only when copying level 0
  16158. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(glTarget);
  16159. state.unbindTexture();
  16160. };
  16161. this.initTexture = function (texture) {
  16162. textures.setTexture2D(texture, 0);
  16163. state.unbindTexture();
  16164. };
  16165. this.resetState = function () {
  16166. _currentActiveCubeFace = 0;
  16167. _currentActiveMipmapLevel = 0;
  16168. _currentRenderTarget = null;
  16169. state.reset();
  16170. bindingStates.reset();
  16171. };
  16172. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  16173. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  16174. detail: this
  16175. })); // eslint-disable-line no-undef
  16176. }
  16177. }
  16178. class WebGL1Renderer extends WebGLRenderer {}
  16179. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  16180. class FogExp2 {
  16181. constructor(color, density = 0.00025) {
  16182. this.name = '';
  16183. this.color = new Color(color);
  16184. this.density = density;
  16185. }
  16186. clone() {
  16187. return new FogExp2(this.color, this.density);
  16188. }
  16189. toJSON() {
  16190. return {
  16191. type: 'FogExp2',
  16192. color: this.color.getHex(),
  16193. density: this.density
  16194. };
  16195. }
  16196. }
  16197. FogExp2.prototype.isFogExp2 = true;
  16198. class Fog {
  16199. constructor(color, near = 1, far = 1000) {
  16200. this.name = '';
  16201. this.color = new Color(color);
  16202. this.near = near;
  16203. this.far = far;
  16204. }
  16205. clone() {
  16206. return new Fog(this.color, this.near, this.far);
  16207. }
  16208. toJSON() {
  16209. return {
  16210. type: 'Fog',
  16211. color: this.color.getHex(),
  16212. near: this.near,
  16213. far: this.far
  16214. };
  16215. }
  16216. }
  16217. Fog.prototype.isFog = true;
  16218. class Scene extends Object3D {
  16219. constructor() {
  16220. super();
  16221. this.type = 'Scene';
  16222. this.background = null;
  16223. this.environment = null;
  16224. this.fog = null;
  16225. this.overrideMaterial = null;
  16226. this.autoUpdate = true; // checked by the renderer
  16227. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  16228. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  16229. detail: this
  16230. })); // eslint-disable-line no-undef
  16231. }
  16232. }
  16233. copy(source, recursive) {
  16234. super.copy(source, recursive);
  16235. if (source.background !== null) this.background = source.background.clone();
  16236. if (source.environment !== null) this.environment = source.environment.clone();
  16237. if (source.fog !== null) this.fog = source.fog.clone();
  16238. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  16239. this.autoUpdate = source.autoUpdate;
  16240. this.matrixAutoUpdate = source.matrixAutoUpdate;
  16241. return this;
  16242. }
  16243. toJSON(meta) {
  16244. const data = super.toJSON(meta);
  16245. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  16246. return data;
  16247. }
  16248. }
  16249. Scene.prototype.isScene = true;
  16250. class InterleavedBuffer {
  16251. constructor(array, stride) {
  16252. this.array = array;
  16253. this.stride = stride;
  16254. this.count = array !== undefined ? array.length / stride : 0;
  16255. this.usage = StaticDrawUsage;
  16256. this.updateRange = {
  16257. offset: 0,
  16258. count: -1
  16259. };
  16260. this.version = 0;
  16261. this.uuid = generateUUID();
  16262. }
  16263. onUploadCallback() {}
  16264. set needsUpdate(value) {
  16265. if (value === true) this.version++;
  16266. }
  16267. setUsage(value) {
  16268. this.usage = value;
  16269. return this;
  16270. }
  16271. copy(source) {
  16272. this.array = new source.array.constructor(source.array);
  16273. this.count = source.count;
  16274. this.stride = source.stride;
  16275. this.usage = source.usage;
  16276. return this;
  16277. }
  16278. copyAt(index1, attribute, index2) {
  16279. index1 *= this.stride;
  16280. index2 *= attribute.stride;
  16281. for (let i = 0, l = this.stride; i < l; i++) {
  16282. this.array[index1 + i] = attribute.array[index2 + i];
  16283. }
  16284. return this;
  16285. }
  16286. set(value, offset = 0) {
  16287. this.array.set(value, offset);
  16288. return this;
  16289. }
  16290. clone(data) {
  16291. if (data.arrayBuffers === undefined) {
  16292. data.arrayBuffers = {};
  16293. }
  16294. if (this.array.buffer._uuid === undefined) {
  16295. this.array.buffer._uuid = generateUUID();
  16296. }
  16297. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  16298. data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
  16299. }
  16300. const array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
  16301. const ib = new this.constructor(array, this.stride);
  16302. ib.setUsage(this.usage);
  16303. return ib;
  16304. }
  16305. onUpload(callback) {
  16306. this.onUploadCallback = callback;
  16307. return this;
  16308. }
  16309. toJSON(data) {
  16310. if (data.arrayBuffers === undefined) {
  16311. data.arrayBuffers = {};
  16312. } // generate UUID for array buffer if necessary
  16313. if (this.array.buffer._uuid === undefined) {
  16314. this.array.buffer._uuid = generateUUID();
  16315. }
  16316. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  16317. data.arrayBuffers[this.array.buffer._uuid] = Array.prototype.slice.call(new Uint32Array(this.array.buffer));
  16318. } //
  16319. return {
  16320. uuid: this.uuid,
  16321. buffer: this.array.buffer._uuid,
  16322. type: this.array.constructor.name,
  16323. stride: this.stride
  16324. };
  16325. }
  16326. }
  16327. InterleavedBuffer.prototype.isInterleavedBuffer = true;
  16328. const _vector$6 = /*@__PURE__*/new Vector3();
  16329. class InterleavedBufferAttribute {
  16330. constructor(interleavedBuffer, itemSize, offset, normalized = false) {
  16331. this.name = '';
  16332. this.data = interleavedBuffer;
  16333. this.itemSize = itemSize;
  16334. this.offset = offset;
  16335. this.normalized = normalized === true;
  16336. }
  16337. get count() {
  16338. return this.data.count;
  16339. }
  16340. get array() {
  16341. return this.data.array;
  16342. }
  16343. set needsUpdate(value) {
  16344. this.data.needsUpdate = value;
  16345. }
  16346. applyMatrix4(m) {
  16347. for (let i = 0, l = this.data.count; i < l; i++) {
  16348. _vector$6.x = this.getX(i);
  16349. _vector$6.y = this.getY(i);
  16350. _vector$6.z = this.getZ(i);
  16351. _vector$6.applyMatrix4(m);
  16352. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  16353. }
  16354. return this;
  16355. }
  16356. applyNormalMatrix(m) {
  16357. for (let i = 0, l = this.count; i < l; i++) {
  16358. _vector$6.x = this.getX(i);
  16359. _vector$6.y = this.getY(i);
  16360. _vector$6.z = this.getZ(i);
  16361. _vector$6.applyNormalMatrix(m);
  16362. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  16363. }
  16364. return this;
  16365. }
  16366. transformDirection(m) {
  16367. for (let i = 0, l = this.count; i < l; i++) {
  16368. _vector$6.x = this.getX(i);
  16369. _vector$6.y = this.getY(i);
  16370. _vector$6.z = this.getZ(i);
  16371. _vector$6.transformDirection(m);
  16372. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  16373. }
  16374. return this;
  16375. }
  16376. setX(index, x) {
  16377. this.data.array[index * this.data.stride + this.offset] = x;
  16378. return this;
  16379. }
  16380. setY(index, y) {
  16381. this.data.array[index * this.data.stride + this.offset + 1] = y;
  16382. return this;
  16383. }
  16384. setZ(index, z) {
  16385. this.data.array[index * this.data.stride + this.offset + 2] = z;
  16386. return this;
  16387. }
  16388. setW(index, w) {
  16389. this.data.array[index * this.data.stride + this.offset + 3] = w;
  16390. return this;
  16391. }
  16392. getX(index) {
  16393. return this.data.array[index * this.data.stride + this.offset];
  16394. }
  16395. getY(index) {
  16396. return this.data.array[index * this.data.stride + this.offset + 1];
  16397. }
  16398. getZ(index) {
  16399. return this.data.array[index * this.data.stride + this.offset + 2];
  16400. }
  16401. getW(index) {
  16402. return this.data.array[index * this.data.stride + this.offset + 3];
  16403. }
  16404. setXY(index, x, y) {
  16405. index = index * this.data.stride + this.offset;
  16406. this.data.array[index + 0] = x;
  16407. this.data.array[index + 1] = y;
  16408. return this;
  16409. }
  16410. setXYZ(index, x, y, z) {
  16411. index = index * this.data.stride + this.offset;
  16412. this.data.array[index + 0] = x;
  16413. this.data.array[index + 1] = y;
  16414. this.data.array[index + 2] = z;
  16415. return this;
  16416. }
  16417. setXYZW(index, x, y, z, w) {
  16418. index = index * this.data.stride + this.offset;
  16419. this.data.array[index + 0] = x;
  16420. this.data.array[index + 1] = y;
  16421. this.data.array[index + 2] = z;
  16422. this.data.array[index + 3] = w;
  16423. return this;
  16424. }
  16425. clone(data) {
  16426. if (data === undefined) {
  16427. console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.');
  16428. const array = [];
  16429. for (let i = 0; i < this.count; i++) {
  16430. const index = i * this.data.stride + this.offset;
  16431. for (let j = 0; j < this.itemSize; j++) {
  16432. array.push(this.data.array[index + j]);
  16433. }
  16434. }
  16435. return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
  16436. } else {
  16437. if (data.interleavedBuffers === undefined) {
  16438. data.interleavedBuffers = {};
  16439. }
  16440. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  16441. data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
  16442. }
  16443. return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  16444. }
  16445. }
  16446. toJSON(data) {
  16447. if (data === undefined) {
  16448. console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.');
  16449. const array = [];
  16450. for (let i = 0; i < this.count; i++) {
  16451. const index = i * this.data.stride + this.offset;
  16452. for (let j = 0; j < this.itemSize; j++) {
  16453. array.push(this.data.array[index + j]);
  16454. }
  16455. } // deinterleave data and save it as an ordinary buffer attribute for now
  16456. return {
  16457. itemSize: this.itemSize,
  16458. type: this.array.constructor.name,
  16459. array: array,
  16460. normalized: this.normalized
  16461. };
  16462. } else {
  16463. // save as true interlaved attribtue
  16464. if (data.interleavedBuffers === undefined) {
  16465. data.interleavedBuffers = {};
  16466. }
  16467. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  16468. data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
  16469. }
  16470. return {
  16471. isInterleavedBufferAttribute: true,
  16472. itemSize: this.itemSize,
  16473. data: this.data.uuid,
  16474. offset: this.offset,
  16475. normalized: this.normalized
  16476. };
  16477. }
  16478. }
  16479. }
  16480. InterleavedBufferAttribute.prototype.isInterleavedBufferAttribute = true;
  16481. /**
  16482. * parameters = {
  16483. * color: <hex>,
  16484. * map: new THREE.Texture( <Image> ),
  16485. * alphaMap: new THREE.Texture( <Image> ),
  16486. * rotation: <float>,
  16487. * sizeAttenuation: <bool>
  16488. * }
  16489. */
  16490. class SpriteMaterial extends Material {
  16491. constructor(parameters) {
  16492. super();
  16493. this.type = 'SpriteMaterial';
  16494. this.color = new Color(0xffffff);
  16495. this.map = null;
  16496. this.alphaMap = null;
  16497. this.rotation = 0;
  16498. this.sizeAttenuation = true;
  16499. this.transparent = true;
  16500. this.setValues(parameters);
  16501. }
  16502. copy(source) {
  16503. super.copy(source);
  16504. this.color.copy(source.color);
  16505. this.map = source.map;
  16506. this.alphaMap = source.alphaMap;
  16507. this.rotation = source.rotation;
  16508. this.sizeAttenuation = source.sizeAttenuation;
  16509. return this;
  16510. }
  16511. }
  16512. SpriteMaterial.prototype.isSpriteMaterial = true;
  16513. let _geometry;
  16514. const _intersectPoint = /*@__PURE__*/new Vector3();
  16515. const _worldScale = /*@__PURE__*/new Vector3();
  16516. const _mvPosition = /*@__PURE__*/new Vector3();
  16517. const _alignedPosition = /*@__PURE__*/new Vector2();
  16518. const _rotatedPosition = /*@__PURE__*/new Vector2();
  16519. const _viewWorldMatrix = /*@__PURE__*/new Matrix4();
  16520. const _vA = /*@__PURE__*/new Vector3();
  16521. const _vB = /*@__PURE__*/new Vector3();
  16522. const _vC = /*@__PURE__*/new Vector3();
  16523. const _uvA = /*@__PURE__*/new Vector2();
  16524. const _uvB = /*@__PURE__*/new Vector2();
  16525. const _uvC = /*@__PURE__*/new Vector2();
  16526. class Sprite extends Object3D {
  16527. constructor(material) {
  16528. super();
  16529. this.type = 'Sprite';
  16530. if (_geometry === undefined) {
  16531. _geometry = new BufferGeometry();
  16532. 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]);
  16533. const interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  16534. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  16535. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  16536. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  16537. }
  16538. this.geometry = _geometry;
  16539. this.material = material !== undefined ? material : new SpriteMaterial();
  16540. this.center = new Vector2(0.5, 0.5);
  16541. }
  16542. raycast(raycaster, intersects) {
  16543. if (raycaster.camera === null) {
  16544. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  16545. }
  16546. _worldScale.setFromMatrixScale(this.matrixWorld);
  16547. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  16548. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  16549. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  16550. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  16551. _worldScale.multiplyScalar(-_mvPosition.z);
  16552. }
  16553. const rotation = this.material.rotation;
  16554. let sin, cos;
  16555. if (rotation !== 0) {
  16556. cos = Math.cos(rotation);
  16557. sin = Math.sin(rotation);
  16558. }
  16559. const center = this.center;
  16560. transformVertex(_vA.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16561. transformVertex(_vB.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16562. transformVertex(_vC.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16563. _uvA.set(0, 0);
  16564. _uvB.set(1, 0);
  16565. _uvC.set(1, 1); // check first triangle
  16566. let intersect = raycaster.ray.intersectTriangle(_vA, _vB, _vC, false, _intersectPoint);
  16567. if (intersect === null) {
  16568. // check second triangle
  16569. transformVertex(_vB.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  16570. _uvB.set(0, 1);
  16571. intersect = raycaster.ray.intersectTriangle(_vA, _vC, _vB, false, _intersectPoint);
  16572. if (intersect === null) {
  16573. return;
  16574. }
  16575. }
  16576. const distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  16577. if (distance < raycaster.near || distance > raycaster.far) return;
  16578. intersects.push({
  16579. distance: distance,
  16580. point: _intersectPoint.clone(),
  16581. uv: Triangle.getUV(_intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2()),
  16582. face: null,
  16583. object: this
  16584. });
  16585. }
  16586. copy(source) {
  16587. super.copy(source);
  16588. if (source.center !== undefined) this.center.copy(source.center);
  16589. this.material = source.material;
  16590. return this;
  16591. }
  16592. }
  16593. Sprite.prototype.isSprite = true;
  16594. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  16595. // compute position in camera space
  16596. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  16597. if (sin !== undefined) {
  16598. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  16599. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  16600. } else {
  16601. _rotatedPosition.copy(_alignedPosition);
  16602. }
  16603. vertexPosition.copy(mvPosition);
  16604. vertexPosition.x += _rotatedPosition.x;
  16605. vertexPosition.y += _rotatedPosition.y; // transform to world space
  16606. vertexPosition.applyMatrix4(_viewWorldMatrix);
  16607. }
  16608. const _v1$2 = /*@__PURE__*/new Vector3();
  16609. const _v2$1 = /*@__PURE__*/new Vector3();
  16610. class LOD extends Object3D {
  16611. constructor() {
  16612. super();
  16613. this._currentLevel = 0;
  16614. this.type = 'LOD';
  16615. Object.defineProperties(this, {
  16616. levels: {
  16617. enumerable: true,
  16618. value: []
  16619. },
  16620. isLOD: {
  16621. value: true
  16622. }
  16623. });
  16624. this.autoUpdate = true;
  16625. }
  16626. copy(source) {
  16627. super.copy(source, false);
  16628. const levels = source.levels;
  16629. for (let i = 0, l = levels.length; i < l; i++) {
  16630. const level = levels[i];
  16631. this.addLevel(level.object.clone(), level.distance);
  16632. }
  16633. this.autoUpdate = source.autoUpdate;
  16634. return this;
  16635. }
  16636. addLevel(object, distance = 0) {
  16637. distance = Math.abs(distance);
  16638. const levels = this.levels;
  16639. let l;
  16640. for (l = 0; l < levels.length; l++) {
  16641. if (distance < levels[l].distance) {
  16642. break;
  16643. }
  16644. }
  16645. levels.splice(l, 0, {
  16646. distance: distance,
  16647. object: object
  16648. });
  16649. this.add(object);
  16650. return this;
  16651. }
  16652. getCurrentLevel() {
  16653. return this._currentLevel;
  16654. }
  16655. getObjectForDistance(distance) {
  16656. const levels = this.levels;
  16657. if (levels.length > 0) {
  16658. let i, l;
  16659. for (i = 1, l = levels.length; i < l; i++) {
  16660. if (distance < levels[i].distance) {
  16661. break;
  16662. }
  16663. }
  16664. return levels[i - 1].object;
  16665. }
  16666. return null;
  16667. }
  16668. raycast(raycaster, intersects) {
  16669. const levels = this.levels;
  16670. if (levels.length > 0) {
  16671. _v1$2.setFromMatrixPosition(this.matrixWorld);
  16672. const distance = raycaster.ray.origin.distanceTo(_v1$2);
  16673. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  16674. }
  16675. }
  16676. update(camera) {
  16677. const levels = this.levels;
  16678. if (levels.length > 1) {
  16679. _v1$2.setFromMatrixPosition(camera.matrixWorld);
  16680. _v2$1.setFromMatrixPosition(this.matrixWorld);
  16681. const distance = _v1$2.distanceTo(_v2$1) / camera.zoom;
  16682. levels[0].object.visible = true;
  16683. let i, l;
  16684. for (i = 1, l = levels.length; i < l; i++) {
  16685. if (distance >= levels[i].distance) {
  16686. levels[i - 1].object.visible = false;
  16687. levels[i].object.visible = true;
  16688. } else {
  16689. break;
  16690. }
  16691. }
  16692. this._currentLevel = i - 1;
  16693. for (; i < l; i++) {
  16694. levels[i].object.visible = false;
  16695. }
  16696. }
  16697. }
  16698. toJSON(meta) {
  16699. const data = super.toJSON(meta);
  16700. if (this.autoUpdate === false) data.object.autoUpdate = false;
  16701. data.object.levels = [];
  16702. const levels = this.levels;
  16703. for (let i = 0, l = levels.length; i < l; i++) {
  16704. const level = levels[i];
  16705. data.object.levels.push({
  16706. object: level.object.uuid,
  16707. distance: level.distance
  16708. });
  16709. }
  16710. return data;
  16711. }
  16712. }
  16713. const _basePosition = /*@__PURE__*/new Vector3();
  16714. const _skinIndex = /*@__PURE__*/new Vector4();
  16715. const _skinWeight = /*@__PURE__*/new Vector4();
  16716. const _vector$5 = /*@__PURE__*/new Vector3();
  16717. const _matrix = /*@__PURE__*/new Matrix4();
  16718. class SkinnedMesh extends Mesh {
  16719. constructor(geometry, material) {
  16720. super(geometry, material);
  16721. this.type = 'SkinnedMesh';
  16722. this.bindMode = 'attached';
  16723. this.bindMatrix = new Matrix4();
  16724. this.bindMatrixInverse = new Matrix4();
  16725. }
  16726. copy(source) {
  16727. super.copy(source);
  16728. this.bindMode = source.bindMode;
  16729. this.bindMatrix.copy(source.bindMatrix);
  16730. this.bindMatrixInverse.copy(source.bindMatrixInverse);
  16731. this.skeleton = source.skeleton;
  16732. return this;
  16733. }
  16734. bind(skeleton, bindMatrix) {
  16735. this.skeleton = skeleton;
  16736. if (bindMatrix === undefined) {
  16737. this.updateMatrixWorld(true);
  16738. this.skeleton.calculateInverses();
  16739. bindMatrix = this.matrixWorld;
  16740. }
  16741. this.bindMatrix.copy(bindMatrix);
  16742. this.bindMatrixInverse.copy(bindMatrix).invert();
  16743. }
  16744. pose() {
  16745. this.skeleton.pose();
  16746. }
  16747. normalizeSkinWeights() {
  16748. const vector = new Vector4();
  16749. const skinWeight = this.geometry.attributes.skinWeight;
  16750. for (let i = 0, l = skinWeight.count; i < l; i++) {
  16751. vector.x = skinWeight.getX(i);
  16752. vector.y = skinWeight.getY(i);
  16753. vector.z = skinWeight.getZ(i);
  16754. vector.w = skinWeight.getW(i);
  16755. const scale = 1.0 / vector.manhattanLength();
  16756. if (scale !== Infinity) {
  16757. vector.multiplyScalar(scale);
  16758. } else {
  16759. vector.set(1, 0, 0, 0); // do something reasonable
  16760. }
  16761. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  16762. }
  16763. }
  16764. updateMatrixWorld(force) {
  16765. super.updateMatrixWorld(force);
  16766. if (this.bindMode === 'attached') {
  16767. this.bindMatrixInverse.copy(this.matrixWorld).invert();
  16768. } else if (this.bindMode === 'detached') {
  16769. this.bindMatrixInverse.copy(this.bindMatrix).invert();
  16770. } else {
  16771. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  16772. }
  16773. }
  16774. boneTransform(index, target) {
  16775. const skeleton = this.skeleton;
  16776. const geometry = this.geometry;
  16777. _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
  16778. _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
  16779. _basePosition.fromBufferAttribute(geometry.attributes.position, index).applyMatrix4(this.bindMatrix);
  16780. target.set(0, 0, 0);
  16781. for (let i = 0; i < 4; i++) {
  16782. const weight = _skinWeight.getComponent(i);
  16783. if (weight !== 0) {
  16784. const boneIndex = _skinIndex.getComponent(i);
  16785. _matrix.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
  16786. target.addScaledVector(_vector$5.copy(_basePosition).applyMatrix4(_matrix), weight);
  16787. }
  16788. }
  16789. return target.applyMatrix4(this.bindMatrixInverse);
  16790. }
  16791. }
  16792. SkinnedMesh.prototype.isSkinnedMesh = true;
  16793. class Bone extends Object3D {
  16794. constructor() {
  16795. super();
  16796. this.type = 'Bone';
  16797. }
  16798. }
  16799. Bone.prototype.isBone = true;
  16800. class DataTexture extends Texture {
  16801. constructor(data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding) {
  16802. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  16803. this.image = {
  16804. data: data,
  16805. width: width,
  16806. height: height
  16807. };
  16808. this.magFilter = magFilter;
  16809. this.minFilter = minFilter;
  16810. this.generateMipmaps = false;
  16811. this.flipY = false;
  16812. this.unpackAlignment = 1;
  16813. this.needsUpdate = true;
  16814. }
  16815. }
  16816. DataTexture.prototype.isDataTexture = true;
  16817. const _offsetMatrix = /*@__PURE__*/new Matrix4();
  16818. const _identityMatrix = /*@__PURE__*/new Matrix4();
  16819. class Skeleton {
  16820. constructor(bones = [], boneInverses = []) {
  16821. this.uuid = generateUUID();
  16822. this.bones = bones.slice(0);
  16823. this.boneInverses = boneInverses;
  16824. this.boneMatrices = null;
  16825. this.boneTexture = null;
  16826. this.boneTextureSize = 0;
  16827. this.frame = -1;
  16828. this.init();
  16829. }
  16830. init() {
  16831. const bones = this.bones;
  16832. const boneInverses = this.boneInverses;
  16833. this.boneMatrices = new Float32Array(bones.length * 16); // calculate inverse bone matrices if necessary
  16834. if (boneInverses.length === 0) {
  16835. this.calculateInverses();
  16836. } else {
  16837. // handle special case
  16838. if (bones.length !== boneInverses.length) {
  16839. console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
  16840. this.boneInverses = [];
  16841. for (let i = 0, il = this.bones.length; i < il; i++) {
  16842. this.boneInverses.push(new Matrix4());
  16843. }
  16844. }
  16845. }
  16846. }
  16847. calculateInverses() {
  16848. this.boneInverses.length = 0;
  16849. for (let i = 0, il = this.bones.length; i < il; i++) {
  16850. const inverse = new Matrix4();
  16851. if (this.bones[i]) {
  16852. inverse.copy(this.bones[i].matrixWorld).invert();
  16853. }
  16854. this.boneInverses.push(inverse);
  16855. }
  16856. }
  16857. pose() {
  16858. // recover the bind-time world matrices
  16859. for (let i = 0, il = this.bones.length; i < il; i++) {
  16860. const bone = this.bones[i];
  16861. if (bone) {
  16862. bone.matrixWorld.copy(this.boneInverses[i]).invert();
  16863. }
  16864. } // compute the local matrices, positions, rotations and scales
  16865. for (let i = 0, il = this.bones.length; i < il; i++) {
  16866. const bone = this.bones[i];
  16867. if (bone) {
  16868. if (bone.parent && bone.parent.isBone) {
  16869. bone.matrix.copy(bone.parent.matrixWorld).invert();
  16870. bone.matrix.multiply(bone.matrixWorld);
  16871. } else {
  16872. bone.matrix.copy(bone.matrixWorld);
  16873. }
  16874. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  16875. }
  16876. }
  16877. }
  16878. update() {
  16879. const bones = this.bones;
  16880. const boneInverses = this.boneInverses;
  16881. const boneMatrices = this.boneMatrices;
  16882. const boneTexture = this.boneTexture; // flatten bone matrices to array
  16883. for (let i = 0, il = bones.length; i < il; i++) {
  16884. // compute the offset between the current and the original transform
  16885. const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  16886. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  16887. _offsetMatrix.toArray(boneMatrices, i * 16);
  16888. }
  16889. if (boneTexture !== null) {
  16890. boneTexture.needsUpdate = true;
  16891. }
  16892. }
  16893. clone() {
  16894. return new Skeleton(this.bones, this.boneInverses);
  16895. }
  16896. computeBoneTexture() {
  16897. // layout (1 matrix = 4 pixels)
  16898. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  16899. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  16900. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  16901. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  16902. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  16903. let size = Math.sqrt(this.bones.length * 4); // 4 pixels needed for 1 matrix
  16904. size = ceilPowerOfTwo(size);
  16905. size = Math.max(size, 4);
  16906. const boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  16907. boneMatrices.set(this.boneMatrices); // copy current values
  16908. const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  16909. this.boneMatrices = boneMatrices;
  16910. this.boneTexture = boneTexture;
  16911. this.boneTextureSize = size;
  16912. return this;
  16913. }
  16914. getBoneByName(name) {
  16915. for (let i = 0, il = this.bones.length; i < il; i++) {
  16916. const bone = this.bones[i];
  16917. if (bone.name === name) {
  16918. return bone;
  16919. }
  16920. }
  16921. return undefined;
  16922. }
  16923. dispose() {
  16924. if (this.boneTexture !== null) {
  16925. this.boneTexture.dispose();
  16926. this.boneTexture = null;
  16927. }
  16928. }
  16929. fromJSON(json, bones) {
  16930. this.uuid = json.uuid;
  16931. for (let i = 0, l = json.bones.length; i < l; i++) {
  16932. const uuid = json.bones[i];
  16933. let bone = bones[uuid];
  16934. if (bone === undefined) {
  16935. console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
  16936. bone = new Bone();
  16937. }
  16938. this.bones.push(bone);
  16939. this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
  16940. }
  16941. this.init();
  16942. return this;
  16943. }
  16944. toJSON() {
  16945. const data = {
  16946. metadata: {
  16947. version: 4.5,
  16948. type: 'Skeleton',
  16949. generator: 'Skeleton.toJSON'
  16950. },
  16951. bones: [],
  16952. boneInverses: []
  16953. };
  16954. data.uuid = this.uuid;
  16955. const bones = this.bones;
  16956. const boneInverses = this.boneInverses;
  16957. for (let i = 0, l = bones.length; i < l; i++) {
  16958. const bone = bones[i];
  16959. data.bones.push(bone.uuid);
  16960. const boneInverse = boneInverses[i];
  16961. data.boneInverses.push(boneInverse.toArray());
  16962. }
  16963. return data;
  16964. }
  16965. }
  16966. const _instanceLocalMatrix = /*@__PURE__*/new Matrix4();
  16967. const _instanceWorldMatrix = /*@__PURE__*/new Matrix4();
  16968. const _instanceIntersects = [];
  16969. const _mesh = /*@__PURE__*/new Mesh();
  16970. class InstancedMesh extends Mesh {
  16971. constructor(geometry, material, count) {
  16972. super(geometry, material);
  16973. this.instanceMatrix = new BufferAttribute(new Float32Array(count * 16), 16);
  16974. this.instanceColor = null;
  16975. this.count = count;
  16976. this.frustumCulled = false;
  16977. }
  16978. copy(source) {
  16979. super.copy(source);
  16980. this.instanceMatrix.copy(source.instanceMatrix);
  16981. if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone();
  16982. this.count = source.count;
  16983. return this;
  16984. }
  16985. getColorAt(index, color) {
  16986. color.fromArray(this.instanceColor.array, index * 3);
  16987. }
  16988. getMatrixAt(index, matrix) {
  16989. matrix.fromArray(this.instanceMatrix.array, index * 16);
  16990. }
  16991. raycast(raycaster, intersects) {
  16992. const matrixWorld = this.matrixWorld;
  16993. const raycastTimes = this.count;
  16994. _mesh.geometry = this.geometry;
  16995. _mesh.material = this.material;
  16996. if (_mesh.material === undefined) return;
  16997. for (let instanceId = 0; instanceId < raycastTimes; instanceId++) {
  16998. // calculate the world matrix for each instance
  16999. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  17000. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
  17001. _mesh.matrixWorld = _instanceWorldMatrix;
  17002. _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
  17003. for (let i = 0, l = _instanceIntersects.length; i < l; i++) {
  17004. const intersect = _instanceIntersects[i];
  17005. intersect.instanceId = instanceId;
  17006. intersect.object = this;
  17007. intersects.push(intersect);
  17008. }
  17009. _instanceIntersects.length = 0;
  17010. }
  17011. }
  17012. setColorAt(index, color) {
  17013. if (this.instanceColor === null) {
  17014. this.instanceColor = new BufferAttribute(new Float32Array(this.instanceMatrix.count * 3), 3);
  17015. }
  17016. color.toArray(this.instanceColor.array, index * 3);
  17017. }
  17018. setMatrixAt(index, matrix) {
  17019. matrix.toArray(this.instanceMatrix.array, index * 16);
  17020. }
  17021. updateMorphTargets() {}
  17022. dispose() {
  17023. this.dispatchEvent({
  17024. type: 'dispose'
  17025. });
  17026. }
  17027. }
  17028. InstancedMesh.prototype.isInstancedMesh = true;
  17029. /**
  17030. * parameters = {
  17031. * color: <hex>,
  17032. * opacity: <float>,
  17033. *
  17034. * linewidth: <float>,
  17035. * linecap: "round",
  17036. * linejoin: "round"
  17037. * }
  17038. */
  17039. class LineBasicMaterial extends Material {
  17040. constructor(parameters) {
  17041. super();
  17042. this.type = 'LineBasicMaterial';
  17043. this.color = new Color(0xffffff);
  17044. this.linewidth = 1;
  17045. this.linecap = 'round';
  17046. this.linejoin = 'round';
  17047. this.setValues(parameters);
  17048. }
  17049. copy(source) {
  17050. super.copy(source);
  17051. this.color.copy(source.color);
  17052. this.linewidth = source.linewidth;
  17053. this.linecap = source.linecap;
  17054. this.linejoin = source.linejoin;
  17055. return this;
  17056. }
  17057. }
  17058. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  17059. const _start$1 = /*@__PURE__*/new Vector3();
  17060. const _end$1 = /*@__PURE__*/new Vector3();
  17061. const _inverseMatrix$1 = /*@__PURE__*/new Matrix4();
  17062. const _ray$1 = /*@__PURE__*/new Ray();
  17063. const _sphere$1 = /*@__PURE__*/new Sphere();
  17064. class Line extends Object3D {
  17065. constructor(geometry = new BufferGeometry(), material = new LineBasicMaterial()) {
  17066. super();
  17067. this.type = 'Line';
  17068. this.geometry = geometry;
  17069. this.material = material;
  17070. this.updateMorphTargets();
  17071. }
  17072. copy(source) {
  17073. super.copy(source);
  17074. this.material = source.material;
  17075. this.geometry = source.geometry;
  17076. return this;
  17077. }
  17078. computeLineDistances() {
  17079. const geometry = this.geometry;
  17080. if (geometry.isBufferGeometry) {
  17081. // we assume non-indexed geometry
  17082. if (geometry.index === null) {
  17083. const positionAttribute = geometry.attributes.position;
  17084. const lineDistances = [0];
  17085. for (let i = 1, l = positionAttribute.count; i < l; i++) {
  17086. _start$1.fromBufferAttribute(positionAttribute, i - 1);
  17087. _end$1.fromBufferAttribute(positionAttribute, i);
  17088. lineDistances[i] = lineDistances[i - 1];
  17089. lineDistances[i] += _start$1.distanceTo(_end$1);
  17090. }
  17091. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  17092. } else {
  17093. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  17094. }
  17095. } else if (geometry.isGeometry) {
  17096. console.error('THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17097. }
  17098. return this;
  17099. }
  17100. raycast(raycaster, intersects) {
  17101. const geometry = this.geometry;
  17102. const matrixWorld = this.matrixWorld;
  17103. const threshold = raycaster.params.Line.threshold;
  17104. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  17105. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  17106. _sphere$1.copy(geometry.boundingSphere);
  17107. _sphere$1.applyMatrix4(matrixWorld);
  17108. _sphere$1.radius += threshold;
  17109. if (raycaster.ray.intersectsSphere(_sphere$1) === false) return; //
  17110. _inverseMatrix$1.copy(matrixWorld).invert();
  17111. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  17112. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  17113. const localThresholdSq = localThreshold * localThreshold;
  17114. const vStart = new Vector3();
  17115. const vEnd = new Vector3();
  17116. const interSegment = new Vector3();
  17117. const interRay = new Vector3();
  17118. const step = this.isLineSegments ? 2 : 1;
  17119. if (geometry.isBufferGeometry) {
  17120. const index = geometry.index;
  17121. const attributes = geometry.attributes;
  17122. const positionAttribute = attributes.position;
  17123. if (index !== null) {
  17124. const start = Math.max(0, drawRange.start);
  17125. const end = Math.min(index.count, drawRange.start + drawRange.count);
  17126. for (let i = start, l = end - 1; i < l; i += step) {
  17127. const a = index.getX(i);
  17128. const b = index.getX(i + 1);
  17129. vStart.fromBufferAttribute(positionAttribute, a);
  17130. vEnd.fromBufferAttribute(positionAttribute, b);
  17131. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  17132. if (distSq > localThresholdSq) continue;
  17133. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17134. const distance = raycaster.ray.origin.distanceTo(interRay);
  17135. if (distance < raycaster.near || distance > raycaster.far) continue;
  17136. intersects.push({
  17137. distance: distance,
  17138. // What do we want? intersection point on the ray or on the segment??
  17139. // point: raycaster.ray.at( distance ),
  17140. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17141. index: i,
  17142. face: null,
  17143. faceIndex: null,
  17144. object: this
  17145. });
  17146. }
  17147. } else {
  17148. const start = Math.max(0, drawRange.start);
  17149. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  17150. for (let i = start, l = end - 1; i < l; i += step) {
  17151. vStart.fromBufferAttribute(positionAttribute, i);
  17152. vEnd.fromBufferAttribute(positionAttribute, i + 1);
  17153. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  17154. if (distSq > localThresholdSq) continue;
  17155. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17156. const distance = raycaster.ray.origin.distanceTo(interRay);
  17157. if (distance < raycaster.near || distance > raycaster.far) continue;
  17158. intersects.push({
  17159. distance: distance,
  17160. // What do we want? intersection point on the ray or on the segment??
  17161. // point: raycaster.ray.at( distance ),
  17162. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17163. index: i,
  17164. face: null,
  17165. faceIndex: null,
  17166. object: this
  17167. });
  17168. }
  17169. }
  17170. } else if (geometry.isGeometry) {
  17171. console.error('THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17172. }
  17173. }
  17174. updateMorphTargets() {
  17175. const geometry = this.geometry;
  17176. if (geometry.isBufferGeometry) {
  17177. const morphAttributes = geometry.morphAttributes;
  17178. const keys = Object.keys(morphAttributes);
  17179. if (keys.length > 0) {
  17180. const morphAttribute = morphAttributes[keys[0]];
  17181. if (morphAttribute !== undefined) {
  17182. this.morphTargetInfluences = [];
  17183. this.morphTargetDictionary = {};
  17184. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  17185. const name = morphAttribute[m].name || String(m);
  17186. this.morphTargetInfluences.push(0);
  17187. this.morphTargetDictionary[name] = m;
  17188. }
  17189. }
  17190. }
  17191. } else {
  17192. const morphTargets = geometry.morphTargets;
  17193. if (morphTargets !== undefined && morphTargets.length > 0) {
  17194. console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  17195. }
  17196. }
  17197. }
  17198. }
  17199. Line.prototype.isLine = true;
  17200. const _start = /*@__PURE__*/new Vector3();
  17201. const _end = /*@__PURE__*/new Vector3();
  17202. class LineSegments extends Line {
  17203. constructor(geometry, material) {
  17204. super(geometry, material);
  17205. this.type = 'LineSegments';
  17206. }
  17207. computeLineDistances() {
  17208. const geometry = this.geometry;
  17209. if (geometry.isBufferGeometry) {
  17210. // we assume non-indexed geometry
  17211. if (geometry.index === null) {
  17212. const positionAttribute = geometry.attributes.position;
  17213. const lineDistances = [];
  17214. for (let i = 0, l = positionAttribute.count; i < l; i += 2) {
  17215. _start.fromBufferAttribute(positionAttribute, i);
  17216. _end.fromBufferAttribute(positionAttribute, i + 1);
  17217. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  17218. lineDistances[i + 1] = lineDistances[i] + _start.distanceTo(_end);
  17219. }
  17220. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  17221. } else {
  17222. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  17223. }
  17224. } else if (geometry.isGeometry) {
  17225. console.error('THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17226. }
  17227. return this;
  17228. }
  17229. }
  17230. LineSegments.prototype.isLineSegments = true;
  17231. class LineLoop extends Line {
  17232. constructor(geometry, material) {
  17233. super(geometry, material);
  17234. this.type = 'LineLoop';
  17235. }
  17236. }
  17237. LineLoop.prototype.isLineLoop = true;
  17238. /**
  17239. * parameters = {
  17240. * color: <hex>,
  17241. * opacity: <float>,
  17242. * map: new THREE.Texture( <Image> ),
  17243. * alphaMap: new THREE.Texture( <Image> ),
  17244. *
  17245. * size: <float>,
  17246. * sizeAttenuation: <bool>
  17247. *
  17248. * }
  17249. */
  17250. class PointsMaterial extends Material {
  17251. constructor(parameters) {
  17252. super();
  17253. this.type = 'PointsMaterial';
  17254. this.color = new Color(0xffffff);
  17255. this.map = null;
  17256. this.alphaMap = null;
  17257. this.size = 1;
  17258. this.sizeAttenuation = true;
  17259. this.setValues(parameters);
  17260. }
  17261. copy(source) {
  17262. super.copy(source);
  17263. this.color.copy(source.color);
  17264. this.map = source.map;
  17265. this.alphaMap = source.alphaMap;
  17266. this.size = source.size;
  17267. this.sizeAttenuation = source.sizeAttenuation;
  17268. return this;
  17269. }
  17270. }
  17271. PointsMaterial.prototype.isPointsMaterial = true;
  17272. const _inverseMatrix = /*@__PURE__*/new Matrix4();
  17273. const _ray = /*@__PURE__*/new Ray();
  17274. const _sphere = /*@__PURE__*/new Sphere();
  17275. const _position$2 = /*@__PURE__*/new Vector3();
  17276. class Points extends Object3D {
  17277. constructor(geometry = new BufferGeometry(), material = new PointsMaterial()) {
  17278. super();
  17279. this.type = 'Points';
  17280. this.geometry = geometry;
  17281. this.material = material;
  17282. this.updateMorphTargets();
  17283. }
  17284. copy(source) {
  17285. super.copy(source);
  17286. this.material = source.material;
  17287. this.geometry = source.geometry;
  17288. return this;
  17289. }
  17290. raycast(raycaster, intersects) {
  17291. const geometry = this.geometry;
  17292. const matrixWorld = this.matrixWorld;
  17293. const threshold = raycaster.params.Points.threshold;
  17294. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  17295. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  17296. _sphere.copy(geometry.boundingSphere);
  17297. _sphere.applyMatrix4(matrixWorld);
  17298. _sphere.radius += threshold;
  17299. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  17300. _inverseMatrix.copy(matrixWorld).invert();
  17301. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix);
  17302. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  17303. const localThresholdSq = localThreshold * localThreshold;
  17304. if (geometry.isBufferGeometry) {
  17305. const index = geometry.index;
  17306. const attributes = geometry.attributes;
  17307. const positionAttribute = attributes.position;
  17308. if (index !== null) {
  17309. const start = Math.max(0, drawRange.start);
  17310. const end = Math.min(index.count, drawRange.start + drawRange.count);
  17311. for (let i = start, il = end; i < il; i++) {
  17312. const a = index.getX(i);
  17313. _position$2.fromBufferAttribute(positionAttribute, a);
  17314. testPoint(_position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17315. }
  17316. } else {
  17317. const start = Math.max(0, drawRange.start);
  17318. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  17319. for (let i = start, l = end; i < l; i++) {
  17320. _position$2.fromBufferAttribute(positionAttribute, i);
  17321. testPoint(_position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17322. }
  17323. }
  17324. } else {
  17325. console.error('THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17326. }
  17327. }
  17328. updateMorphTargets() {
  17329. const geometry = this.geometry;
  17330. if (geometry.isBufferGeometry) {
  17331. const morphAttributes = geometry.morphAttributes;
  17332. const keys = Object.keys(morphAttributes);
  17333. if (keys.length > 0) {
  17334. const morphAttribute = morphAttributes[keys[0]];
  17335. if (morphAttribute !== undefined) {
  17336. this.morphTargetInfluences = [];
  17337. this.morphTargetDictionary = {};
  17338. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  17339. const name = morphAttribute[m].name || String(m);
  17340. this.morphTargetInfluences.push(0);
  17341. this.morphTargetDictionary[name] = m;
  17342. }
  17343. }
  17344. }
  17345. } else {
  17346. const morphTargets = geometry.morphTargets;
  17347. if (morphTargets !== undefined && morphTargets.length > 0) {
  17348. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  17349. }
  17350. }
  17351. }
  17352. }
  17353. Points.prototype.isPoints = true;
  17354. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  17355. const rayPointDistanceSq = _ray.distanceSqToPoint(point);
  17356. if (rayPointDistanceSq < localThresholdSq) {
  17357. const intersectPoint = new Vector3();
  17358. _ray.closestPointToPoint(point, intersectPoint);
  17359. intersectPoint.applyMatrix4(matrixWorld);
  17360. const distance = raycaster.ray.origin.distanceTo(intersectPoint);
  17361. if (distance < raycaster.near || distance > raycaster.far) return;
  17362. intersects.push({
  17363. distance: distance,
  17364. distanceToRay: Math.sqrt(rayPointDistanceSq),
  17365. point: intersectPoint,
  17366. index: index,
  17367. face: null,
  17368. object: object
  17369. });
  17370. }
  17371. }
  17372. class VideoTexture extends Texture {
  17373. constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  17374. super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17375. this.format = format !== undefined ? format : RGBFormat;
  17376. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  17377. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  17378. this.generateMipmaps = false;
  17379. const scope = this;
  17380. function updateVideo() {
  17381. scope.needsUpdate = true;
  17382. video.requestVideoFrameCallback(updateVideo);
  17383. }
  17384. if ('requestVideoFrameCallback' in video) {
  17385. video.requestVideoFrameCallback(updateVideo);
  17386. }
  17387. }
  17388. clone() {
  17389. return new this.constructor(this.image).copy(this);
  17390. }
  17391. update() {
  17392. const video = this.image;
  17393. const hasVideoFrameCallback = ('requestVideoFrameCallback' in video);
  17394. if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
  17395. this.needsUpdate = true;
  17396. }
  17397. }
  17398. }
  17399. VideoTexture.prototype.isVideoTexture = true;
  17400. class CompressedTexture extends Texture {
  17401. constructor(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  17402. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  17403. this.image = {
  17404. width: width,
  17405. height: height
  17406. };
  17407. this.mipmaps = mipmaps; // no flipping for cube textures
  17408. // (also flipping doesn't work for compressed textures )
  17409. this.flipY = false; // can't generate mipmaps for compressed textures
  17410. // mips must be embedded in DDS files
  17411. this.generateMipmaps = false;
  17412. }
  17413. }
  17414. CompressedTexture.prototype.isCompressedTexture = true;
  17415. class CanvasTexture extends Texture {
  17416. constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  17417. super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17418. this.needsUpdate = true;
  17419. }
  17420. }
  17421. CanvasTexture.prototype.isCanvasTexture = true;
  17422. class DepthTexture extends Texture {
  17423. constructor(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  17424. format = format !== undefined ? format : DepthFormat;
  17425. if (format !== DepthFormat && format !== DepthStencilFormat) {
  17426. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  17427. }
  17428. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  17429. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  17430. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17431. this.image = {
  17432. width: width,
  17433. height: height
  17434. };
  17435. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  17436. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  17437. this.flipY = false;
  17438. this.generateMipmaps = false;
  17439. }
  17440. }
  17441. DepthTexture.prototype.isDepthTexture = true;
  17442. class CircleGeometry extends BufferGeometry {
  17443. constructor(radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2) {
  17444. super();
  17445. this.type = 'CircleGeometry';
  17446. this.parameters = {
  17447. radius: radius,
  17448. segments: segments,
  17449. thetaStart: thetaStart,
  17450. thetaLength: thetaLength
  17451. };
  17452. segments = Math.max(3, segments); // buffers
  17453. const indices = [];
  17454. const vertices = [];
  17455. const normals = [];
  17456. const uvs = []; // helper variables
  17457. const vertex = new Vector3();
  17458. const uv = new Vector2(); // center point
  17459. vertices.push(0, 0, 0);
  17460. normals.push(0, 0, 1);
  17461. uvs.push(0.5, 0.5);
  17462. for (let s = 0, i = 3; s <= segments; s++, i += 3) {
  17463. const segment = thetaStart + s / segments * thetaLength; // vertex
  17464. vertex.x = radius * Math.cos(segment);
  17465. vertex.y = radius * Math.sin(segment);
  17466. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17467. normals.push(0, 0, 1); // uvs
  17468. uv.x = (vertices[i] / radius + 1) / 2;
  17469. uv.y = (vertices[i + 1] / radius + 1) / 2;
  17470. uvs.push(uv.x, uv.y);
  17471. } // indices
  17472. for (let i = 1; i <= segments; i++) {
  17473. indices.push(i, i + 1, 0);
  17474. } // build geometry
  17475. this.setIndex(indices);
  17476. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17477. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17478. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17479. }
  17480. static fromJSON(data) {
  17481. return new CircleGeometry(data.radius, data.segments, data.thetaStart, data.thetaLength);
  17482. }
  17483. }
  17484. class CylinderGeometry extends BufferGeometry {
  17485. constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  17486. super();
  17487. this.type = 'CylinderGeometry';
  17488. this.parameters = {
  17489. radiusTop: radiusTop,
  17490. radiusBottom: radiusBottom,
  17491. height: height,
  17492. radialSegments: radialSegments,
  17493. heightSegments: heightSegments,
  17494. openEnded: openEnded,
  17495. thetaStart: thetaStart,
  17496. thetaLength: thetaLength
  17497. };
  17498. const scope = this;
  17499. radialSegments = Math.floor(radialSegments);
  17500. heightSegments = Math.floor(heightSegments); // buffers
  17501. const indices = [];
  17502. const vertices = [];
  17503. const normals = [];
  17504. const uvs = []; // helper variables
  17505. let index = 0;
  17506. const indexArray = [];
  17507. const halfHeight = height / 2;
  17508. let groupStart = 0; // generate geometry
  17509. generateTorso();
  17510. if (openEnded === false) {
  17511. if (radiusTop > 0) generateCap(true);
  17512. if (radiusBottom > 0) generateCap(false);
  17513. } // build geometry
  17514. this.setIndex(indices);
  17515. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17516. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17517. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17518. function generateTorso() {
  17519. const normal = new Vector3();
  17520. const vertex = new Vector3();
  17521. let groupCount = 0; // this will be used to calculate the normal
  17522. const slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  17523. for (let y = 0; y <= heightSegments; y++) {
  17524. const indexRow = [];
  17525. const v = y / heightSegments; // calculate the radius of the current row
  17526. const radius = v * (radiusBottom - radiusTop) + radiusTop;
  17527. for (let x = 0; x <= radialSegments; x++) {
  17528. const u = x / radialSegments;
  17529. const theta = u * thetaLength + thetaStart;
  17530. const sinTheta = Math.sin(theta);
  17531. const cosTheta = Math.cos(theta); // vertex
  17532. vertex.x = radius * sinTheta;
  17533. vertex.y = -v * height + halfHeight;
  17534. vertex.z = radius * cosTheta;
  17535. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17536. normal.set(sinTheta, slope, cosTheta).normalize();
  17537. normals.push(normal.x, normal.y, normal.z); // uv
  17538. uvs.push(u, 1 - v); // save index of vertex in respective row
  17539. indexRow.push(index++);
  17540. } // now save vertices of the row in our index array
  17541. indexArray.push(indexRow);
  17542. } // generate indices
  17543. for (let x = 0; x < radialSegments; x++) {
  17544. for (let y = 0; y < heightSegments; y++) {
  17545. // we use the index array to access the correct indices
  17546. const a = indexArray[y][x];
  17547. const b = indexArray[y + 1][x];
  17548. const c = indexArray[y + 1][x + 1];
  17549. const d = indexArray[y][x + 1]; // faces
  17550. indices.push(a, b, d);
  17551. indices.push(b, c, d); // update group counter
  17552. groupCount += 6;
  17553. }
  17554. } // add a group to the geometry. this will ensure multi material support
  17555. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  17556. groupStart += groupCount;
  17557. }
  17558. function generateCap(top) {
  17559. // save the index of the first center vertex
  17560. const centerIndexStart = index;
  17561. const uv = new Vector2();
  17562. const vertex = new Vector3();
  17563. let groupCount = 0;
  17564. const radius = top === true ? radiusTop : radiusBottom;
  17565. const sign = top === true ? 1 : -1; // first we generate the center vertex data of the cap.
  17566. // because the geometry needs one set of uvs per face,
  17567. // we must generate a center vertex per face/segment
  17568. for (let x = 1; x <= radialSegments; x++) {
  17569. // vertex
  17570. vertices.push(0, halfHeight * sign, 0); // normal
  17571. normals.push(0, sign, 0); // uv
  17572. uvs.push(0.5, 0.5); // increase index
  17573. index++;
  17574. } // save the index of the last center vertex
  17575. const centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  17576. for (let x = 0; x <= radialSegments; x++) {
  17577. const u = x / radialSegments;
  17578. const theta = u * thetaLength + thetaStart;
  17579. const cosTheta = Math.cos(theta);
  17580. const sinTheta = Math.sin(theta); // vertex
  17581. vertex.x = radius * sinTheta;
  17582. vertex.y = halfHeight * sign;
  17583. vertex.z = radius * cosTheta;
  17584. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17585. normals.push(0, sign, 0); // uv
  17586. uv.x = cosTheta * 0.5 + 0.5;
  17587. uv.y = sinTheta * 0.5 * sign + 0.5;
  17588. uvs.push(uv.x, uv.y); // increase index
  17589. index++;
  17590. } // generate indices
  17591. for (let x = 0; x < radialSegments; x++) {
  17592. const c = centerIndexStart + x;
  17593. const i = centerIndexEnd + x;
  17594. if (top === true) {
  17595. // face top
  17596. indices.push(i, i + 1, c);
  17597. } else {
  17598. // face bottom
  17599. indices.push(i + 1, i, c);
  17600. }
  17601. groupCount += 3;
  17602. } // add a group to the geometry. this will ensure multi material support
  17603. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  17604. groupStart += groupCount;
  17605. }
  17606. }
  17607. static fromJSON(data) {
  17608. return new CylinderGeometry(data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  17609. }
  17610. }
  17611. class ConeGeometry extends CylinderGeometry {
  17612. constructor(radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  17613. super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  17614. this.type = 'ConeGeometry';
  17615. this.parameters = {
  17616. radius: radius,
  17617. height: height,
  17618. radialSegments: radialSegments,
  17619. heightSegments: heightSegments,
  17620. openEnded: openEnded,
  17621. thetaStart: thetaStart,
  17622. thetaLength: thetaLength
  17623. };
  17624. }
  17625. static fromJSON(data) {
  17626. return new ConeGeometry(data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  17627. }
  17628. }
  17629. class PolyhedronGeometry extends BufferGeometry {
  17630. constructor(vertices, indices, radius = 1, detail = 0) {
  17631. super();
  17632. this.type = 'PolyhedronGeometry';
  17633. this.parameters = {
  17634. vertices: vertices,
  17635. indices: indices,
  17636. radius: radius,
  17637. detail: detail
  17638. }; // default buffer data
  17639. const vertexBuffer = [];
  17640. const uvBuffer = []; // the subdivision creates the vertex buffer data
  17641. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  17642. applyRadius(radius); // finally, create the uv data
  17643. generateUVs(); // build non-indexed geometry
  17644. this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  17645. this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  17646. this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  17647. if (detail === 0) {
  17648. this.computeVertexNormals(); // flat normals
  17649. } else {
  17650. this.normalizeNormals(); // smooth normals
  17651. } // helper functions
  17652. function subdivide(detail) {
  17653. const a = new Vector3();
  17654. const b = new Vector3();
  17655. const c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  17656. for (let i = 0; i < indices.length; i += 3) {
  17657. // get the vertices of the face
  17658. getVertexByIndex(indices[i + 0], a);
  17659. getVertexByIndex(indices[i + 1], b);
  17660. getVertexByIndex(indices[i + 2], c); // perform subdivision
  17661. subdivideFace(a, b, c, detail);
  17662. }
  17663. }
  17664. function subdivideFace(a, b, c, detail) {
  17665. const cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision
  17666. const v = []; // construct all of the vertices for this subdivision
  17667. for (let i = 0; i <= cols; i++) {
  17668. v[i] = [];
  17669. const aj = a.clone().lerp(c, i / cols);
  17670. const bj = b.clone().lerp(c, i / cols);
  17671. const rows = cols - i;
  17672. for (let j = 0; j <= rows; j++) {
  17673. if (j === 0 && i === cols) {
  17674. v[i][j] = aj;
  17675. } else {
  17676. v[i][j] = aj.clone().lerp(bj, j / rows);
  17677. }
  17678. }
  17679. } // construct all of the faces
  17680. for (let i = 0; i < cols; i++) {
  17681. for (let j = 0; j < 2 * (cols - i) - 1; j++) {
  17682. const k = Math.floor(j / 2);
  17683. if (j % 2 === 0) {
  17684. pushVertex(v[i][k + 1]);
  17685. pushVertex(v[i + 1][k]);
  17686. pushVertex(v[i][k]);
  17687. } else {
  17688. pushVertex(v[i][k + 1]);
  17689. pushVertex(v[i + 1][k + 1]);
  17690. pushVertex(v[i + 1][k]);
  17691. }
  17692. }
  17693. }
  17694. }
  17695. function applyRadius(radius) {
  17696. const vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  17697. for (let i = 0; i < vertexBuffer.length; i += 3) {
  17698. vertex.x = vertexBuffer[i + 0];
  17699. vertex.y = vertexBuffer[i + 1];
  17700. vertex.z = vertexBuffer[i + 2];
  17701. vertex.normalize().multiplyScalar(radius);
  17702. vertexBuffer[i + 0] = vertex.x;
  17703. vertexBuffer[i + 1] = vertex.y;
  17704. vertexBuffer[i + 2] = vertex.z;
  17705. }
  17706. }
  17707. function generateUVs() {
  17708. const vertex = new Vector3();
  17709. for (let i = 0; i < vertexBuffer.length; i += 3) {
  17710. vertex.x = vertexBuffer[i + 0];
  17711. vertex.y = vertexBuffer[i + 1];
  17712. vertex.z = vertexBuffer[i + 2];
  17713. const u = azimuth(vertex) / 2 / Math.PI + 0.5;
  17714. const v = inclination(vertex) / Math.PI + 0.5;
  17715. uvBuffer.push(u, 1 - v);
  17716. }
  17717. correctUVs();
  17718. correctSeam();
  17719. }
  17720. function correctSeam() {
  17721. // handle case when face straddles the seam, see #3269
  17722. for (let i = 0; i < uvBuffer.length; i += 6) {
  17723. // uv data of a single face
  17724. const x0 = uvBuffer[i + 0];
  17725. const x1 = uvBuffer[i + 2];
  17726. const x2 = uvBuffer[i + 4];
  17727. const max = Math.max(x0, x1, x2);
  17728. const min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  17729. if (max > 0.9 && min < 0.1) {
  17730. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  17731. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  17732. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  17733. }
  17734. }
  17735. }
  17736. function pushVertex(vertex) {
  17737. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  17738. }
  17739. function getVertexByIndex(index, vertex) {
  17740. const stride = index * 3;
  17741. vertex.x = vertices[stride + 0];
  17742. vertex.y = vertices[stride + 1];
  17743. vertex.z = vertices[stride + 2];
  17744. }
  17745. function correctUVs() {
  17746. const a = new Vector3();
  17747. const b = new Vector3();
  17748. const c = new Vector3();
  17749. const centroid = new Vector3();
  17750. const uvA = new Vector2();
  17751. const uvB = new Vector2();
  17752. const uvC = new Vector2();
  17753. for (let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  17754. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  17755. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  17756. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  17757. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  17758. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  17759. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  17760. centroid.copy(a).add(b).add(c).divideScalar(3);
  17761. const azi = azimuth(centroid);
  17762. correctUV(uvA, j + 0, a, azi);
  17763. correctUV(uvB, j + 2, b, azi);
  17764. correctUV(uvC, j + 4, c, azi);
  17765. }
  17766. }
  17767. function correctUV(uv, stride, vector, azimuth) {
  17768. if (azimuth < 0 && uv.x === 1) {
  17769. uvBuffer[stride] = uv.x - 1;
  17770. }
  17771. if (vector.x === 0 && vector.z === 0) {
  17772. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  17773. }
  17774. } // Angle around the Y axis, counter-clockwise when looking from above.
  17775. function azimuth(vector) {
  17776. return Math.atan2(vector.z, -vector.x);
  17777. } // Angle above the XZ plane.
  17778. function inclination(vector) {
  17779. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  17780. }
  17781. }
  17782. static fromJSON(data) {
  17783. return new PolyhedronGeometry(data.vertices, data.indices, data.radius, data.details);
  17784. }
  17785. }
  17786. class DodecahedronGeometry extends PolyhedronGeometry {
  17787. constructor(radius = 1, detail = 0) {
  17788. const t = (1 + Math.sqrt(5)) / 2;
  17789. const r = 1 / t;
  17790. const vertices = [// (±1, ±1, ±1)
  17791. -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/φ, ±φ)
  17792. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  17793. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  17794. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  17795. 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];
  17796. super(vertices, indices, radius, detail);
  17797. this.type = 'DodecahedronGeometry';
  17798. this.parameters = {
  17799. radius: radius,
  17800. detail: detail
  17801. };
  17802. }
  17803. static fromJSON(data) {
  17804. return new DodecahedronGeometry(data.radius, data.detail);
  17805. }
  17806. }
  17807. const _v0 = new Vector3();
  17808. const _v1$1 = new Vector3();
  17809. const _normal = new Vector3();
  17810. const _triangle = new Triangle();
  17811. class EdgesGeometry extends BufferGeometry {
  17812. constructor(geometry, thresholdAngle) {
  17813. super();
  17814. this.type = 'EdgesGeometry';
  17815. this.parameters = {
  17816. thresholdAngle: thresholdAngle
  17817. };
  17818. thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1;
  17819. if (geometry.isGeometry === true) {
  17820. console.error('THREE.EdgesGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17821. return;
  17822. }
  17823. const thresholdDot = Math.cos(DEG2RAD * thresholdAngle);
  17824. const indexAttr = geometry.getIndex();
  17825. const positionAttr = geometry.getAttribute('position');
  17826. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  17827. const indexArr = [0, 0, 0];
  17828. const vertKeys = ['a', 'b', 'c'];
  17829. const hashes = new Array(3);
  17830. const edgeData = {};
  17831. const vertices = [];
  17832. for (let i = 0; i < indexCount; i += 3) {
  17833. if (indexAttr) {
  17834. indexArr[0] = indexAttr.getX(i);
  17835. indexArr[1] = indexAttr.getX(i + 1);
  17836. indexArr[2] = indexAttr.getX(i + 2);
  17837. } else {
  17838. indexArr[0] = i;
  17839. indexArr[1] = i + 1;
  17840. indexArr[2] = i + 2;
  17841. }
  17842. const {
  17843. a,
  17844. b,
  17845. c
  17846. } = _triangle;
  17847. a.fromBufferAttribute(positionAttr, indexArr[0]);
  17848. b.fromBufferAttribute(positionAttr, indexArr[1]);
  17849. c.fromBufferAttribute(positionAttr, indexArr[2]);
  17850. _triangle.getNormal(_normal); // create hashes for the edge from the vertices
  17851. hashes[0] = `${a.x},${a.y},${a.z}`;
  17852. hashes[1] = `${b.x},${b.y},${b.z}`;
  17853. hashes[2] = `${c.x},${c.y},${c.z}`; // skip degenerate triangles
  17854. if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
  17855. continue;
  17856. } // iterate over every edge
  17857. for (let j = 0; j < 3; j++) {
  17858. // get the first and next vertex making up the edge
  17859. const jNext = (j + 1) % 3;
  17860. const vecHash0 = hashes[j];
  17861. const vecHash1 = hashes[jNext];
  17862. const v0 = _triangle[vertKeys[j]];
  17863. const v1 = _triangle[vertKeys[jNext]];
  17864. const hash = `${vecHash0}_${vecHash1}`;
  17865. const reverseHash = `${vecHash1}_${vecHash0}`;
  17866. if (reverseHash in edgeData && edgeData[reverseHash]) {
  17867. // if we found a sibling edge add it into the vertex array if
  17868. // it meets the angle threshold and delete the edge from the map.
  17869. if (_normal.dot(edgeData[reverseHash].normal) <= thresholdDot) {
  17870. vertices.push(v0.x, v0.y, v0.z);
  17871. vertices.push(v1.x, v1.y, v1.z);
  17872. }
  17873. edgeData[reverseHash] = null;
  17874. } else if (!(hash in edgeData)) {
  17875. // if we've already got an edge here then skip adding a new one
  17876. edgeData[hash] = {
  17877. index0: indexArr[j],
  17878. index1: indexArr[jNext],
  17879. normal: _normal.clone()
  17880. };
  17881. }
  17882. }
  17883. } // iterate over all remaining, unmatched edges and add them to the vertex array
  17884. for (const key in edgeData) {
  17885. if (edgeData[key]) {
  17886. const {
  17887. index0,
  17888. index1
  17889. } = edgeData[key];
  17890. _v0.fromBufferAttribute(positionAttr, index0);
  17891. _v1$1.fromBufferAttribute(positionAttr, index1);
  17892. vertices.push(_v0.x, _v0.y, _v0.z);
  17893. vertices.push(_v1$1.x, _v1$1.y, _v1$1.z);
  17894. }
  17895. }
  17896. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17897. }
  17898. }
  17899. /**
  17900. * Extensible curve object.
  17901. *
  17902. * Some common of curve methods:
  17903. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  17904. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  17905. * .getPoints(), .getSpacedPoints()
  17906. * .getLength()
  17907. * .updateArcLengths()
  17908. *
  17909. * This following curves inherit from THREE.Curve:
  17910. *
  17911. * -- 2D curves --
  17912. * THREE.ArcCurve
  17913. * THREE.CubicBezierCurve
  17914. * THREE.EllipseCurve
  17915. * THREE.LineCurve
  17916. * THREE.QuadraticBezierCurve
  17917. * THREE.SplineCurve
  17918. *
  17919. * -- 3D curves --
  17920. * THREE.CatmullRomCurve3
  17921. * THREE.CubicBezierCurve3
  17922. * THREE.LineCurve3
  17923. * THREE.QuadraticBezierCurve3
  17924. *
  17925. * A series of curves can be represented as a THREE.CurvePath.
  17926. *
  17927. **/
  17928. class Curve {
  17929. constructor() {
  17930. this.type = 'Curve';
  17931. this.arcLengthDivisions = 200;
  17932. } // Virtual base class method to overwrite and implement in subclasses
  17933. // - t [0 .. 1]
  17934. getPoint() {
  17935. console.warn('THREE.Curve: .getPoint() not implemented.');
  17936. return null;
  17937. } // Get point at relative position in curve according to arc length
  17938. // - u [0 .. 1]
  17939. getPointAt(u, optionalTarget) {
  17940. const t = this.getUtoTmapping(u);
  17941. return this.getPoint(t, optionalTarget);
  17942. } // Get sequence of points using getPoint( t )
  17943. getPoints(divisions = 5) {
  17944. const points = [];
  17945. for (let d = 0; d <= divisions; d++) {
  17946. points.push(this.getPoint(d / divisions));
  17947. }
  17948. return points;
  17949. } // Get sequence of points using getPointAt( u )
  17950. getSpacedPoints(divisions = 5) {
  17951. const points = [];
  17952. for (let d = 0; d <= divisions; d++) {
  17953. points.push(this.getPointAt(d / divisions));
  17954. }
  17955. return points;
  17956. } // Get total curve arc length
  17957. getLength() {
  17958. const lengths = this.getLengths();
  17959. return lengths[lengths.length - 1];
  17960. } // Get list of cumulative segment lengths
  17961. getLengths(divisions = this.arcLengthDivisions) {
  17962. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  17963. return this.cacheArcLengths;
  17964. }
  17965. this.needsUpdate = false;
  17966. const cache = [];
  17967. let current,
  17968. last = this.getPoint(0);
  17969. let sum = 0;
  17970. cache.push(0);
  17971. for (let p = 1; p <= divisions; p++) {
  17972. current = this.getPoint(p / divisions);
  17973. sum += current.distanceTo(last);
  17974. cache.push(sum);
  17975. last = current;
  17976. }
  17977. this.cacheArcLengths = cache;
  17978. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  17979. }
  17980. updateArcLengths() {
  17981. this.needsUpdate = true;
  17982. this.getLengths();
  17983. } // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  17984. getUtoTmapping(u, distance) {
  17985. const arcLengths = this.getLengths();
  17986. let i = 0;
  17987. const il = arcLengths.length;
  17988. let targetArcLength; // The targeted u distance value to get
  17989. if (distance) {
  17990. targetArcLength = distance;
  17991. } else {
  17992. targetArcLength = u * arcLengths[il - 1];
  17993. } // binary search for the index with largest value smaller than target u distance
  17994. let low = 0,
  17995. high = il - 1,
  17996. comparison;
  17997. while (low <= high) {
  17998. 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
  17999. comparison = arcLengths[i] - targetArcLength;
  18000. if (comparison < 0) {
  18001. low = i + 1;
  18002. } else if (comparison > 0) {
  18003. high = i - 1;
  18004. } else {
  18005. high = i;
  18006. break; // DONE
  18007. }
  18008. }
  18009. i = high;
  18010. if (arcLengths[i] === targetArcLength) {
  18011. return i / (il - 1);
  18012. } // we could get finer grain at lengths, or use simple interpolation between two points
  18013. const lengthBefore = arcLengths[i];
  18014. const lengthAfter = arcLengths[i + 1];
  18015. const segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  18016. const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  18017. const t = (i + segmentFraction) / (il - 1);
  18018. return t;
  18019. } // Returns a unit vector tangent at t
  18020. // In case any sub curve does not implement its tangent derivation,
  18021. // 2 points a small delta apart will be used to find its gradient
  18022. // which seems to give a reasonable approximation
  18023. getTangent(t, optionalTarget) {
  18024. const delta = 0.0001;
  18025. let t1 = t - delta;
  18026. let t2 = t + delta; // Capping in case of danger
  18027. if (t1 < 0) t1 = 0;
  18028. if (t2 > 1) t2 = 1;
  18029. const pt1 = this.getPoint(t1);
  18030. const pt2 = this.getPoint(t2);
  18031. const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
  18032. tangent.copy(pt2).sub(pt1).normalize();
  18033. return tangent;
  18034. }
  18035. getTangentAt(u, optionalTarget) {
  18036. const t = this.getUtoTmapping(u);
  18037. return this.getTangent(t, optionalTarget);
  18038. }
  18039. computeFrenetFrames(segments, closed) {
  18040. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18041. const normal = new Vector3();
  18042. const tangents = [];
  18043. const normals = [];
  18044. const binormals = [];
  18045. const vec = new Vector3();
  18046. const mat = new Matrix4(); // compute the tangent vectors for each segment on the curve
  18047. for (let i = 0; i <= segments; i++) {
  18048. const u = i / segments;
  18049. tangents[i] = this.getTangentAt(u, new Vector3());
  18050. tangents[i].normalize();
  18051. } // select an initial normal vector perpendicular to the first tangent vector,
  18052. // and in the direction of the minimum tangent xyz component
  18053. normals[0] = new Vector3();
  18054. binormals[0] = new Vector3();
  18055. let min = Number.MAX_VALUE;
  18056. const tx = Math.abs(tangents[0].x);
  18057. const ty = Math.abs(tangents[0].y);
  18058. const tz = Math.abs(tangents[0].z);
  18059. if (tx <= min) {
  18060. min = tx;
  18061. normal.set(1, 0, 0);
  18062. }
  18063. if (ty <= min) {
  18064. min = ty;
  18065. normal.set(0, 1, 0);
  18066. }
  18067. if (tz <= min) {
  18068. normal.set(0, 0, 1);
  18069. }
  18070. vec.crossVectors(tangents[0], normal).normalize();
  18071. normals[0].crossVectors(tangents[0], vec);
  18072. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  18073. for (let i = 1; i <= segments; i++) {
  18074. normals[i] = normals[i - 1].clone();
  18075. binormals[i] = binormals[i - 1].clone();
  18076. vec.crossVectors(tangents[i - 1], tangents[i]);
  18077. if (vec.length() > Number.EPSILON) {
  18078. vec.normalize();
  18079. const theta = Math.acos(clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  18080. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  18081. }
  18082. binormals[i].crossVectors(tangents[i], normals[i]);
  18083. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18084. if (closed === true) {
  18085. let theta = Math.acos(clamp(normals[0].dot(normals[segments]), -1, 1));
  18086. theta /= segments;
  18087. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  18088. theta = -theta;
  18089. }
  18090. for (let i = 1; i <= segments; i++) {
  18091. // twist a little...
  18092. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  18093. binormals[i].crossVectors(tangents[i], normals[i]);
  18094. }
  18095. }
  18096. return {
  18097. tangents: tangents,
  18098. normals: normals,
  18099. binormals: binormals
  18100. };
  18101. }
  18102. clone() {
  18103. return new this.constructor().copy(this);
  18104. }
  18105. copy(source) {
  18106. this.arcLengthDivisions = source.arcLengthDivisions;
  18107. return this;
  18108. }
  18109. toJSON() {
  18110. const data = {
  18111. metadata: {
  18112. version: 4.5,
  18113. type: 'Curve',
  18114. generator: 'Curve.toJSON'
  18115. }
  18116. };
  18117. data.arcLengthDivisions = this.arcLengthDivisions;
  18118. data.type = this.type;
  18119. return data;
  18120. }
  18121. fromJSON(json) {
  18122. this.arcLengthDivisions = json.arcLengthDivisions;
  18123. return this;
  18124. }
  18125. }
  18126. class EllipseCurve extends Curve {
  18127. constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) {
  18128. super();
  18129. this.type = 'EllipseCurve';
  18130. this.aX = aX;
  18131. this.aY = aY;
  18132. this.xRadius = xRadius;
  18133. this.yRadius = yRadius;
  18134. this.aStartAngle = aStartAngle;
  18135. this.aEndAngle = aEndAngle;
  18136. this.aClockwise = aClockwise;
  18137. this.aRotation = aRotation;
  18138. }
  18139. getPoint(t, optionalTarget) {
  18140. const point = optionalTarget || new Vector2();
  18141. const twoPi = Math.PI * 2;
  18142. let deltaAngle = this.aEndAngle - this.aStartAngle;
  18143. const samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  18144. while (deltaAngle < 0) deltaAngle += twoPi;
  18145. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  18146. if (deltaAngle < Number.EPSILON) {
  18147. if (samePoints) {
  18148. deltaAngle = 0;
  18149. } else {
  18150. deltaAngle = twoPi;
  18151. }
  18152. }
  18153. if (this.aClockwise === true && !samePoints) {
  18154. if (deltaAngle === twoPi) {
  18155. deltaAngle = -twoPi;
  18156. } else {
  18157. deltaAngle = deltaAngle - twoPi;
  18158. }
  18159. }
  18160. const angle = this.aStartAngle + t * deltaAngle;
  18161. let x = this.aX + this.xRadius * Math.cos(angle);
  18162. let y = this.aY + this.yRadius * Math.sin(angle);
  18163. if (this.aRotation !== 0) {
  18164. const cos = Math.cos(this.aRotation);
  18165. const sin = Math.sin(this.aRotation);
  18166. const tx = x - this.aX;
  18167. const ty = y - this.aY; // Rotate the point about the center of the ellipse.
  18168. x = tx * cos - ty * sin + this.aX;
  18169. y = tx * sin + ty * cos + this.aY;
  18170. }
  18171. return point.set(x, y);
  18172. }
  18173. copy(source) {
  18174. super.copy(source);
  18175. this.aX = source.aX;
  18176. this.aY = source.aY;
  18177. this.xRadius = source.xRadius;
  18178. this.yRadius = source.yRadius;
  18179. this.aStartAngle = source.aStartAngle;
  18180. this.aEndAngle = source.aEndAngle;
  18181. this.aClockwise = source.aClockwise;
  18182. this.aRotation = source.aRotation;
  18183. return this;
  18184. }
  18185. toJSON() {
  18186. const data = super.toJSON();
  18187. data.aX = this.aX;
  18188. data.aY = this.aY;
  18189. data.xRadius = this.xRadius;
  18190. data.yRadius = this.yRadius;
  18191. data.aStartAngle = this.aStartAngle;
  18192. data.aEndAngle = this.aEndAngle;
  18193. data.aClockwise = this.aClockwise;
  18194. data.aRotation = this.aRotation;
  18195. return data;
  18196. }
  18197. fromJSON(json) {
  18198. super.fromJSON(json);
  18199. this.aX = json.aX;
  18200. this.aY = json.aY;
  18201. this.xRadius = json.xRadius;
  18202. this.yRadius = json.yRadius;
  18203. this.aStartAngle = json.aStartAngle;
  18204. this.aEndAngle = json.aEndAngle;
  18205. this.aClockwise = json.aClockwise;
  18206. this.aRotation = json.aRotation;
  18207. return this;
  18208. }
  18209. }
  18210. EllipseCurve.prototype.isEllipseCurve = true;
  18211. class ArcCurve extends EllipseCurve {
  18212. constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  18213. super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  18214. this.type = 'ArcCurve';
  18215. }
  18216. }
  18217. ArcCurve.prototype.isArcCurve = true;
  18218. /**
  18219. * Centripetal CatmullRom Curve - which is useful for avoiding
  18220. * cusps and self-intersections in non-uniform catmull rom curves.
  18221. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  18222. *
  18223. * curve.type accepts centripetal(default), chordal and catmullrom
  18224. * curve.tension is used for catmullrom which defaults to 0.5
  18225. */
  18226. /*
  18227. Based on an optimized c++ solution in
  18228. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  18229. - http://ideone.com/NoEbVM
  18230. This CubicPoly class could be used for reusing some variables and calculations,
  18231. but for three.js curve use, it could be possible inlined and flatten into a single function call
  18232. which can be placed in CurveUtils.
  18233. */
  18234. function CubicPoly() {
  18235. let c0 = 0,
  18236. c1 = 0,
  18237. c2 = 0,
  18238. c3 = 0;
  18239. /*
  18240. * Compute coefficients for a cubic polynomial
  18241. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  18242. * such that
  18243. * p(0) = x0, p(1) = x1
  18244. * and
  18245. * p'(0) = t0, p'(1) = t1.
  18246. */
  18247. function init(x0, x1, t0, t1) {
  18248. c0 = x0;
  18249. c1 = t0;
  18250. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  18251. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  18252. }
  18253. return {
  18254. initCatmullRom: function (x0, x1, x2, x3, tension) {
  18255. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  18256. },
  18257. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  18258. // compute tangents when parameterized in [t1,t2]
  18259. let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  18260. let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  18261. t1 *= dt1;
  18262. t2 *= dt1;
  18263. init(x1, x2, t1, t2);
  18264. },
  18265. calc: function (t) {
  18266. const t2 = t * t;
  18267. const t3 = t2 * t;
  18268. return c0 + c1 * t + c2 * t2 + c3 * t3;
  18269. }
  18270. };
  18271. } //
  18272. const tmp = new Vector3();
  18273. const px = new CubicPoly(),
  18274. py = new CubicPoly(),
  18275. pz = new CubicPoly();
  18276. class CatmullRomCurve3 extends Curve {
  18277. constructor(points = [], closed = false, curveType = 'centripetal', tension = 0.5) {
  18278. super();
  18279. this.type = 'CatmullRomCurve3';
  18280. this.points = points;
  18281. this.closed = closed;
  18282. this.curveType = curveType;
  18283. this.tension = tension;
  18284. }
  18285. getPoint(t, optionalTarget = new Vector3()) {
  18286. const point = optionalTarget;
  18287. const points = this.points;
  18288. const l = points.length;
  18289. const p = (l - (this.closed ? 0 : 1)) * t;
  18290. let intPoint = Math.floor(p);
  18291. let weight = p - intPoint;
  18292. if (this.closed) {
  18293. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  18294. } else if (weight === 0 && intPoint === l - 1) {
  18295. intPoint = l - 2;
  18296. weight = 1;
  18297. }
  18298. let p0, p3; // 4 points (p1 & p2 defined below)
  18299. if (this.closed || intPoint > 0) {
  18300. p0 = points[(intPoint - 1) % l];
  18301. } else {
  18302. // extrapolate first point
  18303. tmp.subVectors(points[0], points[1]).add(points[0]);
  18304. p0 = tmp;
  18305. }
  18306. const p1 = points[intPoint % l];
  18307. const p2 = points[(intPoint + 1) % l];
  18308. if (this.closed || intPoint + 2 < l) {
  18309. p3 = points[(intPoint + 2) % l];
  18310. } else {
  18311. // extrapolate last point
  18312. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  18313. p3 = tmp;
  18314. }
  18315. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  18316. // init Centripetal / Chordal Catmull-Rom
  18317. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  18318. let dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  18319. let dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  18320. let dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  18321. if (dt1 < 1e-4) dt1 = 1.0;
  18322. if (dt0 < 1e-4) dt0 = dt1;
  18323. if (dt2 < 1e-4) dt2 = dt1;
  18324. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  18325. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  18326. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  18327. } else if (this.curveType === 'catmullrom') {
  18328. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  18329. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  18330. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  18331. }
  18332. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  18333. return point;
  18334. }
  18335. copy(source) {
  18336. super.copy(source);
  18337. this.points = [];
  18338. for (let i = 0, l = source.points.length; i < l; i++) {
  18339. const point = source.points[i];
  18340. this.points.push(point.clone());
  18341. }
  18342. this.closed = source.closed;
  18343. this.curveType = source.curveType;
  18344. this.tension = source.tension;
  18345. return this;
  18346. }
  18347. toJSON() {
  18348. const data = super.toJSON();
  18349. data.points = [];
  18350. for (let i = 0, l = this.points.length; i < l; i++) {
  18351. const point = this.points[i];
  18352. data.points.push(point.toArray());
  18353. }
  18354. data.closed = this.closed;
  18355. data.curveType = this.curveType;
  18356. data.tension = this.tension;
  18357. return data;
  18358. }
  18359. fromJSON(json) {
  18360. super.fromJSON(json);
  18361. this.points = [];
  18362. for (let i = 0, l = json.points.length; i < l; i++) {
  18363. const point = json.points[i];
  18364. this.points.push(new Vector3().fromArray(point));
  18365. }
  18366. this.closed = json.closed;
  18367. this.curveType = json.curveType;
  18368. this.tension = json.tension;
  18369. return this;
  18370. }
  18371. }
  18372. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  18373. /**
  18374. * Bezier Curves formulas obtained from
  18375. * http://en.wikipedia.org/wiki/Bézier_curve
  18376. */
  18377. function CatmullRom(t, p0, p1, p2, p3) {
  18378. const v0 = (p2 - p0) * 0.5;
  18379. const v1 = (p3 - p1) * 0.5;
  18380. const t2 = t * t;
  18381. const t3 = t * t2;
  18382. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  18383. } //
  18384. function QuadraticBezierP0(t, p) {
  18385. const k = 1 - t;
  18386. return k * k * p;
  18387. }
  18388. function QuadraticBezierP1(t, p) {
  18389. return 2 * (1 - t) * t * p;
  18390. }
  18391. function QuadraticBezierP2(t, p) {
  18392. return t * t * p;
  18393. }
  18394. function QuadraticBezier(t, p0, p1, p2) {
  18395. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  18396. } //
  18397. function CubicBezierP0(t, p) {
  18398. const k = 1 - t;
  18399. return k * k * k * p;
  18400. }
  18401. function CubicBezierP1(t, p) {
  18402. const k = 1 - t;
  18403. return 3 * k * k * t * p;
  18404. }
  18405. function CubicBezierP2(t, p) {
  18406. return 3 * (1 - t) * t * t * p;
  18407. }
  18408. function CubicBezierP3(t, p) {
  18409. return t * t * t * p;
  18410. }
  18411. function CubicBezier(t, p0, p1, p2, p3) {
  18412. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  18413. }
  18414. class CubicBezierCurve extends Curve {
  18415. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) {
  18416. super();
  18417. this.type = 'CubicBezierCurve';
  18418. this.v0 = v0;
  18419. this.v1 = v1;
  18420. this.v2 = v2;
  18421. this.v3 = v3;
  18422. }
  18423. getPoint(t, optionalTarget = new Vector2()) {
  18424. const point = optionalTarget;
  18425. const v0 = this.v0,
  18426. v1 = this.v1,
  18427. v2 = this.v2,
  18428. v3 = this.v3;
  18429. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  18430. return point;
  18431. }
  18432. copy(source) {
  18433. super.copy(source);
  18434. this.v0.copy(source.v0);
  18435. this.v1.copy(source.v1);
  18436. this.v2.copy(source.v2);
  18437. this.v3.copy(source.v3);
  18438. return this;
  18439. }
  18440. toJSON() {
  18441. const data = super.toJSON();
  18442. data.v0 = this.v0.toArray();
  18443. data.v1 = this.v1.toArray();
  18444. data.v2 = this.v2.toArray();
  18445. data.v3 = this.v3.toArray();
  18446. return data;
  18447. }
  18448. fromJSON(json) {
  18449. super.fromJSON(json);
  18450. this.v0.fromArray(json.v0);
  18451. this.v1.fromArray(json.v1);
  18452. this.v2.fromArray(json.v2);
  18453. this.v3.fromArray(json.v3);
  18454. return this;
  18455. }
  18456. }
  18457. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  18458. class CubicBezierCurve3 extends Curve {
  18459. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) {
  18460. super();
  18461. this.type = 'CubicBezierCurve3';
  18462. this.v0 = v0;
  18463. this.v1 = v1;
  18464. this.v2 = v2;
  18465. this.v3 = v3;
  18466. }
  18467. getPoint(t, optionalTarget = new Vector3()) {
  18468. const point = optionalTarget;
  18469. const v0 = this.v0,
  18470. v1 = this.v1,
  18471. v2 = this.v2,
  18472. v3 = this.v3;
  18473. 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));
  18474. return point;
  18475. }
  18476. copy(source) {
  18477. super.copy(source);
  18478. this.v0.copy(source.v0);
  18479. this.v1.copy(source.v1);
  18480. this.v2.copy(source.v2);
  18481. this.v3.copy(source.v3);
  18482. return this;
  18483. }
  18484. toJSON() {
  18485. const data = super.toJSON();
  18486. data.v0 = this.v0.toArray();
  18487. data.v1 = this.v1.toArray();
  18488. data.v2 = this.v2.toArray();
  18489. data.v3 = this.v3.toArray();
  18490. return data;
  18491. }
  18492. fromJSON(json) {
  18493. super.fromJSON(json);
  18494. this.v0.fromArray(json.v0);
  18495. this.v1.fromArray(json.v1);
  18496. this.v2.fromArray(json.v2);
  18497. this.v3.fromArray(json.v3);
  18498. return this;
  18499. }
  18500. }
  18501. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  18502. class LineCurve extends Curve {
  18503. constructor(v1 = new Vector2(), v2 = new Vector2()) {
  18504. super();
  18505. this.type = 'LineCurve';
  18506. this.v1 = v1;
  18507. this.v2 = v2;
  18508. }
  18509. getPoint(t, optionalTarget = new Vector2()) {
  18510. const point = optionalTarget;
  18511. if (t === 1) {
  18512. point.copy(this.v2);
  18513. } else {
  18514. point.copy(this.v2).sub(this.v1);
  18515. point.multiplyScalar(t).add(this.v1);
  18516. }
  18517. return point;
  18518. } // Line curve is linear, so we can overwrite default getPointAt
  18519. getPointAt(u, optionalTarget) {
  18520. return this.getPoint(u, optionalTarget);
  18521. }
  18522. getTangent(t, optionalTarget) {
  18523. const tangent = optionalTarget || new Vector2();
  18524. tangent.copy(this.v2).sub(this.v1).normalize();
  18525. return tangent;
  18526. }
  18527. copy(source) {
  18528. super.copy(source);
  18529. this.v1.copy(source.v1);
  18530. this.v2.copy(source.v2);
  18531. return this;
  18532. }
  18533. toJSON() {
  18534. const data = super.toJSON();
  18535. data.v1 = this.v1.toArray();
  18536. data.v2 = this.v2.toArray();
  18537. return data;
  18538. }
  18539. fromJSON(json) {
  18540. super.fromJSON(json);
  18541. this.v1.fromArray(json.v1);
  18542. this.v2.fromArray(json.v2);
  18543. return this;
  18544. }
  18545. }
  18546. LineCurve.prototype.isLineCurve = true;
  18547. class LineCurve3 extends Curve {
  18548. constructor(v1 = new Vector3(), v2 = new Vector3()) {
  18549. super();
  18550. this.type = 'LineCurve3';
  18551. this.isLineCurve3 = true;
  18552. this.v1 = v1;
  18553. this.v2 = v2;
  18554. }
  18555. getPoint(t, optionalTarget = new Vector3()) {
  18556. const point = optionalTarget;
  18557. if (t === 1) {
  18558. point.copy(this.v2);
  18559. } else {
  18560. point.copy(this.v2).sub(this.v1);
  18561. point.multiplyScalar(t).add(this.v1);
  18562. }
  18563. return point;
  18564. } // Line curve is linear, so we can overwrite default getPointAt
  18565. getPointAt(u, optionalTarget) {
  18566. return this.getPoint(u, optionalTarget);
  18567. }
  18568. copy(source) {
  18569. super.copy(source);
  18570. this.v1.copy(source.v1);
  18571. this.v2.copy(source.v2);
  18572. return this;
  18573. }
  18574. toJSON() {
  18575. const data = super.toJSON();
  18576. data.v1 = this.v1.toArray();
  18577. data.v2 = this.v2.toArray();
  18578. return data;
  18579. }
  18580. fromJSON(json) {
  18581. super.fromJSON(json);
  18582. this.v1.fromArray(json.v1);
  18583. this.v2.fromArray(json.v2);
  18584. return this;
  18585. }
  18586. }
  18587. class QuadraticBezierCurve extends Curve {
  18588. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) {
  18589. super();
  18590. this.type = 'QuadraticBezierCurve';
  18591. this.v0 = v0;
  18592. this.v1 = v1;
  18593. this.v2 = v2;
  18594. }
  18595. getPoint(t, optionalTarget = new Vector2()) {
  18596. const point = optionalTarget;
  18597. const v0 = this.v0,
  18598. v1 = this.v1,
  18599. v2 = this.v2;
  18600. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  18601. return point;
  18602. }
  18603. copy(source) {
  18604. super.copy(source);
  18605. this.v0.copy(source.v0);
  18606. this.v1.copy(source.v1);
  18607. this.v2.copy(source.v2);
  18608. return this;
  18609. }
  18610. toJSON() {
  18611. const data = super.toJSON();
  18612. data.v0 = this.v0.toArray();
  18613. data.v1 = this.v1.toArray();
  18614. data.v2 = this.v2.toArray();
  18615. return data;
  18616. }
  18617. fromJSON(json) {
  18618. super.fromJSON(json);
  18619. this.v0.fromArray(json.v0);
  18620. this.v1.fromArray(json.v1);
  18621. this.v2.fromArray(json.v2);
  18622. return this;
  18623. }
  18624. }
  18625. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  18626. class QuadraticBezierCurve3 extends Curve {
  18627. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) {
  18628. super();
  18629. this.type = 'QuadraticBezierCurve3';
  18630. this.v0 = v0;
  18631. this.v1 = v1;
  18632. this.v2 = v2;
  18633. }
  18634. getPoint(t, optionalTarget = new Vector3()) {
  18635. const point = optionalTarget;
  18636. const v0 = this.v0,
  18637. v1 = this.v1,
  18638. v2 = this.v2;
  18639. 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));
  18640. return point;
  18641. }
  18642. copy(source) {
  18643. super.copy(source);
  18644. this.v0.copy(source.v0);
  18645. this.v1.copy(source.v1);
  18646. this.v2.copy(source.v2);
  18647. return this;
  18648. }
  18649. toJSON() {
  18650. const data = super.toJSON();
  18651. data.v0 = this.v0.toArray();
  18652. data.v1 = this.v1.toArray();
  18653. data.v2 = this.v2.toArray();
  18654. return data;
  18655. }
  18656. fromJSON(json) {
  18657. super.fromJSON(json);
  18658. this.v0.fromArray(json.v0);
  18659. this.v1.fromArray(json.v1);
  18660. this.v2.fromArray(json.v2);
  18661. return this;
  18662. }
  18663. }
  18664. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  18665. class SplineCurve extends Curve {
  18666. constructor(points = []) {
  18667. super();
  18668. this.type = 'SplineCurve';
  18669. this.points = points;
  18670. }
  18671. getPoint(t, optionalTarget = new Vector2()) {
  18672. const point = optionalTarget;
  18673. const points = this.points;
  18674. const p = (points.length - 1) * t;
  18675. const intPoint = Math.floor(p);
  18676. const weight = p - intPoint;
  18677. const p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  18678. const p1 = points[intPoint];
  18679. const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  18680. const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  18681. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  18682. return point;
  18683. }
  18684. copy(source) {
  18685. super.copy(source);
  18686. this.points = [];
  18687. for (let i = 0, l = source.points.length; i < l; i++) {
  18688. const point = source.points[i];
  18689. this.points.push(point.clone());
  18690. }
  18691. return this;
  18692. }
  18693. toJSON() {
  18694. const data = super.toJSON();
  18695. data.points = [];
  18696. for (let i = 0, l = this.points.length; i < l; i++) {
  18697. const point = this.points[i];
  18698. data.points.push(point.toArray());
  18699. }
  18700. return data;
  18701. }
  18702. fromJSON(json) {
  18703. super.fromJSON(json);
  18704. this.points = [];
  18705. for (let i = 0, l = json.points.length; i < l; i++) {
  18706. const point = json.points[i];
  18707. this.points.push(new Vector2().fromArray(point));
  18708. }
  18709. return this;
  18710. }
  18711. }
  18712. SplineCurve.prototype.isSplineCurve = true;
  18713. var Curves = /*#__PURE__*/Object.freeze({
  18714. __proto__: null,
  18715. ArcCurve: ArcCurve,
  18716. CatmullRomCurve3: CatmullRomCurve3,
  18717. CubicBezierCurve: CubicBezierCurve,
  18718. CubicBezierCurve3: CubicBezierCurve3,
  18719. EllipseCurve: EllipseCurve,
  18720. LineCurve: LineCurve,
  18721. LineCurve3: LineCurve3,
  18722. QuadraticBezierCurve: QuadraticBezierCurve,
  18723. QuadraticBezierCurve3: QuadraticBezierCurve3,
  18724. SplineCurve: SplineCurve
  18725. });
  18726. /**
  18727. * Port from https://github.com/mapbox/earcut (v2.2.2)
  18728. */
  18729. const Earcut = {
  18730. triangulate: function (data, holeIndices, dim = 2) {
  18731. const hasHoles = holeIndices && holeIndices.length;
  18732. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  18733. let outerNode = linkedList(data, 0, outerLen, dim, true);
  18734. const triangles = [];
  18735. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  18736. let minX, minY, maxX, maxY, x, y, invSize;
  18737. 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
  18738. if (data.length > 80 * dim) {
  18739. minX = maxX = data[0];
  18740. minY = maxY = data[1];
  18741. for (let i = dim; i < outerLen; i += dim) {
  18742. x = data[i];
  18743. y = data[i + 1];
  18744. if (x < minX) minX = x;
  18745. if (y < minY) minY = y;
  18746. if (x > maxX) maxX = x;
  18747. if (y > maxY) maxY = y;
  18748. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  18749. invSize = Math.max(maxX - minX, maxY - minY);
  18750. invSize = invSize !== 0 ? 1 / invSize : 0;
  18751. }
  18752. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  18753. return triangles;
  18754. }
  18755. }; // create a circular doubly linked list from polygon points in the specified winding order
  18756. function linkedList(data, start, end, dim, clockwise) {
  18757. let i, last;
  18758. if (clockwise === signedArea(data, start, end, dim) > 0) {
  18759. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  18760. } else {
  18761. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  18762. }
  18763. if (last && equals(last, last.next)) {
  18764. removeNode(last);
  18765. last = last.next;
  18766. }
  18767. return last;
  18768. } // eliminate colinear or duplicate points
  18769. function filterPoints(start, end) {
  18770. if (!start) return start;
  18771. if (!end) end = start;
  18772. let p = start,
  18773. again;
  18774. do {
  18775. again = false;
  18776. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  18777. removeNode(p);
  18778. p = end = p.prev;
  18779. if (p === p.next) break;
  18780. again = true;
  18781. } else {
  18782. p = p.next;
  18783. }
  18784. } while (again || p !== end);
  18785. return end;
  18786. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  18787. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  18788. if (!ear) return; // interlink polygon nodes in z-order
  18789. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  18790. let stop = ear,
  18791. prev,
  18792. next; // iterate through ears, slicing them one by one
  18793. while (ear.prev !== ear.next) {
  18794. prev = ear.prev;
  18795. next = ear.next;
  18796. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  18797. // cut off the triangle
  18798. triangles.push(prev.i / dim);
  18799. triangles.push(ear.i / dim);
  18800. triangles.push(next.i / dim);
  18801. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  18802. ear = next.next;
  18803. stop = next.next;
  18804. continue;
  18805. }
  18806. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  18807. if (ear === stop) {
  18808. // try filtering points and slicing again
  18809. if (!pass) {
  18810. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  18811. } else if (pass === 1) {
  18812. ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
  18813. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  18814. } else if (pass === 2) {
  18815. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  18816. }
  18817. break;
  18818. }
  18819. }
  18820. } // check whether a polygon node forms a valid ear with adjacent nodes
  18821. function isEar(ear) {
  18822. const a = ear.prev,
  18823. b = ear,
  18824. c = ear.next;
  18825. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18826. // now make sure we don't have other points inside the potential ear
  18827. let p = ear.next.next;
  18828. while (p !== ear.prev) {
  18829. 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;
  18830. p = p.next;
  18831. }
  18832. return true;
  18833. }
  18834. function isEarHashed(ear, minX, minY, invSize) {
  18835. const a = ear.prev,
  18836. b = ear,
  18837. c = ear.next;
  18838. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18839. // triangle bbox; min & max are calculated like this for speed
  18840. const minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  18841. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  18842. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  18843. 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;
  18844. const minZ = zOrder(minTX, minTY, minX, minY, invSize),
  18845. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  18846. let p = ear.prevZ,
  18847. n = ear.nextZ; // look for points inside the triangle in both directions
  18848. while (p && p.z >= minZ && n && n.z <= maxZ) {
  18849. 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;
  18850. p = p.prevZ;
  18851. 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;
  18852. n = n.nextZ;
  18853. } // look for remaining points in decreasing z-order
  18854. while (p && p.z >= minZ) {
  18855. 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;
  18856. p = p.prevZ;
  18857. } // look for remaining points in increasing z-order
  18858. while (n && n.z <= maxZ) {
  18859. 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;
  18860. n = n.nextZ;
  18861. }
  18862. return true;
  18863. } // go through all polygon nodes and cure small local self-intersections
  18864. function cureLocalIntersections(start, triangles, dim) {
  18865. let p = start;
  18866. do {
  18867. const a = p.prev,
  18868. b = p.next.next;
  18869. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  18870. triangles.push(a.i / dim);
  18871. triangles.push(p.i / dim);
  18872. triangles.push(b.i / dim); // remove two nodes involved
  18873. removeNode(p);
  18874. removeNode(p.next);
  18875. p = start = b;
  18876. }
  18877. p = p.next;
  18878. } while (p !== start);
  18879. return filterPoints(p);
  18880. } // try splitting polygon into two and triangulate them independently
  18881. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  18882. // look for a valid diagonal that divides the polygon into two
  18883. let a = start;
  18884. do {
  18885. let b = a.next.next;
  18886. while (b !== a.prev) {
  18887. if (a.i !== b.i && isValidDiagonal(a, b)) {
  18888. // split the polygon in two by the diagonal
  18889. let c = splitPolygon(a, b); // filter colinear points around the cuts
  18890. a = filterPoints(a, a.next);
  18891. c = filterPoints(c, c.next); // run earcut on each half
  18892. earcutLinked(a, triangles, dim, minX, minY, invSize);
  18893. earcutLinked(c, triangles, dim, minX, minY, invSize);
  18894. return;
  18895. }
  18896. b = b.next;
  18897. }
  18898. a = a.next;
  18899. } while (a !== start);
  18900. } // link every hole into the outer loop, producing a single-ring polygon without holes
  18901. function eliminateHoles(data, holeIndices, outerNode, dim) {
  18902. const queue = [];
  18903. let i, len, start, end, list;
  18904. for (i = 0, len = holeIndices.length; i < len; i++) {
  18905. start = holeIndices[i] * dim;
  18906. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  18907. list = linkedList(data, start, end, dim, false);
  18908. if (list === list.next) list.steiner = true;
  18909. queue.push(getLeftmost(list));
  18910. }
  18911. queue.sort(compareX); // process holes from left to right
  18912. for (i = 0; i < queue.length; i++) {
  18913. eliminateHole(queue[i], outerNode);
  18914. outerNode = filterPoints(outerNode, outerNode.next);
  18915. }
  18916. return outerNode;
  18917. }
  18918. function compareX(a, b) {
  18919. return a.x - b.x;
  18920. } // find a bridge between vertices that connects hole with an outer ring and and link it
  18921. function eliminateHole(hole, outerNode) {
  18922. outerNode = findHoleBridge(hole, outerNode);
  18923. if (outerNode) {
  18924. const b = splitPolygon(outerNode, hole); // filter collinear points around the cuts
  18925. filterPoints(outerNode, outerNode.next);
  18926. filterPoints(b, b.next);
  18927. }
  18928. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  18929. function findHoleBridge(hole, outerNode) {
  18930. let p = outerNode;
  18931. const hx = hole.x;
  18932. const hy = hole.y;
  18933. let qx = -Infinity,
  18934. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  18935. // segment's endpoint with lesser x will be potential connection point
  18936. do {
  18937. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  18938. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  18939. if (x <= hx && x > qx) {
  18940. qx = x;
  18941. if (x === hx) {
  18942. if (hy === p.y) return p;
  18943. if (hy === p.next.y) return p.next;
  18944. }
  18945. m = p.x < p.next.x ? p : p.next;
  18946. }
  18947. }
  18948. p = p.next;
  18949. } while (p !== outerNode);
  18950. if (!m) return null;
  18951. if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint
  18952. // look for points inside the triangle of hole point, segment intersection and endpoint;
  18953. // if there are no points found, we have a valid connection;
  18954. // otherwise choose the point of the minimum angle with the ray as connection point
  18955. const stop = m,
  18956. mx = m.x,
  18957. my = m.y;
  18958. let tanMin = Infinity,
  18959. tan;
  18960. p = m;
  18961. do {
  18962. 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)) {
  18963. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  18964. if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
  18965. m = p;
  18966. tanMin = tan;
  18967. }
  18968. }
  18969. p = p.next;
  18970. } while (p !== stop);
  18971. return m;
  18972. } // whether sector in vertex m contains sector in vertex p in the same coordinates
  18973. function sectorContainsSector(m, p) {
  18974. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  18975. } // interlink polygon nodes in z-order
  18976. function indexCurve(start, minX, minY, invSize) {
  18977. let p = start;
  18978. do {
  18979. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  18980. p.prevZ = p.prev;
  18981. p.nextZ = p.next;
  18982. p = p.next;
  18983. } while (p !== start);
  18984. p.prevZ.nextZ = null;
  18985. p.prevZ = null;
  18986. sortLinked(p);
  18987. } // Simon Tatham's linked list merge sort algorithm
  18988. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  18989. function sortLinked(list) {
  18990. let i,
  18991. p,
  18992. q,
  18993. e,
  18994. tail,
  18995. numMerges,
  18996. pSize,
  18997. qSize,
  18998. inSize = 1;
  18999. do {
  19000. p = list;
  19001. list = null;
  19002. tail = null;
  19003. numMerges = 0;
  19004. while (p) {
  19005. numMerges++;
  19006. q = p;
  19007. pSize = 0;
  19008. for (i = 0; i < inSize; i++) {
  19009. pSize++;
  19010. q = q.nextZ;
  19011. if (!q) break;
  19012. }
  19013. qSize = inSize;
  19014. while (pSize > 0 || qSize > 0 && q) {
  19015. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  19016. e = p;
  19017. p = p.nextZ;
  19018. pSize--;
  19019. } else {
  19020. e = q;
  19021. q = q.nextZ;
  19022. qSize--;
  19023. }
  19024. if (tail) tail.nextZ = e;else list = e;
  19025. e.prevZ = tail;
  19026. tail = e;
  19027. }
  19028. p = q;
  19029. }
  19030. tail.nextZ = null;
  19031. inSize *= 2;
  19032. } while (numMerges > 1);
  19033. return list;
  19034. } // z-order of a point given coords and inverse of the longer side of data bbox
  19035. function zOrder(x, y, minX, minY, invSize) {
  19036. // coords are transformed into non-negative 15-bit integer range
  19037. x = 32767 * (x - minX) * invSize;
  19038. y = 32767 * (y - minY) * invSize;
  19039. x = (x | x << 8) & 0x00FF00FF;
  19040. x = (x | x << 4) & 0x0F0F0F0F;
  19041. x = (x | x << 2) & 0x33333333;
  19042. x = (x | x << 1) & 0x55555555;
  19043. y = (y | y << 8) & 0x00FF00FF;
  19044. y = (y | y << 4) & 0x0F0F0F0F;
  19045. y = (y | y << 2) & 0x33333333;
  19046. y = (y | y << 1) & 0x55555555;
  19047. return x | y << 1;
  19048. } // find the leftmost node of a polygon ring
  19049. function getLeftmost(start) {
  19050. let p = start,
  19051. leftmost = start;
  19052. do {
  19053. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  19054. p = p.next;
  19055. } while (p !== start);
  19056. return leftmost;
  19057. } // check if a point lies within a convex triangle
  19058. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  19059. 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;
  19060. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  19061. function isValidDiagonal(a, b) {
  19062. 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
  19063. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  19064. } // signed area of a triangle
  19065. function area(p, q, r) {
  19066. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  19067. } // check if two points are equal
  19068. function equals(p1, p2) {
  19069. return p1.x === p2.x && p1.y === p2.y;
  19070. } // check if two segments intersect
  19071. function intersects(p1, q1, p2, q2) {
  19072. const o1 = sign(area(p1, q1, p2));
  19073. const o2 = sign(area(p1, q1, q2));
  19074. const o3 = sign(area(p2, q2, p1));
  19075. const o4 = sign(area(p2, q2, q1));
  19076. if (o1 !== o2 && o3 !== o4) return true; // general case
  19077. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  19078. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  19079. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  19080. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  19081. return false;
  19082. } // for collinear points p, q, r, check if point q lies on segment pr
  19083. function onSegment(p, q, r) {
  19084. 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);
  19085. }
  19086. function sign(num) {
  19087. return num > 0 ? 1 : num < 0 ? -1 : 0;
  19088. } // check if a polygon diagonal intersects any polygon segments
  19089. function intersectsPolygon(a, b) {
  19090. let p = a;
  19091. do {
  19092. 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;
  19093. p = p.next;
  19094. } while (p !== a);
  19095. return false;
  19096. } // check if a polygon diagonal is locally inside the polygon
  19097. function locallyInside(a, b) {
  19098. 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;
  19099. } // check if the middle point of a polygon diagonal is inside the polygon
  19100. function middleInside(a, b) {
  19101. let p = a,
  19102. inside = false;
  19103. const px = (a.x + b.x) / 2,
  19104. py = (a.y + b.y) / 2;
  19105. do {
  19106. 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;
  19107. p = p.next;
  19108. } while (p !== a);
  19109. return inside;
  19110. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  19111. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  19112. function splitPolygon(a, b) {
  19113. const a2 = new Node(a.i, a.x, a.y),
  19114. b2 = new Node(b.i, b.x, b.y),
  19115. an = a.next,
  19116. bp = b.prev;
  19117. a.next = b;
  19118. b.prev = a;
  19119. a2.next = an;
  19120. an.prev = a2;
  19121. b2.next = a2;
  19122. a2.prev = b2;
  19123. bp.next = b2;
  19124. b2.prev = bp;
  19125. return b2;
  19126. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  19127. function insertNode(i, x, y, last) {
  19128. const p = new Node(i, x, y);
  19129. if (!last) {
  19130. p.prev = p;
  19131. p.next = p;
  19132. } else {
  19133. p.next = last.next;
  19134. p.prev = last;
  19135. last.next.prev = p;
  19136. last.next = p;
  19137. }
  19138. return p;
  19139. }
  19140. function removeNode(p) {
  19141. p.next.prev = p.prev;
  19142. p.prev.next = p.next;
  19143. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  19144. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  19145. }
  19146. function Node(i, x, y) {
  19147. // vertex index in coordinates array
  19148. this.i = i; // vertex coordinates
  19149. this.x = x;
  19150. this.y = y; // previous and next vertex nodes in a polygon ring
  19151. this.prev = null;
  19152. this.next = null; // z-order curve value
  19153. this.z = null; // previous and next nodes in z-order
  19154. this.prevZ = null;
  19155. this.nextZ = null; // indicates whether this is a steiner point
  19156. this.steiner = false;
  19157. }
  19158. function signedArea(data, start, end, dim) {
  19159. let sum = 0;
  19160. for (let i = start, j = end - dim; i < end; i += dim) {
  19161. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  19162. j = i;
  19163. }
  19164. return sum;
  19165. }
  19166. class ShapeUtils {
  19167. // calculate area of the contour polygon
  19168. static area(contour) {
  19169. const n = contour.length;
  19170. let a = 0.0;
  19171. for (let p = n - 1, q = 0; q < n; p = q++) {
  19172. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  19173. }
  19174. return a * 0.5;
  19175. }
  19176. static isClockWise(pts) {
  19177. return ShapeUtils.area(pts) < 0;
  19178. }
  19179. static triangulateShape(contour, holes) {
  19180. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  19181. const holeIndices = []; // array of hole indices
  19182. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  19183. removeDupEndPts(contour);
  19184. addContour(vertices, contour); //
  19185. let holeIndex = contour.length;
  19186. holes.forEach(removeDupEndPts);
  19187. for (let i = 0; i < holes.length; i++) {
  19188. holeIndices.push(holeIndex);
  19189. holeIndex += holes[i].length;
  19190. addContour(vertices, holes[i]);
  19191. } //
  19192. const triangles = Earcut.triangulate(vertices, holeIndices); //
  19193. for (let i = 0; i < triangles.length; i += 3) {
  19194. faces.push(triangles.slice(i, i + 3));
  19195. }
  19196. return faces;
  19197. }
  19198. }
  19199. function removeDupEndPts(points) {
  19200. const l = points.length;
  19201. if (l > 2 && points[l - 1].equals(points[0])) {
  19202. points.pop();
  19203. }
  19204. }
  19205. function addContour(vertices, contour) {
  19206. for (let i = 0; i < contour.length; i++) {
  19207. vertices.push(contour[i].x);
  19208. vertices.push(contour[i].y);
  19209. }
  19210. }
  19211. /**
  19212. * Creates extruded geometry from a path shape.
  19213. *
  19214. * parameters = {
  19215. *
  19216. * curveSegments: <int>, // number of points on the curves
  19217. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  19218. * depth: <float>, // Depth to extrude the shape
  19219. *
  19220. * bevelEnabled: <bool>, // turn on bevel
  19221. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19222. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  19223. * bevelOffset: <float>, // how far from shape outline does bevel start
  19224. * bevelSegments: <int>, // number of bevel layers
  19225. *
  19226. * extrudePath: <THREE.Curve> // curve to extrude shape along
  19227. *
  19228. * UVGenerator: <Object> // object that provides UV generator functions
  19229. *
  19230. * }
  19231. */
  19232. class ExtrudeGeometry extends BufferGeometry {
  19233. constructor(shapes, options) {
  19234. super();
  19235. this.type = 'ExtrudeGeometry';
  19236. this.parameters = {
  19237. shapes: shapes,
  19238. options: options
  19239. };
  19240. shapes = Array.isArray(shapes) ? shapes : [shapes];
  19241. const scope = this;
  19242. const verticesArray = [];
  19243. const uvArray = [];
  19244. for (let i = 0, l = shapes.length; i < l; i++) {
  19245. const shape = shapes[i];
  19246. addShape(shape);
  19247. } // build geometry
  19248. this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  19249. this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  19250. this.computeVertexNormals(); // functions
  19251. function addShape(shape) {
  19252. const placeholder = []; // options
  19253. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19254. const steps = options.steps !== undefined ? options.steps : 1;
  19255. let depth = options.depth !== undefined ? options.depth : 100;
  19256. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  19257. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  19258. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  19259. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  19260. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19261. const extrudePath = options.extrudePath;
  19262. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  19263. if (options.amount !== undefined) {
  19264. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  19265. depth = options.amount;
  19266. } //
  19267. let extrudePts,
  19268. extrudeByPath = false;
  19269. let splineTube, binormal, normal, position2;
  19270. if (extrudePath) {
  19271. extrudePts = extrudePath.getSpacedPoints(steps);
  19272. extrudeByPath = true;
  19273. bevelEnabled = false; // bevels not supported for path extrusion
  19274. // SETUP TNB variables
  19275. // TODO1 - have a .isClosed in spline?
  19276. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19277. binormal = new Vector3();
  19278. normal = new Vector3();
  19279. position2 = new Vector3();
  19280. } // Safeguards if bevels are not enabled
  19281. if (!bevelEnabled) {
  19282. bevelSegments = 0;
  19283. bevelThickness = 0;
  19284. bevelSize = 0;
  19285. bevelOffset = 0;
  19286. } // Variables initialization
  19287. const shapePoints = shape.extractPoints(curveSegments);
  19288. let vertices = shapePoints.shape;
  19289. const holes = shapePoints.holes;
  19290. const reverse = !ShapeUtils.isClockWise(vertices);
  19291. if (reverse) {
  19292. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19293. for (let h = 0, hl = holes.length; h < hl; h++) {
  19294. const ahole = holes[h];
  19295. if (ShapeUtils.isClockWise(ahole)) {
  19296. holes[h] = ahole.reverse();
  19297. }
  19298. }
  19299. }
  19300. const faces = ShapeUtils.triangulateShape(vertices, holes);
  19301. /* Vertices */
  19302. const contour = vertices; // vertices has all points but contour has only points of circumference
  19303. for (let h = 0, hl = holes.length; h < hl; h++) {
  19304. const ahole = holes[h];
  19305. vertices = vertices.concat(ahole);
  19306. }
  19307. function scalePt2(pt, vec, size) {
  19308. if (!vec) console.error('THREE.ExtrudeGeometry: vec does not exist');
  19309. return vec.clone().multiplyScalar(size).add(pt);
  19310. }
  19311. const vlen = vertices.length,
  19312. flen = faces.length; // Find directions for point movement
  19313. function getBevelVec(inPt, inPrev, inNext) {
  19314. // computes for inPt the corresponding point inPt' on a new contour
  19315. // shifted by 1 unit (length of normalized vector) to the left
  19316. // if we walk along contour clockwise, this new contour is outside the old one
  19317. //
  19318. // inPt' is the intersection of the two lines parallel to the two
  19319. // adjacent edges of inPt at a distance of 1 unit on the left side.
  19320. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  19321. // good reading for geometry algorithms (here: line-line intersection)
  19322. // http://geomalgorithms.com/a05-_intersect-1.html
  19323. const v_prev_x = inPt.x - inPrev.x,
  19324. v_prev_y = inPt.y - inPrev.y;
  19325. const v_next_x = inNext.x - inPt.x,
  19326. v_next_y = inNext.y - inPt.y;
  19327. const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  19328. const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  19329. if (Math.abs(collinear0) > Number.EPSILON) {
  19330. // not collinear
  19331. // length of vectors for normalizing
  19332. const v_prev_len = Math.sqrt(v_prev_lensq);
  19333. 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
  19334. const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  19335. const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  19336. const ptNextShift_x = inNext.x - v_next_y / v_next_len;
  19337. const ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  19338. 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
  19339. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  19340. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  19341. // but prevent crazy spikes
  19342. const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  19343. if (v_trans_lensq <= 2) {
  19344. return new Vector2(v_trans_x, v_trans_y);
  19345. } else {
  19346. shrink_by = Math.sqrt(v_trans_lensq / 2);
  19347. }
  19348. } else {
  19349. // handle special case of collinear edges
  19350. let direction_eq = false; // assumes: opposite
  19351. if (v_prev_x > Number.EPSILON) {
  19352. if (v_next_x > Number.EPSILON) {
  19353. direction_eq = true;
  19354. }
  19355. } else {
  19356. if (v_prev_x < -Number.EPSILON) {
  19357. if (v_next_x < -Number.EPSILON) {
  19358. direction_eq = true;
  19359. }
  19360. } else {
  19361. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  19362. direction_eq = true;
  19363. }
  19364. }
  19365. }
  19366. if (direction_eq) {
  19367. // console.log("Warning: lines are a straight sequence");
  19368. v_trans_x = -v_prev_y;
  19369. v_trans_y = v_prev_x;
  19370. shrink_by = Math.sqrt(v_prev_lensq);
  19371. } else {
  19372. // console.log("Warning: lines are a straight spike");
  19373. v_trans_x = v_prev_x;
  19374. v_trans_y = v_prev_y;
  19375. shrink_by = Math.sqrt(v_prev_lensq / 2);
  19376. }
  19377. }
  19378. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  19379. }
  19380. const contourMovements = [];
  19381. for (let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  19382. if (j === il) j = 0;
  19383. if (k === il) k = 0; // (j)---(i)---(k)
  19384. // console.log('i,j,k', i, j , k)
  19385. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  19386. }
  19387. const holesMovements = [];
  19388. let oneHoleMovements,
  19389. verticesMovements = contourMovements.concat();
  19390. for (let h = 0, hl = holes.length; h < hl; h++) {
  19391. const ahole = holes[h];
  19392. oneHoleMovements = [];
  19393. for (let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  19394. if (j === il) j = 0;
  19395. if (k === il) k = 0; // (j)---(i)---(k)
  19396. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  19397. }
  19398. holesMovements.push(oneHoleMovements);
  19399. verticesMovements = verticesMovements.concat(oneHoleMovements);
  19400. } // Loop bevelSegments, 1 for the front, 1 for the back
  19401. for (let b = 0; b < bevelSegments; b++) {
  19402. //for ( b = bevelSegments; b > 0; b -- ) {
  19403. const t = b / bevelSegments;
  19404. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  19405. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  19406. for (let i = 0, il = contour.length; i < il; i++) {
  19407. const vert = scalePt2(contour[i], contourMovements[i], bs);
  19408. v(vert.x, vert.y, -z);
  19409. } // expand holes
  19410. for (let h = 0, hl = holes.length; h < hl; h++) {
  19411. const ahole = holes[h];
  19412. oneHoleMovements = holesMovements[h];
  19413. for (let i = 0, il = ahole.length; i < il; i++) {
  19414. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  19415. v(vert.x, vert.y, -z);
  19416. }
  19417. }
  19418. }
  19419. const bs = bevelSize + bevelOffset; // Back facing vertices
  19420. for (let i = 0; i < vlen; i++) {
  19421. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  19422. if (!extrudeByPath) {
  19423. v(vert.x, vert.y, 0);
  19424. } else {
  19425. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19426. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  19427. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  19428. position2.copy(extrudePts[0]).add(normal).add(binormal);
  19429. v(position2.x, position2.y, position2.z);
  19430. }
  19431. } // Add stepped vertices...
  19432. // Including front facing vertices
  19433. for (let s = 1; s <= steps; s++) {
  19434. for (let i = 0; i < vlen; i++) {
  19435. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  19436. if (!extrudeByPath) {
  19437. v(vert.x, vert.y, depth / steps * s);
  19438. } else {
  19439. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19440. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  19441. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  19442. position2.copy(extrudePts[s]).add(normal).add(binormal);
  19443. v(position2.x, position2.y, position2.z);
  19444. }
  19445. }
  19446. } // Add bevel segments planes
  19447. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19448. for (let b = bevelSegments - 1; b >= 0; b--) {
  19449. const t = b / bevelSegments;
  19450. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  19451. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  19452. for (let i = 0, il = contour.length; i < il; i++) {
  19453. const vert = scalePt2(contour[i], contourMovements[i], bs);
  19454. v(vert.x, vert.y, depth + z);
  19455. } // expand holes
  19456. for (let h = 0, hl = holes.length; h < hl; h++) {
  19457. const ahole = holes[h];
  19458. oneHoleMovements = holesMovements[h];
  19459. for (let i = 0, il = ahole.length; i < il; i++) {
  19460. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  19461. if (!extrudeByPath) {
  19462. v(vert.x, vert.y, depth + z);
  19463. } else {
  19464. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  19465. }
  19466. }
  19467. }
  19468. }
  19469. /* Faces */
  19470. // Top and bottom faces
  19471. buildLidFaces(); // Sides faces
  19472. buildSideFaces(); ///// Internal functions
  19473. function buildLidFaces() {
  19474. const start = verticesArray.length / 3;
  19475. if (bevelEnabled) {
  19476. let layer = 0; // steps + 1
  19477. let offset = vlen * layer; // Bottom faces
  19478. for (let i = 0; i < flen; i++) {
  19479. const face = faces[i];
  19480. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  19481. }
  19482. layer = steps + bevelSegments * 2;
  19483. offset = vlen * layer; // Top faces
  19484. for (let i = 0; i < flen; i++) {
  19485. const face = faces[i];
  19486. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  19487. }
  19488. } else {
  19489. // Bottom faces
  19490. for (let i = 0; i < flen; i++) {
  19491. const face = faces[i];
  19492. f3(face[2], face[1], face[0]);
  19493. } // Top faces
  19494. for (let i = 0; i < flen; i++) {
  19495. const face = faces[i];
  19496. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  19497. }
  19498. }
  19499. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  19500. } // Create faces for the z-sides of the shape
  19501. function buildSideFaces() {
  19502. const start = verticesArray.length / 3;
  19503. let layeroffset = 0;
  19504. sidewalls(contour, layeroffset);
  19505. layeroffset += contour.length;
  19506. for (let h = 0, hl = holes.length; h < hl; h++) {
  19507. const ahole = holes[h];
  19508. sidewalls(ahole, layeroffset); //, true
  19509. layeroffset += ahole.length;
  19510. }
  19511. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  19512. }
  19513. function sidewalls(contour, layeroffset) {
  19514. let i = contour.length;
  19515. while (--i >= 0) {
  19516. const j = i;
  19517. let k = i - 1;
  19518. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  19519. for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) {
  19520. const slen1 = vlen * s;
  19521. const slen2 = vlen * (s + 1);
  19522. const a = layeroffset + j + slen1,
  19523. b = layeroffset + k + slen1,
  19524. c = layeroffset + k + slen2,
  19525. d = layeroffset + j + slen2;
  19526. f4(a, b, c, d);
  19527. }
  19528. }
  19529. }
  19530. function v(x, y, z) {
  19531. placeholder.push(x);
  19532. placeholder.push(y);
  19533. placeholder.push(z);
  19534. }
  19535. function f3(a, b, c) {
  19536. addVertex(a);
  19537. addVertex(b);
  19538. addVertex(c);
  19539. const nextIndex = verticesArray.length / 3;
  19540. const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  19541. addUV(uvs[0]);
  19542. addUV(uvs[1]);
  19543. addUV(uvs[2]);
  19544. }
  19545. function f4(a, b, c, d) {
  19546. addVertex(a);
  19547. addVertex(b);
  19548. addVertex(d);
  19549. addVertex(b);
  19550. addVertex(c);
  19551. addVertex(d);
  19552. const nextIndex = verticesArray.length / 3;
  19553. const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  19554. addUV(uvs[0]);
  19555. addUV(uvs[1]);
  19556. addUV(uvs[3]);
  19557. addUV(uvs[1]);
  19558. addUV(uvs[2]);
  19559. addUV(uvs[3]);
  19560. }
  19561. function addVertex(index) {
  19562. verticesArray.push(placeholder[index * 3 + 0]);
  19563. verticesArray.push(placeholder[index * 3 + 1]);
  19564. verticesArray.push(placeholder[index * 3 + 2]);
  19565. }
  19566. function addUV(vector2) {
  19567. uvArray.push(vector2.x);
  19568. uvArray.push(vector2.y);
  19569. }
  19570. }
  19571. }
  19572. toJSON() {
  19573. const data = super.toJSON();
  19574. const shapes = this.parameters.shapes;
  19575. const options = this.parameters.options;
  19576. return toJSON$1(shapes, options, data);
  19577. }
  19578. static fromJSON(data, shapes) {
  19579. const geometryShapes = [];
  19580. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  19581. const shape = shapes[data.shapes[j]];
  19582. geometryShapes.push(shape);
  19583. }
  19584. const extrudePath = data.options.extrudePath;
  19585. if (extrudePath !== undefined) {
  19586. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  19587. }
  19588. return new ExtrudeGeometry(geometryShapes, data.options);
  19589. }
  19590. }
  19591. const WorldUVGenerator = {
  19592. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  19593. const a_x = vertices[indexA * 3];
  19594. const a_y = vertices[indexA * 3 + 1];
  19595. const b_x = vertices[indexB * 3];
  19596. const b_y = vertices[indexB * 3 + 1];
  19597. const c_x = vertices[indexC * 3];
  19598. const c_y = vertices[indexC * 3 + 1];
  19599. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  19600. },
  19601. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  19602. const a_x = vertices[indexA * 3];
  19603. const a_y = vertices[indexA * 3 + 1];
  19604. const a_z = vertices[indexA * 3 + 2];
  19605. const b_x = vertices[indexB * 3];
  19606. const b_y = vertices[indexB * 3 + 1];
  19607. const b_z = vertices[indexB * 3 + 2];
  19608. const c_x = vertices[indexC * 3];
  19609. const c_y = vertices[indexC * 3 + 1];
  19610. const c_z = vertices[indexC * 3 + 2];
  19611. const d_x = vertices[indexD * 3];
  19612. const d_y = vertices[indexD * 3 + 1];
  19613. const d_z = vertices[indexD * 3 + 2];
  19614. if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) {
  19615. 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)];
  19616. } else {
  19617. 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)];
  19618. }
  19619. }
  19620. };
  19621. function toJSON$1(shapes, options, data) {
  19622. data.shapes = [];
  19623. if (Array.isArray(shapes)) {
  19624. for (let i = 0, l = shapes.length; i < l; i++) {
  19625. const shape = shapes[i];
  19626. data.shapes.push(shape.uuid);
  19627. }
  19628. } else {
  19629. data.shapes.push(shapes.uuid);
  19630. }
  19631. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  19632. return data;
  19633. }
  19634. class IcosahedronGeometry extends PolyhedronGeometry {
  19635. constructor(radius = 1, detail = 0) {
  19636. const t = (1 + Math.sqrt(5)) / 2;
  19637. 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];
  19638. 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];
  19639. super(vertices, indices, radius, detail);
  19640. this.type = 'IcosahedronGeometry';
  19641. this.parameters = {
  19642. radius: radius,
  19643. detail: detail
  19644. };
  19645. }
  19646. static fromJSON(data) {
  19647. return new IcosahedronGeometry(data.radius, data.detail);
  19648. }
  19649. }
  19650. class LatheGeometry extends BufferGeometry {
  19651. constructor(points, segments = 12, phiStart = 0, phiLength = Math.PI * 2) {
  19652. super();
  19653. this.type = 'LatheGeometry';
  19654. this.parameters = {
  19655. points: points,
  19656. segments: segments,
  19657. phiStart: phiStart,
  19658. phiLength: phiLength
  19659. };
  19660. segments = Math.floor(segments); // clamp phiLength so it's in range of [ 0, 2PI ]
  19661. phiLength = clamp(phiLength, 0, Math.PI * 2); // buffers
  19662. const indices = [];
  19663. const vertices = [];
  19664. const uvs = []; // helper variables
  19665. const inverseSegments = 1.0 / segments;
  19666. const vertex = new Vector3();
  19667. const uv = new Vector2(); // generate vertices and uvs
  19668. for (let i = 0; i <= segments; i++) {
  19669. const phi = phiStart + i * inverseSegments * phiLength;
  19670. const sin = Math.sin(phi);
  19671. const cos = Math.cos(phi);
  19672. for (let j = 0; j <= points.length - 1; j++) {
  19673. // vertex
  19674. vertex.x = points[j].x * sin;
  19675. vertex.y = points[j].y;
  19676. vertex.z = points[j].x * cos;
  19677. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  19678. uv.x = i / segments;
  19679. uv.y = j / (points.length - 1);
  19680. uvs.push(uv.x, uv.y);
  19681. }
  19682. } // indices
  19683. for (let i = 0; i < segments; i++) {
  19684. for (let j = 0; j < points.length - 1; j++) {
  19685. const base = j + i * points.length;
  19686. const a = base;
  19687. const b = base + points.length;
  19688. const c = base + points.length + 1;
  19689. const d = base + 1; // faces
  19690. indices.push(a, b, d);
  19691. indices.push(b, c, d);
  19692. }
  19693. } // build geometry
  19694. this.setIndex(indices);
  19695. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19696. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
  19697. this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
  19698. // because the corresponding vertices are identical (but still have different UVs).
  19699. if (phiLength === Math.PI * 2) {
  19700. const normals = this.attributes.normal.array;
  19701. const n1 = new Vector3();
  19702. const n2 = new Vector3();
  19703. const n = new Vector3(); // this is the buffer offset for the last line of vertices
  19704. const base = segments * points.length * 3;
  19705. for (let i = 0, j = 0; i < points.length; i++, j += 3) {
  19706. // select the normal of the vertex in the first line
  19707. n1.x = normals[j + 0];
  19708. n1.y = normals[j + 1];
  19709. n1.z = normals[j + 2]; // select the normal of the vertex in the last line
  19710. n2.x = normals[base + j + 0];
  19711. n2.y = normals[base + j + 1];
  19712. n2.z = normals[base + j + 2]; // average normals
  19713. n.addVectors(n1, n2).normalize(); // assign the new values to both normals
  19714. normals[j + 0] = normals[base + j + 0] = n.x;
  19715. normals[j + 1] = normals[base + j + 1] = n.y;
  19716. normals[j + 2] = normals[base + j + 2] = n.z;
  19717. }
  19718. }
  19719. }
  19720. static fromJSON(data) {
  19721. return new LatheGeometry(data.points, data.segments, data.phiStart, data.phiLength);
  19722. }
  19723. }
  19724. class OctahedronGeometry extends PolyhedronGeometry {
  19725. constructor(radius = 1, detail = 0) {
  19726. const vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  19727. 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];
  19728. super(vertices, indices, radius, detail);
  19729. this.type = 'OctahedronGeometry';
  19730. this.parameters = {
  19731. radius: radius,
  19732. detail: detail
  19733. };
  19734. }
  19735. static fromJSON(data) {
  19736. return new OctahedronGeometry(data.radius, data.detail);
  19737. }
  19738. }
  19739. /**
  19740. * Parametric Surfaces Geometry
  19741. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  19742. */
  19743. class ParametricGeometry extends BufferGeometry {
  19744. constructor(func, slices, stacks) {
  19745. super();
  19746. this.type = 'ParametricGeometry';
  19747. this.parameters = {
  19748. func: func,
  19749. slices: slices,
  19750. stacks: stacks
  19751. }; // buffers
  19752. const indices = [];
  19753. const vertices = [];
  19754. const normals = [];
  19755. const uvs = [];
  19756. const EPS = 0.00001;
  19757. const normal = new Vector3();
  19758. const p0 = new Vector3(),
  19759. p1 = new Vector3();
  19760. const pu = new Vector3(),
  19761. pv = new Vector3();
  19762. if (func.length < 3) {
  19763. console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');
  19764. } // generate vertices, normals and uvs
  19765. const sliceCount = slices + 1;
  19766. for (let i = 0; i <= stacks; i++) {
  19767. const v = i / stacks;
  19768. for (let j = 0; j <= slices; j++) {
  19769. const u = j / slices; // vertex
  19770. func(u, v, p0);
  19771. vertices.push(p0.x, p0.y, p0.z); // normal
  19772. // approximate tangent vectors via finite differences
  19773. if (u - EPS >= 0) {
  19774. func(u - EPS, v, p1);
  19775. pu.subVectors(p0, p1);
  19776. } else {
  19777. func(u + EPS, v, p1);
  19778. pu.subVectors(p1, p0);
  19779. }
  19780. if (v - EPS >= 0) {
  19781. func(u, v - EPS, p1);
  19782. pv.subVectors(p0, p1);
  19783. } else {
  19784. func(u, v + EPS, p1);
  19785. pv.subVectors(p1, p0);
  19786. } // cross product of tangent vectors returns surface normal
  19787. normal.crossVectors(pu, pv).normalize();
  19788. normals.push(normal.x, normal.y, normal.z); // uv
  19789. uvs.push(u, v);
  19790. }
  19791. } // generate indices
  19792. for (let i = 0; i < stacks; i++) {
  19793. for (let j = 0; j < slices; j++) {
  19794. const a = i * sliceCount + j;
  19795. const b = i * sliceCount + j + 1;
  19796. const c = (i + 1) * sliceCount + j + 1;
  19797. const d = (i + 1) * sliceCount + j; // faces one and two
  19798. indices.push(a, b, d);
  19799. indices.push(b, c, d);
  19800. }
  19801. } // build geometry
  19802. this.setIndex(indices);
  19803. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19804. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19805. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19806. }
  19807. }
  19808. class RingGeometry extends BufferGeometry {
  19809. constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) {
  19810. super();
  19811. this.type = 'RingGeometry';
  19812. this.parameters = {
  19813. innerRadius: innerRadius,
  19814. outerRadius: outerRadius,
  19815. thetaSegments: thetaSegments,
  19816. phiSegments: phiSegments,
  19817. thetaStart: thetaStart,
  19818. thetaLength: thetaLength
  19819. };
  19820. thetaSegments = Math.max(3, thetaSegments);
  19821. phiSegments = Math.max(1, phiSegments); // buffers
  19822. const indices = [];
  19823. const vertices = [];
  19824. const normals = [];
  19825. const uvs = []; // some helper variables
  19826. let radius = innerRadius;
  19827. const radiusStep = (outerRadius - innerRadius) / phiSegments;
  19828. const vertex = new Vector3();
  19829. const uv = new Vector2(); // generate vertices, normals and uvs
  19830. for (let j = 0; j <= phiSegments; j++) {
  19831. for (let i = 0; i <= thetaSegments; i++) {
  19832. // values are generate from the inside of the ring to the outside
  19833. const segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  19834. vertex.x = radius * Math.cos(segment);
  19835. vertex.y = radius * Math.sin(segment);
  19836. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19837. normals.push(0, 0, 1); // uv
  19838. uv.x = (vertex.x / outerRadius + 1) / 2;
  19839. uv.y = (vertex.y / outerRadius + 1) / 2;
  19840. uvs.push(uv.x, uv.y);
  19841. } // increase the radius for next row of vertices
  19842. radius += radiusStep;
  19843. } // indices
  19844. for (let j = 0; j < phiSegments; j++) {
  19845. const thetaSegmentLevel = j * (thetaSegments + 1);
  19846. for (let i = 0; i < thetaSegments; i++) {
  19847. const segment = i + thetaSegmentLevel;
  19848. const a = segment;
  19849. const b = segment + thetaSegments + 1;
  19850. const c = segment + thetaSegments + 2;
  19851. const d = segment + 1; // faces
  19852. indices.push(a, b, d);
  19853. indices.push(b, c, d);
  19854. }
  19855. } // build geometry
  19856. this.setIndex(indices);
  19857. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19858. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19859. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19860. }
  19861. static fromJSON(data) {
  19862. return new RingGeometry(data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  19863. }
  19864. }
  19865. class ShapeGeometry extends BufferGeometry {
  19866. constructor(shapes, curveSegments = 12) {
  19867. super();
  19868. this.type = 'ShapeGeometry';
  19869. this.parameters = {
  19870. shapes: shapes,
  19871. curveSegments: curveSegments
  19872. }; // buffers
  19873. const indices = [];
  19874. const vertices = [];
  19875. const normals = [];
  19876. const uvs = []; // helper variables
  19877. let groupStart = 0;
  19878. let groupCount = 0; // allow single and array values for "shapes" parameter
  19879. if (Array.isArray(shapes) === false) {
  19880. addShape(shapes);
  19881. } else {
  19882. for (let i = 0; i < shapes.length; i++) {
  19883. addShape(shapes[i]);
  19884. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  19885. groupStart += groupCount;
  19886. groupCount = 0;
  19887. }
  19888. } // build geometry
  19889. this.setIndex(indices);
  19890. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19891. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19892. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  19893. function addShape(shape) {
  19894. const indexOffset = vertices.length / 3;
  19895. const points = shape.extractPoints(curveSegments);
  19896. let shapeVertices = points.shape;
  19897. const shapeHoles = points.holes; // check direction of vertices
  19898. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  19899. shapeVertices = shapeVertices.reverse();
  19900. }
  19901. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  19902. const shapeHole = shapeHoles[i];
  19903. if (ShapeUtils.isClockWise(shapeHole) === true) {
  19904. shapeHoles[i] = shapeHole.reverse();
  19905. }
  19906. }
  19907. const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  19908. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  19909. const shapeHole = shapeHoles[i];
  19910. shapeVertices = shapeVertices.concat(shapeHole);
  19911. } // vertices, normals, uvs
  19912. for (let i = 0, l = shapeVertices.length; i < l; i++) {
  19913. const vertex = shapeVertices[i];
  19914. vertices.push(vertex.x, vertex.y, 0);
  19915. normals.push(0, 0, 1);
  19916. uvs.push(vertex.x, vertex.y); // world uvs
  19917. } // incides
  19918. for (let i = 0, l = faces.length; i < l; i++) {
  19919. const face = faces[i];
  19920. const a = face[0] + indexOffset;
  19921. const b = face[1] + indexOffset;
  19922. const c = face[2] + indexOffset;
  19923. indices.push(a, b, c);
  19924. groupCount += 3;
  19925. }
  19926. }
  19927. }
  19928. toJSON() {
  19929. const data = super.toJSON();
  19930. const shapes = this.parameters.shapes;
  19931. return toJSON(shapes, data);
  19932. }
  19933. static fromJSON(data, shapes) {
  19934. const geometryShapes = [];
  19935. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  19936. const shape = shapes[data.shapes[j]];
  19937. geometryShapes.push(shape);
  19938. }
  19939. return new ShapeGeometry(geometryShapes, data.curveSegments);
  19940. }
  19941. }
  19942. function toJSON(shapes, data) {
  19943. data.shapes = [];
  19944. if (Array.isArray(shapes)) {
  19945. for (let i = 0, l = shapes.length; i < l; i++) {
  19946. const shape = shapes[i];
  19947. data.shapes.push(shape.uuid);
  19948. }
  19949. } else {
  19950. data.shapes.push(shapes.uuid);
  19951. }
  19952. return data;
  19953. }
  19954. class SphereGeometry extends BufferGeometry {
  19955. constructor(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) {
  19956. super();
  19957. this.type = 'SphereGeometry';
  19958. this.parameters = {
  19959. radius: radius,
  19960. widthSegments: widthSegments,
  19961. heightSegments: heightSegments,
  19962. phiStart: phiStart,
  19963. phiLength: phiLength,
  19964. thetaStart: thetaStart,
  19965. thetaLength: thetaLength
  19966. };
  19967. widthSegments = Math.max(3, Math.floor(widthSegments));
  19968. heightSegments = Math.max(2, Math.floor(heightSegments));
  19969. const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  19970. let index = 0;
  19971. const grid = [];
  19972. const vertex = new Vector3();
  19973. const normal = new Vector3(); // buffers
  19974. const indices = [];
  19975. const vertices = [];
  19976. const normals = [];
  19977. const uvs = []; // generate vertices, normals and uvs
  19978. for (let iy = 0; iy <= heightSegments; iy++) {
  19979. const verticesRow = [];
  19980. const v = iy / heightSegments; // special case for the poles
  19981. let uOffset = 0;
  19982. if (iy == 0 && thetaStart == 0) {
  19983. uOffset = 0.5 / widthSegments;
  19984. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  19985. uOffset = -0.5 / widthSegments;
  19986. }
  19987. for (let ix = 0; ix <= widthSegments; ix++) {
  19988. const u = ix / widthSegments; // vertex
  19989. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  19990. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  19991. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  19992. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19993. normal.copy(vertex).normalize();
  19994. normals.push(normal.x, normal.y, normal.z); // uv
  19995. uvs.push(u + uOffset, 1 - v);
  19996. verticesRow.push(index++);
  19997. }
  19998. grid.push(verticesRow);
  19999. } // indices
  20000. for (let iy = 0; iy < heightSegments; iy++) {
  20001. for (let ix = 0; ix < widthSegments; ix++) {
  20002. const a = grid[iy][ix + 1];
  20003. const b = grid[iy][ix];
  20004. const c = grid[iy + 1][ix];
  20005. const d = grid[iy + 1][ix + 1];
  20006. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  20007. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  20008. }
  20009. } // build geometry
  20010. this.setIndex(indices);
  20011. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20012. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20013. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20014. }
  20015. static fromJSON(data) {
  20016. return new SphereGeometry(data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  20017. }
  20018. }
  20019. class TetrahedronGeometry extends PolyhedronGeometry {
  20020. constructor(radius = 1, detail = 0) {
  20021. const vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  20022. const indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  20023. super(vertices, indices, radius, detail);
  20024. this.type = 'TetrahedronGeometry';
  20025. this.parameters = {
  20026. radius: radius,
  20027. detail: detail
  20028. };
  20029. }
  20030. static fromJSON(data) {
  20031. return new TetrahedronGeometry(data.radius, data.detail);
  20032. }
  20033. }
  20034. /**
  20035. * Text = 3D Text
  20036. *
  20037. * parameters = {
  20038. * font: <THREE.Font>, // font
  20039. *
  20040. * size: <float>, // size of the text
  20041. * height: <float>, // thickness to extrude text
  20042. * curveSegments: <int>, // number of points on the curves
  20043. *
  20044. * bevelEnabled: <bool>, // turn on bevel
  20045. * bevelThickness: <float>, // how deep into text bevel goes
  20046. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  20047. * bevelOffset: <float> // how far from text outline does bevel start
  20048. * }
  20049. */
  20050. class TextGeometry extends ExtrudeGeometry {
  20051. constructor(text, parameters = {}) {
  20052. const font = parameters.font;
  20053. if (!(font && font.isFont)) {
  20054. console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');
  20055. return new BufferGeometry();
  20056. }
  20057. const shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry API
  20058. parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults
  20059. if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;
  20060. if (parameters.bevelSize === undefined) parameters.bevelSize = 8;
  20061. if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;
  20062. super(shapes, parameters);
  20063. this.type = 'TextGeometry';
  20064. }
  20065. }
  20066. class TorusGeometry extends BufferGeometry {
  20067. constructor(radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) {
  20068. super();
  20069. this.type = 'TorusGeometry';
  20070. this.parameters = {
  20071. radius: radius,
  20072. tube: tube,
  20073. radialSegments: radialSegments,
  20074. tubularSegments: tubularSegments,
  20075. arc: arc
  20076. };
  20077. radialSegments = Math.floor(radialSegments);
  20078. tubularSegments = Math.floor(tubularSegments); // buffers
  20079. const indices = [];
  20080. const vertices = [];
  20081. const normals = [];
  20082. const uvs = []; // helper variables
  20083. const center = new Vector3();
  20084. const vertex = new Vector3();
  20085. const normal = new Vector3(); // generate vertices, normals and uvs
  20086. for (let j = 0; j <= radialSegments; j++) {
  20087. for (let i = 0; i <= tubularSegments; i++) {
  20088. const u = i / tubularSegments * arc;
  20089. const v = j / radialSegments * Math.PI * 2; // vertex
  20090. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  20091. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  20092. vertex.z = tube * Math.sin(v);
  20093. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20094. center.x = radius * Math.cos(u);
  20095. center.y = radius * Math.sin(u);
  20096. normal.subVectors(vertex, center).normalize();
  20097. normals.push(normal.x, normal.y, normal.z); // uv
  20098. uvs.push(i / tubularSegments);
  20099. uvs.push(j / radialSegments);
  20100. }
  20101. } // generate indices
  20102. for (let j = 1; j <= radialSegments; j++) {
  20103. for (let i = 1; i <= tubularSegments; i++) {
  20104. // indices
  20105. const a = (tubularSegments + 1) * j + i - 1;
  20106. const b = (tubularSegments + 1) * (j - 1) + i - 1;
  20107. const c = (tubularSegments + 1) * (j - 1) + i;
  20108. const d = (tubularSegments + 1) * j + i; // faces
  20109. indices.push(a, b, d);
  20110. indices.push(b, c, d);
  20111. }
  20112. } // build geometry
  20113. this.setIndex(indices);
  20114. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20115. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20116. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20117. }
  20118. static fromJSON(data) {
  20119. return new TorusGeometry(data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  20120. }
  20121. }
  20122. class TorusKnotGeometry extends BufferGeometry {
  20123. constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) {
  20124. super();
  20125. this.type = 'TorusKnotGeometry';
  20126. this.parameters = {
  20127. radius: radius,
  20128. tube: tube,
  20129. tubularSegments: tubularSegments,
  20130. radialSegments: radialSegments,
  20131. p: p,
  20132. q: q
  20133. };
  20134. tubularSegments = Math.floor(tubularSegments);
  20135. radialSegments = Math.floor(radialSegments); // buffers
  20136. const indices = [];
  20137. const vertices = [];
  20138. const normals = [];
  20139. const uvs = []; // helper variables
  20140. const vertex = new Vector3();
  20141. const normal = new Vector3();
  20142. const P1 = new Vector3();
  20143. const P2 = new Vector3();
  20144. const B = new Vector3();
  20145. const T = new Vector3();
  20146. const N = new Vector3(); // generate vertices, normals and uvs
  20147. for (let i = 0; i <= tubularSegments; ++i) {
  20148. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  20149. 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.
  20150. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  20151. calculatePositionOnCurve(u, p, q, radius, P1);
  20152. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  20153. T.subVectors(P2, P1);
  20154. N.addVectors(P2, P1);
  20155. B.crossVectors(T, N);
  20156. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  20157. B.normalize();
  20158. N.normalize();
  20159. for (let j = 0; j <= radialSegments; ++j) {
  20160. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  20161. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  20162. const v = j / radialSegments * Math.PI * 2;
  20163. const cx = -tube * Math.cos(v);
  20164. const cy = tube * Math.sin(v); // now calculate the final vertex position.
  20165. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  20166. vertex.x = P1.x + (cx * N.x + cy * B.x);
  20167. vertex.y = P1.y + (cx * N.y + cy * B.y);
  20168. vertex.z = P1.z + (cx * N.z + cy * B.z);
  20169. 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)
  20170. normal.subVectors(vertex, P1).normalize();
  20171. normals.push(normal.x, normal.y, normal.z); // uv
  20172. uvs.push(i / tubularSegments);
  20173. uvs.push(j / radialSegments);
  20174. }
  20175. } // generate indices
  20176. for (let j = 1; j <= tubularSegments; j++) {
  20177. for (let i = 1; i <= radialSegments; i++) {
  20178. // indices
  20179. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  20180. const b = (radialSegments + 1) * j + (i - 1);
  20181. const c = (radialSegments + 1) * j + i;
  20182. const d = (radialSegments + 1) * (j - 1) + i; // faces
  20183. indices.push(a, b, d);
  20184. indices.push(b, c, d);
  20185. }
  20186. } // build geometry
  20187. this.setIndex(indices);
  20188. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20189. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20190. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  20191. function calculatePositionOnCurve(u, p, q, radius, position) {
  20192. const cu = Math.cos(u);
  20193. const su = Math.sin(u);
  20194. const quOverP = q / p * u;
  20195. const cs = Math.cos(quOverP);
  20196. position.x = radius * (2 + cs) * 0.5 * cu;
  20197. position.y = radius * (2 + cs) * su * 0.5;
  20198. position.z = radius * Math.sin(quOverP) * 0.5;
  20199. }
  20200. }
  20201. static fromJSON(data) {
  20202. return new TorusKnotGeometry(data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  20203. }
  20204. }
  20205. class TubeGeometry extends BufferGeometry {
  20206. constructor(path, tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) {
  20207. super();
  20208. this.type = 'TubeGeometry';
  20209. this.parameters = {
  20210. path: path,
  20211. tubularSegments: tubularSegments,
  20212. radius: radius,
  20213. radialSegments: radialSegments,
  20214. closed: closed
  20215. };
  20216. const frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  20217. this.tangents = frames.tangents;
  20218. this.normals = frames.normals;
  20219. this.binormals = frames.binormals; // helper variables
  20220. const vertex = new Vector3();
  20221. const normal = new Vector3();
  20222. const uv = new Vector2();
  20223. let P = new Vector3(); // buffer
  20224. const vertices = [];
  20225. const normals = [];
  20226. const uvs = [];
  20227. const indices = []; // create buffer data
  20228. generateBufferData(); // build geometry
  20229. this.setIndex(indices);
  20230. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20231. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20232. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  20233. function generateBufferData() {
  20234. for (let i = 0; i < tubularSegments; i++) {
  20235. generateSegment(i);
  20236. } // if the geometry is not closed, generate the last row of vertices and normals
  20237. // at the regular position on the given path
  20238. //
  20239. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  20240. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  20241. // this makes it easy compute correct values for closed geometries
  20242. generateUVs(); // finally create faces
  20243. generateIndices();
  20244. }
  20245. function generateSegment(i) {
  20246. // we use getPointAt to sample evenly distributed points from the given path
  20247. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  20248. const N = frames.normals[i];
  20249. const B = frames.binormals[i]; // generate normals and vertices for the current segment
  20250. for (let j = 0; j <= radialSegments; j++) {
  20251. const v = j / radialSegments * Math.PI * 2;
  20252. const sin = Math.sin(v);
  20253. const cos = -Math.cos(v); // normal
  20254. normal.x = cos * N.x + sin * B.x;
  20255. normal.y = cos * N.y + sin * B.y;
  20256. normal.z = cos * N.z + sin * B.z;
  20257. normal.normalize();
  20258. normals.push(normal.x, normal.y, normal.z); // vertex
  20259. vertex.x = P.x + radius * normal.x;
  20260. vertex.y = P.y + radius * normal.y;
  20261. vertex.z = P.z + radius * normal.z;
  20262. vertices.push(vertex.x, vertex.y, vertex.z);
  20263. }
  20264. }
  20265. function generateIndices() {
  20266. for (let j = 1; j <= tubularSegments; j++) {
  20267. for (let i = 1; i <= radialSegments; i++) {
  20268. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  20269. const b = (radialSegments + 1) * j + (i - 1);
  20270. const c = (radialSegments + 1) * j + i;
  20271. const d = (radialSegments + 1) * (j - 1) + i; // faces
  20272. indices.push(a, b, d);
  20273. indices.push(b, c, d);
  20274. }
  20275. }
  20276. }
  20277. function generateUVs() {
  20278. for (let i = 0; i <= tubularSegments; i++) {
  20279. for (let j = 0; j <= radialSegments; j++) {
  20280. uv.x = i / tubularSegments;
  20281. uv.y = j / radialSegments;
  20282. uvs.push(uv.x, uv.y);
  20283. }
  20284. }
  20285. }
  20286. }
  20287. toJSON() {
  20288. const data = super.toJSON();
  20289. data.path = this.parameters.path.toJSON();
  20290. return data;
  20291. }
  20292. static fromJSON(data) {
  20293. // This only works for built-in curves (e.g. CatmullRomCurve3).
  20294. // User defined curves or instances of CurvePath will not be deserialized.
  20295. return new TubeGeometry(new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  20296. }
  20297. }
  20298. class WireframeGeometry extends BufferGeometry {
  20299. constructor(geometry) {
  20300. super();
  20301. this.type = 'WireframeGeometry';
  20302. if (geometry.isGeometry === true) {
  20303. console.error('THREE.WireframeGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  20304. return;
  20305. } // buffer
  20306. const vertices = [];
  20307. const edges = new Set(); // helper variables
  20308. const start = new Vector3();
  20309. const end = new Vector3();
  20310. if (geometry.index !== null) {
  20311. // indexed BufferGeometry
  20312. const position = geometry.attributes.position;
  20313. const indices = geometry.index;
  20314. let groups = geometry.groups;
  20315. if (groups.length === 0) {
  20316. groups = [{
  20317. start: 0,
  20318. count: indices.count,
  20319. materialIndex: 0
  20320. }];
  20321. } // create a data structure that contains all eges without duplicates
  20322. for (let o = 0, ol = groups.length; o < ol; ++o) {
  20323. const group = groups[o];
  20324. const groupStart = group.start;
  20325. const groupCount = group.count;
  20326. for (let i = groupStart, l = groupStart + groupCount; i < l; i += 3) {
  20327. for (let j = 0; j < 3; j++) {
  20328. const index1 = indices.getX(i + j);
  20329. const index2 = indices.getX(i + (j + 1) % 3);
  20330. start.fromBufferAttribute(position, index1);
  20331. end.fromBufferAttribute(position, index2);
  20332. if (isUniqueEdge(start, end, edges) === true) {
  20333. vertices.push(start.x, start.y, start.z);
  20334. vertices.push(end.x, end.y, end.z);
  20335. }
  20336. }
  20337. }
  20338. }
  20339. } else {
  20340. // non-indexed BufferGeometry
  20341. const position = geometry.attributes.position;
  20342. for (let i = 0, l = position.count / 3; i < l; i++) {
  20343. for (let j = 0; j < 3; j++) {
  20344. // three edges per triangle, an edge is represented as (index1, index2)
  20345. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  20346. const index1 = 3 * i + j;
  20347. const index2 = 3 * i + (j + 1) % 3;
  20348. start.fromBufferAttribute(position, index1);
  20349. end.fromBufferAttribute(position, index2);
  20350. if (isUniqueEdge(start, end, edges) === true) {
  20351. vertices.push(start.x, start.y, start.z);
  20352. vertices.push(end.x, end.y, end.z);
  20353. }
  20354. }
  20355. }
  20356. } // build geometry
  20357. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20358. }
  20359. }
  20360. function isUniqueEdge(start, end, edges) {
  20361. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  20362. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  20363. if (edges.has(hash1) === true || edges.has(hash2) === true) {
  20364. return false;
  20365. } else {
  20366. edges.add(hash1, hash2);
  20367. return true;
  20368. }
  20369. }
  20370. var Geometries = /*#__PURE__*/Object.freeze({
  20371. __proto__: null,
  20372. BoxGeometry: BoxGeometry,
  20373. BoxBufferGeometry: BoxGeometry,
  20374. CircleGeometry: CircleGeometry,
  20375. CircleBufferGeometry: CircleGeometry,
  20376. ConeGeometry: ConeGeometry,
  20377. ConeBufferGeometry: ConeGeometry,
  20378. CylinderGeometry: CylinderGeometry,
  20379. CylinderBufferGeometry: CylinderGeometry,
  20380. DodecahedronGeometry: DodecahedronGeometry,
  20381. DodecahedronBufferGeometry: DodecahedronGeometry,
  20382. EdgesGeometry: EdgesGeometry,
  20383. ExtrudeGeometry: ExtrudeGeometry,
  20384. ExtrudeBufferGeometry: ExtrudeGeometry,
  20385. IcosahedronGeometry: IcosahedronGeometry,
  20386. IcosahedronBufferGeometry: IcosahedronGeometry,
  20387. LatheGeometry: LatheGeometry,
  20388. LatheBufferGeometry: LatheGeometry,
  20389. OctahedronGeometry: OctahedronGeometry,
  20390. OctahedronBufferGeometry: OctahedronGeometry,
  20391. ParametricGeometry: ParametricGeometry,
  20392. ParametricBufferGeometry: ParametricGeometry,
  20393. PlaneGeometry: PlaneGeometry,
  20394. PlaneBufferGeometry: PlaneGeometry,
  20395. PolyhedronGeometry: PolyhedronGeometry,
  20396. PolyhedronBufferGeometry: PolyhedronGeometry,
  20397. RingGeometry: RingGeometry,
  20398. RingBufferGeometry: RingGeometry,
  20399. ShapeGeometry: ShapeGeometry,
  20400. ShapeBufferGeometry: ShapeGeometry,
  20401. SphereGeometry: SphereGeometry,
  20402. SphereBufferGeometry: SphereGeometry,
  20403. TetrahedronGeometry: TetrahedronGeometry,
  20404. TetrahedronBufferGeometry: TetrahedronGeometry,
  20405. TextGeometry: TextGeometry,
  20406. TextBufferGeometry: TextGeometry,
  20407. TorusGeometry: TorusGeometry,
  20408. TorusBufferGeometry: TorusGeometry,
  20409. TorusKnotGeometry: TorusKnotGeometry,
  20410. TorusKnotBufferGeometry: TorusKnotGeometry,
  20411. TubeGeometry: TubeGeometry,
  20412. TubeBufferGeometry: TubeGeometry,
  20413. WireframeGeometry: WireframeGeometry
  20414. });
  20415. /**
  20416. * parameters = {
  20417. * color: <THREE.Color>
  20418. * }
  20419. */
  20420. class ShadowMaterial extends Material {
  20421. constructor(parameters) {
  20422. super();
  20423. this.type = 'ShadowMaterial';
  20424. this.color = new Color(0x000000);
  20425. this.transparent = true;
  20426. this.setValues(parameters);
  20427. }
  20428. copy(source) {
  20429. super.copy(source);
  20430. this.color.copy(source.color);
  20431. return this;
  20432. }
  20433. }
  20434. ShadowMaterial.prototype.isShadowMaterial = true;
  20435. /**
  20436. * parameters = {
  20437. * color: <hex>,
  20438. * roughness: <float>,
  20439. * metalness: <float>,
  20440. * opacity: <float>,
  20441. *
  20442. * map: new THREE.Texture( <Image> ),
  20443. *
  20444. * lightMap: new THREE.Texture( <Image> ),
  20445. * lightMapIntensity: <float>
  20446. *
  20447. * aoMap: new THREE.Texture( <Image> ),
  20448. * aoMapIntensity: <float>
  20449. *
  20450. * emissive: <hex>,
  20451. * emissiveIntensity: <float>
  20452. * emissiveMap: new THREE.Texture( <Image> ),
  20453. *
  20454. * bumpMap: new THREE.Texture( <Image> ),
  20455. * bumpScale: <float>,
  20456. *
  20457. * normalMap: new THREE.Texture( <Image> ),
  20458. * normalMapType: THREE.TangentSpaceNormalMap,
  20459. * normalScale: <Vector2>,
  20460. *
  20461. * displacementMap: new THREE.Texture( <Image> ),
  20462. * displacementScale: <float>,
  20463. * displacementBias: <float>,
  20464. *
  20465. * roughnessMap: new THREE.Texture( <Image> ),
  20466. *
  20467. * metalnessMap: new THREE.Texture( <Image> ),
  20468. *
  20469. * alphaMap: new THREE.Texture( <Image> ),
  20470. *
  20471. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20472. * envMapIntensity: <float>
  20473. *
  20474. * refractionRatio: <float>,
  20475. *
  20476. * wireframe: <boolean>,
  20477. * wireframeLinewidth: <float>,
  20478. *
  20479. * flatShading: <bool>
  20480. * }
  20481. */
  20482. class MeshStandardMaterial extends Material {
  20483. constructor(parameters) {
  20484. super();
  20485. this.defines = {
  20486. 'STANDARD': ''
  20487. };
  20488. this.type = 'MeshStandardMaterial';
  20489. this.color = new Color(0xffffff); // diffuse
  20490. this.roughness = 1.0;
  20491. this.metalness = 0.0;
  20492. this.map = null;
  20493. this.lightMap = null;
  20494. this.lightMapIntensity = 1.0;
  20495. this.aoMap = null;
  20496. this.aoMapIntensity = 1.0;
  20497. this.emissive = new Color(0x000000);
  20498. this.emissiveIntensity = 1.0;
  20499. this.emissiveMap = null;
  20500. this.bumpMap = null;
  20501. this.bumpScale = 1;
  20502. this.normalMap = null;
  20503. this.normalMapType = TangentSpaceNormalMap;
  20504. this.normalScale = new Vector2(1, 1);
  20505. this.displacementMap = null;
  20506. this.displacementScale = 1;
  20507. this.displacementBias = 0;
  20508. this.roughnessMap = null;
  20509. this.metalnessMap = null;
  20510. this.alphaMap = null;
  20511. this.envMap = null;
  20512. this.envMapIntensity = 1.0;
  20513. this.refractionRatio = 0.98;
  20514. this.wireframe = false;
  20515. this.wireframeLinewidth = 1;
  20516. this.wireframeLinecap = 'round';
  20517. this.wireframeLinejoin = 'round';
  20518. this.flatShading = false;
  20519. this.setValues(parameters);
  20520. }
  20521. copy(source) {
  20522. super.copy(source);
  20523. this.defines = {
  20524. 'STANDARD': ''
  20525. };
  20526. this.color.copy(source.color);
  20527. this.roughness = source.roughness;
  20528. this.metalness = source.metalness;
  20529. this.map = source.map;
  20530. this.lightMap = source.lightMap;
  20531. this.lightMapIntensity = source.lightMapIntensity;
  20532. this.aoMap = source.aoMap;
  20533. this.aoMapIntensity = source.aoMapIntensity;
  20534. this.emissive.copy(source.emissive);
  20535. this.emissiveMap = source.emissiveMap;
  20536. this.emissiveIntensity = source.emissiveIntensity;
  20537. this.bumpMap = source.bumpMap;
  20538. this.bumpScale = source.bumpScale;
  20539. this.normalMap = source.normalMap;
  20540. this.normalMapType = source.normalMapType;
  20541. this.normalScale.copy(source.normalScale);
  20542. this.displacementMap = source.displacementMap;
  20543. this.displacementScale = source.displacementScale;
  20544. this.displacementBias = source.displacementBias;
  20545. this.roughnessMap = source.roughnessMap;
  20546. this.metalnessMap = source.metalnessMap;
  20547. this.alphaMap = source.alphaMap;
  20548. this.envMap = source.envMap;
  20549. this.envMapIntensity = source.envMapIntensity;
  20550. this.refractionRatio = source.refractionRatio;
  20551. this.wireframe = source.wireframe;
  20552. this.wireframeLinewidth = source.wireframeLinewidth;
  20553. this.wireframeLinecap = source.wireframeLinecap;
  20554. this.wireframeLinejoin = source.wireframeLinejoin;
  20555. this.flatShading = source.flatShading;
  20556. return this;
  20557. }
  20558. }
  20559. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  20560. /**
  20561. * parameters = {
  20562. * clearcoat: <float>,
  20563. * clearcoatMap: new THREE.Texture( <Image> ),
  20564. * clearcoatRoughness: <float>,
  20565. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  20566. * clearcoatNormalScale: <Vector2>,
  20567. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  20568. *
  20569. * ior: <float>,
  20570. * reflectivity: <float>,
  20571. *
  20572. * sheen: <Color>,
  20573. *
  20574. * transmission: <float>,
  20575. * transmissionMap: new THREE.Texture( <Image> ),
  20576. *
  20577. * thickness: <float>,
  20578. * thicknessMap: new THREE.Texture( <Image> ),
  20579. * attenuationDistance: <float>,
  20580. * attenuationTint: <Color>,
  20581. *
  20582. * specularIntensity: <float>,
  20583. * specularIntensityhMap: new THREE.Texture( <Image> ),
  20584. * specularTint: <Color>,
  20585. * specularTintMap: new THREE.Texture( <Image> )
  20586. * }
  20587. */
  20588. class MeshPhysicalMaterial extends MeshStandardMaterial {
  20589. constructor(parameters) {
  20590. super();
  20591. this.defines = {
  20592. 'STANDARD': '',
  20593. 'PHYSICAL': ''
  20594. };
  20595. this.type = 'MeshPhysicalMaterial';
  20596. this.clearcoat = 0.0;
  20597. this.clearcoatMap = null;
  20598. this.clearcoatRoughness = 0.0;
  20599. this.clearcoatRoughnessMap = null;
  20600. this.clearcoatNormalScale = new Vector2(1, 1);
  20601. this.clearcoatNormalMap = null;
  20602. this.ior = 1.5;
  20603. Object.defineProperty(this, 'reflectivity', {
  20604. get: function () {
  20605. return clamp(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1);
  20606. },
  20607. set: function (reflectivity) {
  20608. this.ior = (1 + 0.4 * reflectivity) / (1 - 0.4 * reflectivity);
  20609. }
  20610. });
  20611. this.sheen = null; // null will disable sheen bsdf
  20612. this.transmission = 0.0;
  20613. this.transmissionMap = null;
  20614. this.thickness = 0.01;
  20615. this.thicknessMap = null;
  20616. this.attenuationDistance = 0.0;
  20617. this.attenuationTint = new Color(1, 1, 1);
  20618. this.specularIntensity = 1.0;
  20619. this.specularIntensityMap = null;
  20620. this.specularTint = new Color(1, 1, 1);
  20621. this.specularTintMap = null;
  20622. this.setValues(parameters);
  20623. }
  20624. copy(source) {
  20625. super.copy(source);
  20626. this.defines = {
  20627. 'STANDARD': '',
  20628. 'PHYSICAL': ''
  20629. };
  20630. this.clearcoat = source.clearcoat;
  20631. this.clearcoatMap = source.clearcoatMap;
  20632. this.clearcoatRoughness = source.clearcoatRoughness;
  20633. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  20634. this.clearcoatNormalMap = source.clearcoatNormalMap;
  20635. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  20636. this.ior = source.ior;
  20637. if (source.sheen) {
  20638. this.sheen = (this.sheen || new Color()).copy(source.sheen);
  20639. } else {
  20640. this.sheen = null;
  20641. }
  20642. this.transmission = source.transmission;
  20643. this.transmissionMap = source.transmissionMap;
  20644. this.thickness = source.thickness;
  20645. this.thicknessMap = source.thicknessMap;
  20646. this.attenuationDistance = source.attenuationDistance;
  20647. this.attenuationTint.copy(source.attenuationTint);
  20648. this.specularIntensity = source.specularIntensity;
  20649. this.specularIntensityMap = source.specularIntensityMap;
  20650. this.specularTint.copy(source.specularTint);
  20651. this.specularTintMap = source.specularTintMap;
  20652. return this;
  20653. }
  20654. }
  20655. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  20656. /**
  20657. * parameters = {
  20658. * color: <hex>,
  20659. * specular: <hex>,
  20660. * shininess: <float>,
  20661. * opacity: <float>,
  20662. *
  20663. * map: new THREE.Texture( <Image> ),
  20664. *
  20665. * lightMap: new THREE.Texture( <Image> ),
  20666. * lightMapIntensity: <float>
  20667. *
  20668. * aoMap: new THREE.Texture( <Image> ),
  20669. * aoMapIntensity: <float>
  20670. *
  20671. * emissive: <hex>,
  20672. * emissiveIntensity: <float>
  20673. * emissiveMap: new THREE.Texture( <Image> ),
  20674. *
  20675. * bumpMap: new THREE.Texture( <Image> ),
  20676. * bumpScale: <float>,
  20677. *
  20678. * normalMap: new THREE.Texture( <Image> ),
  20679. * normalMapType: THREE.TangentSpaceNormalMap,
  20680. * normalScale: <Vector2>,
  20681. *
  20682. * displacementMap: new THREE.Texture( <Image> ),
  20683. * displacementScale: <float>,
  20684. * displacementBias: <float>,
  20685. *
  20686. * specularMap: new THREE.Texture( <Image> ),
  20687. *
  20688. * alphaMap: new THREE.Texture( <Image> ),
  20689. *
  20690. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20691. * combine: THREE.MultiplyOperation,
  20692. * reflectivity: <float>,
  20693. * refractionRatio: <float>,
  20694. *
  20695. * wireframe: <boolean>,
  20696. * wireframeLinewidth: <float>,
  20697. *
  20698. * flatShading: <bool>
  20699. * }
  20700. */
  20701. class MeshPhongMaterial extends Material {
  20702. constructor(parameters) {
  20703. super();
  20704. this.type = 'MeshPhongMaterial';
  20705. this.color = new Color(0xffffff); // diffuse
  20706. this.specular = new Color(0x111111);
  20707. this.shininess = 30;
  20708. this.map = null;
  20709. this.lightMap = null;
  20710. this.lightMapIntensity = 1.0;
  20711. this.aoMap = null;
  20712. this.aoMapIntensity = 1.0;
  20713. this.emissive = new Color(0x000000);
  20714. this.emissiveIntensity = 1.0;
  20715. this.emissiveMap = null;
  20716. this.bumpMap = null;
  20717. this.bumpScale = 1;
  20718. this.normalMap = null;
  20719. this.normalMapType = TangentSpaceNormalMap;
  20720. this.normalScale = new Vector2(1, 1);
  20721. this.displacementMap = null;
  20722. this.displacementScale = 1;
  20723. this.displacementBias = 0;
  20724. this.specularMap = null;
  20725. this.alphaMap = null;
  20726. this.envMap = null;
  20727. this.combine = MultiplyOperation;
  20728. this.reflectivity = 1;
  20729. this.refractionRatio = 0.98;
  20730. this.wireframe = false;
  20731. this.wireframeLinewidth = 1;
  20732. this.wireframeLinecap = 'round';
  20733. this.wireframeLinejoin = 'round';
  20734. this.flatShading = false;
  20735. this.setValues(parameters);
  20736. }
  20737. copy(source) {
  20738. super.copy(source);
  20739. this.color.copy(source.color);
  20740. this.specular.copy(source.specular);
  20741. this.shininess = source.shininess;
  20742. this.map = source.map;
  20743. this.lightMap = source.lightMap;
  20744. this.lightMapIntensity = source.lightMapIntensity;
  20745. this.aoMap = source.aoMap;
  20746. this.aoMapIntensity = source.aoMapIntensity;
  20747. this.emissive.copy(source.emissive);
  20748. this.emissiveMap = source.emissiveMap;
  20749. this.emissiveIntensity = source.emissiveIntensity;
  20750. this.bumpMap = source.bumpMap;
  20751. this.bumpScale = source.bumpScale;
  20752. this.normalMap = source.normalMap;
  20753. this.normalMapType = source.normalMapType;
  20754. this.normalScale.copy(source.normalScale);
  20755. this.displacementMap = source.displacementMap;
  20756. this.displacementScale = source.displacementScale;
  20757. this.displacementBias = source.displacementBias;
  20758. this.specularMap = source.specularMap;
  20759. this.alphaMap = source.alphaMap;
  20760. this.envMap = source.envMap;
  20761. this.combine = source.combine;
  20762. this.reflectivity = source.reflectivity;
  20763. this.refractionRatio = source.refractionRatio;
  20764. this.wireframe = source.wireframe;
  20765. this.wireframeLinewidth = source.wireframeLinewidth;
  20766. this.wireframeLinecap = source.wireframeLinecap;
  20767. this.wireframeLinejoin = source.wireframeLinejoin;
  20768. this.flatShading = source.flatShading;
  20769. return this;
  20770. }
  20771. }
  20772. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  20773. /**
  20774. * parameters = {
  20775. * color: <hex>,
  20776. *
  20777. * map: new THREE.Texture( <Image> ),
  20778. * gradientMap: new THREE.Texture( <Image> ),
  20779. *
  20780. * lightMap: new THREE.Texture( <Image> ),
  20781. * lightMapIntensity: <float>
  20782. *
  20783. * aoMap: new THREE.Texture( <Image> ),
  20784. * aoMapIntensity: <float>
  20785. *
  20786. * emissive: <hex>,
  20787. * emissiveIntensity: <float>
  20788. * emissiveMap: new THREE.Texture( <Image> ),
  20789. *
  20790. * bumpMap: new THREE.Texture( <Image> ),
  20791. * bumpScale: <float>,
  20792. *
  20793. * normalMap: new THREE.Texture( <Image> ),
  20794. * normalMapType: THREE.TangentSpaceNormalMap,
  20795. * normalScale: <Vector2>,
  20796. *
  20797. * displacementMap: new THREE.Texture( <Image> ),
  20798. * displacementScale: <float>,
  20799. * displacementBias: <float>,
  20800. *
  20801. * alphaMap: new THREE.Texture( <Image> ),
  20802. *
  20803. * wireframe: <boolean>,
  20804. * wireframeLinewidth: <float>,
  20805. *
  20806. * }
  20807. */
  20808. class MeshToonMaterial extends Material {
  20809. constructor(parameters) {
  20810. super();
  20811. this.defines = {
  20812. 'TOON': ''
  20813. };
  20814. this.type = 'MeshToonMaterial';
  20815. this.color = new Color(0xffffff);
  20816. this.map = null;
  20817. this.gradientMap = null;
  20818. this.lightMap = null;
  20819. this.lightMapIntensity = 1.0;
  20820. this.aoMap = null;
  20821. this.aoMapIntensity = 1.0;
  20822. this.emissive = new Color(0x000000);
  20823. this.emissiveIntensity = 1.0;
  20824. this.emissiveMap = null;
  20825. this.bumpMap = null;
  20826. this.bumpScale = 1;
  20827. this.normalMap = null;
  20828. this.normalMapType = TangentSpaceNormalMap;
  20829. this.normalScale = new Vector2(1, 1);
  20830. this.displacementMap = null;
  20831. this.displacementScale = 1;
  20832. this.displacementBias = 0;
  20833. this.alphaMap = null;
  20834. this.wireframe = false;
  20835. this.wireframeLinewidth = 1;
  20836. this.wireframeLinecap = 'round';
  20837. this.wireframeLinejoin = 'round';
  20838. this.setValues(parameters);
  20839. }
  20840. copy(source) {
  20841. super.copy(source);
  20842. this.color.copy(source.color);
  20843. this.map = source.map;
  20844. this.gradientMap = source.gradientMap;
  20845. this.lightMap = source.lightMap;
  20846. this.lightMapIntensity = source.lightMapIntensity;
  20847. this.aoMap = source.aoMap;
  20848. this.aoMapIntensity = source.aoMapIntensity;
  20849. this.emissive.copy(source.emissive);
  20850. this.emissiveMap = source.emissiveMap;
  20851. this.emissiveIntensity = source.emissiveIntensity;
  20852. this.bumpMap = source.bumpMap;
  20853. this.bumpScale = source.bumpScale;
  20854. this.normalMap = source.normalMap;
  20855. this.normalMapType = source.normalMapType;
  20856. this.normalScale.copy(source.normalScale);
  20857. this.displacementMap = source.displacementMap;
  20858. this.displacementScale = source.displacementScale;
  20859. this.displacementBias = source.displacementBias;
  20860. this.alphaMap = source.alphaMap;
  20861. this.wireframe = source.wireframe;
  20862. this.wireframeLinewidth = source.wireframeLinewidth;
  20863. this.wireframeLinecap = source.wireframeLinecap;
  20864. this.wireframeLinejoin = source.wireframeLinejoin;
  20865. return this;
  20866. }
  20867. }
  20868. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  20869. /**
  20870. * parameters = {
  20871. * opacity: <float>,
  20872. *
  20873. * bumpMap: new THREE.Texture( <Image> ),
  20874. * bumpScale: <float>,
  20875. *
  20876. * normalMap: new THREE.Texture( <Image> ),
  20877. * normalMapType: THREE.TangentSpaceNormalMap,
  20878. * normalScale: <Vector2>,
  20879. *
  20880. * displacementMap: new THREE.Texture( <Image> ),
  20881. * displacementScale: <float>,
  20882. * displacementBias: <float>,
  20883. *
  20884. * wireframe: <boolean>,
  20885. * wireframeLinewidth: <float>
  20886. *
  20887. * flatShading: <bool>
  20888. * }
  20889. */
  20890. class MeshNormalMaterial extends Material {
  20891. constructor(parameters) {
  20892. super();
  20893. this.type = 'MeshNormalMaterial';
  20894. this.bumpMap = null;
  20895. this.bumpScale = 1;
  20896. this.normalMap = null;
  20897. this.normalMapType = TangentSpaceNormalMap;
  20898. this.normalScale = new Vector2(1, 1);
  20899. this.displacementMap = null;
  20900. this.displacementScale = 1;
  20901. this.displacementBias = 0;
  20902. this.wireframe = false;
  20903. this.wireframeLinewidth = 1;
  20904. this.fog = false;
  20905. this.flatShading = false;
  20906. this.setValues(parameters);
  20907. }
  20908. copy(source) {
  20909. super.copy(source);
  20910. this.bumpMap = source.bumpMap;
  20911. this.bumpScale = source.bumpScale;
  20912. this.normalMap = source.normalMap;
  20913. this.normalMapType = source.normalMapType;
  20914. this.normalScale.copy(source.normalScale);
  20915. this.displacementMap = source.displacementMap;
  20916. this.displacementScale = source.displacementScale;
  20917. this.displacementBias = source.displacementBias;
  20918. this.wireframe = source.wireframe;
  20919. this.wireframeLinewidth = source.wireframeLinewidth;
  20920. this.flatShading = source.flatShading;
  20921. return this;
  20922. }
  20923. }
  20924. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  20925. /**
  20926. * parameters = {
  20927. * color: <hex>,
  20928. * opacity: <float>,
  20929. *
  20930. * map: new THREE.Texture( <Image> ),
  20931. *
  20932. * lightMap: new THREE.Texture( <Image> ),
  20933. * lightMapIntensity: <float>
  20934. *
  20935. * aoMap: new THREE.Texture( <Image> ),
  20936. * aoMapIntensity: <float>
  20937. *
  20938. * emissive: <hex>,
  20939. * emissiveIntensity: <float>
  20940. * emissiveMap: new THREE.Texture( <Image> ),
  20941. *
  20942. * specularMap: new THREE.Texture( <Image> ),
  20943. *
  20944. * alphaMap: new THREE.Texture( <Image> ),
  20945. *
  20946. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20947. * combine: THREE.Multiply,
  20948. * reflectivity: <float>,
  20949. * refractionRatio: <float>,
  20950. *
  20951. * wireframe: <boolean>,
  20952. * wireframeLinewidth: <float>,
  20953. *
  20954. * }
  20955. */
  20956. class MeshLambertMaterial extends Material {
  20957. constructor(parameters) {
  20958. super();
  20959. this.type = 'MeshLambertMaterial';
  20960. this.color = new Color(0xffffff); // diffuse
  20961. this.map = null;
  20962. this.lightMap = null;
  20963. this.lightMapIntensity = 1.0;
  20964. this.aoMap = null;
  20965. this.aoMapIntensity = 1.0;
  20966. this.emissive = new Color(0x000000);
  20967. this.emissiveIntensity = 1.0;
  20968. this.emissiveMap = null;
  20969. this.specularMap = null;
  20970. this.alphaMap = null;
  20971. this.envMap = null;
  20972. this.combine = MultiplyOperation;
  20973. this.reflectivity = 1;
  20974. this.refractionRatio = 0.98;
  20975. this.wireframe = false;
  20976. this.wireframeLinewidth = 1;
  20977. this.wireframeLinecap = 'round';
  20978. this.wireframeLinejoin = 'round';
  20979. this.setValues(parameters);
  20980. }
  20981. copy(source) {
  20982. super.copy(source);
  20983. this.color.copy(source.color);
  20984. this.map = source.map;
  20985. this.lightMap = source.lightMap;
  20986. this.lightMapIntensity = source.lightMapIntensity;
  20987. this.aoMap = source.aoMap;
  20988. this.aoMapIntensity = source.aoMapIntensity;
  20989. this.emissive.copy(source.emissive);
  20990. this.emissiveMap = source.emissiveMap;
  20991. this.emissiveIntensity = source.emissiveIntensity;
  20992. this.specularMap = source.specularMap;
  20993. this.alphaMap = source.alphaMap;
  20994. this.envMap = source.envMap;
  20995. this.combine = source.combine;
  20996. this.reflectivity = source.reflectivity;
  20997. this.refractionRatio = source.refractionRatio;
  20998. this.wireframe = source.wireframe;
  20999. this.wireframeLinewidth = source.wireframeLinewidth;
  21000. this.wireframeLinecap = source.wireframeLinecap;
  21001. this.wireframeLinejoin = source.wireframeLinejoin;
  21002. return this;
  21003. }
  21004. }
  21005. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  21006. /**
  21007. * parameters = {
  21008. * color: <hex>,
  21009. * opacity: <float>,
  21010. *
  21011. * matcap: new THREE.Texture( <Image> ),
  21012. *
  21013. * map: new THREE.Texture( <Image> ),
  21014. *
  21015. * bumpMap: new THREE.Texture( <Image> ),
  21016. * bumpScale: <float>,
  21017. *
  21018. * normalMap: new THREE.Texture( <Image> ),
  21019. * normalMapType: THREE.TangentSpaceNormalMap,
  21020. * normalScale: <Vector2>,
  21021. *
  21022. * displacementMap: new THREE.Texture( <Image> ),
  21023. * displacementScale: <float>,
  21024. * displacementBias: <float>,
  21025. *
  21026. * alphaMap: new THREE.Texture( <Image> ),
  21027. *
  21028. * flatShading: <bool>
  21029. * }
  21030. */
  21031. class MeshMatcapMaterial extends Material {
  21032. constructor(parameters) {
  21033. super();
  21034. this.defines = {
  21035. 'MATCAP': ''
  21036. };
  21037. this.type = 'MeshMatcapMaterial';
  21038. this.color = new Color(0xffffff); // diffuse
  21039. this.matcap = null;
  21040. this.map = null;
  21041. this.bumpMap = null;
  21042. this.bumpScale = 1;
  21043. this.normalMap = null;
  21044. this.normalMapType = TangentSpaceNormalMap;
  21045. this.normalScale = new Vector2(1, 1);
  21046. this.displacementMap = null;
  21047. this.displacementScale = 1;
  21048. this.displacementBias = 0;
  21049. this.alphaMap = null;
  21050. this.flatShading = false;
  21051. this.setValues(parameters);
  21052. }
  21053. copy(source) {
  21054. super.copy(source);
  21055. this.defines = {
  21056. 'MATCAP': ''
  21057. };
  21058. this.color.copy(source.color);
  21059. this.matcap = source.matcap;
  21060. this.map = source.map;
  21061. this.bumpMap = source.bumpMap;
  21062. this.bumpScale = source.bumpScale;
  21063. this.normalMap = source.normalMap;
  21064. this.normalMapType = source.normalMapType;
  21065. this.normalScale.copy(source.normalScale);
  21066. this.displacementMap = source.displacementMap;
  21067. this.displacementScale = source.displacementScale;
  21068. this.displacementBias = source.displacementBias;
  21069. this.alphaMap = source.alphaMap;
  21070. this.flatShading = source.flatShading;
  21071. return this;
  21072. }
  21073. }
  21074. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  21075. /**
  21076. * parameters = {
  21077. * color: <hex>,
  21078. * opacity: <float>,
  21079. *
  21080. * linewidth: <float>,
  21081. *
  21082. * scale: <float>,
  21083. * dashSize: <float>,
  21084. * gapSize: <float>
  21085. * }
  21086. */
  21087. class LineDashedMaterial extends LineBasicMaterial {
  21088. constructor(parameters) {
  21089. super();
  21090. this.type = 'LineDashedMaterial';
  21091. this.scale = 1;
  21092. this.dashSize = 3;
  21093. this.gapSize = 1;
  21094. this.setValues(parameters);
  21095. }
  21096. copy(source) {
  21097. super.copy(source);
  21098. this.scale = source.scale;
  21099. this.dashSize = source.dashSize;
  21100. this.gapSize = source.gapSize;
  21101. return this;
  21102. }
  21103. }
  21104. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  21105. var Materials = /*#__PURE__*/Object.freeze({
  21106. __proto__: null,
  21107. ShadowMaterial: ShadowMaterial,
  21108. SpriteMaterial: SpriteMaterial,
  21109. RawShaderMaterial: RawShaderMaterial,
  21110. ShaderMaterial: ShaderMaterial,
  21111. PointsMaterial: PointsMaterial,
  21112. MeshPhysicalMaterial: MeshPhysicalMaterial,
  21113. MeshStandardMaterial: MeshStandardMaterial,
  21114. MeshPhongMaterial: MeshPhongMaterial,
  21115. MeshToonMaterial: MeshToonMaterial,
  21116. MeshNormalMaterial: MeshNormalMaterial,
  21117. MeshLambertMaterial: MeshLambertMaterial,
  21118. MeshDepthMaterial: MeshDepthMaterial,
  21119. MeshDistanceMaterial: MeshDistanceMaterial,
  21120. MeshBasicMaterial: MeshBasicMaterial,
  21121. MeshMatcapMaterial: MeshMatcapMaterial,
  21122. LineDashedMaterial: LineDashedMaterial,
  21123. LineBasicMaterial: LineBasicMaterial,
  21124. Material: Material
  21125. });
  21126. const AnimationUtils = {
  21127. // same as Array.prototype.slice, but also works on typed arrays
  21128. arraySlice: function (array, from, to) {
  21129. if (AnimationUtils.isTypedArray(array)) {
  21130. // in ios9 array.subarray(from, undefined) will return empty array
  21131. // but array.subarray(from) or array.subarray(from, len) is correct
  21132. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  21133. }
  21134. return array.slice(from, to);
  21135. },
  21136. // converts an array to a specific type
  21137. convertArray: function (array, type, forceClone) {
  21138. if (!array || // let 'undefined' and 'null' pass
  21139. !forceClone && array.constructor === type) return array;
  21140. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  21141. return new type(array); // create typed array
  21142. }
  21143. return Array.prototype.slice.call(array); // create Array
  21144. },
  21145. isTypedArray: function (object) {
  21146. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  21147. },
  21148. // returns an array by which times and values can be sorted
  21149. getKeyframeOrder: function (times) {
  21150. function compareTime(i, j) {
  21151. return times[i] - times[j];
  21152. }
  21153. const n = times.length;
  21154. const result = new Array(n);
  21155. for (let i = 0; i !== n; ++i) result[i] = i;
  21156. result.sort(compareTime);
  21157. return result;
  21158. },
  21159. // uses the array previously returned by 'getKeyframeOrder' to sort data
  21160. sortedArray: function (values, stride, order) {
  21161. const nValues = values.length;
  21162. const result = new values.constructor(nValues);
  21163. for (let i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  21164. const srcOffset = order[i] * stride;
  21165. for (let j = 0; j !== stride; ++j) {
  21166. result[dstOffset++] = values[srcOffset + j];
  21167. }
  21168. }
  21169. return result;
  21170. },
  21171. // function for parsing AOS keyframe formats
  21172. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  21173. let i = 1,
  21174. key = jsonKeys[0];
  21175. while (key !== undefined && key[valuePropertyName] === undefined) {
  21176. key = jsonKeys[i++];
  21177. }
  21178. if (key === undefined) return; // no data
  21179. let value = key[valuePropertyName];
  21180. if (value === undefined) return; // no data
  21181. if (Array.isArray(value)) {
  21182. do {
  21183. value = key[valuePropertyName];
  21184. if (value !== undefined) {
  21185. times.push(key.time);
  21186. values.push.apply(values, value); // push all elements
  21187. }
  21188. key = jsonKeys[i++];
  21189. } while (key !== undefined);
  21190. } else if (value.toArray !== undefined) {
  21191. // ...assume THREE.Math-ish
  21192. do {
  21193. value = key[valuePropertyName];
  21194. if (value !== undefined) {
  21195. times.push(key.time);
  21196. value.toArray(values, values.length);
  21197. }
  21198. key = jsonKeys[i++];
  21199. } while (key !== undefined);
  21200. } else {
  21201. // otherwise push as-is
  21202. do {
  21203. value = key[valuePropertyName];
  21204. if (value !== undefined) {
  21205. times.push(key.time);
  21206. values.push(value);
  21207. }
  21208. key = jsonKeys[i++];
  21209. } while (key !== undefined);
  21210. }
  21211. },
  21212. subclip: function (sourceClip, name, startFrame, endFrame, fps = 30) {
  21213. const clip = sourceClip.clone();
  21214. clip.name = name;
  21215. const tracks = [];
  21216. for (let i = 0; i < clip.tracks.length; ++i) {
  21217. const track = clip.tracks[i];
  21218. const valueSize = track.getValueSize();
  21219. const times = [];
  21220. const values = [];
  21221. for (let j = 0; j < track.times.length; ++j) {
  21222. const frame = track.times[j] * fps;
  21223. if (frame < startFrame || frame >= endFrame) continue;
  21224. times.push(track.times[j]);
  21225. for (let k = 0; k < valueSize; ++k) {
  21226. values.push(track.values[j * valueSize + k]);
  21227. }
  21228. }
  21229. if (times.length === 0) continue;
  21230. track.times = AnimationUtils.convertArray(times, track.times.constructor);
  21231. track.values = AnimationUtils.convertArray(values, track.values.constructor);
  21232. tracks.push(track);
  21233. }
  21234. clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
  21235. let minStartTime = Infinity;
  21236. for (let i = 0; i < clip.tracks.length; ++i) {
  21237. if (minStartTime > clip.tracks[i].times[0]) {
  21238. minStartTime = clip.tracks[i].times[0];
  21239. }
  21240. } // shift all tracks such that clip begins at t=0
  21241. for (let i = 0; i < clip.tracks.length; ++i) {
  21242. clip.tracks[i].shift(-1 * minStartTime);
  21243. }
  21244. clip.resetDuration();
  21245. return clip;
  21246. },
  21247. makeClipAdditive: function (targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) {
  21248. if (fps <= 0) fps = 30;
  21249. const numTracks = referenceClip.tracks.length;
  21250. const referenceTime = referenceFrame / fps; // Make each track's values relative to the values at the reference frame
  21251. for (let i = 0; i < numTracks; ++i) {
  21252. const referenceTrack = referenceClip.tracks[i];
  21253. const referenceTrackType = referenceTrack.ValueTypeName; // Skip this track if it's non-numeric
  21254. if (referenceTrackType === 'bool' || referenceTrackType === 'string') continue; // Find the track in the target clip whose name and type matches the reference track
  21255. const targetTrack = targetClip.tracks.find(function (track) {
  21256. return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
  21257. });
  21258. if (targetTrack === undefined) continue;
  21259. let referenceOffset = 0;
  21260. const referenceValueSize = referenceTrack.getValueSize();
  21261. if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  21262. referenceOffset = referenceValueSize / 3;
  21263. }
  21264. let targetOffset = 0;
  21265. const targetValueSize = targetTrack.getValueSize();
  21266. if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  21267. targetOffset = targetValueSize / 3;
  21268. }
  21269. const lastIndex = referenceTrack.times.length - 1;
  21270. let referenceValue; // Find the value to subtract out of the track
  21271. if (referenceTime <= referenceTrack.times[0]) {
  21272. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  21273. const startIndex = referenceOffset;
  21274. const endIndex = referenceValueSize - referenceOffset;
  21275. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  21276. } else if (referenceTime >= referenceTrack.times[lastIndex]) {
  21277. // Reference frame is after the last keyframe, so just use the last keyframe
  21278. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  21279. const endIndex = startIndex + referenceValueSize - referenceOffset;
  21280. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  21281. } else {
  21282. // Interpolate to the reference value
  21283. const interpolant = referenceTrack.createInterpolant();
  21284. const startIndex = referenceOffset;
  21285. const endIndex = referenceValueSize - referenceOffset;
  21286. interpolant.evaluate(referenceTime);
  21287. referenceValue = AnimationUtils.arraySlice(interpolant.resultBuffer, startIndex, endIndex);
  21288. } // Conjugate the quaternion
  21289. if (referenceTrackType === 'quaternion') {
  21290. const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
  21291. referenceQuat.toArray(referenceValue);
  21292. } // Subtract the reference value from all of the track values
  21293. const numTimes = targetTrack.times.length;
  21294. for (let j = 0; j < numTimes; ++j) {
  21295. const valueStart = j * targetValueSize + targetOffset;
  21296. if (referenceTrackType === 'quaternion') {
  21297. // Multiply the conjugate for quaternion track types
  21298. Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
  21299. } else {
  21300. const valueEnd = targetValueSize - targetOffset * 2; // Subtract each value for all other numeric track types
  21301. for (let k = 0; k < valueEnd; ++k) {
  21302. targetTrack.values[valueStart + k] -= referenceValue[k];
  21303. }
  21304. }
  21305. }
  21306. }
  21307. targetClip.blendMode = AdditiveAnimationBlendMode;
  21308. return targetClip;
  21309. }
  21310. };
  21311. /**
  21312. * Abstract base class of interpolants over parametric samples.
  21313. *
  21314. * The parameter domain is one dimensional, typically the time or a path
  21315. * along a curve defined by the data.
  21316. *
  21317. * The sample values can have any dimensionality and derived classes may
  21318. * apply special interpretations to the data.
  21319. *
  21320. * This class provides the interval seek in a Template Method, deferring
  21321. * the actual interpolation to derived classes.
  21322. *
  21323. * Time complexity is O(1) for linear access crossing at most two points
  21324. * and O(log N) for random access, where N is the number of positions.
  21325. *
  21326. * References:
  21327. *
  21328. * http://www.oodesign.com/template-method-pattern.html
  21329. *
  21330. */
  21331. class Interpolant {
  21332. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21333. this.parameterPositions = parameterPositions;
  21334. this._cachedIndex = 0;
  21335. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  21336. this.sampleValues = sampleValues;
  21337. this.valueSize = sampleSize;
  21338. this.settings = null;
  21339. this.DefaultSettings_ = {};
  21340. }
  21341. evaluate(t) {
  21342. const pp = this.parameterPositions;
  21343. let i1 = this._cachedIndex,
  21344. t1 = pp[i1],
  21345. t0 = pp[i1 - 1];
  21346. validate_interval: {
  21347. seek: {
  21348. let right;
  21349. linear_scan: {
  21350. //- See http://jsperf.com/comparison-to-undefined/3
  21351. //- slower code:
  21352. //-
  21353. //- if ( t >= t1 || t1 === undefined ) {
  21354. forward_scan: if (!(t < t1)) {
  21355. for (let giveUpAt = i1 + 2;;) {
  21356. if (t1 === undefined) {
  21357. if (t < t0) break forward_scan; // after end
  21358. i1 = pp.length;
  21359. this._cachedIndex = i1;
  21360. return this.afterEnd_(i1 - 1, t, t0);
  21361. }
  21362. if (i1 === giveUpAt) break; // this loop
  21363. t0 = t1;
  21364. t1 = pp[++i1];
  21365. if (t < t1) {
  21366. // we have arrived at the sought interval
  21367. break seek;
  21368. }
  21369. } // prepare binary search on the right side of the index
  21370. right = pp.length;
  21371. break linear_scan;
  21372. } //- slower code:
  21373. //- if ( t < t0 || t0 === undefined ) {
  21374. if (!(t >= t0)) {
  21375. // looping?
  21376. const t1global = pp[1];
  21377. if (t < t1global) {
  21378. i1 = 2; // + 1, using the scan for the details
  21379. t0 = t1global;
  21380. } // linear reverse scan
  21381. for (let giveUpAt = i1 - 2;;) {
  21382. if (t0 === undefined) {
  21383. // before start
  21384. this._cachedIndex = 0;
  21385. return this.beforeStart_(0, t, t1);
  21386. }
  21387. if (i1 === giveUpAt) break; // this loop
  21388. t1 = t0;
  21389. t0 = pp[--i1 - 1];
  21390. if (t >= t0) {
  21391. // we have arrived at the sought interval
  21392. break seek;
  21393. }
  21394. } // prepare binary search on the left side of the index
  21395. right = i1;
  21396. i1 = 0;
  21397. break linear_scan;
  21398. } // the interval is valid
  21399. break validate_interval;
  21400. } // linear scan
  21401. // binary search
  21402. while (i1 < right) {
  21403. const mid = i1 + right >>> 1;
  21404. if (t < pp[mid]) {
  21405. right = mid;
  21406. } else {
  21407. i1 = mid + 1;
  21408. }
  21409. }
  21410. t1 = pp[i1];
  21411. t0 = pp[i1 - 1]; // check boundary cases, again
  21412. if (t0 === undefined) {
  21413. this._cachedIndex = 0;
  21414. return this.beforeStart_(0, t, t1);
  21415. }
  21416. if (t1 === undefined) {
  21417. i1 = pp.length;
  21418. this._cachedIndex = i1;
  21419. return this.afterEnd_(i1 - 1, t0, t);
  21420. }
  21421. } // seek
  21422. this._cachedIndex = i1;
  21423. this.intervalChanged_(i1, t0, t1);
  21424. } // validate_interval
  21425. return this.interpolate_(i1, t0, t, t1);
  21426. }
  21427. getSettings_() {
  21428. return this.settings || this.DefaultSettings_;
  21429. }
  21430. copySampleValue_(index) {
  21431. // copies a sample value to the result buffer
  21432. const result = this.resultBuffer,
  21433. values = this.sampleValues,
  21434. stride = this.valueSize,
  21435. offset = index * stride;
  21436. for (let i = 0; i !== stride; ++i) {
  21437. result[i] = values[offset + i];
  21438. }
  21439. return result;
  21440. } // Template methods for derived classes:
  21441. interpolate_() {
  21442. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  21443. }
  21444. intervalChanged_() {// empty
  21445. }
  21446. } // ALIAS DEFINITIONS
  21447. Interpolant.prototype.beforeStart_ = Interpolant.prototype.copySampleValue_;
  21448. Interpolant.prototype.afterEnd_ = Interpolant.prototype.copySampleValue_;
  21449. /**
  21450. * Fast and simple cubic spline interpolant.
  21451. *
  21452. * It was derived from a Hermitian construction setting the first derivative
  21453. * at each sample position to the linear slope between neighboring positions
  21454. * over their parameter interval.
  21455. */
  21456. class CubicInterpolant extends Interpolant {
  21457. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21458. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  21459. this._weightPrev = -0;
  21460. this._offsetPrev = -0;
  21461. this._weightNext = -0;
  21462. this._offsetNext = -0;
  21463. this.DefaultSettings_ = {
  21464. endingStart: ZeroCurvatureEnding,
  21465. endingEnd: ZeroCurvatureEnding
  21466. };
  21467. }
  21468. intervalChanged_(i1, t0, t1) {
  21469. const pp = this.parameterPositions;
  21470. let iPrev = i1 - 2,
  21471. iNext = i1 + 1,
  21472. tPrev = pp[iPrev],
  21473. tNext = pp[iNext];
  21474. if (tPrev === undefined) {
  21475. switch (this.getSettings_().endingStart) {
  21476. case ZeroSlopeEnding:
  21477. // f'(t0) = 0
  21478. iPrev = i1;
  21479. tPrev = 2 * t0 - t1;
  21480. break;
  21481. case WrapAroundEnding:
  21482. // use the other end of the curve
  21483. iPrev = pp.length - 2;
  21484. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  21485. break;
  21486. default:
  21487. // ZeroCurvatureEnding
  21488. // f''(t0) = 0 a.k.a. Natural Spline
  21489. iPrev = i1;
  21490. tPrev = t1;
  21491. }
  21492. }
  21493. if (tNext === undefined) {
  21494. switch (this.getSettings_().endingEnd) {
  21495. case ZeroSlopeEnding:
  21496. // f'(tN) = 0
  21497. iNext = i1;
  21498. tNext = 2 * t1 - t0;
  21499. break;
  21500. case WrapAroundEnding:
  21501. // use the other end of the curve
  21502. iNext = 1;
  21503. tNext = t1 + pp[1] - pp[0];
  21504. break;
  21505. default:
  21506. // ZeroCurvatureEnding
  21507. // f''(tN) = 0, a.k.a. Natural Spline
  21508. iNext = i1 - 1;
  21509. tNext = t0;
  21510. }
  21511. }
  21512. const halfDt = (t1 - t0) * 0.5,
  21513. stride = this.valueSize;
  21514. this._weightPrev = halfDt / (t0 - tPrev);
  21515. this._weightNext = halfDt / (tNext - t1);
  21516. this._offsetPrev = iPrev * stride;
  21517. this._offsetNext = iNext * stride;
  21518. }
  21519. interpolate_(i1, t0, t, t1) {
  21520. const result = this.resultBuffer,
  21521. values = this.sampleValues,
  21522. stride = this.valueSize,
  21523. o1 = i1 * stride,
  21524. o0 = o1 - stride,
  21525. oP = this._offsetPrev,
  21526. oN = this._offsetNext,
  21527. wP = this._weightPrev,
  21528. wN = this._weightNext,
  21529. p = (t - t0) / (t1 - t0),
  21530. pp = p * p,
  21531. ppp = pp * p; // evaluate polynomials
  21532. const sP = -wP * ppp + 2 * wP * pp - wP * p;
  21533. const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  21534. const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  21535. const sN = wN * ppp - wN * pp; // combine data linearly
  21536. for (let i = 0; i !== stride; ++i) {
  21537. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  21538. }
  21539. return result;
  21540. }
  21541. }
  21542. class LinearInterpolant extends Interpolant {
  21543. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21544. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  21545. }
  21546. interpolate_(i1, t0, t, t1) {
  21547. const result = this.resultBuffer,
  21548. values = this.sampleValues,
  21549. stride = this.valueSize,
  21550. offset1 = i1 * stride,
  21551. offset0 = offset1 - stride,
  21552. weight1 = (t - t0) / (t1 - t0),
  21553. weight0 = 1 - weight1;
  21554. for (let i = 0; i !== stride; ++i) {
  21555. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  21556. }
  21557. return result;
  21558. }
  21559. }
  21560. /**
  21561. *
  21562. * Interpolant that evaluates to the sample value at the position preceeding
  21563. * the parameter.
  21564. */
  21565. class DiscreteInterpolant extends Interpolant {
  21566. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21567. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  21568. }
  21569. interpolate_(i1
  21570. /*, t0, t, t1 */
  21571. ) {
  21572. return this.copySampleValue_(i1 - 1);
  21573. }
  21574. }
  21575. class KeyframeTrack {
  21576. constructor(name, times, values, interpolation) {
  21577. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  21578. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  21579. this.name = name;
  21580. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  21581. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  21582. this.setInterpolation(interpolation || this.DefaultInterpolation);
  21583. } // Serialization (in static context, because of constructor invocation
  21584. // and automatic invocation of .toJSON):
  21585. static toJSON(track) {
  21586. const trackType = track.constructor;
  21587. let json; // derived classes can define a static toJSON method
  21588. if (trackType.toJSON !== this.toJSON) {
  21589. json = trackType.toJSON(track);
  21590. } else {
  21591. // by default, we assume the data can be serialized as-is
  21592. json = {
  21593. 'name': track.name,
  21594. 'times': AnimationUtils.convertArray(track.times, Array),
  21595. 'values': AnimationUtils.convertArray(track.values, Array)
  21596. };
  21597. const interpolation = track.getInterpolation();
  21598. if (interpolation !== track.DefaultInterpolation) {
  21599. json.interpolation = interpolation;
  21600. }
  21601. }
  21602. json.type = track.ValueTypeName; // mandatory
  21603. return json;
  21604. }
  21605. InterpolantFactoryMethodDiscrete(result) {
  21606. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  21607. }
  21608. InterpolantFactoryMethodLinear(result) {
  21609. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  21610. }
  21611. InterpolantFactoryMethodSmooth(result) {
  21612. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  21613. }
  21614. setInterpolation(interpolation) {
  21615. let factoryMethod;
  21616. switch (interpolation) {
  21617. case InterpolateDiscrete:
  21618. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  21619. break;
  21620. case InterpolateLinear:
  21621. factoryMethod = this.InterpolantFactoryMethodLinear;
  21622. break;
  21623. case InterpolateSmooth:
  21624. factoryMethod = this.InterpolantFactoryMethodSmooth;
  21625. break;
  21626. }
  21627. if (factoryMethod === undefined) {
  21628. const message = 'unsupported interpolation for ' + this.ValueTypeName + ' keyframe track named ' + this.name;
  21629. if (this.createInterpolant === undefined) {
  21630. // fall back to default, unless the default itself is messed up
  21631. if (interpolation !== this.DefaultInterpolation) {
  21632. this.setInterpolation(this.DefaultInterpolation);
  21633. } else {
  21634. throw new Error(message); // fatal, in this case
  21635. }
  21636. }
  21637. console.warn('THREE.KeyframeTrack:', message);
  21638. return this;
  21639. }
  21640. this.createInterpolant = factoryMethod;
  21641. return this;
  21642. }
  21643. getInterpolation() {
  21644. switch (this.createInterpolant) {
  21645. case this.InterpolantFactoryMethodDiscrete:
  21646. return InterpolateDiscrete;
  21647. case this.InterpolantFactoryMethodLinear:
  21648. return InterpolateLinear;
  21649. case this.InterpolantFactoryMethodSmooth:
  21650. return InterpolateSmooth;
  21651. }
  21652. }
  21653. getValueSize() {
  21654. return this.values.length / this.times.length;
  21655. } // move all keyframes either forwards or backwards in time
  21656. shift(timeOffset) {
  21657. if (timeOffset !== 0.0) {
  21658. const times = this.times;
  21659. for (let i = 0, n = times.length; i !== n; ++i) {
  21660. times[i] += timeOffset;
  21661. }
  21662. }
  21663. return this;
  21664. } // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  21665. scale(timeScale) {
  21666. if (timeScale !== 1.0) {
  21667. const times = this.times;
  21668. for (let i = 0, n = times.length; i !== n; ++i) {
  21669. times[i] *= timeScale;
  21670. }
  21671. }
  21672. return this;
  21673. } // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  21674. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  21675. trim(startTime, endTime) {
  21676. const times = this.times,
  21677. nKeys = times.length;
  21678. let from = 0,
  21679. to = nKeys - 1;
  21680. while (from !== nKeys && times[from] < startTime) {
  21681. ++from;
  21682. }
  21683. while (to !== -1 && times[to] > endTime) {
  21684. --to;
  21685. }
  21686. ++to; // inclusive -> exclusive bound
  21687. if (from !== 0 || to !== nKeys) {
  21688. // empty tracks are forbidden, so keep at least one keyframe
  21689. if (from >= to) {
  21690. to = Math.max(to, 1);
  21691. from = to - 1;
  21692. }
  21693. const stride = this.getValueSize();
  21694. this.times = AnimationUtils.arraySlice(times, from, to);
  21695. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  21696. }
  21697. return this;
  21698. } // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  21699. validate() {
  21700. let valid = true;
  21701. const valueSize = this.getValueSize();
  21702. if (valueSize - Math.floor(valueSize) !== 0) {
  21703. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  21704. valid = false;
  21705. }
  21706. const times = this.times,
  21707. values = this.values,
  21708. nKeys = times.length;
  21709. if (nKeys === 0) {
  21710. console.error('THREE.KeyframeTrack: Track is empty.', this);
  21711. valid = false;
  21712. }
  21713. let prevTime = null;
  21714. for (let i = 0; i !== nKeys; i++) {
  21715. const currTime = times[i];
  21716. if (typeof currTime === 'number' && isNaN(currTime)) {
  21717. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  21718. valid = false;
  21719. break;
  21720. }
  21721. if (prevTime !== null && prevTime > currTime) {
  21722. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  21723. valid = false;
  21724. break;
  21725. }
  21726. prevTime = currTime;
  21727. }
  21728. if (values !== undefined) {
  21729. if (AnimationUtils.isTypedArray(values)) {
  21730. for (let i = 0, n = values.length; i !== n; ++i) {
  21731. const value = values[i];
  21732. if (isNaN(value)) {
  21733. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  21734. valid = false;
  21735. break;
  21736. }
  21737. }
  21738. }
  21739. }
  21740. return valid;
  21741. } // removes equivalent sequential keys as common in morph target sequences
  21742. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  21743. optimize() {
  21744. // times or values may be shared with other tracks, so overwriting is unsafe
  21745. const times = AnimationUtils.arraySlice(this.times),
  21746. values = AnimationUtils.arraySlice(this.values),
  21747. stride = this.getValueSize(),
  21748. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  21749. lastIndex = times.length - 1;
  21750. let writeIndex = 1;
  21751. for (let i = 1; i < lastIndex; ++i) {
  21752. let keep = false;
  21753. const time = times[i];
  21754. const timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  21755. if (time !== timeNext && (i !== 1 || time !== times[0])) {
  21756. if (!smoothInterpolation) {
  21757. // remove unnecessary keyframes same as their neighbors
  21758. const offset = i * stride,
  21759. offsetP = offset - stride,
  21760. offsetN = offset + stride;
  21761. for (let j = 0; j !== stride; ++j) {
  21762. const value = values[offset + j];
  21763. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  21764. keep = true;
  21765. break;
  21766. }
  21767. }
  21768. } else {
  21769. keep = true;
  21770. }
  21771. } // in-place compaction
  21772. if (keep) {
  21773. if (i !== writeIndex) {
  21774. times[writeIndex] = times[i];
  21775. const readOffset = i * stride,
  21776. writeOffset = writeIndex * stride;
  21777. for (let j = 0; j !== stride; ++j) {
  21778. values[writeOffset + j] = values[readOffset + j];
  21779. }
  21780. }
  21781. ++writeIndex;
  21782. }
  21783. } // flush last keyframe (compaction looks ahead)
  21784. if (lastIndex > 0) {
  21785. times[writeIndex] = times[lastIndex];
  21786. for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  21787. values[writeOffset + j] = values[readOffset + j];
  21788. }
  21789. ++writeIndex;
  21790. }
  21791. if (writeIndex !== times.length) {
  21792. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  21793. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  21794. } else {
  21795. this.times = times;
  21796. this.values = values;
  21797. }
  21798. return this;
  21799. }
  21800. clone() {
  21801. const times = AnimationUtils.arraySlice(this.times, 0);
  21802. const values = AnimationUtils.arraySlice(this.values, 0);
  21803. const TypedKeyframeTrack = this.constructor;
  21804. const track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  21805. track.createInterpolant = this.createInterpolant;
  21806. return track;
  21807. }
  21808. }
  21809. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  21810. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  21811. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  21812. /**
  21813. * A Track of Boolean keyframe values.
  21814. */
  21815. class BooleanKeyframeTrack extends KeyframeTrack {}
  21816. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  21817. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  21818. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  21819. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  21820. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; // Note: Actually this track could have a optimized / compressed
  21821. /**
  21822. * A Track of keyframe values that represent color.
  21823. */
  21824. class ColorKeyframeTrack extends KeyframeTrack {}
  21825. ColorKeyframeTrack.prototype.ValueTypeName = 'color'; // ValueBufferType is inherited
  21826. /**
  21827. * A Track of numeric keyframe values.
  21828. */
  21829. class NumberKeyframeTrack extends KeyframeTrack {}
  21830. NumberKeyframeTrack.prototype.ValueTypeName = 'number'; // ValueBufferType is inherited
  21831. /**
  21832. * Spherical linear unit quaternion interpolant.
  21833. */
  21834. class QuaternionLinearInterpolant extends Interpolant {
  21835. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21836. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  21837. }
  21838. interpolate_(i1, t0, t, t1) {
  21839. const result = this.resultBuffer,
  21840. values = this.sampleValues,
  21841. stride = this.valueSize,
  21842. alpha = (t - t0) / (t1 - t0);
  21843. let offset = i1 * stride;
  21844. for (let end = offset + stride; offset !== end; offset += 4) {
  21845. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  21846. }
  21847. return result;
  21848. }
  21849. }
  21850. /**
  21851. * A Track of quaternion keyframe values.
  21852. */
  21853. class QuaternionKeyframeTrack extends KeyframeTrack {
  21854. InterpolantFactoryMethodLinear(result) {
  21855. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  21856. }
  21857. }
  21858. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion'; // ValueBufferType is inherited
  21859. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  21860. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  21861. /**
  21862. * A Track that interpolates Strings
  21863. */
  21864. class StringKeyframeTrack extends KeyframeTrack {}
  21865. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  21866. StringKeyframeTrack.prototype.ValueBufferType = Array;
  21867. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  21868. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  21869. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  21870. /**
  21871. * A Track of vectored keyframe values.
  21872. */
  21873. class VectorKeyframeTrack extends KeyframeTrack {}
  21874. VectorKeyframeTrack.prototype.ValueTypeName = 'vector'; // ValueBufferType is inherited
  21875. class AnimationClip {
  21876. constructor(name, duration = -1, tracks, blendMode = NormalAnimationBlendMode) {
  21877. this.name = name;
  21878. this.tracks = tracks;
  21879. this.duration = duration;
  21880. this.blendMode = blendMode;
  21881. this.uuid = generateUUID(); // this means it should figure out its duration by scanning the tracks
  21882. if (this.duration < 0) {
  21883. this.resetDuration();
  21884. }
  21885. }
  21886. static parse(json) {
  21887. const tracks = [],
  21888. jsonTracks = json.tracks,
  21889. frameTime = 1.0 / (json.fps || 1.0);
  21890. for (let i = 0, n = jsonTracks.length; i !== n; ++i) {
  21891. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  21892. }
  21893. const clip = new this(json.name, json.duration, tracks, json.blendMode);
  21894. clip.uuid = json.uuid;
  21895. return clip;
  21896. }
  21897. static toJSON(clip) {
  21898. const tracks = [],
  21899. clipTracks = clip.tracks;
  21900. const json = {
  21901. 'name': clip.name,
  21902. 'duration': clip.duration,
  21903. 'tracks': tracks,
  21904. 'uuid': clip.uuid,
  21905. 'blendMode': clip.blendMode
  21906. };
  21907. for (let i = 0, n = clipTracks.length; i !== n; ++i) {
  21908. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  21909. }
  21910. return json;
  21911. }
  21912. static CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) {
  21913. const numMorphTargets = morphTargetSequence.length;
  21914. const tracks = [];
  21915. for (let i = 0; i < numMorphTargets; i++) {
  21916. let times = [];
  21917. let values = [];
  21918. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  21919. values.push(0, 1, 0);
  21920. const order = AnimationUtils.getKeyframeOrder(times);
  21921. times = AnimationUtils.sortedArray(times, 1, order);
  21922. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  21923. // last frame as well for perfect loop.
  21924. if (!noLoop && times[0] === 0) {
  21925. times.push(numMorphTargets);
  21926. values.push(values[0]);
  21927. }
  21928. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  21929. }
  21930. return new this(name, -1, tracks);
  21931. }
  21932. static findByName(objectOrClipArray, name) {
  21933. let clipArray = objectOrClipArray;
  21934. if (!Array.isArray(objectOrClipArray)) {
  21935. const o = objectOrClipArray;
  21936. clipArray = o.geometry && o.geometry.animations || o.animations;
  21937. }
  21938. for (let i = 0; i < clipArray.length; i++) {
  21939. if (clipArray[i].name === name) {
  21940. return clipArray[i];
  21941. }
  21942. }
  21943. return null;
  21944. }
  21945. static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {
  21946. const animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  21947. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  21948. const pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  21949. // patterns like Walk_001, Walk_002, Run_001, Run_002
  21950. for (let i = 0, il = morphTargets.length; i < il; i++) {
  21951. const morphTarget = morphTargets[i];
  21952. const parts = morphTarget.name.match(pattern);
  21953. if (parts && parts.length > 1) {
  21954. const name = parts[1];
  21955. let animationMorphTargets = animationToMorphTargets[name];
  21956. if (!animationMorphTargets) {
  21957. animationToMorphTargets[name] = animationMorphTargets = [];
  21958. }
  21959. animationMorphTargets.push(morphTarget);
  21960. }
  21961. }
  21962. const clips = [];
  21963. for (const name in animationToMorphTargets) {
  21964. clips.push(this.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  21965. }
  21966. return clips;
  21967. } // parse the animation.hierarchy format
  21968. static parseAnimation(animation, bones) {
  21969. if (!animation) {
  21970. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  21971. return null;
  21972. }
  21973. const addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  21974. // only return track if there are actually keys.
  21975. if (animationKeys.length !== 0) {
  21976. const times = [];
  21977. const values = [];
  21978. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  21979. if (times.length !== 0) {
  21980. destTracks.push(new trackType(trackName, times, values));
  21981. }
  21982. }
  21983. };
  21984. const tracks = [];
  21985. const clipName = animation.name || 'default';
  21986. const fps = animation.fps || 30;
  21987. const blendMode = animation.blendMode; // automatic length determination in AnimationClip.
  21988. let duration = animation.length || -1;
  21989. const hierarchyTracks = animation.hierarchy || [];
  21990. for (let h = 0; h < hierarchyTracks.length; h++) {
  21991. const animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  21992. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  21993. if (animationKeys[0].morphTargets) {
  21994. // figure out all morph targets used in this track
  21995. const morphTargetNames = {};
  21996. let k;
  21997. for (k = 0; k < animationKeys.length; k++) {
  21998. if (animationKeys[k].morphTargets) {
  21999. for (let m = 0; m < animationKeys[k].morphTargets.length; m++) {
  22000. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  22001. }
  22002. }
  22003. } // create a track for each morph target with all zero
  22004. // morphTargetInfluences except for the keys in which
  22005. // the morphTarget is named.
  22006. for (const morphTargetName in morphTargetNames) {
  22007. const times = [];
  22008. const values = [];
  22009. for (let m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  22010. const animationKey = animationKeys[k];
  22011. times.push(animationKey.time);
  22012. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  22013. }
  22014. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  22015. }
  22016. duration = morphTargetNames.length * (fps || 1.0);
  22017. } else {
  22018. // ...assume skeletal animation
  22019. const boneName = '.bones[' + bones[h].name + ']';
  22020. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  22021. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  22022. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  22023. }
  22024. }
  22025. if (tracks.length === 0) {
  22026. return null;
  22027. }
  22028. const clip = new this(clipName, duration, tracks, blendMode);
  22029. return clip;
  22030. }
  22031. resetDuration() {
  22032. const tracks = this.tracks;
  22033. let duration = 0;
  22034. for (let i = 0, n = tracks.length; i !== n; ++i) {
  22035. const track = this.tracks[i];
  22036. duration = Math.max(duration, track.times[track.times.length - 1]);
  22037. }
  22038. this.duration = duration;
  22039. return this;
  22040. }
  22041. trim() {
  22042. for (let i = 0; i < this.tracks.length; i++) {
  22043. this.tracks[i].trim(0, this.duration);
  22044. }
  22045. return this;
  22046. }
  22047. validate() {
  22048. let valid = true;
  22049. for (let i = 0; i < this.tracks.length; i++) {
  22050. valid = valid && this.tracks[i].validate();
  22051. }
  22052. return valid;
  22053. }
  22054. optimize() {
  22055. for (let i = 0; i < this.tracks.length; i++) {
  22056. this.tracks[i].optimize();
  22057. }
  22058. return this;
  22059. }
  22060. clone() {
  22061. const tracks = [];
  22062. for (let i = 0; i < this.tracks.length; i++) {
  22063. tracks.push(this.tracks[i].clone());
  22064. }
  22065. return new this.constructor(this.name, this.duration, tracks, this.blendMode);
  22066. }
  22067. toJSON() {
  22068. return this.constructor.toJSON(this);
  22069. }
  22070. }
  22071. function getTrackTypeForValueTypeName(typeName) {
  22072. switch (typeName.toLowerCase()) {
  22073. case 'scalar':
  22074. case 'double':
  22075. case 'float':
  22076. case 'number':
  22077. case 'integer':
  22078. return NumberKeyframeTrack;
  22079. case 'vector':
  22080. case 'vector2':
  22081. case 'vector3':
  22082. case 'vector4':
  22083. return VectorKeyframeTrack;
  22084. case 'color':
  22085. return ColorKeyframeTrack;
  22086. case 'quaternion':
  22087. return QuaternionKeyframeTrack;
  22088. case 'bool':
  22089. case 'boolean':
  22090. return BooleanKeyframeTrack;
  22091. case 'string':
  22092. return StringKeyframeTrack;
  22093. }
  22094. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  22095. }
  22096. function parseKeyframeTrack(json) {
  22097. if (json.type === undefined) {
  22098. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  22099. }
  22100. const trackType = getTrackTypeForValueTypeName(json.type);
  22101. if (json.times === undefined) {
  22102. const times = [],
  22103. values = [];
  22104. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  22105. json.times = times;
  22106. json.values = values;
  22107. } // derived classes can define a static parse method
  22108. if (trackType.parse !== undefined) {
  22109. return trackType.parse(json);
  22110. } else {
  22111. // by default, we assume a constructor compatible with the base
  22112. return new trackType(json.name, json.times, json.values, json.interpolation);
  22113. }
  22114. }
  22115. const Cache = {
  22116. enabled: false,
  22117. files: {},
  22118. add: function (key, file) {
  22119. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  22120. this.files[key] = file;
  22121. },
  22122. get: function (key) {
  22123. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  22124. return this.files[key];
  22125. },
  22126. remove: function (key) {
  22127. delete this.files[key];
  22128. },
  22129. clear: function () {
  22130. this.files = {};
  22131. }
  22132. };
  22133. class LoadingManager {
  22134. constructor(onLoad, onProgress, onError) {
  22135. const scope = this;
  22136. let isLoading = false;
  22137. let itemsLoaded = 0;
  22138. let itemsTotal = 0;
  22139. let urlModifier = undefined;
  22140. const handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  22141. // in the constructor
  22142. this.onStart = undefined;
  22143. this.onLoad = onLoad;
  22144. this.onProgress = onProgress;
  22145. this.onError = onError;
  22146. this.itemStart = function (url) {
  22147. itemsTotal++;
  22148. if (isLoading === false) {
  22149. if (scope.onStart !== undefined) {
  22150. scope.onStart(url, itemsLoaded, itemsTotal);
  22151. }
  22152. }
  22153. isLoading = true;
  22154. };
  22155. this.itemEnd = function (url) {
  22156. itemsLoaded++;
  22157. if (scope.onProgress !== undefined) {
  22158. scope.onProgress(url, itemsLoaded, itemsTotal);
  22159. }
  22160. if (itemsLoaded === itemsTotal) {
  22161. isLoading = false;
  22162. if (scope.onLoad !== undefined) {
  22163. scope.onLoad();
  22164. }
  22165. }
  22166. };
  22167. this.itemError = function (url) {
  22168. if (scope.onError !== undefined) {
  22169. scope.onError(url);
  22170. }
  22171. };
  22172. this.resolveURL = function (url) {
  22173. if (urlModifier) {
  22174. return urlModifier(url);
  22175. }
  22176. return url;
  22177. };
  22178. this.setURLModifier = function (transform) {
  22179. urlModifier = transform;
  22180. return this;
  22181. };
  22182. this.addHandler = function (regex, loader) {
  22183. handlers.push(regex, loader);
  22184. return this;
  22185. };
  22186. this.removeHandler = function (regex) {
  22187. const index = handlers.indexOf(regex);
  22188. if (index !== -1) {
  22189. handlers.splice(index, 2);
  22190. }
  22191. return this;
  22192. };
  22193. this.getHandler = function (file) {
  22194. for (let i = 0, l = handlers.length; i < l; i += 2) {
  22195. const regex = handlers[i];
  22196. const loader = handlers[i + 1];
  22197. if (regex.global) regex.lastIndex = 0; // see #17920
  22198. if (regex.test(file)) {
  22199. return loader;
  22200. }
  22201. }
  22202. return null;
  22203. };
  22204. }
  22205. }
  22206. const DefaultLoadingManager = new LoadingManager();
  22207. class Loader {
  22208. constructor(manager) {
  22209. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  22210. this.crossOrigin = 'anonymous';
  22211. this.withCredentials = false;
  22212. this.path = '';
  22213. this.resourcePath = '';
  22214. this.requestHeader = {};
  22215. }
  22216. load() {}
  22217. loadAsync(url, onProgress) {
  22218. const scope = this;
  22219. return new Promise(function (resolve, reject) {
  22220. scope.load(url, resolve, onProgress, reject);
  22221. });
  22222. }
  22223. parse() {}
  22224. setCrossOrigin(crossOrigin) {
  22225. this.crossOrigin = crossOrigin;
  22226. return this;
  22227. }
  22228. setWithCredentials(value) {
  22229. this.withCredentials = value;
  22230. return this;
  22231. }
  22232. setPath(path) {
  22233. this.path = path;
  22234. return this;
  22235. }
  22236. setResourcePath(resourcePath) {
  22237. this.resourcePath = resourcePath;
  22238. return this;
  22239. }
  22240. setRequestHeader(requestHeader) {
  22241. this.requestHeader = requestHeader;
  22242. return this;
  22243. }
  22244. }
  22245. const loading = {};
  22246. class FileLoader extends Loader {
  22247. constructor(manager) {
  22248. super(manager);
  22249. }
  22250. load(url, onLoad, onProgress, onError) {
  22251. if (url === undefined) url = '';
  22252. if (this.path !== undefined) url = this.path + url;
  22253. url = this.manager.resolveURL(url);
  22254. const scope = this;
  22255. const cached = Cache.get(url);
  22256. if (cached !== undefined) {
  22257. scope.manager.itemStart(url);
  22258. setTimeout(function () {
  22259. if (onLoad) onLoad(cached);
  22260. scope.manager.itemEnd(url);
  22261. }, 0);
  22262. return cached;
  22263. } // Check if request is duplicate
  22264. if (loading[url] !== undefined) {
  22265. loading[url].push({
  22266. onLoad: onLoad,
  22267. onProgress: onProgress,
  22268. onError: onError
  22269. });
  22270. return;
  22271. } // Check for data: URI
  22272. const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  22273. const dataUriRegexResult = url.match(dataUriRegex);
  22274. let request; // Safari can not handle Data URIs through XMLHttpRequest so process manually
  22275. if (dataUriRegexResult) {
  22276. const mimeType = dataUriRegexResult[1];
  22277. const isBase64 = !!dataUriRegexResult[2];
  22278. let data = dataUriRegexResult[3];
  22279. data = decodeURIComponent(data);
  22280. if (isBase64) data = atob(data);
  22281. try {
  22282. let response;
  22283. const responseType = (this.responseType || '').toLowerCase();
  22284. switch (responseType) {
  22285. case 'arraybuffer':
  22286. case 'blob':
  22287. const view = new Uint8Array(data.length);
  22288. for (let i = 0; i < data.length; i++) {
  22289. view[i] = data.charCodeAt(i);
  22290. }
  22291. if (responseType === 'blob') {
  22292. response = new Blob([view.buffer], {
  22293. type: mimeType
  22294. });
  22295. } else {
  22296. response = view.buffer;
  22297. }
  22298. break;
  22299. case 'document':
  22300. const parser = new DOMParser();
  22301. response = parser.parseFromString(data, mimeType);
  22302. break;
  22303. case 'json':
  22304. response = JSON.parse(data);
  22305. break;
  22306. default:
  22307. // 'text' or other
  22308. response = data;
  22309. break;
  22310. } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22311. setTimeout(function () {
  22312. if (onLoad) onLoad(response);
  22313. scope.manager.itemEnd(url);
  22314. }, 0);
  22315. } catch (error) {
  22316. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22317. setTimeout(function () {
  22318. if (onError) onError(error);
  22319. scope.manager.itemError(url);
  22320. scope.manager.itemEnd(url);
  22321. }, 0);
  22322. }
  22323. } else {
  22324. // Initialise array for duplicate requests
  22325. loading[url] = [];
  22326. loading[url].push({
  22327. onLoad: onLoad,
  22328. onProgress: onProgress,
  22329. onError: onError
  22330. });
  22331. request = new XMLHttpRequest();
  22332. request.open('GET', url, true);
  22333. request.addEventListener('load', function (event) {
  22334. const response = this.response;
  22335. const callbacks = loading[url];
  22336. delete loading[url];
  22337. if (this.status === 200 || this.status === 0) {
  22338. // Some browsers return HTTP Status 0 when using non-http protocol
  22339. // e.g. 'file://' or 'data://'. Handle as success.
  22340. 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
  22341. // error response bodies as proper responses to requests.
  22342. Cache.add(url, response);
  22343. for (let i = 0, il = callbacks.length; i < il; i++) {
  22344. const callback = callbacks[i];
  22345. if (callback.onLoad) callback.onLoad(response);
  22346. }
  22347. scope.manager.itemEnd(url);
  22348. } else {
  22349. for (let i = 0, il = callbacks.length; i < il; i++) {
  22350. const callback = callbacks[i];
  22351. if (callback.onError) callback.onError(event);
  22352. }
  22353. scope.manager.itemError(url);
  22354. scope.manager.itemEnd(url);
  22355. }
  22356. }, false);
  22357. request.addEventListener('progress', function (event) {
  22358. const callbacks = loading[url];
  22359. for (let i = 0, il = callbacks.length; i < il; i++) {
  22360. const callback = callbacks[i];
  22361. if (callback.onProgress) callback.onProgress(event);
  22362. }
  22363. }, false);
  22364. request.addEventListener('error', function (event) {
  22365. const callbacks = loading[url];
  22366. delete loading[url];
  22367. for (let i = 0, il = callbacks.length; i < il; i++) {
  22368. const callback = callbacks[i];
  22369. if (callback.onError) callback.onError(event);
  22370. }
  22371. scope.manager.itemError(url);
  22372. scope.manager.itemEnd(url);
  22373. }, false);
  22374. request.addEventListener('abort', function (event) {
  22375. const callbacks = loading[url];
  22376. delete loading[url];
  22377. for (let i = 0, il = callbacks.length; i < il; i++) {
  22378. const callback = callbacks[i];
  22379. if (callback.onError) callback.onError(event);
  22380. }
  22381. scope.manager.itemError(url);
  22382. scope.manager.itemEnd(url);
  22383. }, false);
  22384. if (this.responseType !== undefined) request.responseType = this.responseType;
  22385. if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
  22386. if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
  22387. for (const header in this.requestHeader) {
  22388. request.setRequestHeader(header, this.requestHeader[header]);
  22389. }
  22390. request.send(null);
  22391. }
  22392. scope.manager.itemStart(url);
  22393. return request;
  22394. }
  22395. setResponseType(value) {
  22396. this.responseType = value;
  22397. return this;
  22398. }
  22399. setMimeType(value) {
  22400. this.mimeType = value;
  22401. return this;
  22402. }
  22403. }
  22404. class AnimationLoader extends Loader {
  22405. constructor(manager) {
  22406. super(manager);
  22407. }
  22408. load(url, onLoad, onProgress, onError) {
  22409. const scope = this;
  22410. const loader = new FileLoader(this.manager);
  22411. loader.setPath(this.path);
  22412. loader.setRequestHeader(this.requestHeader);
  22413. loader.setWithCredentials(this.withCredentials);
  22414. loader.load(url, function (text) {
  22415. try {
  22416. onLoad(scope.parse(JSON.parse(text)));
  22417. } catch (e) {
  22418. if (onError) {
  22419. onError(e);
  22420. } else {
  22421. console.error(e);
  22422. }
  22423. scope.manager.itemError(url);
  22424. }
  22425. }, onProgress, onError);
  22426. }
  22427. parse(json) {
  22428. const animations = [];
  22429. for (let i = 0; i < json.length; i++) {
  22430. const clip = AnimationClip.parse(json[i]);
  22431. animations.push(clip);
  22432. }
  22433. return animations;
  22434. }
  22435. }
  22436. /**
  22437. * Abstract Base class to block based textures loader (dds, pvr, ...)
  22438. *
  22439. * Sub classes have to implement the parse() method which will be used in load().
  22440. */
  22441. class CompressedTextureLoader extends Loader {
  22442. constructor(manager) {
  22443. super(manager);
  22444. }
  22445. load(url, onLoad, onProgress, onError) {
  22446. const scope = this;
  22447. const images = [];
  22448. const texture = new CompressedTexture();
  22449. const loader = new FileLoader(this.manager);
  22450. loader.setPath(this.path);
  22451. loader.setResponseType('arraybuffer');
  22452. loader.setRequestHeader(this.requestHeader);
  22453. loader.setWithCredentials(scope.withCredentials);
  22454. let loaded = 0;
  22455. function loadTexture(i) {
  22456. loader.load(url[i], function (buffer) {
  22457. const texDatas = scope.parse(buffer, true);
  22458. images[i] = {
  22459. width: texDatas.width,
  22460. height: texDatas.height,
  22461. format: texDatas.format,
  22462. mipmaps: texDatas.mipmaps
  22463. };
  22464. loaded += 1;
  22465. if (loaded === 6) {
  22466. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  22467. texture.image = images;
  22468. texture.format = texDatas.format;
  22469. texture.needsUpdate = true;
  22470. if (onLoad) onLoad(texture);
  22471. }
  22472. }, onProgress, onError);
  22473. }
  22474. if (Array.isArray(url)) {
  22475. for (let i = 0, il = url.length; i < il; ++i) {
  22476. loadTexture(i);
  22477. }
  22478. } else {
  22479. // compressed cubemap texture stored in a single DDS file
  22480. loader.load(url, function (buffer) {
  22481. const texDatas = scope.parse(buffer, true);
  22482. if (texDatas.isCubemap) {
  22483. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  22484. for (let f = 0; f < faces; f++) {
  22485. images[f] = {
  22486. mipmaps: []
  22487. };
  22488. for (let i = 0; i < texDatas.mipmapCount; i++) {
  22489. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  22490. images[f].format = texDatas.format;
  22491. images[f].width = texDatas.width;
  22492. images[f].height = texDatas.height;
  22493. }
  22494. }
  22495. texture.image = images;
  22496. } else {
  22497. texture.image.width = texDatas.width;
  22498. texture.image.height = texDatas.height;
  22499. texture.mipmaps = texDatas.mipmaps;
  22500. }
  22501. if (texDatas.mipmapCount === 1) {
  22502. texture.minFilter = LinearFilter;
  22503. }
  22504. texture.format = texDatas.format;
  22505. texture.needsUpdate = true;
  22506. if (onLoad) onLoad(texture);
  22507. }, onProgress, onError);
  22508. }
  22509. return texture;
  22510. }
  22511. }
  22512. class ImageLoader extends Loader {
  22513. constructor(manager) {
  22514. super(manager);
  22515. }
  22516. load(url, onLoad, onProgress, onError) {
  22517. if (this.path !== undefined) url = this.path + url;
  22518. url = this.manager.resolveURL(url);
  22519. const scope = this;
  22520. const cached = Cache.get(url);
  22521. if (cached !== undefined) {
  22522. scope.manager.itemStart(url);
  22523. setTimeout(function () {
  22524. if (onLoad) onLoad(cached);
  22525. scope.manager.itemEnd(url);
  22526. }, 0);
  22527. return cached;
  22528. }
  22529. const image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
  22530. function onImageLoad() {
  22531. image.removeEventListener('load', onImageLoad, false);
  22532. image.removeEventListener('error', onImageError, false);
  22533. Cache.add(url, this);
  22534. if (onLoad) onLoad(this);
  22535. scope.manager.itemEnd(url);
  22536. }
  22537. function onImageError(event) {
  22538. image.removeEventListener('load', onImageLoad, false);
  22539. image.removeEventListener('error', onImageError, false);
  22540. if (onError) onError(event);
  22541. scope.manager.itemError(url);
  22542. scope.manager.itemEnd(url);
  22543. }
  22544. image.addEventListener('load', onImageLoad, false);
  22545. image.addEventListener('error', onImageError, false);
  22546. if (url.substr(0, 5) !== 'data:') {
  22547. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  22548. }
  22549. scope.manager.itemStart(url);
  22550. image.src = url;
  22551. return image;
  22552. }
  22553. }
  22554. class CubeTextureLoader extends Loader {
  22555. constructor(manager) {
  22556. super(manager);
  22557. }
  22558. load(urls, onLoad, onProgress, onError) {
  22559. const texture = new CubeTexture();
  22560. const loader = new ImageLoader(this.manager);
  22561. loader.setCrossOrigin(this.crossOrigin);
  22562. loader.setPath(this.path);
  22563. let loaded = 0;
  22564. function loadTexture(i) {
  22565. loader.load(urls[i], function (image) {
  22566. texture.images[i] = image;
  22567. loaded++;
  22568. if (loaded === 6) {
  22569. texture.needsUpdate = true;
  22570. if (onLoad) onLoad(texture);
  22571. }
  22572. }, undefined, onError);
  22573. }
  22574. for (let i = 0; i < urls.length; ++i) {
  22575. loadTexture(i);
  22576. }
  22577. return texture;
  22578. }
  22579. }
  22580. /**
  22581. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  22582. *
  22583. * Sub classes have to implement the parse() method which will be used in load().
  22584. */
  22585. class DataTextureLoader extends Loader {
  22586. constructor(manager) {
  22587. super(manager);
  22588. }
  22589. load(url, onLoad, onProgress, onError) {
  22590. const scope = this;
  22591. const texture = new DataTexture();
  22592. const loader = new FileLoader(this.manager);
  22593. loader.setResponseType('arraybuffer');
  22594. loader.setRequestHeader(this.requestHeader);
  22595. loader.setPath(this.path);
  22596. loader.setWithCredentials(scope.withCredentials);
  22597. loader.load(url, function (buffer) {
  22598. const texData = scope.parse(buffer);
  22599. if (!texData) return;
  22600. if (texData.image !== undefined) {
  22601. texture.image = texData.image;
  22602. } else if (texData.data !== undefined) {
  22603. texture.image.width = texData.width;
  22604. texture.image.height = texData.height;
  22605. texture.image.data = texData.data;
  22606. }
  22607. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  22608. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  22609. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  22610. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  22611. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  22612. if (texData.encoding !== undefined) {
  22613. texture.encoding = texData.encoding;
  22614. }
  22615. if (texData.flipY !== undefined) {
  22616. texture.flipY = texData.flipY;
  22617. }
  22618. if (texData.format !== undefined) {
  22619. texture.format = texData.format;
  22620. }
  22621. if (texData.type !== undefined) {
  22622. texture.type = texData.type;
  22623. }
  22624. if (texData.mipmaps !== undefined) {
  22625. texture.mipmaps = texData.mipmaps;
  22626. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  22627. }
  22628. if (texData.mipmapCount === 1) {
  22629. texture.minFilter = LinearFilter;
  22630. }
  22631. if (texData.generateMipmaps !== undefined) {
  22632. texture.generateMipmaps = texData.generateMipmaps;
  22633. }
  22634. texture.needsUpdate = true;
  22635. if (onLoad) onLoad(texture, texData);
  22636. }, onProgress, onError);
  22637. return texture;
  22638. }
  22639. }
  22640. class TextureLoader extends Loader {
  22641. constructor(manager) {
  22642. super(manager);
  22643. }
  22644. load(url, onLoad, onProgress, onError) {
  22645. const texture = new Texture();
  22646. const loader = new ImageLoader(this.manager);
  22647. loader.setCrossOrigin(this.crossOrigin);
  22648. loader.setPath(this.path);
  22649. loader.load(url, function (image) {
  22650. texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  22651. const isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;
  22652. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  22653. texture.needsUpdate = true;
  22654. if (onLoad !== undefined) {
  22655. onLoad(texture);
  22656. }
  22657. }, onProgress, onError);
  22658. return texture;
  22659. }
  22660. }
  22661. /**************************************************************
  22662. * Curved Path - a curve path is simply a array of connected
  22663. * curves, but retains the api of a curve
  22664. **************************************************************/
  22665. class CurvePath extends Curve {
  22666. constructor() {
  22667. super();
  22668. this.type = 'CurvePath';
  22669. this.curves = [];
  22670. this.autoClose = false; // Automatically closes the path
  22671. }
  22672. add(curve) {
  22673. this.curves.push(curve);
  22674. }
  22675. closePath() {
  22676. // Add a line curve if start and end of lines are not connected
  22677. const startPoint = this.curves[0].getPoint(0);
  22678. const endPoint = this.curves[this.curves.length - 1].getPoint(1);
  22679. if (!startPoint.equals(endPoint)) {
  22680. this.curves.push(new LineCurve(endPoint, startPoint));
  22681. }
  22682. } // To get accurate point with reference to
  22683. // entire path distance at time t,
  22684. // following has to be done:
  22685. // 1. Length of each sub path have to be known
  22686. // 2. Locate and identify type of curve
  22687. // 3. Get t for the curve
  22688. // 4. Return curve.getPointAt(t')
  22689. getPoint(t) {
  22690. const d = t * this.getLength();
  22691. const curveLengths = this.getCurveLengths();
  22692. let i = 0; // To think about boundaries points.
  22693. while (i < curveLengths.length) {
  22694. if (curveLengths[i] >= d) {
  22695. const diff = curveLengths[i] - d;
  22696. const curve = this.curves[i];
  22697. const segmentLength = curve.getLength();
  22698. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  22699. return curve.getPointAt(u);
  22700. }
  22701. i++;
  22702. }
  22703. return null; // loop where sum != 0, sum > d , sum+1 <d
  22704. } // We cannot use the default THREE.Curve getPoint() with getLength() because in
  22705. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  22706. // getPoint() depends on getLength
  22707. getLength() {
  22708. const lens = this.getCurveLengths();
  22709. return lens[lens.length - 1];
  22710. } // cacheLengths must be recalculated.
  22711. updateArcLengths() {
  22712. this.needsUpdate = true;
  22713. this.cacheLengths = null;
  22714. this.getCurveLengths();
  22715. } // Compute lengths and cache them
  22716. // We cannot overwrite getLengths() because UtoT mapping uses it.
  22717. getCurveLengths() {
  22718. // We use cache values if curves and cache array are same length
  22719. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  22720. return this.cacheLengths;
  22721. } // Get length of sub-curve
  22722. // Push sums into cached array
  22723. const lengths = [];
  22724. let sums = 0;
  22725. for (let i = 0, l = this.curves.length; i < l; i++) {
  22726. sums += this.curves[i].getLength();
  22727. lengths.push(sums);
  22728. }
  22729. this.cacheLengths = lengths;
  22730. return lengths;
  22731. }
  22732. getSpacedPoints(divisions = 40) {
  22733. const points = [];
  22734. for (let i = 0; i <= divisions; i++) {
  22735. points.push(this.getPoint(i / divisions));
  22736. }
  22737. if (this.autoClose) {
  22738. points.push(points[0]);
  22739. }
  22740. return points;
  22741. }
  22742. getPoints(divisions = 12) {
  22743. const points = [];
  22744. let last;
  22745. for (let i = 0, curves = this.curves; i < curves.length; i++) {
  22746. const curve = curves[i];
  22747. const resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  22748. const pts = curve.getPoints(resolution);
  22749. for (let j = 0; j < pts.length; j++) {
  22750. const point = pts[j];
  22751. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  22752. points.push(point);
  22753. last = point;
  22754. }
  22755. }
  22756. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  22757. points.push(points[0]);
  22758. }
  22759. return points;
  22760. }
  22761. copy(source) {
  22762. super.copy(source);
  22763. this.curves = [];
  22764. for (let i = 0, l = source.curves.length; i < l; i++) {
  22765. const curve = source.curves[i];
  22766. this.curves.push(curve.clone());
  22767. }
  22768. this.autoClose = source.autoClose;
  22769. return this;
  22770. }
  22771. toJSON() {
  22772. const data = super.toJSON();
  22773. data.autoClose = this.autoClose;
  22774. data.curves = [];
  22775. for (let i = 0, l = this.curves.length; i < l; i++) {
  22776. const curve = this.curves[i];
  22777. data.curves.push(curve.toJSON());
  22778. }
  22779. return data;
  22780. }
  22781. fromJSON(json) {
  22782. super.fromJSON(json);
  22783. this.autoClose = json.autoClose;
  22784. this.curves = [];
  22785. for (let i = 0, l = json.curves.length; i < l; i++) {
  22786. const curve = json.curves[i];
  22787. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  22788. }
  22789. return this;
  22790. }
  22791. }
  22792. class Path extends CurvePath {
  22793. constructor(points) {
  22794. super();
  22795. this.type = 'Path';
  22796. this.currentPoint = new Vector2();
  22797. if (points) {
  22798. this.setFromPoints(points);
  22799. }
  22800. }
  22801. setFromPoints(points) {
  22802. this.moveTo(points[0].x, points[0].y);
  22803. for (let i = 1, l = points.length; i < l; i++) {
  22804. this.lineTo(points[i].x, points[i].y);
  22805. }
  22806. return this;
  22807. }
  22808. moveTo(x, y) {
  22809. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  22810. return this;
  22811. }
  22812. lineTo(x, y) {
  22813. const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  22814. this.curves.push(curve);
  22815. this.currentPoint.set(x, y);
  22816. return this;
  22817. }
  22818. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  22819. const curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  22820. this.curves.push(curve);
  22821. this.currentPoint.set(aX, aY);
  22822. return this;
  22823. }
  22824. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  22825. const curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  22826. this.curves.push(curve);
  22827. this.currentPoint.set(aX, aY);
  22828. return this;
  22829. }
  22830. splineThru(pts
  22831. /*Array of Vector*/
  22832. ) {
  22833. const npts = [this.currentPoint.clone()].concat(pts);
  22834. const curve = new SplineCurve(npts);
  22835. this.curves.push(curve);
  22836. this.currentPoint.copy(pts[pts.length - 1]);
  22837. return this;
  22838. }
  22839. arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  22840. const x0 = this.currentPoint.x;
  22841. const y0 = this.currentPoint.y;
  22842. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  22843. return this;
  22844. }
  22845. absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  22846. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  22847. return this;
  22848. }
  22849. ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  22850. const x0 = this.currentPoint.x;
  22851. const y0 = this.currentPoint.y;
  22852. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  22853. return this;
  22854. }
  22855. absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  22856. const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  22857. if (this.curves.length > 0) {
  22858. // if a previous curve is present, attempt to join
  22859. const firstPoint = curve.getPoint(0);
  22860. if (!firstPoint.equals(this.currentPoint)) {
  22861. this.lineTo(firstPoint.x, firstPoint.y);
  22862. }
  22863. }
  22864. this.curves.push(curve);
  22865. const lastPoint = curve.getPoint(1);
  22866. this.currentPoint.copy(lastPoint);
  22867. return this;
  22868. }
  22869. copy(source) {
  22870. super.copy(source);
  22871. this.currentPoint.copy(source.currentPoint);
  22872. return this;
  22873. }
  22874. toJSON() {
  22875. const data = super.toJSON();
  22876. data.currentPoint = this.currentPoint.toArray();
  22877. return data;
  22878. }
  22879. fromJSON(json) {
  22880. super.fromJSON(json);
  22881. this.currentPoint.fromArray(json.currentPoint);
  22882. return this;
  22883. }
  22884. }
  22885. class Shape extends Path {
  22886. constructor(points) {
  22887. super(points);
  22888. this.uuid = generateUUID();
  22889. this.type = 'Shape';
  22890. this.holes = [];
  22891. }
  22892. getPointsHoles(divisions) {
  22893. const holesPts = [];
  22894. for (let i = 0, l = this.holes.length; i < l; i++) {
  22895. holesPts[i] = this.holes[i].getPoints(divisions);
  22896. }
  22897. return holesPts;
  22898. } // get points of shape and holes (keypoints based on segments parameter)
  22899. extractPoints(divisions) {
  22900. return {
  22901. shape: this.getPoints(divisions),
  22902. holes: this.getPointsHoles(divisions)
  22903. };
  22904. }
  22905. copy(source) {
  22906. super.copy(source);
  22907. this.holes = [];
  22908. for (let i = 0, l = source.holes.length; i < l; i++) {
  22909. const hole = source.holes[i];
  22910. this.holes.push(hole.clone());
  22911. }
  22912. return this;
  22913. }
  22914. toJSON() {
  22915. const data = super.toJSON();
  22916. data.uuid = this.uuid;
  22917. data.holes = [];
  22918. for (let i = 0, l = this.holes.length; i < l; i++) {
  22919. const hole = this.holes[i];
  22920. data.holes.push(hole.toJSON());
  22921. }
  22922. return data;
  22923. }
  22924. fromJSON(json) {
  22925. super.fromJSON(json);
  22926. this.uuid = json.uuid;
  22927. this.holes = [];
  22928. for (let i = 0, l = json.holes.length; i < l; i++) {
  22929. const hole = json.holes[i];
  22930. this.holes.push(new Path().fromJSON(hole));
  22931. }
  22932. return this;
  22933. }
  22934. }
  22935. class Light extends Object3D {
  22936. constructor(color, intensity = 1) {
  22937. super();
  22938. this.type = 'Light';
  22939. this.color = new Color(color);
  22940. this.intensity = intensity;
  22941. }
  22942. dispose() {// Empty here in base class; some subclasses override.
  22943. }
  22944. copy(source) {
  22945. super.copy(source);
  22946. this.color.copy(source.color);
  22947. this.intensity = source.intensity;
  22948. return this;
  22949. }
  22950. toJSON(meta) {
  22951. const data = super.toJSON(meta);
  22952. data.object.color = this.color.getHex();
  22953. data.object.intensity = this.intensity;
  22954. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  22955. if (this.distance !== undefined) data.object.distance = this.distance;
  22956. if (this.angle !== undefined) data.object.angle = this.angle;
  22957. if (this.decay !== undefined) data.object.decay = this.decay;
  22958. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  22959. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  22960. return data;
  22961. }
  22962. }
  22963. Light.prototype.isLight = true;
  22964. class HemisphereLight extends Light {
  22965. constructor(skyColor, groundColor, intensity) {
  22966. super(skyColor, intensity);
  22967. this.type = 'HemisphereLight';
  22968. this.position.copy(Object3D.DefaultUp);
  22969. this.updateMatrix();
  22970. this.groundColor = new Color(groundColor);
  22971. }
  22972. copy(source) {
  22973. Light.prototype.copy.call(this, source);
  22974. this.groundColor.copy(source.groundColor);
  22975. return this;
  22976. }
  22977. }
  22978. HemisphereLight.prototype.isHemisphereLight = true;
  22979. const _projScreenMatrix$1 = /*@__PURE__*/new Matrix4();
  22980. const _lightPositionWorld$1 = /*@__PURE__*/new Vector3();
  22981. const _lookTarget$1 = /*@__PURE__*/new Vector3();
  22982. class LightShadow {
  22983. constructor(camera) {
  22984. this.camera = camera;
  22985. this.bias = 0;
  22986. this.normalBias = 0;
  22987. this.radius = 1;
  22988. this.blurSamples = 8;
  22989. this.mapSize = new Vector2(512, 512);
  22990. this.map = null;
  22991. this.mapPass = null;
  22992. this.matrix = new Matrix4();
  22993. this.autoUpdate = true;
  22994. this.needsUpdate = false;
  22995. this._frustum = new Frustum();
  22996. this._frameExtents = new Vector2(1, 1);
  22997. this._viewportCount = 1;
  22998. this._viewports = [new Vector4(0, 0, 1, 1)];
  22999. }
  23000. getViewportCount() {
  23001. return this._viewportCount;
  23002. }
  23003. getFrustum() {
  23004. return this._frustum;
  23005. }
  23006. updateMatrices(light) {
  23007. const shadowCamera = this.camera;
  23008. const shadowMatrix = this.matrix;
  23009. _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld);
  23010. shadowCamera.position.copy(_lightPositionWorld$1);
  23011. _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld);
  23012. shadowCamera.lookAt(_lookTarget$1);
  23013. shadowCamera.updateMatrixWorld();
  23014. _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  23015. this._frustum.setFromProjectionMatrix(_projScreenMatrix$1);
  23016. 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);
  23017. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  23018. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  23019. }
  23020. getViewport(viewportIndex) {
  23021. return this._viewports[viewportIndex];
  23022. }
  23023. getFrameExtents() {
  23024. return this._frameExtents;
  23025. }
  23026. dispose() {
  23027. if (this.map) {
  23028. this.map.dispose();
  23029. }
  23030. if (this.mapPass) {
  23031. this.mapPass.dispose();
  23032. }
  23033. }
  23034. copy(source) {
  23035. this.camera = source.camera.clone();
  23036. this.bias = source.bias;
  23037. this.radius = source.radius;
  23038. this.mapSize.copy(source.mapSize);
  23039. return this;
  23040. }
  23041. clone() {
  23042. return new this.constructor().copy(this);
  23043. }
  23044. toJSON() {
  23045. const object = {};
  23046. if (this.bias !== 0) object.bias = this.bias;
  23047. if (this.normalBias !== 0) object.normalBias = this.normalBias;
  23048. if (this.radius !== 1) object.radius = this.radius;
  23049. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  23050. object.camera = this.camera.toJSON(false).object;
  23051. delete object.camera.matrix;
  23052. return object;
  23053. }
  23054. }
  23055. class SpotLightShadow extends LightShadow {
  23056. constructor() {
  23057. super(new PerspectiveCamera(50, 1, 0.5, 500));
  23058. this.focus = 1;
  23059. }
  23060. updateMatrices(light) {
  23061. const camera = this.camera;
  23062. const fov = RAD2DEG * 2 * light.angle * this.focus;
  23063. const aspect = this.mapSize.width / this.mapSize.height;
  23064. const far = light.distance || camera.far;
  23065. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  23066. camera.fov = fov;
  23067. camera.aspect = aspect;
  23068. camera.far = far;
  23069. camera.updateProjectionMatrix();
  23070. }
  23071. super.updateMatrices(light);
  23072. }
  23073. copy(source) {
  23074. super.copy(source);
  23075. this.focus = source.focus;
  23076. return this;
  23077. }
  23078. }
  23079. SpotLightShadow.prototype.isSpotLightShadow = true;
  23080. class SpotLight extends Light {
  23081. constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1) {
  23082. super(color, intensity);
  23083. this.type = 'SpotLight';
  23084. this.position.copy(Object3D.DefaultUp);
  23085. this.updateMatrix();
  23086. this.target = new Object3D();
  23087. this.distance = distance;
  23088. this.angle = angle;
  23089. this.penumbra = penumbra;
  23090. this.decay = decay; // for physically correct lights, should be 2.
  23091. this.shadow = new SpotLightShadow();
  23092. }
  23093. get power() {
  23094. // intensity = power per solid angle.
  23095. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23096. return this.intensity * Math.PI;
  23097. }
  23098. set power(power) {
  23099. // intensity = power per solid angle.
  23100. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23101. this.intensity = power / Math.PI;
  23102. }
  23103. dispose() {
  23104. this.shadow.dispose();
  23105. }
  23106. copy(source) {
  23107. super.copy(source);
  23108. this.distance = source.distance;
  23109. this.angle = source.angle;
  23110. this.penumbra = source.penumbra;
  23111. this.decay = source.decay;
  23112. this.target = source.target.clone();
  23113. this.shadow = source.shadow.clone();
  23114. return this;
  23115. }
  23116. }
  23117. SpotLight.prototype.isSpotLight = true;
  23118. const _projScreenMatrix = /*@__PURE__*/new Matrix4();
  23119. const _lightPositionWorld = /*@__PURE__*/new Vector3();
  23120. const _lookTarget = /*@__PURE__*/new Vector3();
  23121. class PointLightShadow extends LightShadow {
  23122. constructor() {
  23123. super(new PerspectiveCamera(90, 1, 0.5, 500));
  23124. this._frameExtents = new Vector2(4, 2);
  23125. this._viewportCount = 6;
  23126. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  23127. // following orientation:
  23128. //
  23129. // xzXZ
  23130. // y Y
  23131. //
  23132. // X - Positive x direction
  23133. // x - Negative x direction
  23134. // Y - Positive y direction
  23135. // y - Negative y direction
  23136. // Z - Positive z direction
  23137. // z - Negative z direction
  23138. // positive X
  23139. new Vector4(2, 1, 1, 1), // negative X
  23140. new Vector4(0, 1, 1, 1), // positive Z
  23141. new Vector4(3, 1, 1, 1), // negative Z
  23142. new Vector4(1, 1, 1, 1), // positive Y
  23143. new Vector4(3, 0, 1, 1), // negative Y
  23144. new Vector4(1, 0, 1, 1)];
  23145. 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)];
  23146. 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)];
  23147. }
  23148. updateMatrices(light, viewportIndex = 0) {
  23149. const camera = this.camera;
  23150. const shadowMatrix = this.matrix;
  23151. const far = light.distance || camera.far;
  23152. if (far !== camera.far) {
  23153. camera.far = far;
  23154. camera.updateProjectionMatrix();
  23155. }
  23156. _lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23157. camera.position.copy(_lightPositionWorld);
  23158. _lookTarget.copy(camera.position);
  23159. _lookTarget.add(this._cubeDirections[viewportIndex]);
  23160. camera.up.copy(this._cubeUps[viewportIndex]);
  23161. camera.lookAt(_lookTarget);
  23162. camera.updateMatrixWorld();
  23163. shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z);
  23164. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  23165. this._frustum.setFromProjectionMatrix(_projScreenMatrix);
  23166. }
  23167. }
  23168. PointLightShadow.prototype.isPointLightShadow = true;
  23169. class PointLight extends Light {
  23170. constructor(color, intensity, distance = 0, decay = 1) {
  23171. super(color, intensity);
  23172. this.type = 'PointLight';
  23173. this.distance = distance;
  23174. this.decay = decay; // for physically correct lights, should be 2.
  23175. this.shadow = new PointLightShadow();
  23176. }
  23177. get power() {
  23178. // intensity = power per solid angle.
  23179. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23180. return this.intensity * 4 * Math.PI;
  23181. }
  23182. set power(power) {
  23183. // intensity = power per solid angle.
  23184. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23185. this.intensity = power / (4 * Math.PI);
  23186. }
  23187. dispose() {
  23188. this.shadow.dispose();
  23189. }
  23190. copy(source) {
  23191. super.copy(source);
  23192. this.distance = source.distance;
  23193. this.decay = source.decay;
  23194. this.shadow = source.shadow.clone();
  23195. return this;
  23196. }
  23197. }
  23198. PointLight.prototype.isPointLight = true;
  23199. class DirectionalLightShadow extends LightShadow {
  23200. constructor() {
  23201. super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  23202. }
  23203. }
  23204. DirectionalLightShadow.prototype.isDirectionalLightShadow = true;
  23205. class DirectionalLight extends Light {
  23206. constructor(color, intensity) {
  23207. super(color, intensity);
  23208. this.type = 'DirectionalLight';
  23209. this.position.copy(Object3D.DefaultUp);
  23210. this.updateMatrix();
  23211. this.target = new Object3D();
  23212. this.shadow = new DirectionalLightShadow();
  23213. }
  23214. dispose() {
  23215. this.shadow.dispose();
  23216. }
  23217. copy(source) {
  23218. super.copy(source);
  23219. this.target = source.target.clone();
  23220. this.shadow = source.shadow.clone();
  23221. return this;
  23222. }
  23223. }
  23224. DirectionalLight.prototype.isDirectionalLight = true;
  23225. class AmbientLight extends Light {
  23226. constructor(color, intensity) {
  23227. super(color, intensity);
  23228. this.type = 'AmbientLight';
  23229. }
  23230. }
  23231. AmbientLight.prototype.isAmbientLight = true;
  23232. class RectAreaLight extends Light {
  23233. constructor(color, intensity, width = 10, height = 10) {
  23234. super(color, intensity);
  23235. this.type = 'RectAreaLight';
  23236. this.width = width;
  23237. this.height = height;
  23238. }
  23239. copy(source) {
  23240. super.copy(source);
  23241. this.width = source.width;
  23242. this.height = source.height;
  23243. return this;
  23244. }
  23245. toJSON(meta) {
  23246. const data = super.toJSON(meta);
  23247. data.object.width = this.width;
  23248. data.object.height = this.height;
  23249. return data;
  23250. }
  23251. }
  23252. RectAreaLight.prototype.isRectAreaLight = true;
  23253. /**
  23254. * Primary reference:
  23255. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23256. *
  23257. * Secondary reference:
  23258. * https://www.ppsloan.org/publications/StupidSH36.pdf
  23259. */
  23260. // 3-band SH defined by 9 coefficients
  23261. class SphericalHarmonics3 {
  23262. constructor() {
  23263. this.coefficients = [];
  23264. for (let i = 0; i < 9; i++) {
  23265. this.coefficients.push(new Vector3());
  23266. }
  23267. }
  23268. set(coefficients) {
  23269. for (let i = 0; i < 9; i++) {
  23270. this.coefficients[i].copy(coefficients[i]);
  23271. }
  23272. return this;
  23273. }
  23274. zero() {
  23275. for (let i = 0; i < 9; i++) {
  23276. this.coefficients[i].set(0, 0, 0);
  23277. }
  23278. return this;
  23279. } // get the radiance in the direction of the normal
  23280. // target is a Vector3
  23281. getAt(normal, target) {
  23282. // normal is assumed to be unit length
  23283. const x = normal.x,
  23284. y = normal.y,
  23285. z = normal.z;
  23286. const coeff = this.coefficients; // band 0
  23287. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  23288. target.addScaledVector(coeff[1], 0.488603 * y);
  23289. target.addScaledVector(coeff[2], 0.488603 * z);
  23290. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  23291. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  23292. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  23293. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  23294. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  23295. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  23296. return target;
  23297. } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  23298. // target is a Vector3
  23299. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23300. getIrradianceAt(normal, target) {
  23301. // normal is assumed to be unit length
  23302. const x = normal.x,
  23303. y = normal.y,
  23304. z = normal.z;
  23305. const coeff = this.coefficients; // band 0
  23306. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  23307. // band 1
  23308. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  23309. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  23310. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  23311. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  23312. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  23313. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  23314. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  23315. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  23316. return target;
  23317. }
  23318. add(sh) {
  23319. for (let i = 0; i < 9; i++) {
  23320. this.coefficients[i].add(sh.coefficients[i]);
  23321. }
  23322. return this;
  23323. }
  23324. addScaledSH(sh, s) {
  23325. for (let i = 0; i < 9; i++) {
  23326. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  23327. }
  23328. return this;
  23329. }
  23330. scale(s) {
  23331. for (let i = 0; i < 9; i++) {
  23332. this.coefficients[i].multiplyScalar(s);
  23333. }
  23334. return this;
  23335. }
  23336. lerp(sh, alpha) {
  23337. for (let i = 0; i < 9; i++) {
  23338. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  23339. }
  23340. return this;
  23341. }
  23342. equals(sh) {
  23343. for (let i = 0; i < 9; i++) {
  23344. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  23345. return false;
  23346. }
  23347. }
  23348. return true;
  23349. }
  23350. copy(sh) {
  23351. return this.set(sh.coefficients);
  23352. }
  23353. clone() {
  23354. return new this.constructor().copy(this);
  23355. }
  23356. fromArray(array, offset = 0) {
  23357. const coefficients = this.coefficients;
  23358. for (let i = 0; i < 9; i++) {
  23359. coefficients[i].fromArray(array, offset + i * 3);
  23360. }
  23361. return this;
  23362. }
  23363. toArray(array = [], offset = 0) {
  23364. const coefficients = this.coefficients;
  23365. for (let i = 0; i < 9; i++) {
  23366. coefficients[i].toArray(array, offset + i * 3);
  23367. }
  23368. return array;
  23369. } // evaluate the basis functions
  23370. // shBasis is an Array[ 9 ]
  23371. static getBasisAt(normal, shBasis) {
  23372. // normal is assumed to be unit length
  23373. const x = normal.x,
  23374. y = normal.y,
  23375. z = normal.z; // band 0
  23376. shBasis[0] = 0.282095; // band 1
  23377. shBasis[1] = 0.488603 * y;
  23378. shBasis[2] = 0.488603 * z;
  23379. shBasis[3] = 0.488603 * x; // band 2
  23380. shBasis[4] = 1.092548 * x * y;
  23381. shBasis[5] = 1.092548 * y * z;
  23382. shBasis[6] = 0.315392 * (3 * z * z - 1);
  23383. shBasis[7] = 1.092548 * x * z;
  23384. shBasis[8] = 0.546274 * (x * x - y * y);
  23385. }
  23386. }
  23387. SphericalHarmonics3.prototype.isSphericalHarmonics3 = true;
  23388. class LightProbe extends Light {
  23389. constructor(sh = new SphericalHarmonics3(), intensity = 1) {
  23390. super(undefined, intensity);
  23391. this.sh = sh;
  23392. }
  23393. copy(source) {
  23394. super.copy(source);
  23395. this.sh.copy(source.sh);
  23396. return this;
  23397. }
  23398. fromJSON(json) {
  23399. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  23400. this.sh.fromArray(json.sh);
  23401. return this;
  23402. }
  23403. toJSON(meta) {
  23404. const data = super.toJSON(meta);
  23405. data.object.sh = this.sh.toArray();
  23406. return data;
  23407. }
  23408. }
  23409. LightProbe.prototype.isLightProbe = true;
  23410. class MaterialLoader extends Loader {
  23411. constructor(manager) {
  23412. super(manager);
  23413. this.textures = {};
  23414. }
  23415. load(url, onLoad, onProgress, onError) {
  23416. const scope = this;
  23417. const loader = new FileLoader(scope.manager);
  23418. loader.setPath(scope.path);
  23419. loader.setRequestHeader(scope.requestHeader);
  23420. loader.setWithCredentials(scope.withCredentials);
  23421. loader.load(url, function (text) {
  23422. try {
  23423. onLoad(scope.parse(JSON.parse(text)));
  23424. } catch (e) {
  23425. if (onError) {
  23426. onError(e);
  23427. } else {
  23428. console.error(e);
  23429. }
  23430. scope.manager.itemError(url);
  23431. }
  23432. }, onProgress, onError);
  23433. }
  23434. parse(json) {
  23435. const textures = this.textures;
  23436. function getTexture(name) {
  23437. if (textures[name] === undefined) {
  23438. console.warn('THREE.MaterialLoader: Undefined texture', name);
  23439. }
  23440. return textures[name];
  23441. }
  23442. const material = new Materials[json.type]();
  23443. if (json.uuid !== undefined) material.uuid = json.uuid;
  23444. if (json.name !== undefined) material.name = json.name;
  23445. if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
  23446. if (json.roughness !== undefined) material.roughness = json.roughness;
  23447. if (json.metalness !== undefined) material.metalness = json.metalness;
  23448. if (json.sheen !== undefined) material.sheen = new Color().setHex(json.sheen);
  23449. if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
  23450. if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
  23451. if (json.specularIntensity !== undefined) material.specularIntensity = json.specularIntensity;
  23452. if (json.specularTint !== undefined && material.specularTint !== undefined) material.specularTint.setHex(json.specularTint);
  23453. if (json.shininess !== undefined) material.shininess = json.shininess;
  23454. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  23455. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  23456. if (json.transmission !== undefined) material.transmission = json.transmission;
  23457. if (json.thickness !== undefined) material.thickness = json.thickness;
  23458. if (json.attenuationDistance !== undefined) material.attenuationDistance = json.attenuationDistance;
  23459. if (json.attenuationTint !== undefined && material.attenuationTint !== undefined) material.attenuationTint.setHex(json.attenuationTint);
  23460. if (json.fog !== undefined) material.fog = json.fog;
  23461. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  23462. if (json.blending !== undefined) material.blending = json.blending;
  23463. if (json.combine !== undefined) material.combine = json.combine;
  23464. if (json.side !== undefined) material.side = json.side;
  23465. if (json.shadowSide !== undefined) material.shadowSide = json.shadowSide;
  23466. if (json.opacity !== undefined) material.opacity = json.opacity;
  23467. if (json.transparent !== undefined) material.transparent = json.transparent;
  23468. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  23469. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  23470. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  23471. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  23472. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  23473. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  23474. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  23475. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  23476. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  23477. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  23478. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  23479. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  23480. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  23481. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  23482. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  23483. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  23484. if (json.rotation !== undefined) material.rotation = json.rotation;
  23485. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  23486. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  23487. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  23488. if (json.scale !== undefined) material.scale = json.scale;
  23489. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  23490. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  23491. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  23492. if (json.dithering !== undefined) material.dithering = json.dithering;
  23493. if (json.alphaToCoverage !== undefined) material.alphaToCoverage = json.alphaToCoverage;
  23494. if (json.premultipliedAlpha !== undefined) material.premultipliedAlpha = json.premultipliedAlpha;
  23495. if (json.visible !== undefined) material.visible = json.visible;
  23496. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  23497. if (json.userData !== undefined) material.userData = json.userData;
  23498. if (json.vertexColors !== undefined) {
  23499. if (typeof json.vertexColors === 'number') {
  23500. material.vertexColors = json.vertexColors > 0 ? true : false;
  23501. } else {
  23502. material.vertexColors = json.vertexColors;
  23503. }
  23504. } // Shader Material
  23505. if (json.uniforms !== undefined) {
  23506. for (const name in json.uniforms) {
  23507. const uniform = json.uniforms[name];
  23508. material.uniforms[name] = {};
  23509. switch (uniform.type) {
  23510. case 't':
  23511. material.uniforms[name].value = getTexture(uniform.value);
  23512. break;
  23513. case 'c':
  23514. material.uniforms[name].value = new Color().setHex(uniform.value);
  23515. break;
  23516. case 'v2':
  23517. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  23518. break;
  23519. case 'v3':
  23520. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  23521. break;
  23522. case 'v4':
  23523. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  23524. break;
  23525. case 'm3':
  23526. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  23527. break;
  23528. case 'm4':
  23529. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  23530. break;
  23531. default:
  23532. material.uniforms[name].value = uniform.value;
  23533. }
  23534. }
  23535. }
  23536. if (json.defines !== undefined) material.defines = json.defines;
  23537. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  23538. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  23539. if (json.extensions !== undefined) {
  23540. for (const key in json.extensions) {
  23541. material.extensions[key] = json.extensions[key];
  23542. }
  23543. } // Deprecated
  23544. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  23545. // for PointsMaterial
  23546. if (json.size !== undefined) material.size = json.size;
  23547. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  23548. if (json.map !== undefined) material.map = getTexture(json.map);
  23549. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  23550. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  23551. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  23552. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  23553. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  23554. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  23555. if (json.normalScale !== undefined) {
  23556. let normalScale = json.normalScale;
  23557. if (Array.isArray(normalScale) === false) {
  23558. // Blender exporter used to export a scalar. See #7459
  23559. normalScale = [normalScale, normalScale];
  23560. }
  23561. material.normalScale = new Vector2().fromArray(normalScale);
  23562. }
  23563. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  23564. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  23565. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  23566. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  23567. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  23568. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  23569. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  23570. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  23571. if (json.specularIntensityMap !== undefined) material.specularIntensityMap = getTexture(json.specularIntensityMap);
  23572. if (json.specularTintMap !== undefined) material.specularTintMap = getTexture(json.specularTintMap);
  23573. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  23574. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  23575. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  23576. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  23577. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  23578. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  23579. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  23580. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  23581. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  23582. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  23583. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  23584. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  23585. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  23586. if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
  23587. if (json.thicknessMap !== undefined) material.thicknessMap = getTexture(json.thicknessMap);
  23588. return material;
  23589. }
  23590. setTextures(value) {
  23591. this.textures = value;
  23592. return this;
  23593. }
  23594. }
  23595. class LoaderUtils {
  23596. static decodeText(array) {
  23597. if (typeof TextDecoder !== 'undefined') {
  23598. return new TextDecoder().decode(array);
  23599. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  23600. // throws a "maximum call stack size exceeded" error for large arrays.
  23601. let s = '';
  23602. for (let i = 0, il = array.length; i < il; i++) {
  23603. // Implicitly assumes little-endian.
  23604. s += String.fromCharCode(array[i]);
  23605. }
  23606. try {
  23607. // merges multi-byte utf-8 characters.
  23608. return decodeURIComponent(escape(s));
  23609. } catch (e) {
  23610. // see #16358
  23611. return s;
  23612. }
  23613. }
  23614. static extractUrlBase(url) {
  23615. const index = url.lastIndexOf('/');
  23616. if (index === -1) return './';
  23617. return url.substr(0, index + 1);
  23618. }
  23619. }
  23620. class InstancedBufferGeometry extends BufferGeometry {
  23621. constructor() {
  23622. super();
  23623. this.type = 'InstancedBufferGeometry';
  23624. this.instanceCount = Infinity;
  23625. }
  23626. copy(source) {
  23627. super.copy(source);
  23628. this.instanceCount = source.instanceCount;
  23629. return this;
  23630. }
  23631. clone() {
  23632. return new this.constructor().copy(this);
  23633. }
  23634. toJSON() {
  23635. const data = super.toJSON(this);
  23636. data.instanceCount = this.instanceCount;
  23637. data.isInstancedBufferGeometry = true;
  23638. return data;
  23639. }
  23640. }
  23641. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  23642. class InstancedBufferAttribute extends BufferAttribute {
  23643. constructor(array, itemSize, normalized, meshPerAttribute = 1) {
  23644. if (typeof normalized === 'number') {
  23645. meshPerAttribute = normalized;
  23646. normalized = false;
  23647. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  23648. }
  23649. super(array, itemSize, normalized);
  23650. this.meshPerAttribute = meshPerAttribute;
  23651. }
  23652. copy(source) {
  23653. super.copy(source);
  23654. this.meshPerAttribute = source.meshPerAttribute;
  23655. return this;
  23656. }
  23657. toJSON() {
  23658. const data = super.toJSON();
  23659. data.meshPerAttribute = this.meshPerAttribute;
  23660. data.isInstancedBufferAttribute = true;
  23661. return data;
  23662. }
  23663. }
  23664. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  23665. class BufferGeometryLoader extends Loader {
  23666. constructor(manager) {
  23667. super(manager);
  23668. }
  23669. load(url, onLoad, onProgress, onError) {
  23670. const scope = this;
  23671. const loader = new FileLoader(scope.manager);
  23672. loader.setPath(scope.path);
  23673. loader.setRequestHeader(scope.requestHeader);
  23674. loader.setWithCredentials(scope.withCredentials);
  23675. loader.load(url, function (text) {
  23676. try {
  23677. onLoad(scope.parse(JSON.parse(text)));
  23678. } catch (e) {
  23679. if (onError) {
  23680. onError(e);
  23681. } else {
  23682. console.error(e);
  23683. }
  23684. scope.manager.itemError(url);
  23685. }
  23686. }, onProgress, onError);
  23687. }
  23688. parse(json) {
  23689. const interleavedBufferMap = {};
  23690. const arrayBufferMap = {};
  23691. function getInterleavedBuffer(json, uuid) {
  23692. if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
  23693. const interleavedBuffers = json.interleavedBuffers;
  23694. const interleavedBuffer = interleavedBuffers[uuid];
  23695. const buffer = getArrayBuffer(json, interleavedBuffer.buffer);
  23696. const array = getTypedArray(interleavedBuffer.type, buffer);
  23697. const ib = new InterleavedBuffer(array, interleavedBuffer.stride);
  23698. ib.uuid = interleavedBuffer.uuid;
  23699. interleavedBufferMap[uuid] = ib;
  23700. return ib;
  23701. }
  23702. function getArrayBuffer(json, uuid) {
  23703. if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
  23704. const arrayBuffers = json.arrayBuffers;
  23705. const arrayBuffer = arrayBuffers[uuid];
  23706. const ab = new Uint32Array(arrayBuffer).buffer;
  23707. arrayBufferMap[uuid] = ab;
  23708. return ab;
  23709. }
  23710. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  23711. const index = json.data.index;
  23712. if (index !== undefined) {
  23713. const typedArray = getTypedArray(index.type, index.array);
  23714. geometry.setIndex(new BufferAttribute(typedArray, 1));
  23715. }
  23716. const attributes = json.data.attributes;
  23717. for (const key in attributes) {
  23718. const attribute = attributes[key];
  23719. let bufferAttribute;
  23720. if (attribute.isInterleavedBufferAttribute) {
  23721. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  23722. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  23723. } else {
  23724. const typedArray = getTypedArray(attribute.type, attribute.array);
  23725. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  23726. bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  23727. }
  23728. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  23729. if (attribute.usage !== undefined) bufferAttribute.setUsage(attribute.usage);
  23730. if (attribute.updateRange !== undefined) {
  23731. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  23732. bufferAttribute.updateRange.count = attribute.updateRange.count;
  23733. }
  23734. geometry.setAttribute(key, bufferAttribute);
  23735. }
  23736. const morphAttributes = json.data.morphAttributes;
  23737. if (morphAttributes) {
  23738. for (const key in morphAttributes) {
  23739. const attributeArray = morphAttributes[key];
  23740. const array = [];
  23741. for (let i = 0, il = attributeArray.length; i < il; i++) {
  23742. const attribute = attributeArray[i];
  23743. let bufferAttribute;
  23744. if (attribute.isInterleavedBufferAttribute) {
  23745. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  23746. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  23747. } else {
  23748. const typedArray = getTypedArray(attribute.type, attribute.array);
  23749. bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  23750. }
  23751. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  23752. array.push(bufferAttribute);
  23753. }
  23754. geometry.morphAttributes[key] = array;
  23755. }
  23756. }
  23757. const morphTargetsRelative = json.data.morphTargetsRelative;
  23758. if (morphTargetsRelative) {
  23759. geometry.morphTargetsRelative = true;
  23760. }
  23761. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  23762. if (groups !== undefined) {
  23763. for (let i = 0, n = groups.length; i !== n; ++i) {
  23764. const group = groups[i];
  23765. geometry.addGroup(group.start, group.count, group.materialIndex);
  23766. }
  23767. }
  23768. const boundingSphere = json.data.boundingSphere;
  23769. if (boundingSphere !== undefined) {
  23770. const center = new Vector3();
  23771. if (boundingSphere.center !== undefined) {
  23772. center.fromArray(boundingSphere.center);
  23773. }
  23774. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  23775. }
  23776. if (json.name) geometry.name = json.name;
  23777. if (json.userData) geometry.userData = json.userData;
  23778. return geometry;
  23779. }
  23780. }
  23781. class ObjectLoader extends Loader {
  23782. constructor(manager) {
  23783. super(manager);
  23784. }
  23785. load(url, onLoad, onProgress, onError) {
  23786. const scope = this;
  23787. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  23788. this.resourcePath = this.resourcePath || path;
  23789. const loader = new FileLoader(this.manager);
  23790. loader.setPath(this.path);
  23791. loader.setRequestHeader(this.requestHeader);
  23792. loader.setWithCredentials(this.withCredentials);
  23793. loader.load(url, function (text) {
  23794. let json = null;
  23795. try {
  23796. json = JSON.parse(text);
  23797. } catch (error) {
  23798. if (onError !== undefined) onError(error);
  23799. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  23800. return;
  23801. }
  23802. const metadata = json.metadata;
  23803. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  23804. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  23805. return;
  23806. }
  23807. scope.parse(json, onLoad);
  23808. }, onProgress, onError);
  23809. }
  23810. async loadAsync(url, onProgress) {
  23811. const scope = this;
  23812. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  23813. this.resourcePath = this.resourcePath || path;
  23814. const loader = new FileLoader(this.manager);
  23815. loader.setPath(this.path);
  23816. loader.setRequestHeader(this.requestHeader);
  23817. loader.setWithCredentials(this.withCredentials);
  23818. const text = await loader.loadAsync(url, onProgress);
  23819. const json = JSON.parse(text);
  23820. const metadata = json.metadata;
  23821. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  23822. throw new Error('THREE.ObjectLoader: Can\'t load ' + url);
  23823. }
  23824. return await scope.parseAsync(json);
  23825. }
  23826. parse(json, onLoad) {
  23827. const animations = this.parseAnimations(json.animations);
  23828. const shapes = this.parseShapes(json.shapes);
  23829. const geometries = this.parseGeometries(json.geometries, shapes);
  23830. const images = this.parseImages(json.images, function () {
  23831. if (onLoad !== undefined) onLoad(object);
  23832. });
  23833. const textures = this.parseTextures(json.textures, images);
  23834. const materials = this.parseMaterials(json.materials, textures);
  23835. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  23836. const skeletons = this.parseSkeletons(json.skeletons, object);
  23837. this.bindSkeletons(object, skeletons); //
  23838. if (onLoad !== undefined) {
  23839. let hasImages = false;
  23840. for (const uuid in images) {
  23841. if (images[uuid] instanceof HTMLImageElement) {
  23842. hasImages = true;
  23843. break;
  23844. }
  23845. }
  23846. if (hasImages === false) onLoad(object);
  23847. }
  23848. return object;
  23849. }
  23850. async parseAsync(json) {
  23851. const animations = this.parseAnimations(json.animations);
  23852. const shapes = this.parseShapes(json.shapes);
  23853. const geometries = this.parseGeometries(json.geometries, shapes);
  23854. const images = await this.parseImagesAsync(json.images);
  23855. const textures = this.parseTextures(json.textures, images);
  23856. const materials = this.parseMaterials(json.materials, textures);
  23857. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  23858. const skeletons = this.parseSkeletons(json.skeletons, object);
  23859. this.bindSkeletons(object, skeletons);
  23860. return object;
  23861. }
  23862. parseShapes(json) {
  23863. const shapes = {};
  23864. if (json !== undefined) {
  23865. for (let i = 0, l = json.length; i < l; i++) {
  23866. const shape = new Shape().fromJSON(json[i]);
  23867. shapes[shape.uuid] = shape;
  23868. }
  23869. }
  23870. return shapes;
  23871. }
  23872. parseSkeletons(json, object) {
  23873. const skeletons = {};
  23874. const bones = {}; // generate bone lookup table
  23875. object.traverse(function (child) {
  23876. if (child.isBone) bones[child.uuid] = child;
  23877. }); // create skeletons
  23878. if (json !== undefined) {
  23879. for (let i = 0, l = json.length; i < l; i++) {
  23880. const skeleton = new Skeleton().fromJSON(json[i], bones);
  23881. skeletons[skeleton.uuid] = skeleton;
  23882. }
  23883. }
  23884. return skeletons;
  23885. }
  23886. parseGeometries(json, shapes) {
  23887. const geometries = {};
  23888. if (json !== undefined) {
  23889. const bufferGeometryLoader = new BufferGeometryLoader();
  23890. for (let i = 0, l = json.length; i < l; i++) {
  23891. let geometry;
  23892. const data = json[i];
  23893. switch (data.type) {
  23894. case 'BufferGeometry':
  23895. case 'InstancedBufferGeometry':
  23896. geometry = bufferGeometryLoader.parse(data);
  23897. break;
  23898. case 'Geometry':
  23899. console.error('THREE.ObjectLoader: The legacy Geometry type is no longer supported.');
  23900. break;
  23901. default:
  23902. if (data.type in Geometries) {
  23903. geometry = Geometries[data.type].fromJSON(data, shapes);
  23904. } else {
  23905. console.warn(`THREE.ObjectLoader: Unsupported geometry type "${data.type}"`);
  23906. }
  23907. }
  23908. geometry.uuid = data.uuid;
  23909. if (data.name !== undefined) geometry.name = data.name;
  23910. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  23911. geometries[data.uuid] = geometry;
  23912. }
  23913. }
  23914. return geometries;
  23915. }
  23916. parseMaterials(json, textures) {
  23917. const cache = {}; // MultiMaterial
  23918. const materials = {};
  23919. if (json !== undefined) {
  23920. const loader = new MaterialLoader();
  23921. loader.setTextures(textures);
  23922. for (let i = 0, l = json.length; i < l; i++) {
  23923. const data = json[i];
  23924. if (data.type === 'MultiMaterial') {
  23925. // Deprecated
  23926. const array = [];
  23927. for (let j = 0; j < data.materials.length; j++) {
  23928. const material = data.materials[j];
  23929. if (cache[material.uuid] === undefined) {
  23930. cache[material.uuid] = loader.parse(material);
  23931. }
  23932. array.push(cache[material.uuid]);
  23933. }
  23934. materials[data.uuid] = array;
  23935. } else {
  23936. if (cache[data.uuid] === undefined) {
  23937. cache[data.uuid] = loader.parse(data);
  23938. }
  23939. materials[data.uuid] = cache[data.uuid];
  23940. }
  23941. }
  23942. }
  23943. return materials;
  23944. }
  23945. parseAnimations(json) {
  23946. const animations = {};
  23947. if (json !== undefined) {
  23948. for (let i = 0; i < json.length; i++) {
  23949. const data = json[i];
  23950. const clip = AnimationClip.parse(data);
  23951. animations[clip.uuid] = clip;
  23952. }
  23953. }
  23954. return animations;
  23955. }
  23956. parseImages(json, onLoad) {
  23957. const scope = this;
  23958. const images = {};
  23959. let loader;
  23960. function loadImage(url) {
  23961. scope.manager.itemStart(url);
  23962. return loader.load(url, function () {
  23963. scope.manager.itemEnd(url);
  23964. }, undefined, function () {
  23965. scope.manager.itemError(url);
  23966. scope.manager.itemEnd(url);
  23967. });
  23968. }
  23969. function deserializeImage(image) {
  23970. if (typeof image === 'string') {
  23971. const url = image;
  23972. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  23973. return loadImage(path);
  23974. } else {
  23975. if (image.data) {
  23976. return {
  23977. data: getTypedArray(image.type, image.data),
  23978. width: image.width,
  23979. height: image.height
  23980. };
  23981. } else {
  23982. return null;
  23983. }
  23984. }
  23985. }
  23986. if (json !== undefined && json.length > 0) {
  23987. const manager = new LoadingManager(onLoad);
  23988. loader = new ImageLoader(manager);
  23989. loader.setCrossOrigin(this.crossOrigin);
  23990. for (let i = 0, il = json.length; i < il; i++) {
  23991. const image = json[i];
  23992. const url = image.url;
  23993. if (Array.isArray(url)) {
  23994. // load array of images e.g CubeTexture
  23995. images[image.uuid] = [];
  23996. for (let j = 0, jl = url.length; j < jl; j++) {
  23997. const currentUrl = url[j];
  23998. const deserializedImage = deserializeImage(currentUrl);
  23999. if (deserializedImage !== null) {
  24000. if (deserializedImage instanceof HTMLImageElement) {
  24001. images[image.uuid].push(deserializedImage);
  24002. } else {
  24003. // special case: handle array of data textures for cube textures
  24004. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  24005. }
  24006. }
  24007. }
  24008. } else {
  24009. // load single image
  24010. const deserializedImage = deserializeImage(image.url);
  24011. if (deserializedImage !== null) {
  24012. images[image.uuid] = deserializedImage;
  24013. }
  24014. }
  24015. }
  24016. }
  24017. return images;
  24018. }
  24019. async parseImagesAsync(json) {
  24020. const scope = this;
  24021. const images = {};
  24022. let loader;
  24023. async function deserializeImage(image) {
  24024. if (typeof image === 'string') {
  24025. const url = image;
  24026. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  24027. return await loader.loadAsync(path);
  24028. } else {
  24029. if (image.data) {
  24030. return {
  24031. data: getTypedArray(image.type, image.data),
  24032. width: image.width,
  24033. height: image.height
  24034. };
  24035. } else {
  24036. return null;
  24037. }
  24038. }
  24039. }
  24040. if (json !== undefined && json.length > 0) {
  24041. loader = new ImageLoader(this.manager);
  24042. loader.setCrossOrigin(this.crossOrigin);
  24043. for (let i = 0, il = json.length; i < il; i++) {
  24044. const image = json[i];
  24045. const url = image.url;
  24046. if (Array.isArray(url)) {
  24047. // load array of images e.g CubeTexture
  24048. images[image.uuid] = [];
  24049. for (let j = 0, jl = url.length; j < jl; j++) {
  24050. const currentUrl = url[j];
  24051. const deserializedImage = await deserializeImage(currentUrl);
  24052. if (deserializedImage !== null) {
  24053. if (deserializedImage instanceof HTMLImageElement) {
  24054. images[image.uuid].push(deserializedImage);
  24055. } else {
  24056. // special case: handle array of data textures for cube textures
  24057. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  24058. }
  24059. }
  24060. }
  24061. } else {
  24062. // load single image
  24063. const deserializedImage = await deserializeImage(image.url);
  24064. if (deserializedImage !== null) {
  24065. images[image.uuid] = deserializedImage;
  24066. }
  24067. }
  24068. }
  24069. }
  24070. return images;
  24071. }
  24072. parseTextures(json, images) {
  24073. function parseConstant(value, type) {
  24074. if (typeof value === 'number') return value;
  24075. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  24076. return type[value];
  24077. }
  24078. const textures = {};
  24079. if (json !== undefined) {
  24080. for (let i = 0, l = json.length; i < l; i++) {
  24081. const data = json[i];
  24082. if (data.image === undefined) {
  24083. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  24084. }
  24085. if (images[data.image] === undefined) {
  24086. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  24087. }
  24088. let texture;
  24089. const image = images[data.image];
  24090. if (Array.isArray(image)) {
  24091. texture = new CubeTexture(image);
  24092. if (image.length === 6) texture.needsUpdate = true;
  24093. } else {
  24094. if (image && image.data) {
  24095. texture = new DataTexture(image.data, image.width, image.height);
  24096. } else {
  24097. texture = new Texture(image);
  24098. }
  24099. if (image) texture.needsUpdate = true; // textures can have undefined image data
  24100. }
  24101. texture.uuid = data.uuid;
  24102. if (data.name !== undefined) texture.name = data.name;
  24103. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  24104. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  24105. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  24106. if (data.center !== undefined) texture.center.fromArray(data.center);
  24107. if (data.rotation !== undefined) texture.rotation = data.rotation;
  24108. if (data.wrap !== undefined) {
  24109. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  24110. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  24111. }
  24112. if (data.format !== undefined) texture.format = data.format;
  24113. if (data.type !== undefined) texture.type = data.type;
  24114. if (data.encoding !== undefined) texture.encoding = data.encoding;
  24115. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  24116. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  24117. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  24118. if (data.flipY !== undefined) texture.flipY = data.flipY;
  24119. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  24120. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  24121. textures[data.uuid] = texture;
  24122. }
  24123. }
  24124. return textures;
  24125. }
  24126. parseObject(data, geometries, materials, textures, animations) {
  24127. let object;
  24128. function getGeometry(name) {
  24129. if (geometries[name] === undefined) {
  24130. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  24131. }
  24132. return geometries[name];
  24133. }
  24134. function getMaterial(name) {
  24135. if (name === undefined) return undefined;
  24136. if (Array.isArray(name)) {
  24137. const array = [];
  24138. for (let i = 0, l = name.length; i < l; i++) {
  24139. const uuid = name[i];
  24140. if (materials[uuid] === undefined) {
  24141. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  24142. }
  24143. array.push(materials[uuid]);
  24144. }
  24145. return array;
  24146. }
  24147. if (materials[name] === undefined) {
  24148. console.warn('THREE.ObjectLoader: Undefined material', name);
  24149. }
  24150. return materials[name];
  24151. }
  24152. function getTexture(uuid) {
  24153. if (textures[uuid] === undefined) {
  24154. console.warn('THREE.ObjectLoader: Undefined texture', uuid);
  24155. }
  24156. return textures[uuid];
  24157. }
  24158. let geometry, material;
  24159. switch (data.type) {
  24160. case 'Scene':
  24161. object = new Scene();
  24162. if (data.background !== undefined) {
  24163. if (Number.isInteger(data.background)) {
  24164. object.background = new Color(data.background);
  24165. } else {
  24166. object.background = getTexture(data.background);
  24167. }
  24168. }
  24169. if (data.environment !== undefined) {
  24170. object.environment = getTexture(data.environment);
  24171. }
  24172. if (data.fog !== undefined) {
  24173. if (data.fog.type === 'Fog') {
  24174. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  24175. } else if (data.fog.type === 'FogExp2') {
  24176. object.fog = new FogExp2(data.fog.color, data.fog.density);
  24177. }
  24178. }
  24179. break;
  24180. case 'PerspectiveCamera':
  24181. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  24182. if (data.focus !== undefined) object.focus = data.focus;
  24183. if (data.zoom !== undefined) object.zoom = data.zoom;
  24184. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  24185. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  24186. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24187. break;
  24188. case 'OrthographicCamera':
  24189. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  24190. if (data.zoom !== undefined) object.zoom = data.zoom;
  24191. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24192. break;
  24193. case 'AmbientLight':
  24194. object = new AmbientLight(data.color, data.intensity);
  24195. break;
  24196. case 'DirectionalLight':
  24197. object = new DirectionalLight(data.color, data.intensity);
  24198. break;
  24199. case 'PointLight':
  24200. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  24201. break;
  24202. case 'RectAreaLight':
  24203. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  24204. break;
  24205. case 'SpotLight':
  24206. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  24207. break;
  24208. case 'HemisphereLight':
  24209. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  24210. break;
  24211. case 'LightProbe':
  24212. object = new LightProbe().fromJSON(data);
  24213. break;
  24214. case 'SkinnedMesh':
  24215. geometry = getGeometry(data.geometry);
  24216. material = getMaterial(data.material);
  24217. object = new SkinnedMesh(geometry, material);
  24218. if (data.bindMode !== undefined) object.bindMode = data.bindMode;
  24219. if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
  24220. if (data.skeleton !== undefined) object.skeleton = data.skeleton;
  24221. break;
  24222. case 'Mesh':
  24223. geometry = getGeometry(data.geometry);
  24224. material = getMaterial(data.material);
  24225. object = new Mesh(geometry, material);
  24226. break;
  24227. case 'InstancedMesh':
  24228. geometry = getGeometry(data.geometry);
  24229. material = getMaterial(data.material);
  24230. const count = data.count;
  24231. const instanceMatrix = data.instanceMatrix;
  24232. const instanceColor = data.instanceColor;
  24233. object = new InstancedMesh(geometry, material, count);
  24234. object.instanceMatrix = new BufferAttribute(new Float32Array(instanceMatrix.array), 16);
  24235. if (instanceColor !== undefined) object.instanceColor = new BufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize);
  24236. break;
  24237. case 'LOD':
  24238. object = new LOD();
  24239. break;
  24240. case 'Line':
  24241. object = new Line(getGeometry(data.geometry), getMaterial(data.material));
  24242. break;
  24243. case 'LineLoop':
  24244. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  24245. break;
  24246. case 'LineSegments':
  24247. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  24248. break;
  24249. case 'PointCloud':
  24250. case 'Points':
  24251. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  24252. break;
  24253. case 'Sprite':
  24254. object = new Sprite(getMaterial(data.material));
  24255. break;
  24256. case 'Group':
  24257. object = new Group();
  24258. break;
  24259. case 'Bone':
  24260. object = new Bone();
  24261. break;
  24262. default:
  24263. object = new Object3D();
  24264. }
  24265. object.uuid = data.uuid;
  24266. if (data.name !== undefined) object.name = data.name;
  24267. if (data.matrix !== undefined) {
  24268. object.matrix.fromArray(data.matrix);
  24269. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  24270. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  24271. } else {
  24272. if (data.position !== undefined) object.position.fromArray(data.position);
  24273. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  24274. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  24275. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  24276. }
  24277. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  24278. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  24279. if (data.shadow) {
  24280. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  24281. if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
  24282. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  24283. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  24284. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  24285. }
  24286. if (data.visible !== undefined) object.visible = data.visible;
  24287. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  24288. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  24289. if (data.userData !== undefined) object.userData = data.userData;
  24290. if (data.layers !== undefined) object.layers.mask = data.layers;
  24291. if (data.children !== undefined) {
  24292. const children = data.children;
  24293. for (let i = 0; i < children.length; i++) {
  24294. object.add(this.parseObject(children[i], geometries, materials, textures, animations));
  24295. }
  24296. }
  24297. if (data.animations !== undefined) {
  24298. const objectAnimations = data.animations;
  24299. for (let i = 0; i < objectAnimations.length; i++) {
  24300. const uuid = objectAnimations[i];
  24301. object.animations.push(animations[uuid]);
  24302. }
  24303. }
  24304. if (data.type === 'LOD') {
  24305. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  24306. const levels = data.levels;
  24307. for (let l = 0; l < levels.length; l++) {
  24308. const level = levels[l];
  24309. const child = object.getObjectByProperty('uuid', level.object);
  24310. if (child !== undefined) {
  24311. object.addLevel(child, level.distance);
  24312. }
  24313. }
  24314. }
  24315. return object;
  24316. }
  24317. bindSkeletons(object, skeletons) {
  24318. if (Object.keys(skeletons).length === 0) return;
  24319. object.traverse(function (child) {
  24320. if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
  24321. const skeleton = skeletons[child.skeleton];
  24322. if (skeleton === undefined) {
  24323. console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
  24324. } else {
  24325. child.bind(skeleton, child.bindMatrix);
  24326. }
  24327. }
  24328. });
  24329. }
  24330. /* DEPRECATED */
  24331. setTexturePath(value) {
  24332. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  24333. return this.setResourcePath(value);
  24334. }
  24335. }
  24336. const TEXTURE_MAPPING = {
  24337. UVMapping: UVMapping,
  24338. CubeReflectionMapping: CubeReflectionMapping,
  24339. CubeRefractionMapping: CubeRefractionMapping,
  24340. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  24341. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  24342. CubeUVReflectionMapping: CubeUVReflectionMapping,
  24343. CubeUVRefractionMapping: CubeUVRefractionMapping
  24344. };
  24345. const TEXTURE_WRAPPING = {
  24346. RepeatWrapping: RepeatWrapping,
  24347. ClampToEdgeWrapping: ClampToEdgeWrapping,
  24348. MirroredRepeatWrapping: MirroredRepeatWrapping
  24349. };
  24350. const TEXTURE_FILTER = {
  24351. NearestFilter: NearestFilter,
  24352. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  24353. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  24354. LinearFilter: LinearFilter,
  24355. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  24356. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  24357. };
  24358. class ImageBitmapLoader extends Loader {
  24359. constructor(manager) {
  24360. super(manager);
  24361. if (typeof createImageBitmap === 'undefined') {
  24362. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  24363. }
  24364. if (typeof fetch === 'undefined') {
  24365. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  24366. }
  24367. this.options = {
  24368. premultiplyAlpha: 'none'
  24369. };
  24370. }
  24371. setOptions(options) {
  24372. this.options = options;
  24373. return this;
  24374. }
  24375. load(url, onLoad, onProgress, onError) {
  24376. if (url === undefined) url = '';
  24377. if (this.path !== undefined) url = this.path + url;
  24378. url = this.manager.resolveURL(url);
  24379. const scope = this;
  24380. const cached = Cache.get(url);
  24381. if (cached !== undefined) {
  24382. scope.manager.itemStart(url);
  24383. setTimeout(function () {
  24384. if (onLoad) onLoad(cached);
  24385. scope.manager.itemEnd(url);
  24386. }, 0);
  24387. return cached;
  24388. }
  24389. const fetchOptions = {};
  24390. fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
  24391. fetchOptions.headers = this.requestHeader;
  24392. fetch(url, fetchOptions).then(function (res) {
  24393. return res.blob();
  24394. }).then(function (blob) {
  24395. return createImageBitmap(blob, Object.assign(scope.options, {
  24396. colorSpaceConversion: 'none'
  24397. }));
  24398. }).then(function (imageBitmap) {
  24399. Cache.add(url, imageBitmap);
  24400. if (onLoad) onLoad(imageBitmap);
  24401. scope.manager.itemEnd(url);
  24402. }).catch(function (e) {
  24403. if (onError) onError(e);
  24404. scope.manager.itemError(url);
  24405. scope.manager.itemEnd(url);
  24406. });
  24407. scope.manager.itemStart(url);
  24408. }
  24409. }
  24410. ImageBitmapLoader.prototype.isImageBitmapLoader = true;
  24411. class ShapePath {
  24412. constructor() {
  24413. this.type = 'ShapePath';
  24414. this.color = new Color();
  24415. this.subPaths = [];
  24416. this.currentPath = null;
  24417. }
  24418. moveTo(x, y) {
  24419. this.currentPath = new Path();
  24420. this.subPaths.push(this.currentPath);
  24421. this.currentPath.moveTo(x, y);
  24422. return this;
  24423. }
  24424. lineTo(x, y) {
  24425. this.currentPath.lineTo(x, y);
  24426. return this;
  24427. }
  24428. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  24429. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  24430. return this;
  24431. }
  24432. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  24433. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  24434. return this;
  24435. }
  24436. splineThru(pts) {
  24437. this.currentPath.splineThru(pts);
  24438. return this;
  24439. }
  24440. toShapes(isCCW, noHoles) {
  24441. function toShapesNoHoles(inSubpaths) {
  24442. const shapes = [];
  24443. for (let i = 0, l = inSubpaths.length; i < l; i++) {
  24444. const tmpPath = inSubpaths[i];
  24445. const tmpShape = new Shape();
  24446. tmpShape.curves = tmpPath.curves;
  24447. shapes.push(tmpShape);
  24448. }
  24449. return shapes;
  24450. }
  24451. function isPointInsidePolygon(inPt, inPolygon) {
  24452. const polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  24453. // toggling of inside/outside at every single! intersection point of an edge
  24454. // with the horizontal line through inPt, left of inPt
  24455. // not counting lowerY endpoints of edges and whole edges on that line
  24456. let inside = false;
  24457. for (let p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  24458. let edgeLowPt = inPolygon[p];
  24459. let edgeHighPt = inPolygon[q];
  24460. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  24461. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  24462. if (Math.abs(edgeDy) > Number.EPSILON) {
  24463. // not parallel
  24464. if (edgeDy < 0) {
  24465. edgeLowPt = inPolygon[q];
  24466. edgeDx = -edgeDx;
  24467. edgeHighPt = inPolygon[p];
  24468. edgeDy = -edgeDy;
  24469. }
  24470. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  24471. if (inPt.y === edgeLowPt.y) {
  24472. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  24473. // continue; // no intersection or edgeLowPt => doesn't count !!!
  24474. } else {
  24475. const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  24476. if (perpEdge === 0) return true; // inPt is on contour ?
  24477. if (perpEdge < 0) continue;
  24478. inside = !inside; // true intersection left of inPt
  24479. }
  24480. } else {
  24481. // parallel or collinear
  24482. if (inPt.y !== edgeLowPt.y) continue; // parallel
  24483. // edge lies on the same horizontal line as inPt
  24484. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  24485. // continue;
  24486. }
  24487. }
  24488. return inside;
  24489. }
  24490. const isClockWise = ShapeUtils.isClockWise;
  24491. const subPaths = this.subPaths;
  24492. if (subPaths.length === 0) return [];
  24493. if (noHoles === true) return toShapesNoHoles(subPaths);
  24494. let solid, tmpPath, tmpShape;
  24495. const shapes = [];
  24496. if (subPaths.length === 1) {
  24497. tmpPath = subPaths[0];
  24498. tmpShape = new Shape();
  24499. tmpShape.curves = tmpPath.curves;
  24500. shapes.push(tmpShape);
  24501. return shapes;
  24502. }
  24503. let holesFirst = !isClockWise(subPaths[0].getPoints());
  24504. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  24505. const betterShapeHoles = [];
  24506. const newShapes = [];
  24507. let newShapeHoles = [];
  24508. let mainIdx = 0;
  24509. let tmpPoints;
  24510. newShapes[mainIdx] = undefined;
  24511. newShapeHoles[mainIdx] = [];
  24512. for (let i = 0, l = subPaths.length; i < l; i++) {
  24513. tmpPath = subPaths[i];
  24514. tmpPoints = tmpPath.getPoints();
  24515. solid = isClockWise(tmpPoints);
  24516. solid = isCCW ? !solid : solid;
  24517. if (solid) {
  24518. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  24519. newShapes[mainIdx] = {
  24520. s: new Shape(),
  24521. p: tmpPoints
  24522. };
  24523. newShapes[mainIdx].s.curves = tmpPath.curves;
  24524. if (holesFirst) mainIdx++;
  24525. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  24526. } else {
  24527. newShapeHoles[mainIdx].push({
  24528. h: tmpPath,
  24529. p: tmpPoints[0]
  24530. }); //console.log('ccw', i);
  24531. }
  24532. } // only Holes? -> probably all Shapes with wrong orientation
  24533. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  24534. if (newShapes.length > 1) {
  24535. let ambiguous = false;
  24536. const toChange = [];
  24537. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  24538. betterShapeHoles[sIdx] = [];
  24539. }
  24540. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  24541. const sho = newShapeHoles[sIdx];
  24542. for (let hIdx = 0; hIdx < sho.length; hIdx++) {
  24543. const ho = sho[hIdx];
  24544. let hole_unassigned = true;
  24545. for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  24546. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  24547. if (sIdx !== s2Idx) toChange.push({
  24548. froms: sIdx,
  24549. tos: s2Idx,
  24550. hole: hIdx
  24551. });
  24552. if (hole_unassigned) {
  24553. hole_unassigned = false;
  24554. betterShapeHoles[s2Idx].push(ho);
  24555. } else {
  24556. ambiguous = true;
  24557. }
  24558. }
  24559. }
  24560. if (hole_unassigned) {
  24561. betterShapeHoles[sIdx].push(ho);
  24562. }
  24563. }
  24564. } // console.log("ambiguous: ", ambiguous);
  24565. if (toChange.length > 0) {
  24566. // console.log("to change: ", toChange);
  24567. if (!ambiguous) newShapeHoles = betterShapeHoles;
  24568. }
  24569. }
  24570. let tmpHoles;
  24571. for (let i = 0, il = newShapes.length; i < il; i++) {
  24572. tmpShape = newShapes[i].s;
  24573. shapes.push(tmpShape);
  24574. tmpHoles = newShapeHoles[i];
  24575. for (let j = 0, jl = tmpHoles.length; j < jl; j++) {
  24576. tmpShape.holes.push(tmpHoles[j].h);
  24577. }
  24578. } //console.log("shape", shapes);
  24579. return shapes;
  24580. }
  24581. }
  24582. class Font {
  24583. constructor(data) {
  24584. this.type = 'Font';
  24585. this.data = data;
  24586. }
  24587. generateShapes(text, size = 100) {
  24588. const shapes = [];
  24589. const paths = createPaths(text, size, this.data);
  24590. for (let p = 0, pl = paths.length; p < pl; p++) {
  24591. Array.prototype.push.apply(shapes, paths[p].toShapes());
  24592. }
  24593. return shapes;
  24594. }
  24595. }
  24596. function createPaths(text, size, data) {
  24597. const chars = Array.from(text);
  24598. const scale = size / data.resolution;
  24599. const line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
  24600. const paths = [];
  24601. let offsetX = 0,
  24602. offsetY = 0;
  24603. for (let i = 0; i < chars.length; i++) {
  24604. const char = chars[i];
  24605. if (char === '\n') {
  24606. offsetX = 0;
  24607. offsetY -= line_height;
  24608. } else {
  24609. const ret = createPath(char, scale, offsetX, offsetY, data);
  24610. offsetX += ret.offsetX;
  24611. paths.push(ret.path);
  24612. }
  24613. }
  24614. return paths;
  24615. }
  24616. function createPath(char, scale, offsetX, offsetY, data) {
  24617. const glyph = data.glyphs[char] || data.glyphs['?'];
  24618. if (!glyph) {
  24619. console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
  24620. return;
  24621. }
  24622. const path = new ShapePath();
  24623. let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  24624. if (glyph.o) {
  24625. const outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
  24626. for (let i = 0, l = outline.length; i < l;) {
  24627. const action = outline[i++];
  24628. switch (action) {
  24629. case 'm':
  24630. // moveTo
  24631. x = outline[i++] * scale + offsetX;
  24632. y = outline[i++] * scale + offsetY;
  24633. path.moveTo(x, y);
  24634. break;
  24635. case 'l':
  24636. // lineTo
  24637. x = outline[i++] * scale + offsetX;
  24638. y = outline[i++] * scale + offsetY;
  24639. path.lineTo(x, y);
  24640. break;
  24641. case 'q':
  24642. // quadraticCurveTo
  24643. cpx = outline[i++] * scale + offsetX;
  24644. cpy = outline[i++] * scale + offsetY;
  24645. cpx1 = outline[i++] * scale + offsetX;
  24646. cpy1 = outline[i++] * scale + offsetY;
  24647. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  24648. break;
  24649. case 'b':
  24650. // bezierCurveTo
  24651. cpx = outline[i++] * scale + offsetX;
  24652. cpy = outline[i++] * scale + offsetY;
  24653. cpx1 = outline[i++] * scale + offsetX;
  24654. cpy1 = outline[i++] * scale + offsetY;
  24655. cpx2 = outline[i++] * scale + offsetX;
  24656. cpy2 = outline[i++] * scale + offsetY;
  24657. path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
  24658. break;
  24659. }
  24660. }
  24661. }
  24662. return {
  24663. offsetX: glyph.ha * scale,
  24664. path: path
  24665. };
  24666. }
  24667. Font.prototype.isFont = true;
  24668. class FontLoader extends Loader {
  24669. constructor(manager) {
  24670. super(manager);
  24671. }
  24672. load(url, onLoad, onProgress, onError) {
  24673. const scope = this;
  24674. const loader = new FileLoader(this.manager);
  24675. loader.setPath(this.path);
  24676. loader.setRequestHeader(this.requestHeader);
  24677. loader.setWithCredentials(scope.withCredentials);
  24678. loader.load(url, function (text) {
  24679. let json;
  24680. try {
  24681. json = JSON.parse(text);
  24682. } catch (e) {
  24683. console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
  24684. json = JSON.parse(text.substring(65, text.length - 2));
  24685. }
  24686. const font = scope.parse(json);
  24687. if (onLoad) onLoad(font);
  24688. }, onProgress, onError);
  24689. }
  24690. parse(json) {
  24691. return new Font(json);
  24692. }
  24693. }
  24694. let _context;
  24695. const AudioContext = {
  24696. getContext: function () {
  24697. if (_context === undefined) {
  24698. _context = new (window.AudioContext || window.webkitAudioContext)();
  24699. }
  24700. return _context;
  24701. },
  24702. setContext: function (value) {
  24703. _context = value;
  24704. }
  24705. };
  24706. class AudioLoader extends Loader {
  24707. constructor(manager) {
  24708. super(manager);
  24709. }
  24710. load(url, onLoad, onProgress, onError) {
  24711. const scope = this;
  24712. const loader = new FileLoader(this.manager);
  24713. loader.setResponseType('arraybuffer');
  24714. loader.setPath(this.path);
  24715. loader.setRequestHeader(this.requestHeader);
  24716. loader.setWithCredentials(this.withCredentials);
  24717. loader.load(url, function (buffer) {
  24718. try {
  24719. // Create a copy of the buffer. The `decodeAudioData` method
  24720. // detaches the buffer when complete, preventing reuse.
  24721. const bufferCopy = buffer.slice(0);
  24722. const context = AudioContext.getContext();
  24723. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  24724. onLoad(audioBuffer);
  24725. });
  24726. } catch (e) {
  24727. if (onError) {
  24728. onError(e);
  24729. } else {
  24730. console.error(e);
  24731. }
  24732. scope.manager.itemError(url);
  24733. }
  24734. }, onProgress, onError);
  24735. }
  24736. }
  24737. class HemisphereLightProbe extends LightProbe {
  24738. constructor(skyColor, groundColor, intensity = 1) {
  24739. super(undefined, intensity);
  24740. const color1 = new Color().set(skyColor);
  24741. const color2 = new Color().set(groundColor);
  24742. const sky = new Vector3(color1.r, color1.g, color1.b);
  24743. const ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  24744. const c0 = Math.sqrt(Math.PI);
  24745. const c1 = c0 * Math.sqrt(0.75);
  24746. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  24747. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  24748. }
  24749. }
  24750. HemisphereLightProbe.prototype.isHemisphereLightProbe = true;
  24751. class AmbientLightProbe extends LightProbe {
  24752. constructor(color, intensity = 1) {
  24753. super(undefined, intensity);
  24754. const color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  24755. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  24756. }
  24757. }
  24758. AmbientLightProbe.prototype.isAmbientLightProbe = true;
  24759. const _eyeRight = /*@__PURE__*/new Matrix4();
  24760. const _eyeLeft = /*@__PURE__*/new Matrix4();
  24761. class StereoCamera {
  24762. constructor() {
  24763. this.type = 'StereoCamera';
  24764. this.aspect = 1;
  24765. this.eyeSep = 0.064;
  24766. this.cameraL = new PerspectiveCamera();
  24767. this.cameraL.layers.enable(1);
  24768. this.cameraL.matrixAutoUpdate = false;
  24769. this.cameraR = new PerspectiveCamera();
  24770. this.cameraR.layers.enable(2);
  24771. this.cameraR.matrixAutoUpdate = false;
  24772. this._cache = {
  24773. focus: null,
  24774. fov: null,
  24775. aspect: null,
  24776. near: null,
  24777. far: null,
  24778. zoom: null,
  24779. eyeSep: null
  24780. };
  24781. }
  24782. update(camera) {
  24783. const cache = this._cache;
  24784. 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;
  24785. if (needsUpdate) {
  24786. cache.focus = camera.focus;
  24787. cache.fov = camera.fov;
  24788. cache.aspect = camera.aspect * this.aspect;
  24789. cache.near = camera.near;
  24790. cache.far = camera.far;
  24791. cache.zoom = camera.zoom;
  24792. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  24793. // http://paulbourke.net/stereographics/stereorender/
  24794. const projectionMatrix = camera.projectionMatrix.clone();
  24795. const eyeSepHalf = cache.eyeSep / 2;
  24796. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  24797. const ymax = cache.near * Math.tan(DEG2RAD * cache.fov * 0.5) / cache.zoom;
  24798. let xmin, xmax; // translate xOffset
  24799. _eyeLeft.elements[12] = -eyeSepHalf;
  24800. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  24801. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  24802. xmax = ymax * cache.aspect + eyeSepOnProjection;
  24803. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  24804. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  24805. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  24806. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  24807. xmax = ymax * cache.aspect - eyeSepOnProjection;
  24808. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  24809. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  24810. this.cameraR.projectionMatrix.copy(projectionMatrix);
  24811. }
  24812. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  24813. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  24814. }
  24815. }
  24816. class Clock {
  24817. constructor(autoStart = true) {
  24818. this.autoStart = autoStart;
  24819. this.startTime = 0;
  24820. this.oldTime = 0;
  24821. this.elapsedTime = 0;
  24822. this.running = false;
  24823. }
  24824. start() {
  24825. this.startTime = now();
  24826. this.oldTime = this.startTime;
  24827. this.elapsedTime = 0;
  24828. this.running = true;
  24829. }
  24830. stop() {
  24831. this.getElapsedTime();
  24832. this.running = false;
  24833. this.autoStart = false;
  24834. }
  24835. getElapsedTime() {
  24836. this.getDelta();
  24837. return this.elapsedTime;
  24838. }
  24839. getDelta() {
  24840. let diff = 0;
  24841. if (this.autoStart && !this.running) {
  24842. this.start();
  24843. return 0;
  24844. }
  24845. if (this.running) {
  24846. const newTime = now();
  24847. diff = (newTime - this.oldTime) / 1000;
  24848. this.oldTime = newTime;
  24849. this.elapsedTime += diff;
  24850. }
  24851. return diff;
  24852. }
  24853. }
  24854. function now() {
  24855. return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  24856. }
  24857. const _position$1 = /*@__PURE__*/new Vector3();
  24858. const _quaternion$1 = /*@__PURE__*/new Quaternion();
  24859. const _scale$1 = /*@__PURE__*/new Vector3();
  24860. const _orientation$1 = /*@__PURE__*/new Vector3();
  24861. class AudioListener extends Object3D {
  24862. constructor() {
  24863. super();
  24864. this.type = 'AudioListener';
  24865. this.context = AudioContext.getContext();
  24866. this.gain = this.context.createGain();
  24867. this.gain.connect(this.context.destination);
  24868. this.filter = null;
  24869. this.timeDelta = 0; // private
  24870. this._clock = new Clock();
  24871. }
  24872. getInput() {
  24873. return this.gain;
  24874. }
  24875. removeFilter() {
  24876. if (this.filter !== null) {
  24877. this.gain.disconnect(this.filter);
  24878. this.filter.disconnect(this.context.destination);
  24879. this.gain.connect(this.context.destination);
  24880. this.filter = null;
  24881. }
  24882. return this;
  24883. }
  24884. getFilter() {
  24885. return this.filter;
  24886. }
  24887. setFilter(value) {
  24888. if (this.filter !== null) {
  24889. this.gain.disconnect(this.filter);
  24890. this.filter.disconnect(this.context.destination);
  24891. } else {
  24892. this.gain.disconnect(this.context.destination);
  24893. }
  24894. this.filter = value;
  24895. this.gain.connect(this.filter);
  24896. this.filter.connect(this.context.destination);
  24897. return this;
  24898. }
  24899. getMasterVolume() {
  24900. return this.gain.gain.value;
  24901. }
  24902. setMasterVolume(value) {
  24903. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  24904. return this;
  24905. }
  24906. updateMatrixWorld(force) {
  24907. super.updateMatrixWorld(force);
  24908. const listener = this.context.listener;
  24909. const up = this.up;
  24910. this.timeDelta = this._clock.getDelta();
  24911. this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1);
  24912. _orientation$1.set(0, 0, -1).applyQuaternion(_quaternion$1);
  24913. if (listener.positionX) {
  24914. // code path for Chrome (see #14393)
  24915. const endTime = this.context.currentTime + this.timeDelta;
  24916. listener.positionX.linearRampToValueAtTime(_position$1.x, endTime);
  24917. listener.positionY.linearRampToValueAtTime(_position$1.y, endTime);
  24918. listener.positionZ.linearRampToValueAtTime(_position$1.z, endTime);
  24919. listener.forwardX.linearRampToValueAtTime(_orientation$1.x, endTime);
  24920. listener.forwardY.linearRampToValueAtTime(_orientation$1.y, endTime);
  24921. listener.forwardZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  24922. listener.upX.linearRampToValueAtTime(up.x, endTime);
  24923. listener.upY.linearRampToValueAtTime(up.y, endTime);
  24924. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  24925. } else {
  24926. listener.setPosition(_position$1.x, _position$1.y, _position$1.z);
  24927. listener.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z);
  24928. }
  24929. }
  24930. }
  24931. class Audio extends Object3D {
  24932. constructor(listener) {
  24933. super();
  24934. this.type = 'Audio';
  24935. this.listener = listener;
  24936. this.context = listener.context;
  24937. this.gain = this.context.createGain();
  24938. this.gain.connect(listener.getInput());
  24939. this.autoplay = false;
  24940. this.buffer = null;
  24941. this.detune = 0;
  24942. this.loop = false;
  24943. this.loopStart = 0;
  24944. this.loopEnd = 0;
  24945. this.offset = 0;
  24946. this.duration = undefined;
  24947. this.playbackRate = 1;
  24948. this.isPlaying = false;
  24949. this.hasPlaybackControl = true;
  24950. this.source = null;
  24951. this.sourceType = 'empty';
  24952. this._startedAt = 0;
  24953. this._progress = 0;
  24954. this._connected = false;
  24955. this.filters = [];
  24956. }
  24957. getOutput() {
  24958. return this.gain;
  24959. }
  24960. setNodeSource(audioNode) {
  24961. this.hasPlaybackControl = false;
  24962. this.sourceType = 'audioNode';
  24963. this.source = audioNode;
  24964. this.connect();
  24965. return this;
  24966. }
  24967. setMediaElementSource(mediaElement) {
  24968. this.hasPlaybackControl = false;
  24969. this.sourceType = 'mediaNode';
  24970. this.source = this.context.createMediaElementSource(mediaElement);
  24971. this.connect();
  24972. return this;
  24973. }
  24974. setMediaStreamSource(mediaStream) {
  24975. this.hasPlaybackControl = false;
  24976. this.sourceType = 'mediaStreamNode';
  24977. this.source = this.context.createMediaStreamSource(mediaStream);
  24978. this.connect();
  24979. return this;
  24980. }
  24981. setBuffer(audioBuffer) {
  24982. this.buffer = audioBuffer;
  24983. this.sourceType = 'buffer';
  24984. if (this.autoplay) this.play();
  24985. return this;
  24986. }
  24987. play(delay = 0) {
  24988. if (this.isPlaying === true) {
  24989. console.warn('THREE.Audio: Audio is already playing.');
  24990. return;
  24991. }
  24992. if (this.hasPlaybackControl === false) {
  24993. console.warn('THREE.Audio: this Audio has no playback control.');
  24994. return;
  24995. }
  24996. this._startedAt = this.context.currentTime + delay;
  24997. const source = this.context.createBufferSource();
  24998. source.buffer = this.buffer;
  24999. source.loop = this.loop;
  25000. source.loopStart = this.loopStart;
  25001. source.loopEnd = this.loopEnd;
  25002. source.onended = this.onEnded.bind(this);
  25003. source.start(this._startedAt, this._progress + this.offset, this.duration);
  25004. this.isPlaying = true;
  25005. this.source = source;
  25006. this.setDetune(this.detune);
  25007. this.setPlaybackRate(this.playbackRate);
  25008. return this.connect();
  25009. }
  25010. pause() {
  25011. if (this.hasPlaybackControl === false) {
  25012. console.warn('THREE.Audio: this Audio has no playback control.');
  25013. return;
  25014. }
  25015. if (this.isPlaying === true) {
  25016. // update current progress
  25017. this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  25018. if (this.loop === true) {
  25019. // ensure _progress does not exceed duration with looped audios
  25020. this._progress = this._progress % (this.duration || this.buffer.duration);
  25021. }
  25022. this.source.stop();
  25023. this.source.onended = null;
  25024. this.isPlaying = false;
  25025. }
  25026. return this;
  25027. }
  25028. stop() {
  25029. if (this.hasPlaybackControl === false) {
  25030. console.warn('THREE.Audio: this Audio has no playback control.');
  25031. return;
  25032. }
  25033. this._progress = 0;
  25034. this.source.stop();
  25035. this.source.onended = null;
  25036. this.isPlaying = false;
  25037. return this;
  25038. }
  25039. connect() {
  25040. if (this.filters.length > 0) {
  25041. this.source.connect(this.filters[0]);
  25042. for (let i = 1, l = this.filters.length; i < l; i++) {
  25043. this.filters[i - 1].connect(this.filters[i]);
  25044. }
  25045. this.filters[this.filters.length - 1].connect(this.getOutput());
  25046. } else {
  25047. this.source.connect(this.getOutput());
  25048. }
  25049. this._connected = true;
  25050. return this;
  25051. }
  25052. disconnect() {
  25053. if (this.filters.length > 0) {
  25054. this.source.disconnect(this.filters[0]);
  25055. for (let i = 1, l = this.filters.length; i < l; i++) {
  25056. this.filters[i - 1].disconnect(this.filters[i]);
  25057. }
  25058. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  25059. } else {
  25060. this.source.disconnect(this.getOutput());
  25061. }
  25062. this._connected = false;
  25063. return this;
  25064. }
  25065. getFilters() {
  25066. return this.filters;
  25067. }
  25068. setFilters(value) {
  25069. if (!value) value = [];
  25070. if (this._connected === true) {
  25071. this.disconnect();
  25072. this.filters = value.slice();
  25073. this.connect();
  25074. } else {
  25075. this.filters = value.slice();
  25076. }
  25077. return this;
  25078. }
  25079. setDetune(value) {
  25080. this.detune = value;
  25081. if (this.source.detune === undefined) return; // only set detune when available
  25082. if (this.isPlaying === true) {
  25083. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  25084. }
  25085. return this;
  25086. }
  25087. getDetune() {
  25088. return this.detune;
  25089. }
  25090. getFilter() {
  25091. return this.getFilters()[0];
  25092. }
  25093. setFilter(filter) {
  25094. return this.setFilters(filter ? [filter] : []);
  25095. }
  25096. setPlaybackRate(value) {
  25097. if (this.hasPlaybackControl === false) {
  25098. console.warn('THREE.Audio: this Audio has no playback control.');
  25099. return;
  25100. }
  25101. this.playbackRate = value;
  25102. if (this.isPlaying === true) {
  25103. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  25104. }
  25105. return this;
  25106. }
  25107. getPlaybackRate() {
  25108. return this.playbackRate;
  25109. }
  25110. onEnded() {
  25111. this.isPlaying = false;
  25112. }
  25113. getLoop() {
  25114. if (this.hasPlaybackControl === false) {
  25115. console.warn('THREE.Audio: this Audio has no playback control.');
  25116. return false;
  25117. }
  25118. return this.loop;
  25119. }
  25120. setLoop(value) {
  25121. if (this.hasPlaybackControl === false) {
  25122. console.warn('THREE.Audio: this Audio has no playback control.');
  25123. return;
  25124. }
  25125. this.loop = value;
  25126. if (this.isPlaying === true) {
  25127. this.source.loop = this.loop;
  25128. }
  25129. return this;
  25130. }
  25131. setLoopStart(value) {
  25132. this.loopStart = value;
  25133. return this;
  25134. }
  25135. setLoopEnd(value) {
  25136. this.loopEnd = value;
  25137. return this;
  25138. }
  25139. getVolume() {
  25140. return this.gain.gain.value;
  25141. }
  25142. setVolume(value) {
  25143. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25144. return this;
  25145. }
  25146. }
  25147. const _position = /*@__PURE__*/new Vector3();
  25148. const _quaternion = /*@__PURE__*/new Quaternion();
  25149. const _scale = /*@__PURE__*/new Vector3();
  25150. const _orientation = /*@__PURE__*/new Vector3();
  25151. class PositionalAudio extends Audio {
  25152. constructor(listener) {
  25153. super(listener);
  25154. this.panner = this.context.createPanner();
  25155. this.panner.panningModel = 'HRTF';
  25156. this.panner.connect(this.gain);
  25157. }
  25158. getOutput() {
  25159. return this.panner;
  25160. }
  25161. getRefDistance() {
  25162. return this.panner.refDistance;
  25163. }
  25164. setRefDistance(value) {
  25165. this.panner.refDistance = value;
  25166. return this;
  25167. }
  25168. getRolloffFactor() {
  25169. return this.panner.rolloffFactor;
  25170. }
  25171. setRolloffFactor(value) {
  25172. this.panner.rolloffFactor = value;
  25173. return this;
  25174. }
  25175. getDistanceModel() {
  25176. return this.panner.distanceModel;
  25177. }
  25178. setDistanceModel(value) {
  25179. this.panner.distanceModel = value;
  25180. return this;
  25181. }
  25182. getMaxDistance() {
  25183. return this.panner.maxDistance;
  25184. }
  25185. setMaxDistance(value) {
  25186. this.panner.maxDistance = value;
  25187. return this;
  25188. }
  25189. setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25190. this.panner.coneInnerAngle = coneInnerAngle;
  25191. this.panner.coneOuterAngle = coneOuterAngle;
  25192. this.panner.coneOuterGain = coneOuterGain;
  25193. return this;
  25194. }
  25195. updateMatrixWorld(force) {
  25196. super.updateMatrixWorld(force);
  25197. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  25198. this.matrixWorld.decompose(_position, _quaternion, _scale);
  25199. _orientation.set(0, 0, 1).applyQuaternion(_quaternion);
  25200. const panner = this.panner;
  25201. if (panner.positionX) {
  25202. // code path for Chrome and Firefox (see #14393)
  25203. const endTime = this.context.currentTime + this.listener.timeDelta;
  25204. panner.positionX.linearRampToValueAtTime(_position.x, endTime);
  25205. panner.positionY.linearRampToValueAtTime(_position.y, endTime);
  25206. panner.positionZ.linearRampToValueAtTime(_position.z, endTime);
  25207. panner.orientationX.linearRampToValueAtTime(_orientation.x, endTime);
  25208. panner.orientationY.linearRampToValueAtTime(_orientation.y, endTime);
  25209. panner.orientationZ.linearRampToValueAtTime(_orientation.z, endTime);
  25210. } else {
  25211. panner.setPosition(_position.x, _position.y, _position.z);
  25212. panner.setOrientation(_orientation.x, _orientation.y, _orientation.z);
  25213. }
  25214. }
  25215. }
  25216. class AudioAnalyser {
  25217. constructor(audio, fftSize = 2048) {
  25218. this.analyser = audio.context.createAnalyser();
  25219. this.analyser.fftSize = fftSize;
  25220. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  25221. audio.getOutput().connect(this.analyser);
  25222. }
  25223. getFrequencyData() {
  25224. this.analyser.getByteFrequencyData(this.data);
  25225. return this.data;
  25226. }
  25227. getAverageFrequency() {
  25228. let value = 0;
  25229. const data = this.getFrequencyData();
  25230. for (let i = 0; i < data.length; i++) {
  25231. value += data[i];
  25232. }
  25233. return value / data.length;
  25234. }
  25235. }
  25236. class PropertyMixer {
  25237. constructor(binding, typeName, valueSize) {
  25238. this.binding = binding;
  25239. this.valueSize = valueSize;
  25240. let mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  25241. //
  25242. // interpolators can use .buffer as their .result
  25243. // the data then goes to 'incoming'
  25244. //
  25245. // 'accu0' and 'accu1' are used frame-interleaved for
  25246. // the cumulative result and are compared to detect
  25247. // changes
  25248. //
  25249. // 'orig' stores the original state of the property
  25250. //
  25251. // 'add' is used for additive cumulative results
  25252. //
  25253. // 'work' is optional and is only present for quaternion types. It is used
  25254. // to store intermediate quaternion multiplication results
  25255. switch (typeName) {
  25256. case 'quaternion':
  25257. mixFunction = this._slerp;
  25258. mixFunctionAdditive = this._slerpAdditive;
  25259. setIdentity = this._setAdditiveIdentityQuaternion;
  25260. this.buffer = new Float64Array(valueSize * 6);
  25261. this._workIndex = 5;
  25262. break;
  25263. case 'string':
  25264. case 'bool':
  25265. mixFunction = this._select; // Use the regular mix function and for additive on these types,
  25266. // additive is not relevant for non-numeric types
  25267. mixFunctionAdditive = this._select;
  25268. setIdentity = this._setAdditiveIdentityOther;
  25269. this.buffer = new Array(valueSize * 5);
  25270. break;
  25271. default:
  25272. mixFunction = this._lerp;
  25273. mixFunctionAdditive = this._lerpAdditive;
  25274. setIdentity = this._setAdditiveIdentityNumeric;
  25275. this.buffer = new Float64Array(valueSize * 5);
  25276. }
  25277. this._mixBufferRegion = mixFunction;
  25278. this._mixBufferRegionAdditive = mixFunctionAdditive;
  25279. this._setIdentity = setIdentity;
  25280. this._origIndex = 3;
  25281. this._addIndex = 4;
  25282. this.cumulativeWeight = 0;
  25283. this.cumulativeWeightAdditive = 0;
  25284. this.useCount = 0;
  25285. this.referenceCount = 0;
  25286. } // accumulate data in the 'incoming' region into 'accu<i>'
  25287. accumulate(accuIndex, weight) {
  25288. // note: happily accumulating nothing when weight = 0, the caller knows
  25289. // the weight and shouldn't have made the call in the first place
  25290. const buffer = this.buffer,
  25291. stride = this.valueSize,
  25292. offset = accuIndex * stride + stride;
  25293. let currentWeight = this.cumulativeWeight;
  25294. if (currentWeight === 0) {
  25295. // accuN := incoming * weight
  25296. for (let i = 0; i !== stride; ++i) {
  25297. buffer[offset + i] = buffer[i];
  25298. }
  25299. currentWeight = weight;
  25300. } else {
  25301. // accuN := accuN + incoming * weight
  25302. currentWeight += weight;
  25303. const mix = weight / currentWeight;
  25304. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  25305. }
  25306. this.cumulativeWeight = currentWeight;
  25307. } // accumulate data in the 'incoming' region into 'add'
  25308. accumulateAdditive(weight) {
  25309. const buffer = this.buffer,
  25310. stride = this.valueSize,
  25311. offset = stride * this._addIndex;
  25312. if (this.cumulativeWeightAdditive === 0) {
  25313. // add = identity
  25314. this._setIdentity();
  25315. } // add := add + incoming * weight
  25316. this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
  25317. this.cumulativeWeightAdditive += weight;
  25318. } // apply the state of 'accu<i>' to the binding when accus differ
  25319. apply(accuIndex) {
  25320. const stride = this.valueSize,
  25321. buffer = this.buffer,
  25322. offset = accuIndex * stride + stride,
  25323. weight = this.cumulativeWeight,
  25324. weightAdditive = this.cumulativeWeightAdditive,
  25325. binding = this.binding;
  25326. this.cumulativeWeight = 0;
  25327. this.cumulativeWeightAdditive = 0;
  25328. if (weight < 1) {
  25329. // accuN := accuN + original * ( 1 - cumulativeWeight )
  25330. const originalValueOffset = stride * this._origIndex;
  25331. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  25332. }
  25333. if (weightAdditive > 0) {
  25334. // accuN := accuN + additive accuN
  25335. this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
  25336. }
  25337. for (let i = stride, e = stride + stride; i !== e; ++i) {
  25338. if (buffer[i] !== buffer[i + stride]) {
  25339. // value has changed -> update scene graph
  25340. binding.setValue(buffer, offset);
  25341. break;
  25342. }
  25343. }
  25344. } // remember the state of the bound property and copy it to both accus
  25345. saveOriginalState() {
  25346. const binding = this.binding;
  25347. const buffer = this.buffer,
  25348. stride = this.valueSize,
  25349. originalValueOffset = stride * this._origIndex;
  25350. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  25351. for (let i = stride, e = originalValueOffset; i !== e; ++i) {
  25352. buffer[i] = buffer[originalValueOffset + i % stride];
  25353. } // Add to identity for additive
  25354. this._setIdentity();
  25355. this.cumulativeWeight = 0;
  25356. this.cumulativeWeightAdditive = 0;
  25357. } // apply the state previously taken via 'saveOriginalState' to the binding
  25358. restoreOriginalState() {
  25359. const originalValueOffset = this.valueSize * 3;
  25360. this.binding.setValue(this.buffer, originalValueOffset);
  25361. }
  25362. _setAdditiveIdentityNumeric() {
  25363. const startIndex = this._addIndex * this.valueSize;
  25364. const endIndex = startIndex + this.valueSize;
  25365. for (let i = startIndex; i < endIndex; i++) {
  25366. this.buffer[i] = 0;
  25367. }
  25368. }
  25369. _setAdditiveIdentityQuaternion() {
  25370. this._setAdditiveIdentityNumeric();
  25371. this.buffer[this._addIndex * this.valueSize + 3] = 1;
  25372. }
  25373. _setAdditiveIdentityOther() {
  25374. const startIndex = this._origIndex * this.valueSize;
  25375. const targetIndex = this._addIndex * this.valueSize;
  25376. for (let i = 0; i < this.valueSize; i++) {
  25377. this.buffer[targetIndex + i] = this.buffer[startIndex + i];
  25378. }
  25379. } // mix functions
  25380. _select(buffer, dstOffset, srcOffset, t, stride) {
  25381. if (t >= 0.5) {
  25382. for (let i = 0; i !== stride; ++i) {
  25383. buffer[dstOffset + i] = buffer[srcOffset + i];
  25384. }
  25385. }
  25386. }
  25387. _slerp(buffer, dstOffset, srcOffset, t) {
  25388. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  25389. }
  25390. _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  25391. const workOffset = this._workIndex * stride; // Store result in intermediate buffer offset
  25392. Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
  25393. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
  25394. }
  25395. _lerp(buffer, dstOffset, srcOffset, t, stride) {
  25396. const s = 1 - t;
  25397. for (let i = 0; i !== stride; ++i) {
  25398. const j = dstOffset + i;
  25399. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  25400. }
  25401. }
  25402. _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  25403. for (let i = 0; i !== stride; ++i) {
  25404. const j = dstOffset + i;
  25405. buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
  25406. }
  25407. }
  25408. }
  25409. // Characters [].:/ are reserved for track binding syntax.
  25410. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  25411. const _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  25412. // only latin characters, and the unicode \p{L} is not yet supported. So
  25413. // instead, we exclude reserved characters and match everything else.
  25414. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  25415. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  25416. // be matched to parse the rest of the track name.
  25417. const _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  25418. const _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  25419. // characters. Accessor may contain any character except closing bracket.
  25420. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  25421. // contain any non-bracket characters.
  25422. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  25423. const _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  25424. const _supportedObjectNames = ['material', 'materials', 'bones'];
  25425. class Composite {
  25426. constructor(targetGroup, path, optionalParsedPath) {
  25427. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  25428. this._targetGroup = targetGroup;
  25429. this._bindings = targetGroup.subscribe_(path, parsedPath);
  25430. }
  25431. getValue(array, offset) {
  25432. this.bind(); // bind all binding
  25433. const firstValidIndex = this._targetGroup.nCachedObjects_,
  25434. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  25435. if (binding !== undefined) binding.getValue(array, offset);
  25436. }
  25437. setValue(array, offset) {
  25438. const bindings = this._bindings;
  25439. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25440. bindings[i].setValue(array, offset);
  25441. }
  25442. }
  25443. bind() {
  25444. const bindings = this._bindings;
  25445. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25446. bindings[i].bind();
  25447. }
  25448. }
  25449. unbind() {
  25450. const bindings = this._bindings;
  25451. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25452. bindings[i].unbind();
  25453. }
  25454. }
  25455. } // Note: This class uses a State pattern on a per-method basis:
  25456. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  25457. // prototype version of these methods with one that represents
  25458. // the bound state. When the property is not found, the methods
  25459. // become no-ops.
  25460. class PropertyBinding {
  25461. constructor(rootNode, path, parsedPath) {
  25462. this.path = path;
  25463. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  25464. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  25465. this.rootNode = rootNode; // initial state of these methods that calls 'bind'
  25466. this.getValue = this._getValue_unbound;
  25467. this.setValue = this._setValue_unbound;
  25468. }
  25469. static create(root, path, parsedPath) {
  25470. if (!(root && root.isAnimationObjectGroup)) {
  25471. return new PropertyBinding(root, path, parsedPath);
  25472. } else {
  25473. return new PropertyBinding.Composite(root, path, parsedPath);
  25474. }
  25475. }
  25476. /**
  25477. * Replaces spaces with underscores and removes unsupported characters from
  25478. * node names, to ensure compatibility with parseTrackName().
  25479. *
  25480. * @param {string} name Node name to be sanitized.
  25481. * @return {string}
  25482. */
  25483. static sanitizeNodeName(name) {
  25484. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  25485. }
  25486. static parseTrackName(trackName) {
  25487. const matches = _trackRe.exec(trackName);
  25488. if (!matches) {
  25489. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  25490. }
  25491. const results = {
  25492. // directoryName: matches[ 1 ], // (tschw) currently unused
  25493. nodeName: matches[2],
  25494. objectName: matches[3],
  25495. objectIndex: matches[4],
  25496. propertyName: matches[5],
  25497. // required
  25498. propertyIndex: matches[6]
  25499. };
  25500. const lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  25501. if (lastDot !== undefined && lastDot !== -1) {
  25502. const objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
  25503. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  25504. // 'bar' could be the objectName, or part of a nodeName (which can
  25505. // include '.' characters).
  25506. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  25507. results.nodeName = results.nodeName.substring(0, lastDot);
  25508. results.objectName = objectName;
  25509. }
  25510. }
  25511. if (results.propertyName === null || results.propertyName.length === 0) {
  25512. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  25513. }
  25514. return results;
  25515. }
  25516. static findNode(root, nodeName) {
  25517. if (!nodeName || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  25518. return root;
  25519. } // search into skeleton bones.
  25520. if (root.skeleton) {
  25521. const bone = root.skeleton.getBoneByName(nodeName);
  25522. if (bone !== undefined) {
  25523. return bone;
  25524. }
  25525. } // search into node subtree.
  25526. if (root.children) {
  25527. const searchNodeSubtree = function (children) {
  25528. for (let i = 0; i < children.length; i++) {
  25529. const childNode = children[i];
  25530. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  25531. return childNode;
  25532. }
  25533. const result = searchNodeSubtree(childNode.children);
  25534. if (result) return result;
  25535. }
  25536. return null;
  25537. };
  25538. const subTreeNode = searchNodeSubtree(root.children);
  25539. if (subTreeNode) {
  25540. return subTreeNode;
  25541. }
  25542. }
  25543. return null;
  25544. } // these are used to "bind" a nonexistent property
  25545. _getValue_unavailable() {}
  25546. _setValue_unavailable() {} // Getters
  25547. _getValue_direct(buffer, offset) {
  25548. buffer[offset] = this.node[this.propertyName];
  25549. }
  25550. _getValue_array(buffer, offset) {
  25551. const source = this.resolvedProperty;
  25552. for (let i = 0, n = source.length; i !== n; ++i) {
  25553. buffer[offset++] = source[i];
  25554. }
  25555. }
  25556. _getValue_arrayElement(buffer, offset) {
  25557. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  25558. }
  25559. _getValue_toArray(buffer, offset) {
  25560. this.resolvedProperty.toArray(buffer, offset);
  25561. } // Direct
  25562. _setValue_direct(buffer, offset) {
  25563. this.targetObject[this.propertyName] = buffer[offset];
  25564. }
  25565. _setValue_direct_setNeedsUpdate(buffer, offset) {
  25566. this.targetObject[this.propertyName] = buffer[offset];
  25567. this.targetObject.needsUpdate = true;
  25568. }
  25569. _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  25570. this.targetObject[this.propertyName] = buffer[offset];
  25571. this.targetObject.matrixWorldNeedsUpdate = true;
  25572. } // EntireArray
  25573. _setValue_array(buffer, offset) {
  25574. const dest = this.resolvedProperty;
  25575. for (let i = 0, n = dest.length; i !== n; ++i) {
  25576. dest[i] = buffer[offset++];
  25577. }
  25578. }
  25579. _setValue_array_setNeedsUpdate(buffer, offset) {
  25580. const dest = this.resolvedProperty;
  25581. for (let i = 0, n = dest.length; i !== n; ++i) {
  25582. dest[i] = buffer[offset++];
  25583. }
  25584. this.targetObject.needsUpdate = true;
  25585. }
  25586. _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  25587. const dest = this.resolvedProperty;
  25588. for (let i = 0, n = dest.length; i !== n; ++i) {
  25589. dest[i] = buffer[offset++];
  25590. }
  25591. this.targetObject.matrixWorldNeedsUpdate = true;
  25592. } // ArrayElement
  25593. _setValue_arrayElement(buffer, offset) {
  25594. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25595. }
  25596. _setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  25597. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25598. this.targetObject.needsUpdate = true;
  25599. }
  25600. _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  25601. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25602. this.targetObject.matrixWorldNeedsUpdate = true;
  25603. } // HasToFromArray
  25604. _setValue_fromArray(buffer, offset) {
  25605. this.resolvedProperty.fromArray(buffer, offset);
  25606. }
  25607. _setValue_fromArray_setNeedsUpdate(buffer, offset) {
  25608. this.resolvedProperty.fromArray(buffer, offset);
  25609. this.targetObject.needsUpdate = true;
  25610. }
  25611. _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  25612. this.resolvedProperty.fromArray(buffer, offset);
  25613. this.targetObject.matrixWorldNeedsUpdate = true;
  25614. }
  25615. _getValue_unbound(targetArray, offset) {
  25616. this.bind();
  25617. this.getValue(targetArray, offset);
  25618. }
  25619. _setValue_unbound(sourceArray, offset) {
  25620. this.bind();
  25621. this.setValue(sourceArray, offset);
  25622. } // create getter / setter pair for a property in the scene graph
  25623. bind() {
  25624. let targetObject = this.node;
  25625. const parsedPath = this.parsedPath;
  25626. const objectName = parsedPath.objectName;
  25627. const propertyName = parsedPath.propertyName;
  25628. let propertyIndex = parsedPath.propertyIndex;
  25629. if (!targetObject) {
  25630. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  25631. this.node = targetObject;
  25632. } // set fail state so we can just 'return' on error
  25633. this.getValue = this._getValue_unavailable;
  25634. this.setValue = this._setValue_unavailable; // ensure there is a value node
  25635. if (!targetObject) {
  25636. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  25637. return;
  25638. }
  25639. if (objectName) {
  25640. let objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  25641. switch (objectName) {
  25642. case 'materials':
  25643. if (!targetObject.material) {
  25644. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  25645. return;
  25646. }
  25647. if (!targetObject.material.materials) {
  25648. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  25649. return;
  25650. }
  25651. targetObject = targetObject.material.materials;
  25652. break;
  25653. case 'bones':
  25654. if (!targetObject.skeleton) {
  25655. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  25656. return;
  25657. } // potential future optimization: skip this if propertyIndex is already an integer
  25658. // and convert the integer string to a true integer.
  25659. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  25660. for (let i = 0; i < targetObject.length; i++) {
  25661. if (targetObject[i].name === objectIndex) {
  25662. objectIndex = i;
  25663. break;
  25664. }
  25665. }
  25666. break;
  25667. default:
  25668. if (targetObject[objectName] === undefined) {
  25669. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  25670. return;
  25671. }
  25672. targetObject = targetObject[objectName];
  25673. }
  25674. if (objectIndex !== undefined) {
  25675. if (targetObject[objectIndex] === undefined) {
  25676. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  25677. return;
  25678. }
  25679. targetObject = targetObject[objectIndex];
  25680. }
  25681. } // resolve property
  25682. const nodeProperty = targetObject[propertyName];
  25683. if (nodeProperty === undefined) {
  25684. const nodeName = parsedPath.nodeName;
  25685. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  25686. return;
  25687. } // determine versioning scheme
  25688. let versioning = this.Versioning.None;
  25689. this.targetObject = targetObject;
  25690. if (targetObject.needsUpdate !== undefined) {
  25691. // material
  25692. versioning = this.Versioning.NeedsUpdate;
  25693. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  25694. // node transform
  25695. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  25696. } // determine how the property gets bound
  25697. let bindingType = this.BindingType.Direct;
  25698. if (propertyIndex !== undefined) {
  25699. // access a sub element of the property array (only primitives are supported right now)
  25700. if (propertyName === 'morphTargetInfluences') {
  25701. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  25702. // support resolving morphTarget names into indices.
  25703. if (!targetObject.geometry) {
  25704. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  25705. return;
  25706. }
  25707. if (targetObject.geometry.isBufferGeometry) {
  25708. if (!targetObject.geometry.morphAttributes) {
  25709. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  25710. return;
  25711. }
  25712. if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
  25713. propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
  25714. }
  25715. } else {
  25716. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this);
  25717. return;
  25718. }
  25719. }
  25720. bindingType = this.BindingType.ArrayElement;
  25721. this.resolvedProperty = nodeProperty;
  25722. this.propertyIndex = propertyIndex;
  25723. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  25724. // must use copy for Object3D.Euler/Quaternion
  25725. bindingType = this.BindingType.HasFromToArray;
  25726. this.resolvedProperty = nodeProperty;
  25727. } else if (Array.isArray(nodeProperty)) {
  25728. bindingType = this.BindingType.EntireArray;
  25729. this.resolvedProperty = nodeProperty;
  25730. } else {
  25731. this.propertyName = propertyName;
  25732. } // select getter / setter
  25733. this.getValue = this.GetterByBindingType[bindingType];
  25734. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  25735. }
  25736. unbind() {
  25737. this.node = null; // back to the prototype version of getValue / setValue
  25738. // note: avoiding to mutate the shape of 'this' via 'delete'
  25739. this.getValue = this._getValue_unbound;
  25740. this.setValue = this._setValue_unbound;
  25741. }
  25742. }
  25743. PropertyBinding.Composite = Composite;
  25744. PropertyBinding.prototype.BindingType = {
  25745. Direct: 0,
  25746. EntireArray: 1,
  25747. ArrayElement: 2,
  25748. HasFromToArray: 3
  25749. };
  25750. PropertyBinding.prototype.Versioning = {
  25751. None: 0,
  25752. NeedsUpdate: 1,
  25753. MatrixWorldNeedsUpdate: 2
  25754. };
  25755. PropertyBinding.prototype.GetterByBindingType = [PropertyBinding.prototype._getValue_direct, PropertyBinding.prototype._getValue_array, PropertyBinding.prototype._getValue_arrayElement, PropertyBinding.prototype._getValue_toArray];
  25756. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [[// Direct
  25757. PropertyBinding.prototype._setValue_direct, PropertyBinding.prototype._setValue_direct_setNeedsUpdate, PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate], [// EntireArray
  25758. PropertyBinding.prototype._setValue_array, PropertyBinding.prototype._setValue_array_setNeedsUpdate, PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate], [// ArrayElement
  25759. PropertyBinding.prototype._setValue_arrayElement, PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate], [// HasToFromArray
  25760. PropertyBinding.prototype._setValue_fromArray, PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];
  25761. /**
  25762. *
  25763. * A group of objects that receives a shared animation state.
  25764. *
  25765. * Usage:
  25766. *
  25767. * - Add objects you would otherwise pass as 'root' to the
  25768. * constructor or the .clipAction method of AnimationMixer.
  25769. *
  25770. * - Instead pass this object as 'root'.
  25771. *
  25772. * - You can also add and remove objects later when the mixer
  25773. * is running.
  25774. *
  25775. * Note:
  25776. *
  25777. * Objects of this class appear as one object to the mixer,
  25778. * so cache control of the individual objects must be done
  25779. * on the group.
  25780. *
  25781. * Limitation:
  25782. *
  25783. * - The animated properties must be compatible among the
  25784. * all objects in the group.
  25785. *
  25786. * - A single property can either be controlled through a
  25787. * target group or directly, but not both.
  25788. */
  25789. class AnimationObjectGroup {
  25790. constructor() {
  25791. this.uuid = generateUUID(); // cached objects followed by the active ones
  25792. this._objects = Array.prototype.slice.call(arguments);
  25793. this.nCachedObjects_ = 0; // threshold
  25794. // note: read by PropertyBinding.Composite
  25795. const indices = {};
  25796. this._indicesByUUID = indices; // for bookkeeping
  25797. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25798. indices[arguments[i].uuid] = i;
  25799. }
  25800. this._paths = []; // inside: string
  25801. this._parsedPaths = []; // inside: { we don't care, here }
  25802. this._bindings = []; // inside: Array< PropertyBinding >
  25803. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  25804. const scope = this;
  25805. this.stats = {
  25806. objects: {
  25807. get total() {
  25808. return scope._objects.length;
  25809. },
  25810. get inUse() {
  25811. return this.total - scope.nCachedObjects_;
  25812. }
  25813. },
  25814. get bindingsPerObject() {
  25815. return scope._bindings.length;
  25816. }
  25817. };
  25818. }
  25819. add() {
  25820. const objects = this._objects,
  25821. indicesByUUID = this._indicesByUUID,
  25822. paths = this._paths,
  25823. parsedPaths = this._parsedPaths,
  25824. bindings = this._bindings,
  25825. nBindings = bindings.length;
  25826. let knownObject = undefined,
  25827. nObjects = objects.length,
  25828. nCachedObjects = this.nCachedObjects_;
  25829. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25830. const object = arguments[i],
  25831. uuid = object.uuid;
  25832. let index = indicesByUUID[uuid];
  25833. if (index === undefined) {
  25834. // unknown object -> add it to the ACTIVE region
  25835. index = nObjects++;
  25836. indicesByUUID[uuid] = index;
  25837. objects.push(object); // accounting is done, now do the same for all bindings
  25838. for (let j = 0, m = nBindings; j !== m; ++j) {
  25839. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  25840. }
  25841. } else if (index < nCachedObjects) {
  25842. knownObject = objects[index]; // move existing object to the ACTIVE region
  25843. const firstActiveIndex = --nCachedObjects,
  25844. lastCachedObject = objects[firstActiveIndex];
  25845. indicesByUUID[lastCachedObject.uuid] = index;
  25846. objects[index] = lastCachedObject;
  25847. indicesByUUID[uuid] = firstActiveIndex;
  25848. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  25849. for (let j = 0, m = nBindings; j !== m; ++j) {
  25850. const bindingsForPath = bindings[j],
  25851. lastCached = bindingsForPath[firstActiveIndex];
  25852. let binding = bindingsForPath[index];
  25853. bindingsForPath[index] = lastCached;
  25854. if (binding === undefined) {
  25855. // since we do not bother to create new bindings
  25856. // for objects that are cached, the binding may
  25857. // or may not exist
  25858. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  25859. }
  25860. bindingsForPath[firstActiveIndex] = binding;
  25861. }
  25862. } else if (objects[index] !== knownObject) {
  25863. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  25864. } // else the object is already where we want it to be
  25865. } // for arguments
  25866. this.nCachedObjects_ = nCachedObjects;
  25867. }
  25868. remove() {
  25869. const objects = this._objects,
  25870. indicesByUUID = this._indicesByUUID,
  25871. bindings = this._bindings,
  25872. nBindings = bindings.length;
  25873. let nCachedObjects = this.nCachedObjects_;
  25874. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25875. const object = arguments[i],
  25876. uuid = object.uuid,
  25877. index = indicesByUUID[uuid];
  25878. if (index !== undefined && index >= nCachedObjects) {
  25879. // move existing object into the CACHED region
  25880. const lastCachedIndex = nCachedObjects++,
  25881. firstActiveObject = objects[lastCachedIndex];
  25882. indicesByUUID[firstActiveObject.uuid] = index;
  25883. objects[index] = firstActiveObject;
  25884. indicesByUUID[uuid] = lastCachedIndex;
  25885. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  25886. for (let j = 0, m = nBindings; j !== m; ++j) {
  25887. const bindingsForPath = bindings[j],
  25888. firstActive = bindingsForPath[lastCachedIndex],
  25889. binding = bindingsForPath[index];
  25890. bindingsForPath[index] = firstActive;
  25891. bindingsForPath[lastCachedIndex] = binding;
  25892. }
  25893. }
  25894. } // for arguments
  25895. this.nCachedObjects_ = nCachedObjects;
  25896. } // remove & forget
  25897. uncache() {
  25898. const objects = this._objects,
  25899. indicesByUUID = this._indicesByUUID,
  25900. bindings = this._bindings,
  25901. nBindings = bindings.length;
  25902. let nCachedObjects = this.nCachedObjects_,
  25903. nObjects = objects.length;
  25904. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25905. const object = arguments[i],
  25906. uuid = object.uuid,
  25907. index = indicesByUUID[uuid];
  25908. if (index !== undefined) {
  25909. delete indicesByUUID[uuid];
  25910. if (index < nCachedObjects) {
  25911. // object is cached, shrink the CACHED region
  25912. const firstActiveIndex = --nCachedObjects,
  25913. lastCachedObject = objects[firstActiveIndex],
  25914. lastIndex = --nObjects,
  25915. lastObject = objects[lastIndex]; // last cached object takes this object's place
  25916. indicesByUUID[lastCachedObject.uuid] = index;
  25917. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  25918. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  25919. objects[firstActiveIndex] = lastObject;
  25920. objects.pop(); // accounting is done, now do the same for all bindings
  25921. for (let j = 0, m = nBindings; j !== m; ++j) {
  25922. const bindingsForPath = bindings[j],
  25923. lastCached = bindingsForPath[firstActiveIndex],
  25924. last = bindingsForPath[lastIndex];
  25925. bindingsForPath[index] = lastCached;
  25926. bindingsForPath[firstActiveIndex] = last;
  25927. bindingsForPath.pop();
  25928. }
  25929. } else {
  25930. // object is active, just swap with the last and pop
  25931. const lastIndex = --nObjects,
  25932. lastObject = objects[lastIndex];
  25933. if (lastIndex > 0) {
  25934. indicesByUUID[lastObject.uuid] = index;
  25935. }
  25936. objects[index] = lastObject;
  25937. objects.pop(); // accounting is done, now do the same for all bindings
  25938. for (let j = 0, m = nBindings; j !== m; ++j) {
  25939. const bindingsForPath = bindings[j];
  25940. bindingsForPath[index] = bindingsForPath[lastIndex];
  25941. bindingsForPath.pop();
  25942. }
  25943. } // cached or active
  25944. } // if object is known
  25945. } // for arguments
  25946. this.nCachedObjects_ = nCachedObjects;
  25947. } // Internal interface used by befriended PropertyBinding.Composite:
  25948. subscribe_(path, parsedPath) {
  25949. // returns an array of bindings for the given path that is changed
  25950. // according to the contained objects in the group
  25951. const indicesByPath = this._bindingsIndicesByPath;
  25952. let index = indicesByPath[path];
  25953. const bindings = this._bindings;
  25954. if (index !== undefined) return bindings[index];
  25955. const paths = this._paths,
  25956. parsedPaths = this._parsedPaths,
  25957. objects = this._objects,
  25958. nObjects = objects.length,
  25959. nCachedObjects = this.nCachedObjects_,
  25960. bindingsForPath = new Array(nObjects);
  25961. index = bindings.length;
  25962. indicesByPath[path] = index;
  25963. paths.push(path);
  25964. parsedPaths.push(parsedPath);
  25965. bindings.push(bindingsForPath);
  25966. for (let i = nCachedObjects, n = objects.length; i !== n; ++i) {
  25967. const object = objects[i];
  25968. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  25969. }
  25970. return bindingsForPath;
  25971. }
  25972. unsubscribe_(path) {
  25973. // tells the group to forget about a property path and no longer
  25974. // update the array previously obtained with 'subscribe_'
  25975. const indicesByPath = this._bindingsIndicesByPath,
  25976. index = indicesByPath[path];
  25977. if (index !== undefined) {
  25978. const paths = this._paths,
  25979. parsedPaths = this._parsedPaths,
  25980. bindings = this._bindings,
  25981. lastBindingsIndex = bindings.length - 1,
  25982. lastBindings = bindings[lastBindingsIndex],
  25983. lastBindingsPath = path[lastBindingsIndex];
  25984. indicesByPath[lastBindingsPath] = index;
  25985. bindings[index] = lastBindings;
  25986. bindings.pop();
  25987. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  25988. parsedPaths.pop();
  25989. paths[index] = paths[lastBindingsIndex];
  25990. paths.pop();
  25991. }
  25992. }
  25993. }
  25994. AnimationObjectGroup.prototype.isAnimationObjectGroup = true;
  25995. class AnimationAction {
  25996. constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) {
  25997. this._mixer = mixer;
  25998. this._clip = clip;
  25999. this._localRoot = localRoot;
  26000. this.blendMode = blendMode;
  26001. const tracks = clip.tracks,
  26002. nTracks = tracks.length,
  26003. interpolants = new Array(nTracks);
  26004. const interpolantSettings = {
  26005. endingStart: ZeroCurvatureEnding,
  26006. endingEnd: ZeroCurvatureEnding
  26007. };
  26008. for (let i = 0; i !== nTracks; ++i) {
  26009. const interpolant = tracks[i].createInterpolant(null);
  26010. interpolants[i] = interpolant;
  26011. interpolant.settings = interpolantSettings;
  26012. }
  26013. this._interpolantSettings = interpolantSettings;
  26014. this._interpolants = interpolants; // bound by the mixer
  26015. // inside: PropertyMixer (managed by the mixer)
  26016. this._propertyBindings = new Array(nTracks);
  26017. this._cacheIndex = null; // for the memory manager
  26018. this._byClipCacheIndex = null; // for the memory manager
  26019. this._timeScaleInterpolant = null;
  26020. this._weightInterpolant = null;
  26021. this.loop = LoopRepeat;
  26022. this._loopCount = -1; // global mixer time when the action is to be started
  26023. // it's set back to 'null' upon start of the action
  26024. this._startTime = null; // scaled local time of the action
  26025. // gets clamped or wrapped to 0..clip.duration according to loop
  26026. this.time = 0;
  26027. this.timeScale = 1;
  26028. this._effectiveTimeScale = 1;
  26029. this.weight = 1;
  26030. this._effectiveWeight = 1;
  26031. this.repetitions = Infinity; // no. of repetitions when looping
  26032. this.paused = false; // true -> zero effective time scale
  26033. this.enabled = true; // false -> zero effective weight
  26034. this.clampWhenFinished = false; // keep feeding the last frame?
  26035. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  26036. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  26037. } // State & Scheduling
  26038. play() {
  26039. this._mixer._activateAction(this);
  26040. return this;
  26041. }
  26042. stop() {
  26043. this._mixer._deactivateAction(this);
  26044. return this.reset();
  26045. }
  26046. reset() {
  26047. this.paused = false;
  26048. this.enabled = true;
  26049. this.time = 0; // restart clip
  26050. this._loopCount = -1; // forget previous loops
  26051. this._startTime = null; // forget scheduling
  26052. return this.stopFading().stopWarping();
  26053. }
  26054. isRunning() {
  26055. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  26056. } // return true when play has been called
  26057. isScheduled() {
  26058. return this._mixer._isActiveAction(this);
  26059. }
  26060. startAt(time) {
  26061. this._startTime = time;
  26062. return this;
  26063. }
  26064. setLoop(mode, repetitions) {
  26065. this.loop = mode;
  26066. this.repetitions = repetitions;
  26067. return this;
  26068. } // Weight
  26069. // set the weight stopping any scheduled fading
  26070. // although .enabled = false yields an effective weight of zero, this
  26071. // method does *not* change .enabled, because it would be confusing
  26072. setEffectiveWeight(weight) {
  26073. this.weight = weight; // note: same logic as when updated at runtime
  26074. this._effectiveWeight = this.enabled ? weight : 0;
  26075. return this.stopFading();
  26076. } // return the weight considering fading and .enabled
  26077. getEffectiveWeight() {
  26078. return this._effectiveWeight;
  26079. }
  26080. fadeIn(duration) {
  26081. return this._scheduleFading(duration, 0, 1);
  26082. }
  26083. fadeOut(duration) {
  26084. return this._scheduleFading(duration, 1, 0);
  26085. }
  26086. crossFadeFrom(fadeOutAction, duration, warp) {
  26087. fadeOutAction.fadeOut(duration);
  26088. this.fadeIn(duration);
  26089. if (warp) {
  26090. const fadeInDuration = this._clip.duration,
  26091. fadeOutDuration = fadeOutAction._clip.duration,
  26092. startEndRatio = fadeOutDuration / fadeInDuration,
  26093. endStartRatio = fadeInDuration / fadeOutDuration;
  26094. fadeOutAction.warp(1.0, startEndRatio, duration);
  26095. this.warp(endStartRatio, 1.0, duration);
  26096. }
  26097. return this;
  26098. }
  26099. crossFadeTo(fadeInAction, duration, warp) {
  26100. return fadeInAction.crossFadeFrom(this, duration, warp);
  26101. }
  26102. stopFading() {
  26103. const weightInterpolant = this._weightInterpolant;
  26104. if (weightInterpolant !== null) {
  26105. this._weightInterpolant = null;
  26106. this._mixer._takeBackControlInterpolant(weightInterpolant);
  26107. }
  26108. return this;
  26109. } // Time Scale Control
  26110. // set the time scale stopping any scheduled warping
  26111. // although .paused = true yields an effective time scale of zero, this
  26112. // method does *not* change .paused, because it would be confusing
  26113. setEffectiveTimeScale(timeScale) {
  26114. this.timeScale = timeScale;
  26115. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  26116. return this.stopWarping();
  26117. } // return the time scale considering warping and .paused
  26118. getEffectiveTimeScale() {
  26119. return this._effectiveTimeScale;
  26120. }
  26121. setDuration(duration) {
  26122. this.timeScale = this._clip.duration / duration;
  26123. return this.stopWarping();
  26124. }
  26125. syncWith(action) {
  26126. this.time = action.time;
  26127. this.timeScale = action.timeScale;
  26128. return this.stopWarping();
  26129. }
  26130. halt(duration) {
  26131. return this.warp(this._effectiveTimeScale, 0, duration);
  26132. }
  26133. warp(startTimeScale, endTimeScale, duration) {
  26134. const mixer = this._mixer,
  26135. now = mixer.time,
  26136. timeScale = this.timeScale;
  26137. let interpolant = this._timeScaleInterpolant;
  26138. if (interpolant === null) {
  26139. interpolant = mixer._lendControlInterpolant();
  26140. this._timeScaleInterpolant = interpolant;
  26141. }
  26142. const times = interpolant.parameterPositions,
  26143. values = interpolant.sampleValues;
  26144. times[0] = now;
  26145. times[1] = now + duration;
  26146. values[0] = startTimeScale / timeScale;
  26147. values[1] = endTimeScale / timeScale;
  26148. return this;
  26149. }
  26150. stopWarping() {
  26151. const timeScaleInterpolant = this._timeScaleInterpolant;
  26152. if (timeScaleInterpolant !== null) {
  26153. this._timeScaleInterpolant = null;
  26154. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  26155. }
  26156. return this;
  26157. } // Object Accessors
  26158. getMixer() {
  26159. return this._mixer;
  26160. }
  26161. getClip() {
  26162. return this._clip;
  26163. }
  26164. getRoot() {
  26165. return this._localRoot || this._mixer._root;
  26166. } // Interna
  26167. _update(time, deltaTime, timeDirection, accuIndex) {
  26168. // called by the mixer
  26169. if (!this.enabled) {
  26170. // call ._updateWeight() to update ._effectiveWeight
  26171. this._updateWeight(time);
  26172. return;
  26173. }
  26174. const startTime = this._startTime;
  26175. if (startTime !== null) {
  26176. // check for scheduled start of action
  26177. const timeRunning = (time - startTime) * timeDirection;
  26178. if (timeRunning < 0 || timeDirection === 0) {
  26179. return; // yet to come / don't decide when delta = 0
  26180. } // start
  26181. this._startTime = null; // unschedule
  26182. deltaTime = timeDirection * timeRunning;
  26183. } // apply time scale and advance time
  26184. deltaTime *= this._updateTimeScale(time);
  26185. const clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  26186. // an effective weight of 0
  26187. const weight = this._updateWeight(time);
  26188. if (weight > 0) {
  26189. const interpolants = this._interpolants;
  26190. const propertyMixers = this._propertyBindings;
  26191. switch (this.blendMode) {
  26192. case AdditiveAnimationBlendMode:
  26193. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26194. interpolants[j].evaluate(clipTime);
  26195. propertyMixers[j].accumulateAdditive(weight);
  26196. }
  26197. break;
  26198. case NormalAnimationBlendMode:
  26199. default:
  26200. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26201. interpolants[j].evaluate(clipTime);
  26202. propertyMixers[j].accumulate(accuIndex, weight);
  26203. }
  26204. }
  26205. }
  26206. }
  26207. _updateWeight(time) {
  26208. let weight = 0;
  26209. if (this.enabled) {
  26210. weight = this.weight;
  26211. const interpolant = this._weightInterpolant;
  26212. if (interpolant !== null) {
  26213. const interpolantValue = interpolant.evaluate(time)[0];
  26214. weight *= interpolantValue;
  26215. if (time > interpolant.parameterPositions[1]) {
  26216. this.stopFading();
  26217. if (interpolantValue === 0) {
  26218. // faded out, disable
  26219. this.enabled = false;
  26220. }
  26221. }
  26222. }
  26223. }
  26224. this._effectiveWeight = weight;
  26225. return weight;
  26226. }
  26227. _updateTimeScale(time) {
  26228. let timeScale = 0;
  26229. if (!this.paused) {
  26230. timeScale = this.timeScale;
  26231. const interpolant = this._timeScaleInterpolant;
  26232. if (interpolant !== null) {
  26233. const interpolantValue = interpolant.evaluate(time)[0];
  26234. timeScale *= interpolantValue;
  26235. if (time > interpolant.parameterPositions[1]) {
  26236. this.stopWarping();
  26237. if (timeScale === 0) {
  26238. // motion has halted, pause
  26239. this.paused = true;
  26240. } else {
  26241. // warp done - apply final time scale
  26242. this.timeScale = timeScale;
  26243. }
  26244. }
  26245. }
  26246. }
  26247. this._effectiveTimeScale = timeScale;
  26248. return timeScale;
  26249. }
  26250. _updateTime(deltaTime) {
  26251. const duration = this._clip.duration;
  26252. const loop = this.loop;
  26253. let time = this.time + deltaTime;
  26254. let loopCount = this._loopCount;
  26255. const pingPong = loop === LoopPingPong;
  26256. if (deltaTime === 0) {
  26257. if (loopCount === -1) return time;
  26258. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  26259. }
  26260. if (loop === LoopOnce) {
  26261. if (loopCount === -1) {
  26262. // just started
  26263. this._loopCount = 0;
  26264. this._setEndings(true, true, false);
  26265. }
  26266. handle_stop: {
  26267. if (time >= duration) {
  26268. time = duration;
  26269. } else if (time < 0) {
  26270. time = 0;
  26271. } else {
  26272. this.time = time;
  26273. break handle_stop;
  26274. }
  26275. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26276. this.time = time;
  26277. this._mixer.dispatchEvent({
  26278. type: 'finished',
  26279. action: this,
  26280. direction: deltaTime < 0 ? -1 : 1
  26281. });
  26282. }
  26283. } else {
  26284. // repetitive Repeat or PingPong
  26285. if (loopCount === -1) {
  26286. // just started
  26287. if (deltaTime >= 0) {
  26288. loopCount = 0;
  26289. this._setEndings(true, this.repetitions === 0, pingPong);
  26290. } else {
  26291. // when looping in reverse direction, the initial
  26292. // transition through zero counts as a repetition,
  26293. // so leave loopCount at -1
  26294. this._setEndings(this.repetitions === 0, true, pingPong);
  26295. }
  26296. }
  26297. if (time >= duration || time < 0) {
  26298. // wrap around
  26299. const loopDelta = Math.floor(time / duration); // signed
  26300. time -= duration * loopDelta;
  26301. loopCount += Math.abs(loopDelta);
  26302. const pending = this.repetitions - loopCount;
  26303. if (pending <= 0) {
  26304. // have to stop (switch state, clamp time, fire event)
  26305. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26306. time = deltaTime > 0 ? duration : 0;
  26307. this.time = time;
  26308. this._mixer.dispatchEvent({
  26309. type: 'finished',
  26310. action: this,
  26311. direction: deltaTime > 0 ? 1 : -1
  26312. });
  26313. } else {
  26314. // keep running
  26315. if (pending === 1) {
  26316. // entering the last round
  26317. const atStart = deltaTime < 0;
  26318. this._setEndings(atStart, !atStart, pingPong);
  26319. } else {
  26320. this._setEndings(false, false, pingPong);
  26321. }
  26322. this._loopCount = loopCount;
  26323. this.time = time;
  26324. this._mixer.dispatchEvent({
  26325. type: 'loop',
  26326. action: this,
  26327. loopDelta: loopDelta
  26328. });
  26329. }
  26330. } else {
  26331. this.time = time;
  26332. }
  26333. if (pingPong && (loopCount & 1) === 1) {
  26334. // invert time for the "pong round"
  26335. return duration - time;
  26336. }
  26337. }
  26338. return time;
  26339. }
  26340. _setEndings(atStart, atEnd, pingPong) {
  26341. const settings = this._interpolantSettings;
  26342. if (pingPong) {
  26343. settings.endingStart = ZeroSlopeEnding;
  26344. settings.endingEnd = ZeroSlopeEnding;
  26345. } else {
  26346. // assuming for LoopOnce atStart == atEnd == true
  26347. if (atStart) {
  26348. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26349. } else {
  26350. settings.endingStart = WrapAroundEnding;
  26351. }
  26352. if (atEnd) {
  26353. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26354. } else {
  26355. settings.endingEnd = WrapAroundEnding;
  26356. }
  26357. }
  26358. }
  26359. _scheduleFading(duration, weightNow, weightThen) {
  26360. const mixer = this._mixer,
  26361. now = mixer.time;
  26362. let interpolant = this._weightInterpolant;
  26363. if (interpolant === null) {
  26364. interpolant = mixer._lendControlInterpolant();
  26365. this._weightInterpolant = interpolant;
  26366. }
  26367. const times = interpolant.parameterPositions,
  26368. values = interpolant.sampleValues;
  26369. times[0] = now;
  26370. values[0] = weightNow;
  26371. times[1] = now + duration;
  26372. values[1] = weightThen;
  26373. return this;
  26374. }
  26375. }
  26376. class AnimationMixer extends EventDispatcher {
  26377. constructor(root) {
  26378. super();
  26379. this._root = root;
  26380. this._initMemoryManager();
  26381. this._accuIndex = 0;
  26382. this.time = 0;
  26383. this.timeScale = 1.0;
  26384. }
  26385. _bindAction(action, prototypeAction) {
  26386. const root = action._localRoot || this._root,
  26387. tracks = action._clip.tracks,
  26388. nTracks = tracks.length,
  26389. bindings = action._propertyBindings,
  26390. interpolants = action._interpolants,
  26391. rootUuid = root.uuid,
  26392. bindingsByRoot = this._bindingsByRootAndName;
  26393. let bindingsByName = bindingsByRoot[rootUuid];
  26394. if (bindingsByName === undefined) {
  26395. bindingsByName = {};
  26396. bindingsByRoot[rootUuid] = bindingsByName;
  26397. }
  26398. for (let i = 0; i !== nTracks; ++i) {
  26399. const track = tracks[i],
  26400. trackName = track.name;
  26401. let binding = bindingsByName[trackName];
  26402. if (binding !== undefined) {
  26403. bindings[i] = binding;
  26404. } else {
  26405. binding = bindings[i];
  26406. if (binding !== undefined) {
  26407. // existing binding, make sure the cache knows
  26408. if (binding._cacheIndex === null) {
  26409. ++binding.referenceCount;
  26410. this._addInactiveBinding(binding, rootUuid, trackName);
  26411. }
  26412. continue;
  26413. }
  26414. const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  26415. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  26416. ++binding.referenceCount;
  26417. this._addInactiveBinding(binding, rootUuid, trackName);
  26418. bindings[i] = binding;
  26419. }
  26420. interpolants[i].resultBuffer = binding.buffer;
  26421. }
  26422. }
  26423. _activateAction(action) {
  26424. if (!this._isActiveAction(action)) {
  26425. if (action._cacheIndex === null) {
  26426. // this action has been forgotten by the cache, but the user
  26427. // appears to be still using it -> rebind
  26428. const rootUuid = (action._localRoot || this._root).uuid,
  26429. clipUuid = action._clip.uuid,
  26430. actionsForClip = this._actionsByClip[clipUuid];
  26431. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  26432. this._addInactiveAction(action, clipUuid, rootUuid);
  26433. }
  26434. const bindings = action._propertyBindings; // increment reference counts / sort out state
  26435. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26436. const binding = bindings[i];
  26437. if (binding.useCount++ === 0) {
  26438. this._lendBinding(binding);
  26439. binding.saveOriginalState();
  26440. }
  26441. }
  26442. this._lendAction(action);
  26443. }
  26444. }
  26445. _deactivateAction(action) {
  26446. if (this._isActiveAction(action)) {
  26447. const bindings = action._propertyBindings; // decrement reference counts / sort out state
  26448. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26449. const binding = bindings[i];
  26450. if (--binding.useCount === 0) {
  26451. binding.restoreOriginalState();
  26452. this._takeBackBinding(binding);
  26453. }
  26454. }
  26455. this._takeBackAction(action);
  26456. }
  26457. } // Memory manager
  26458. _initMemoryManager() {
  26459. this._actions = []; // 'nActiveActions' followed by inactive ones
  26460. this._nActiveActions = 0;
  26461. this._actionsByClip = {}; // inside:
  26462. // {
  26463. // knownActions: Array< AnimationAction > - used as prototypes
  26464. // actionByRoot: AnimationAction - lookup
  26465. // }
  26466. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  26467. this._nActiveBindings = 0;
  26468. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  26469. this._controlInterpolants = []; // same game as above
  26470. this._nActiveControlInterpolants = 0;
  26471. const scope = this;
  26472. this.stats = {
  26473. actions: {
  26474. get total() {
  26475. return scope._actions.length;
  26476. },
  26477. get inUse() {
  26478. return scope._nActiveActions;
  26479. }
  26480. },
  26481. bindings: {
  26482. get total() {
  26483. return scope._bindings.length;
  26484. },
  26485. get inUse() {
  26486. return scope._nActiveBindings;
  26487. }
  26488. },
  26489. controlInterpolants: {
  26490. get total() {
  26491. return scope._controlInterpolants.length;
  26492. },
  26493. get inUse() {
  26494. return scope._nActiveControlInterpolants;
  26495. }
  26496. }
  26497. };
  26498. } // Memory management for AnimationAction objects
  26499. _isActiveAction(action) {
  26500. const index = action._cacheIndex;
  26501. return index !== null && index < this._nActiveActions;
  26502. }
  26503. _addInactiveAction(action, clipUuid, rootUuid) {
  26504. const actions = this._actions,
  26505. actionsByClip = this._actionsByClip;
  26506. let actionsForClip = actionsByClip[clipUuid];
  26507. if (actionsForClip === undefined) {
  26508. actionsForClip = {
  26509. knownActions: [action],
  26510. actionByRoot: {}
  26511. };
  26512. action._byClipCacheIndex = 0;
  26513. actionsByClip[clipUuid] = actionsForClip;
  26514. } else {
  26515. const knownActions = actionsForClip.knownActions;
  26516. action._byClipCacheIndex = knownActions.length;
  26517. knownActions.push(action);
  26518. }
  26519. action._cacheIndex = actions.length;
  26520. actions.push(action);
  26521. actionsForClip.actionByRoot[rootUuid] = action;
  26522. }
  26523. _removeInactiveAction(action) {
  26524. const actions = this._actions,
  26525. lastInactiveAction = actions[actions.length - 1],
  26526. cacheIndex = action._cacheIndex;
  26527. lastInactiveAction._cacheIndex = cacheIndex;
  26528. actions[cacheIndex] = lastInactiveAction;
  26529. actions.pop();
  26530. action._cacheIndex = null;
  26531. const clipUuid = action._clip.uuid,
  26532. actionsByClip = this._actionsByClip,
  26533. actionsForClip = actionsByClip[clipUuid],
  26534. knownActionsForClip = actionsForClip.knownActions,
  26535. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  26536. byClipCacheIndex = action._byClipCacheIndex;
  26537. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  26538. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  26539. knownActionsForClip.pop();
  26540. action._byClipCacheIndex = null;
  26541. const actionByRoot = actionsForClip.actionByRoot,
  26542. rootUuid = (action._localRoot || this._root).uuid;
  26543. delete actionByRoot[rootUuid];
  26544. if (knownActionsForClip.length === 0) {
  26545. delete actionsByClip[clipUuid];
  26546. }
  26547. this._removeInactiveBindingsForAction(action);
  26548. }
  26549. _removeInactiveBindingsForAction(action) {
  26550. const bindings = action._propertyBindings;
  26551. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26552. const binding = bindings[i];
  26553. if (--binding.referenceCount === 0) {
  26554. this._removeInactiveBinding(binding);
  26555. }
  26556. }
  26557. }
  26558. _lendAction(action) {
  26559. // [ active actions | inactive actions ]
  26560. // [ active actions >| inactive actions ]
  26561. // s a
  26562. // <-swap->
  26563. // a s
  26564. const actions = this._actions,
  26565. prevIndex = action._cacheIndex,
  26566. lastActiveIndex = this._nActiveActions++,
  26567. firstInactiveAction = actions[lastActiveIndex];
  26568. action._cacheIndex = lastActiveIndex;
  26569. actions[lastActiveIndex] = action;
  26570. firstInactiveAction._cacheIndex = prevIndex;
  26571. actions[prevIndex] = firstInactiveAction;
  26572. }
  26573. _takeBackAction(action) {
  26574. // [ active actions | inactive actions ]
  26575. // [ active actions |< inactive actions ]
  26576. // a s
  26577. // <-swap->
  26578. // s a
  26579. const actions = this._actions,
  26580. prevIndex = action._cacheIndex,
  26581. firstInactiveIndex = --this._nActiveActions,
  26582. lastActiveAction = actions[firstInactiveIndex];
  26583. action._cacheIndex = firstInactiveIndex;
  26584. actions[firstInactiveIndex] = action;
  26585. lastActiveAction._cacheIndex = prevIndex;
  26586. actions[prevIndex] = lastActiveAction;
  26587. } // Memory management for PropertyMixer objects
  26588. _addInactiveBinding(binding, rootUuid, trackName) {
  26589. const bindingsByRoot = this._bindingsByRootAndName,
  26590. bindings = this._bindings;
  26591. let bindingByName = bindingsByRoot[rootUuid];
  26592. if (bindingByName === undefined) {
  26593. bindingByName = {};
  26594. bindingsByRoot[rootUuid] = bindingByName;
  26595. }
  26596. bindingByName[trackName] = binding;
  26597. binding._cacheIndex = bindings.length;
  26598. bindings.push(binding);
  26599. }
  26600. _removeInactiveBinding(binding) {
  26601. const bindings = this._bindings,
  26602. propBinding = binding.binding,
  26603. rootUuid = propBinding.rootNode.uuid,
  26604. trackName = propBinding.path,
  26605. bindingsByRoot = this._bindingsByRootAndName,
  26606. bindingByName = bindingsByRoot[rootUuid],
  26607. lastInactiveBinding = bindings[bindings.length - 1],
  26608. cacheIndex = binding._cacheIndex;
  26609. lastInactiveBinding._cacheIndex = cacheIndex;
  26610. bindings[cacheIndex] = lastInactiveBinding;
  26611. bindings.pop();
  26612. delete bindingByName[trackName];
  26613. if (Object.keys(bindingByName).length === 0) {
  26614. delete bindingsByRoot[rootUuid];
  26615. }
  26616. }
  26617. _lendBinding(binding) {
  26618. const bindings = this._bindings,
  26619. prevIndex = binding._cacheIndex,
  26620. lastActiveIndex = this._nActiveBindings++,
  26621. firstInactiveBinding = bindings[lastActiveIndex];
  26622. binding._cacheIndex = lastActiveIndex;
  26623. bindings[lastActiveIndex] = binding;
  26624. firstInactiveBinding._cacheIndex = prevIndex;
  26625. bindings[prevIndex] = firstInactiveBinding;
  26626. }
  26627. _takeBackBinding(binding) {
  26628. const bindings = this._bindings,
  26629. prevIndex = binding._cacheIndex,
  26630. firstInactiveIndex = --this._nActiveBindings,
  26631. lastActiveBinding = bindings[firstInactiveIndex];
  26632. binding._cacheIndex = firstInactiveIndex;
  26633. bindings[firstInactiveIndex] = binding;
  26634. lastActiveBinding._cacheIndex = prevIndex;
  26635. bindings[prevIndex] = lastActiveBinding;
  26636. } // Memory management of Interpolants for weight and time scale
  26637. _lendControlInterpolant() {
  26638. const interpolants = this._controlInterpolants,
  26639. lastActiveIndex = this._nActiveControlInterpolants++;
  26640. let interpolant = interpolants[lastActiveIndex];
  26641. if (interpolant === undefined) {
  26642. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  26643. interpolant.__cacheIndex = lastActiveIndex;
  26644. interpolants[lastActiveIndex] = interpolant;
  26645. }
  26646. return interpolant;
  26647. }
  26648. _takeBackControlInterpolant(interpolant) {
  26649. const interpolants = this._controlInterpolants,
  26650. prevIndex = interpolant.__cacheIndex,
  26651. firstInactiveIndex = --this._nActiveControlInterpolants,
  26652. lastActiveInterpolant = interpolants[firstInactiveIndex];
  26653. interpolant.__cacheIndex = firstInactiveIndex;
  26654. interpolants[firstInactiveIndex] = interpolant;
  26655. lastActiveInterpolant.__cacheIndex = prevIndex;
  26656. interpolants[prevIndex] = lastActiveInterpolant;
  26657. } // return an action for a clip optionally using a custom root target
  26658. // object (this method allocates a lot of dynamic memory in case a
  26659. // previously unknown clip/root combination is specified)
  26660. clipAction(clip, optionalRoot, blendMode) {
  26661. const root = optionalRoot || this._root,
  26662. rootUuid = root.uuid;
  26663. let clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
  26664. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  26665. const actionsForClip = this._actionsByClip[clipUuid];
  26666. let prototypeAction = null;
  26667. if (blendMode === undefined) {
  26668. if (clipObject !== null) {
  26669. blendMode = clipObject.blendMode;
  26670. } else {
  26671. blendMode = NormalAnimationBlendMode;
  26672. }
  26673. }
  26674. if (actionsForClip !== undefined) {
  26675. const existingAction = actionsForClip.actionByRoot[rootUuid];
  26676. if (existingAction !== undefined && existingAction.blendMode === blendMode) {
  26677. return existingAction;
  26678. } // we know the clip, so we don't have to parse all
  26679. // the bindings again but can just copy
  26680. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  26681. if (clipObject === null) clipObject = prototypeAction._clip;
  26682. } // clip must be known when specified via string
  26683. if (clipObject === null) return null; // allocate all resources required to run it
  26684. const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
  26685. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  26686. this._addInactiveAction(newAction, clipUuid, rootUuid);
  26687. return newAction;
  26688. } // get an existing action
  26689. existingAction(clip, optionalRoot) {
  26690. const root = optionalRoot || this._root,
  26691. rootUuid = root.uuid,
  26692. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  26693. clipUuid = clipObject ? clipObject.uuid : clip,
  26694. actionsForClip = this._actionsByClip[clipUuid];
  26695. if (actionsForClip !== undefined) {
  26696. return actionsForClip.actionByRoot[rootUuid] || null;
  26697. }
  26698. return null;
  26699. } // deactivates all previously scheduled actions
  26700. stopAllAction() {
  26701. const actions = this._actions,
  26702. nActions = this._nActiveActions;
  26703. for (let i = nActions - 1; i >= 0; --i) {
  26704. actions[i].stop();
  26705. }
  26706. return this;
  26707. } // advance the time and update apply the animation
  26708. update(deltaTime) {
  26709. deltaTime *= this.timeScale;
  26710. const actions = this._actions,
  26711. nActions = this._nActiveActions,
  26712. time = this.time += deltaTime,
  26713. timeDirection = Math.sign(deltaTime),
  26714. accuIndex = this._accuIndex ^= 1; // run active actions
  26715. for (let i = 0; i !== nActions; ++i) {
  26716. const action = actions[i];
  26717. action._update(time, deltaTime, timeDirection, accuIndex);
  26718. } // update scene graph
  26719. const bindings = this._bindings,
  26720. nBindings = this._nActiveBindings;
  26721. for (let i = 0; i !== nBindings; ++i) {
  26722. bindings[i].apply(accuIndex);
  26723. }
  26724. return this;
  26725. } // Allows you to seek to a specific time in an animation.
  26726. setTime(timeInSeconds) {
  26727. this.time = 0; // Zero out time attribute for AnimationMixer object;
  26728. for (let i = 0; i < this._actions.length; i++) {
  26729. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  26730. }
  26731. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  26732. } // return this mixer's root target object
  26733. getRoot() {
  26734. return this._root;
  26735. } // free all resources specific to a particular clip
  26736. uncacheClip(clip) {
  26737. const actions = this._actions,
  26738. clipUuid = clip.uuid,
  26739. actionsByClip = this._actionsByClip,
  26740. actionsForClip = actionsByClip[clipUuid];
  26741. if (actionsForClip !== undefined) {
  26742. // note: just calling _removeInactiveAction would mess up the
  26743. // iteration state and also require updating the state we can
  26744. // just throw away
  26745. const actionsToRemove = actionsForClip.knownActions;
  26746. for (let i = 0, n = actionsToRemove.length; i !== n; ++i) {
  26747. const action = actionsToRemove[i];
  26748. this._deactivateAction(action);
  26749. const cacheIndex = action._cacheIndex,
  26750. lastInactiveAction = actions[actions.length - 1];
  26751. action._cacheIndex = null;
  26752. action._byClipCacheIndex = null;
  26753. lastInactiveAction._cacheIndex = cacheIndex;
  26754. actions[cacheIndex] = lastInactiveAction;
  26755. actions.pop();
  26756. this._removeInactiveBindingsForAction(action);
  26757. }
  26758. delete actionsByClip[clipUuid];
  26759. }
  26760. } // free all resources specific to a particular root target object
  26761. uncacheRoot(root) {
  26762. const rootUuid = root.uuid,
  26763. actionsByClip = this._actionsByClip;
  26764. for (const clipUuid in actionsByClip) {
  26765. const actionByRoot = actionsByClip[clipUuid].actionByRoot,
  26766. action = actionByRoot[rootUuid];
  26767. if (action !== undefined) {
  26768. this._deactivateAction(action);
  26769. this._removeInactiveAction(action);
  26770. }
  26771. }
  26772. const bindingsByRoot = this._bindingsByRootAndName,
  26773. bindingByName = bindingsByRoot[rootUuid];
  26774. if (bindingByName !== undefined) {
  26775. for (const trackName in bindingByName) {
  26776. const binding = bindingByName[trackName];
  26777. binding.restoreOriginalState();
  26778. this._removeInactiveBinding(binding);
  26779. }
  26780. }
  26781. } // remove a targeted clip from the cache
  26782. uncacheAction(clip, optionalRoot) {
  26783. const action = this.existingAction(clip, optionalRoot);
  26784. if (action !== null) {
  26785. this._deactivateAction(action);
  26786. this._removeInactiveAction(action);
  26787. }
  26788. }
  26789. }
  26790. AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array(1);
  26791. class Uniform {
  26792. constructor(value) {
  26793. if (typeof value === 'string') {
  26794. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  26795. value = arguments[1];
  26796. }
  26797. this.value = value;
  26798. }
  26799. clone() {
  26800. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  26801. }
  26802. }
  26803. class InstancedInterleavedBuffer extends InterleavedBuffer {
  26804. constructor(array, stride, meshPerAttribute = 1) {
  26805. super(array, stride);
  26806. this.meshPerAttribute = meshPerAttribute;
  26807. }
  26808. copy(source) {
  26809. super.copy(source);
  26810. this.meshPerAttribute = source.meshPerAttribute;
  26811. return this;
  26812. }
  26813. clone(data) {
  26814. const ib = super.clone(data);
  26815. ib.meshPerAttribute = this.meshPerAttribute;
  26816. return ib;
  26817. }
  26818. toJSON(data) {
  26819. const json = super.toJSON(data);
  26820. json.isInstancedInterleavedBuffer = true;
  26821. json.meshPerAttribute = this.meshPerAttribute;
  26822. return json;
  26823. }
  26824. }
  26825. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  26826. class GLBufferAttribute {
  26827. constructor(buffer, type, itemSize, elementSize, count) {
  26828. this.buffer = buffer;
  26829. this.type = type;
  26830. this.itemSize = itemSize;
  26831. this.elementSize = elementSize;
  26832. this.count = count;
  26833. this.version = 0;
  26834. }
  26835. set needsUpdate(value) {
  26836. if (value === true) this.version++;
  26837. }
  26838. setBuffer(buffer) {
  26839. this.buffer = buffer;
  26840. return this;
  26841. }
  26842. setType(type, elementSize) {
  26843. this.type = type;
  26844. this.elementSize = elementSize;
  26845. return this;
  26846. }
  26847. setItemSize(itemSize) {
  26848. this.itemSize = itemSize;
  26849. return this;
  26850. }
  26851. setCount(count) {
  26852. this.count = count;
  26853. return this;
  26854. }
  26855. }
  26856. GLBufferAttribute.prototype.isGLBufferAttribute = true;
  26857. class Raycaster {
  26858. constructor(origin, direction, near = 0, far = Infinity) {
  26859. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  26860. this.near = near;
  26861. this.far = far;
  26862. this.camera = null;
  26863. this.layers = new Layers();
  26864. this.params = {
  26865. Mesh: {},
  26866. Line: {
  26867. threshold: 1
  26868. },
  26869. LOD: {},
  26870. Points: {
  26871. threshold: 1
  26872. },
  26873. Sprite: {}
  26874. };
  26875. }
  26876. set(origin, direction) {
  26877. // direction is assumed to be normalized (for accurate distance calculations)
  26878. this.ray.set(origin, direction);
  26879. }
  26880. setFromCamera(coords, camera) {
  26881. if (camera && camera.isPerspectiveCamera) {
  26882. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  26883. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  26884. this.camera = camera;
  26885. } else if (camera && camera.isOrthographicCamera) {
  26886. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  26887. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  26888. this.camera = camera;
  26889. } else {
  26890. console.error('THREE.Raycaster: Unsupported camera type: ' + camera.type);
  26891. }
  26892. }
  26893. intersectObject(object, recursive = false, intersects = []) {
  26894. intersectObject(object, this, intersects, recursive);
  26895. intersects.sort(ascSort);
  26896. return intersects;
  26897. }
  26898. intersectObjects(objects, recursive = false, intersects = []) {
  26899. for (let i = 0, l = objects.length; i < l; i++) {
  26900. intersectObject(objects[i], this, intersects, recursive);
  26901. }
  26902. intersects.sort(ascSort);
  26903. return intersects;
  26904. }
  26905. }
  26906. function ascSort(a, b) {
  26907. return a.distance - b.distance;
  26908. }
  26909. function intersectObject(object, raycaster, intersects, recursive) {
  26910. if (object.layers.test(raycaster.layers)) {
  26911. object.raycast(raycaster, intersects);
  26912. }
  26913. if (recursive === true) {
  26914. const children = object.children;
  26915. for (let i = 0, l = children.length; i < l; i++) {
  26916. intersectObject(children[i], raycaster, intersects, true);
  26917. }
  26918. }
  26919. }
  26920. /**
  26921. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  26922. *
  26923. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  26924. * The azimuthal angle (theta) is measured from the positive z-axis.
  26925. */
  26926. class Spherical {
  26927. constructor(radius = 1, phi = 0, theta = 0) {
  26928. this.radius = radius;
  26929. this.phi = phi; // polar angle
  26930. this.theta = theta; // azimuthal angle
  26931. return this;
  26932. }
  26933. set(radius, phi, theta) {
  26934. this.radius = radius;
  26935. this.phi = phi;
  26936. this.theta = theta;
  26937. return this;
  26938. }
  26939. copy(other) {
  26940. this.radius = other.radius;
  26941. this.phi = other.phi;
  26942. this.theta = other.theta;
  26943. return this;
  26944. } // restrict phi to be betwee EPS and PI-EPS
  26945. makeSafe() {
  26946. const EPS = 0.000001;
  26947. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  26948. return this;
  26949. }
  26950. setFromVector3(v) {
  26951. return this.setFromCartesianCoords(v.x, v.y, v.z);
  26952. }
  26953. setFromCartesianCoords(x, y, z) {
  26954. this.radius = Math.sqrt(x * x + y * y + z * z);
  26955. if (this.radius === 0) {
  26956. this.theta = 0;
  26957. this.phi = 0;
  26958. } else {
  26959. this.theta = Math.atan2(x, z);
  26960. this.phi = Math.acos(clamp(y / this.radius, -1, 1));
  26961. }
  26962. return this;
  26963. }
  26964. clone() {
  26965. return new this.constructor().copy(this);
  26966. }
  26967. }
  26968. /**
  26969. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  26970. */
  26971. class Cylindrical {
  26972. constructor(radius = 1, theta = 0, y = 0) {
  26973. this.radius = radius; // distance from the origin to a point in the x-z plane
  26974. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  26975. this.y = y; // height above the x-z plane
  26976. return this;
  26977. }
  26978. set(radius, theta, y) {
  26979. this.radius = radius;
  26980. this.theta = theta;
  26981. this.y = y;
  26982. return this;
  26983. }
  26984. copy(other) {
  26985. this.radius = other.radius;
  26986. this.theta = other.theta;
  26987. this.y = other.y;
  26988. return this;
  26989. }
  26990. setFromVector3(v) {
  26991. return this.setFromCartesianCoords(v.x, v.y, v.z);
  26992. }
  26993. setFromCartesianCoords(x, y, z) {
  26994. this.radius = Math.sqrt(x * x + z * z);
  26995. this.theta = Math.atan2(x, z);
  26996. this.y = y;
  26997. return this;
  26998. }
  26999. clone() {
  27000. return new this.constructor().copy(this);
  27001. }
  27002. }
  27003. const _vector$4 = /*@__PURE__*/new Vector2();
  27004. class Box2 {
  27005. constructor(min = new Vector2(+Infinity, +Infinity), max = new Vector2(-Infinity, -Infinity)) {
  27006. this.min = min;
  27007. this.max = max;
  27008. }
  27009. set(min, max) {
  27010. this.min.copy(min);
  27011. this.max.copy(max);
  27012. return this;
  27013. }
  27014. setFromPoints(points) {
  27015. this.makeEmpty();
  27016. for (let i = 0, il = points.length; i < il; i++) {
  27017. this.expandByPoint(points[i]);
  27018. }
  27019. return this;
  27020. }
  27021. setFromCenterAndSize(center, size) {
  27022. const halfSize = _vector$4.copy(size).multiplyScalar(0.5);
  27023. this.min.copy(center).sub(halfSize);
  27024. this.max.copy(center).add(halfSize);
  27025. return this;
  27026. }
  27027. clone() {
  27028. return new this.constructor().copy(this);
  27029. }
  27030. copy(box) {
  27031. this.min.copy(box.min);
  27032. this.max.copy(box.max);
  27033. return this;
  27034. }
  27035. makeEmpty() {
  27036. this.min.x = this.min.y = +Infinity;
  27037. this.max.x = this.max.y = -Infinity;
  27038. return this;
  27039. }
  27040. isEmpty() {
  27041. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27042. return this.max.x < this.min.x || this.max.y < this.min.y;
  27043. }
  27044. getCenter(target) {
  27045. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  27046. }
  27047. getSize(target) {
  27048. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  27049. }
  27050. expandByPoint(point) {
  27051. this.min.min(point);
  27052. this.max.max(point);
  27053. return this;
  27054. }
  27055. expandByVector(vector) {
  27056. this.min.sub(vector);
  27057. this.max.add(vector);
  27058. return this;
  27059. }
  27060. expandByScalar(scalar) {
  27061. this.min.addScalar(-scalar);
  27062. this.max.addScalar(scalar);
  27063. return this;
  27064. }
  27065. containsPoint(point) {
  27066. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  27067. }
  27068. containsBox(box) {
  27069. 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;
  27070. }
  27071. getParameter(point, target) {
  27072. // This can potentially have a divide by zero if the box
  27073. // has a size dimension of 0.
  27074. 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));
  27075. }
  27076. intersectsBox(box) {
  27077. // using 4 splitting planes to rule out intersections
  27078. 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;
  27079. }
  27080. clampPoint(point, target) {
  27081. return target.copy(point).clamp(this.min, this.max);
  27082. }
  27083. distanceToPoint(point) {
  27084. const clampedPoint = _vector$4.copy(point).clamp(this.min, this.max);
  27085. return clampedPoint.sub(point).length();
  27086. }
  27087. intersect(box) {
  27088. this.min.max(box.min);
  27089. this.max.min(box.max);
  27090. return this;
  27091. }
  27092. union(box) {
  27093. this.min.min(box.min);
  27094. this.max.max(box.max);
  27095. return this;
  27096. }
  27097. translate(offset) {
  27098. this.min.add(offset);
  27099. this.max.add(offset);
  27100. return this;
  27101. }
  27102. equals(box) {
  27103. return box.min.equals(this.min) && box.max.equals(this.max);
  27104. }
  27105. }
  27106. Box2.prototype.isBox2 = true;
  27107. const _startP = /*@__PURE__*/new Vector3();
  27108. const _startEnd = /*@__PURE__*/new Vector3();
  27109. class Line3 {
  27110. constructor(start = new Vector3(), end = new Vector3()) {
  27111. this.start = start;
  27112. this.end = end;
  27113. }
  27114. set(start, end) {
  27115. this.start.copy(start);
  27116. this.end.copy(end);
  27117. return this;
  27118. }
  27119. copy(line) {
  27120. this.start.copy(line.start);
  27121. this.end.copy(line.end);
  27122. return this;
  27123. }
  27124. getCenter(target) {
  27125. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  27126. }
  27127. delta(target) {
  27128. return target.subVectors(this.end, this.start);
  27129. }
  27130. distanceSq() {
  27131. return this.start.distanceToSquared(this.end);
  27132. }
  27133. distance() {
  27134. return this.start.distanceTo(this.end);
  27135. }
  27136. at(t, target) {
  27137. return this.delta(target).multiplyScalar(t).add(this.start);
  27138. }
  27139. closestPointToPointParameter(point, clampToLine) {
  27140. _startP.subVectors(point, this.start);
  27141. _startEnd.subVectors(this.end, this.start);
  27142. const startEnd2 = _startEnd.dot(_startEnd);
  27143. const startEnd_startP = _startEnd.dot(_startP);
  27144. let t = startEnd_startP / startEnd2;
  27145. if (clampToLine) {
  27146. t = clamp(t, 0, 1);
  27147. }
  27148. return t;
  27149. }
  27150. closestPointToPoint(point, clampToLine, target) {
  27151. const t = this.closestPointToPointParameter(point, clampToLine);
  27152. return this.delta(target).multiplyScalar(t).add(this.start);
  27153. }
  27154. applyMatrix4(matrix) {
  27155. this.start.applyMatrix4(matrix);
  27156. this.end.applyMatrix4(matrix);
  27157. return this;
  27158. }
  27159. equals(line) {
  27160. return line.start.equals(this.start) && line.end.equals(this.end);
  27161. }
  27162. clone() {
  27163. return new this.constructor().copy(this);
  27164. }
  27165. }
  27166. class ImmediateRenderObject extends Object3D {
  27167. constructor(material) {
  27168. super();
  27169. this.material = material;
  27170. this.render = function () {};
  27171. this.hasPositions = false;
  27172. this.hasNormals = false;
  27173. this.hasColors = false;
  27174. this.hasUvs = false;
  27175. this.positionArray = null;
  27176. this.normalArray = null;
  27177. this.colorArray = null;
  27178. this.uvArray = null;
  27179. this.count = 0;
  27180. }
  27181. }
  27182. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  27183. const _vector$3 = /*@__PURE__*/new Vector3();
  27184. class SpotLightHelper extends Object3D {
  27185. constructor(light, color) {
  27186. super();
  27187. this.light = light;
  27188. this.light.updateMatrixWorld();
  27189. this.matrix = light.matrixWorld;
  27190. this.matrixAutoUpdate = false;
  27191. this.color = color;
  27192. const geometry = new BufferGeometry();
  27193. 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];
  27194. for (let i = 0, j = 1, l = 32; i < l; i++, j++) {
  27195. const p1 = i / l * Math.PI * 2;
  27196. const p2 = j / l * Math.PI * 2;
  27197. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  27198. }
  27199. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27200. const material = new LineBasicMaterial({
  27201. fog: false,
  27202. toneMapped: false
  27203. });
  27204. this.cone = new LineSegments(geometry, material);
  27205. this.add(this.cone);
  27206. this.update();
  27207. }
  27208. dispose() {
  27209. this.cone.geometry.dispose();
  27210. this.cone.material.dispose();
  27211. }
  27212. update() {
  27213. this.light.updateMatrixWorld();
  27214. const coneLength = this.light.distance ? this.light.distance : 1000;
  27215. const coneWidth = coneLength * Math.tan(this.light.angle);
  27216. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  27217. _vector$3.setFromMatrixPosition(this.light.target.matrixWorld);
  27218. this.cone.lookAt(_vector$3);
  27219. if (this.color !== undefined) {
  27220. this.cone.material.color.set(this.color);
  27221. } else {
  27222. this.cone.material.color.copy(this.light.color);
  27223. }
  27224. }
  27225. }
  27226. const _vector$2 = /*@__PURE__*/new Vector3();
  27227. const _boneMatrix = /*@__PURE__*/new Matrix4();
  27228. const _matrixWorldInv = /*@__PURE__*/new Matrix4();
  27229. class SkeletonHelper extends LineSegments {
  27230. constructor(object) {
  27231. const bones = getBoneList(object);
  27232. const geometry = new BufferGeometry();
  27233. const vertices = [];
  27234. const colors = [];
  27235. const color1 = new Color(0, 0, 1);
  27236. const color2 = new Color(0, 1, 0);
  27237. for (let i = 0; i < bones.length; i++) {
  27238. const bone = bones[i];
  27239. if (bone.parent && bone.parent.isBone) {
  27240. vertices.push(0, 0, 0);
  27241. vertices.push(0, 0, 0);
  27242. colors.push(color1.r, color1.g, color1.b);
  27243. colors.push(color2.r, color2.g, color2.b);
  27244. }
  27245. }
  27246. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27247. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27248. const material = new LineBasicMaterial({
  27249. vertexColors: true,
  27250. depthTest: false,
  27251. depthWrite: false,
  27252. toneMapped: false,
  27253. transparent: true
  27254. });
  27255. super(geometry, material);
  27256. this.type = 'SkeletonHelper';
  27257. this.isSkeletonHelper = true;
  27258. this.root = object;
  27259. this.bones = bones;
  27260. this.matrix = object.matrixWorld;
  27261. this.matrixAutoUpdate = false;
  27262. }
  27263. updateMatrixWorld(force) {
  27264. const bones = this.bones;
  27265. const geometry = this.geometry;
  27266. const position = geometry.getAttribute('position');
  27267. _matrixWorldInv.copy(this.root.matrixWorld).invert();
  27268. for (let i = 0, j = 0; i < bones.length; i++) {
  27269. const bone = bones[i];
  27270. if (bone.parent && bone.parent.isBone) {
  27271. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  27272. _vector$2.setFromMatrixPosition(_boneMatrix);
  27273. position.setXYZ(j, _vector$2.x, _vector$2.y, _vector$2.z);
  27274. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  27275. _vector$2.setFromMatrixPosition(_boneMatrix);
  27276. position.setXYZ(j + 1, _vector$2.x, _vector$2.y, _vector$2.z);
  27277. j += 2;
  27278. }
  27279. }
  27280. geometry.getAttribute('position').needsUpdate = true;
  27281. super.updateMatrixWorld(force);
  27282. }
  27283. }
  27284. function getBoneList(object) {
  27285. const boneList = [];
  27286. if (object && object.isBone) {
  27287. boneList.push(object);
  27288. }
  27289. for (let i = 0; i < object.children.length; i++) {
  27290. boneList.push.apply(boneList, getBoneList(object.children[i]));
  27291. }
  27292. return boneList;
  27293. }
  27294. class PointLightHelper extends Mesh {
  27295. constructor(light, sphereSize, color) {
  27296. const geometry = new SphereGeometry(sphereSize, 4, 2);
  27297. const material = new MeshBasicMaterial({
  27298. wireframe: true,
  27299. fog: false,
  27300. toneMapped: false
  27301. });
  27302. super(geometry, material);
  27303. this.light = light;
  27304. this.light.updateMatrixWorld();
  27305. this.color = color;
  27306. this.type = 'PointLightHelper';
  27307. this.matrix = this.light.matrixWorld;
  27308. this.matrixAutoUpdate = false;
  27309. this.update();
  27310. /*
  27311. // TODO: delete this comment?
  27312. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  27313. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  27314. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  27315. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  27316. const d = light.distance;
  27317. if ( d === 0.0 ) {
  27318. this.lightDistance.visible = false;
  27319. } else {
  27320. this.lightDistance.scale.set( d, d, d );
  27321. }
  27322. this.add( this.lightDistance );
  27323. */
  27324. }
  27325. dispose() {
  27326. this.geometry.dispose();
  27327. this.material.dispose();
  27328. }
  27329. update() {
  27330. if (this.color !== undefined) {
  27331. this.material.color.set(this.color);
  27332. } else {
  27333. this.material.color.copy(this.light.color);
  27334. }
  27335. /*
  27336. const d = this.light.distance;
  27337. if ( d === 0.0 ) {
  27338. this.lightDistance.visible = false;
  27339. } else {
  27340. this.lightDistance.visible = true;
  27341. this.lightDistance.scale.set( d, d, d );
  27342. }
  27343. */
  27344. }
  27345. }
  27346. const _vector$1 = /*@__PURE__*/new Vector3();
  27347. const _color1 = /*@__PURE__*/new Color();
  27348. const _color2 = /*@__PURE__*/new Color();
  27349. class HemisphereLightHelper extends Object3D {
  27350. constructor(light, size, color) {
  27351. super();
  27352. this.light = light;
  27353. this.light.updateMatrixWorld();
  27354. this.matrix = light.matrixWorld;
  27355. this.matrixAutoUpdate = false;
  27356. this.color = color;
  27357. const geometry = new OctahedronGeometry(size);
  27358. geometry.rotateY(Math.PI * 0.5);
  27359. this.material = new MeshBasicMaterial({
  27360. wireframe: true,
  27361. fog: false,
  27362. toneMapped: false
  27363. });
  27364. if (this.color === undefined) this.material.vertexColors = true;
  27365. const position = geometry.getAttribute('position');
  27366. const colors = new Float32Array(position.count * 3);
  27367. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  27368. this.add(new Mesh(geometry, this.material));
  27369. this.update();
  27370. }
  27371. dispose() {
  27372. this.children[0].geometry.dispose();
  27373. this.children[0].material.dispose();
  27374. }
  27375. update() {
  27376. const mesh = this.children[0];
  27377. if (this.color !== undefined) {
  27378. this.material.color.set(this.color);
  27379. } else {
  27380. const colors = mesh.geometry.getAttribute('color');
  27381. _color1.copy(this.light.color);
  27382. _color2.copy(this.light.groundColor);
  27383. for (let i = 0, l = colors.count; i < l; i++) {
  27384. const color = i < l / 2 ? _color1 : _color2;
  27385. colors.setXYZ(i, color.r, color.g, color.b);
  27386. }
  27387. colors.needsUpdate = true;
  27388. }
  27389. mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate());
  27390. }
  27391. }
  27392. class GridHelper extends LineSegments {
  27393. constructor(size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888) {
  27394. color1 = new Color(color1);
  27395. color2 = new Color(color2);
  27396. const center = divisions / 2;
  27397. const step = size / divisions;
  27398. const halfSize = size / 2;
  27399. const vertices = [],
  27400. colors = [];
  27401. for (let i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  27402. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  27403. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  27404. const color = i === center ? color1 : color2;
  27405. color.toArray(colors, j);
  27406. j += 3;
  27407. color.toArray(colors, j);
  27408. j += 3;
  27409. color.toArray(colors, j);
  27410. j += 3;
  27411. color.toArray(colors, j);
  27412. j += 3;
  27413. }
  27414. const geometry = new BufferGeometry();
  27415. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27416. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27417. const material = new LineBasicMaterial({
  27418. vertexColors: true,
  27419. toneMapped: false
  27420. });
  27421. super(geometry, material);
  27422. this.type = 'GridHelper';
  27423. }
  27424. }
  27425. class PolarGridHelper extends LineSegments {
  27426. constructor(radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888) {
  27427. color1 = new Color(color1);
  27428. color2 = new Color(color2);
  27429. const vertices = [];
  27430. const colors = []; // create the radials
  27431. for (let i = 0; i <= radials; i++) {
  27432. const v = i / radials * (Math.PI * 2);
  27433. const x = Math.sin(v) * radius;
  27434. const z = Math.cos(v) * radius;
  27435. vertices.push(0, 0, 0);
  27436. vertices.push(x, 0, z);
  27437. const color = i & 1 ? color1 : color2;
  27438. colors.push(color.r, color.g, color.b);
  27439. colors.push(color.r, color.g, color.b);
  27440. } // create the circles
  27441. for (let i = 0; i <= circles; i++) {
  27442. const color = i & 1 ? color1 : color2;
  27443. const r = radius - radius / circles * i;
  27444. for (let j = 0; j < divisions; j++) {
  27445. // first vertex
  27446. let v = j / divisions * (Math.PI * 2);
  27447. let x = Math.sin(v) * r;
  27448. let z = Math.cos(v) * r;
  27449. vertices.push(x, 0, z);
  27450. colors.push(color.r, color.g, color.b); // second vertex
  27451. v = (j + 1) / divisions * (Math.PI * 2);
  27452. x = Math.sin(v) * r;
  27453. z = Math.cos(v) * r;
  27454. vertices.push(x, 0, z);
  27455. colors.push(color.r, color.g, color.b);
  27456. }
  27457. }
  27458. const geometry = new BufferGeometry();
  27459. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27460. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27461. const material = new LineBasicMaterial({
  27462. vertexColors: true,
  27463. toneMapped: false
  27464. });
  27465. super(geometry, material);
  27466. this.type = 'PolarGridHelper';
  27467. }
  27468. }
  27469. const _v1 = /*@__PURE__*/new Vector3();
  27470. const _v2 = /*@__PURE__*/new Vector3();
  27471. const _v3 = /*@__PURE__*/new Vector3();
  27472. class DirectionalLightHelper extends Object3D {
  27473. constructor(light, size, color) {
  27474. super();
  27475. this.light = light;
  27476. this.light.updateMatrixWorld();
  27477. this.matrix = light.matrixWorld;
  27478. this.matrixAutoUpdate = false;
  27479. this.color = color;
  27480. if (size === undefined) size = 1;
  27481. let geometry = new BufferGeometry();
  27482. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  27483. const material = new LineBasicMaterial({
  27484. fog: false,
  27485. toneMapped: false
  27486. });
  27487. this.lightPlane = new Line(geometry, material);
  27488. this.add(this.lightPlane);
  27489. geometry = new BufferGeometry();
  27490. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  27491. this.targetLine = new Line(geometry, material);
  27492. this.add(this.targetLine);
  27493. this.update();
  27494. }
  27495. dispose() {
  27496. this.lightPlane.geometry.dispose();
  27497. this.lightPlane.material.dispose();
  27498. this.targetLine.geometry.dispose();
  27499. this.targetLine.material.dispose();
  27500. }
  27501. update() {
  27502. _v1.setFromMatrixPosition(this.light.matrixWorld);
  27503. _v2.setFromMatrixPosition(this.light.target.matrixWorld);
  27504. _v3.subVectors(_v2, _v1);
  27505. this.lightPlane.lookAt(_v2);
  27506. if (this.color !== undefined) {
  27507. this.lightPlane.material.color.set(this.color);
  27508. this.targetLine.material.color.set(this.color);
  27509. } else {
  27510. this.lightPlane.material.color.copy(this.light.color);
  27511. this.targetLine.material.color.copy(this.light.color);
  27512. }
  27513. this.targetLine.lookAt(_v2);
  27514. this.targetLine.scale.z = _v3.length();
  27515. }
  27516. }
  27517. const _vector = /*@__PURE__*/new Vector3();
  27518. const _camera = /*@__PURE__*/new Camera();
  27519. /**
  27520. * - shows frustum, line of sight and up of the camera
  27521. * - suitable for fast updates
  27522. * - based on frustum visualization in lightgl.js shadowmap example
  27523. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  27524. */
  27525. class CameraHelper extends LineSegments {
  27526. constructor(camera) {
  27527. const geometry = new BufferGeometry();
  27528. const material = new LineBasicMaterial({
  27529. color: 0xffffff,
  27530. vertexColors: true,
  27531. toneMapped: false
  27532. });
  27533. const vertices = [];
  27534. const colors = [];
  27535. const pointMap = {}; // colors
  27536. const colorFrustum = new Color(0xffaa00);
  27537. const colorCone = new Color(0xff0000);
  27538. const colorUp = new Color(0x00aaff);
  27539. const colorTarget = new Color(0xffffff);
  27540. const colorCross = new Color(0x333333); // near
  27541. addLine('n1', 'n2', colorFrustum);
  27542. addLine('n2', 'n4', colorFrustum);
  27543. addLine('n4', 'n3', colorFrustum);
  27544. addLine('n3', 'n1', colorFrustum); // far
  27545. addLine('f1', 'f2', colorFrustum);
  27546. addLine('f2', 'f4', colorFrustum);
  27547. addLine('f4', 'f3', colorFrustum);
  27548. addLine('f3', 'f1', colorFrustum); // sides
  27549. addLine('n1', 'f1', colorFrustum);
  27550. addLine('n2', 'f2', colorFrustum);
  27551. addLine('n3', 'f3', colorFrustum);
  27552. addLine('n4', 'f4', colorFrustum); // cone
  27553. addLine('p', 'n1', colorCone);
  27554. addLine('p', 'n2', colorCone);
  27555. addLine('p', 'n3', colorCone);
  27556. addLine('p', 'n4', colorCone); // up
  27557. addLine('u1', 'u2', colorUp);
  27558. addLine('u2', 'u3', colorUp);
  27559. addLine('u3', 'u1', colorUp); // target
  27560. addLine('c', 't', colorTarget);
  27561. addLine('p', 'c', colorCross); // cross
  27562. addLine('cn1', 'cn2', colorCross);
  27563. addLine('cn3', 'cn4', colorCross);
  27564. addLine('cf1', 'cf2', colorCross);
  27565. addLine('cf3', 'cf4', colorCross);
  27566. function addLine(a, b, color) {
  27567. addPoint(a, color);
  27568. addPoint(b, color);
  27569. }
  27570. function addPoint(id, color) {
  27571. vertices.push(0, 0, 0);
  27572. colors.push(color.r, color.g, color.b);
  27573. if (pointMap[id] === undefined) {
  27574. pointMap[id] = [];
  27575. }
  27576. pointMap[id].push(vertices.length / 3 - 1);
  27577. }
  27578. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27579. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27580. super(geometry, material);
  27581. this.type = 'CameraHelper';
  27582. this.camera = camera;
  27583. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  27584. this.matrix = camera.matrixWorld;
  27585. this.matrixAutoUpdate = false;
  27586. this.pointMap = pointMap;
  27587. this.update();
  27588. }
  27589. update() {
  27590. const geometry = this.geometry;
  27591. const pointMap = this.pointMap;
  27592. const w = 1,
  27593. h = 1; // we need just camera projection matrix inverse
  27594. // world matrix must be identity
  27595. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  27596. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  27597. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  27598. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  27599. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  27600. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  27601. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  27602. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  27603. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  27604. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  27605. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  27606. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  27607. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  27608. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  27609. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  27610. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  27611. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  27612. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  27613. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  27614. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  27615. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  27616. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  27617. geometry.getAttribute('position').needsUpdate = true;
  27618. }
  27619. dispose() {
  27620. this.geometry.dispose();
  27621. this.material.dispose();
  27622. }
  27623. }
  27624. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  27625. _vector.set(x, y, z).unproject(camera);
  27626. const points = pointMap[point];
  27627. if (points !== undefined) {
  27628. const position = geometry.getAttribute('position');
  27629. for (let i = 0, l = points.length; i < l; i++) {
  27630. position.setXYZ(points[i], _vector.x, _vector.y, _vector.z);
  27631. }
  27632. }
  27633. }
  27634. const _box = /*@__PURE__*/new Box3();
  27635. class BoxHelper extends LineSegments {
  27636. constructor(object, color = 0xffff00) {
  27637. 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]);
  27638. const positions = new Float32Array(8 * 3);
  27639. const geometry = new BufferGeometry();
  27640. geometry.setIndex(new BufferAttribute(indices, 1));
  27641. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  27642. super(geometry, new LineBasicMaterial({
  27643. color: color,
  27644. toneMapped: false
  27645. }));
  27646. this.object = object;
  27647. this.type = 'BoxHelper';
  27648. this.matrixAutoUpdate = false;
  27649. this.update();
  27650. }
  27651. update(object) {
  27652. if (object !== undefined) {
  27653. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  27654. }
  27655. if (this.object !== undefined) {
  27656. _box.setFromObject(this.object);
  27657. }
  27658. if (_box.isEmpty()) return;
  27659. const min = _box.min;
  27660. const max = _box.max;
  27661. /*
  27662. 5____4
  27663. 1/___0/|
  27664. | 6__|_7
  27665. 2/___3/
  27666. 0: max.x, max.y, max.z
  27667. 1: min.x, max.y, max.z
  27668. 2: min.x, min.y, max.z
  27669. 3: max.x, min.y, max.z
  27670. 4: max.x, max.y, min.z
  27671. 5: min.x, max.y, min.z
  27672. 6: min.x, min.y, min.z
  27673. 7: max.x, min.y, min.z
  27674. */
  27675. const position = this.geometry.attributes.position;
  27676. const array = position.array;
  27677. array[0] = max.x;
  27678. array[1] = max.y;
  27679. array[2] = max.z;
  27680. array[3] = min.x;
  27681. array[4] = max.y;
  27682. array[5] = max.z;
  27683. array[6] = min.x;
  27684. array[7] = min.y;
  27685. array[8] = max.z;
  27686. array[9] = max.x;
  27687. array[10] = min.y;
  27688. array[11] = max.z;
  27689. array[12] = max.x;
  27690. array[13] = max.y;
  27691. array[14] = min.z;
  27692. array[15] = min.x;
  27693. array[16] = max.y;
  27694. array[17] = min.z;
  27695. array[18] = min.x;
  27696. array[19] = min.y;
  27697. array[20] = min.z;
  27698. array[21] = max.x;
  27699. array[22] = min.y;
  27700. array[23] = min.z;
  27701. position.needsUpdate = true;
  27702. this.geometry.computeBoundingSphere();
  27703. }
  27704. setFromObject(object) {
  27705. this.object = object;
  27706. this.update();
  27707. return this;
  27708. }
  27709. copy(source) {
  27710. LineSegments.prototype.copy.call(this, source);
  27711. this.object = source.object;
  27712. return this;
  27713. }
  27714. }
  27715. class Box3Helper extends LineSegments {
  27716. constructor(box, color = 0xffff00) {
  27717. 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]);
  27718. 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];
  27719. const geometry = new BufferGeometry();
  27720. geometry.setIndex(new BufferAttribute(indices, 1));
  27721. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27722. super(geometry, new LineBasicMaterial({
  27723. color: color,
  27724. toneMapped: false
  27725. }));
  27726. this.box = box;
  27727. this.type = 'Box3Helper';
  27728. this.geometry.computeBoundingSphere();
  27729. }
  27730. updateMatrixWorld(force) {
  27731. const box = this.box;
  27732. if (box.isEmpty()) return;
  27733. box.getCenter(this.position);
  27734. box.getSize(this.scale);
  27735. this.scale.multiplyScalar(0.5);
  27736. super.updateMatrixWorld(force);
  27737. }
  27738. }
  27739. class PlaneHelper extends Line {
  27740. constructor(plane, size = 1, hex = 0xffff00) {
  27741. const color = hex;
  27742. 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];
  27743. const geometry = new BufferGeometry();
  27744. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27745. geometry.computeBoundingSphere();
  27746. super(geometry, new LineBasicMaterial({
  27747. color: color,
  27748. toneMapped: false
  27749. }));
  27750. this.type = 'PlaneHelper';
  27751. this.plane = plane;
  27752. this.size = size;
  27753. const positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  27754. const geometry2 = new BufferGeometry();
  27755. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  27756. geometry2.computeBoundingSphere();
  27757. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  27758. color: color,
  27759. opacity: 0.2,
  27760. transparent: true,
  27761. depthWrite: false,
  27762. toneMapped: false
  27763. })));
  27764. }
  27765. updateMatrixWorld(force) {
  27766. let scale = -this.plane.constant;
  27767. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  27768. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  27769. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  27770. this.lookAt(this.plane.normal);
  27771. super.updateMatrixWorld(force);
  27772. }
  27773. }
  27774. const _axis = /*@__PURE__*/new Vector3();
  27775. let _lineGeometry, _coneGeometry;
  27776. class ArrowHelper extends Object3D {
  27777. // dir is assumed to be normalized
  27778. 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) {
  27779. super();
  27780. this.type = 'ArrowHelper';
  27781. if (_lineGeometry === undefined) {
  27782. _lineGeometry = new BufferGeometry();
  27783. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  27784. _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1);
  27785. _coneGeometry.translate(0, -0.5, 0);
  27786. }
  27787. this.position.copy(origin);
  27788. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  27789. color: color,
  27790. toneMapped: false
  27791. }));
  27792. this.line.matrixAutoUpdate = false;
  27793. this.add(this.line);
  27794. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  27795. color: color,
  27796. toneMapped: false
  27797. }));
  27798. this.cone.matrixAutoUpdate = false;
  27799. this.add(this.cone);
  27800. this.setDirection(dir);
  27801. this.setLength(length, headLength, headWidth);
  27802. }
  27803. setDirection(dir) {
  27804. // dir is assumed to be normalized
  27805. if (dir.y > 0.99999) {
  27806. this.quaternion.set(0, 0, 0, 1);
  27807. } else if (dir.y < -0.99999) {
  27808. this.quaternion.set(1, 0, 0, 0);
  27809. } else {
  27810. _axis.set(dir.z, 0, -dir.x).normalize();
  27811. const radians = Math.acos(dir.y);
  27812. this.quaternion.setFromAxisAngle(_axis, radians);
  27813. }
  27814. }
  27815. setLength(length, headLength = length * 0.2, headWidth = headLength * 0.2) {
  27816. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  27817. this.line.updateMatrix();
  27818. this.cone.scale.set(headWidth, headLength, headWidth);
  27819. this.cone.position.y = length;
  27820. this.cone.updateMatrix();
  27821. }
  27822. setColor(color) {
  27823. this.line.material.color.set(color);
  27824. this.cone.material.color.set(color);
  27825. }
  27826. copy(source) {
  27827. super.copy(source, false);
  27828. this.line.copy(source.line);
  27829. this.cone.copy(source.cone);
  27830. return this;
  27831. }
  27832. }
  27833. class AxesHelper extends LineSegments {
  27834. constructor(size = 1) {
  27835. const vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  27836. const colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  27837. const geometry = new BufferGeometry();
  27838. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27839. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27840. const material = new LineBasicMaterial({
  27841. vertexColors: true,
  27842. toneMapped: false
  27843. });
  27844. super(geometry, material);
  27845. this.type = 'AxesHelper';
  27846. }
  27847. setColors(xAxisColor, yAxisColor, zAxisColor) {
  27848. const color = new Color();
  27849. const array = this.geometry.attributes.color.array;
  27850. color.set(xAxisColor);
  27851. color.toArray(array, 0);
  27852. color.toArray(array, 3);
  27853. color.set(yAxisColor);
  27854. color.toArray(array, 6);
  27855. color.toArray(array, 9);
  27856. color.set(zAxisColor);
  27857. color.toArray(array, 12);
  27858. color.toArray(array, 15);
  27859. this.geometry.attributes.color.needsUpdate = true;
  27860. return this;
  27861. }
  27862. dispose() {
  27863. this.geometry.dispose();
  27864. this.material.dispose();
  27865. }
  27866. }
  27867. const _floatView = new Float32Array(1);
  27868. const _int32View = new Int32Array(_floatView.buffer);
  27869. class DataUtils {
  27870. // Converts float32 to float16 (stored as uint16 value).
  27871. static toHalfFloat(val) {
  27872. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  27873. /* This method is faster than the OpenEXR implementation (very often
  27874. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  27875. * by James Tursa?s half-precision code. */
  27876. _floatView[0] = val;
  27877. const x = _int32View[0];
  27878. let bits = x >> 16 & 0x8000;
  27879. /* Get the sign */
  27880. let m = x >> 12 & 0x07ff;
  27881. /* Keep one extra bit for rounding */
  27882. const e = x >> 23 & 0xff;
  27883. /* Using int is faster here */
  27884. /* If zero, or denormal, or exponent underflows too much for a denormal
  27885. * half, return signed zero. */
  27886. if (e < 103) return bits;
  27887. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  27888. if (e > 142) {
  27889. bits |= 0x7c00;
  27890. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  27891. * not Inf, so make sure we set one mantissa bit too. */
  27892. bits |= (e == 255 ? 0 : 1) && x & 0x007fffff;
  27893. return bits;
  27894. }
  27895. /* If exponent underflows but not too much, return a denormal */
  27896. if (e < 113) {
  27897. m |= 0x0800;
  27898. /* Extra rounding may overflow and set mantissa to 0 and exponent
  27899. * to 1, which is OK. */
  27900. bits |= (m >> 114 - e) + (m >> 113 - e & 1);
  27901. return bits;
  27902. }
  27903. bits |= e - 112 << 10 | m >> 1;
  27904. /* Extra rounding. An overflow will set mantissa to 0 and increment
  27905. * the exponent, which is OK. */
  27906. bits += m & 1;
  27907. return bits;
  27908. }
  27909. }
  27910. const LineStrip = 0;
  27911. const LinePieces = 1;
  27912. const NoColors = 0;
  27913. const FaceColors = 1;
  27914. const VertexColors = 2;
  27915. function MeshFaceMaterial(materials) {
  27916. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  27917. return materials;
  27918. }
  27919. function MultiMaterial(materials = []) {
  27920. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  27921. materials.isMultiMaterial = true;
  27922. materials.materials = materials;
  27923. materials.clone = function () {
  27924. return materials.slice();
  27925. };
  27926. return materials;
  27927. }
  27928. function PointCloud(geometry, material) {
  27929. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  27930. return new Points(geometry, material);
  27931. }
  27932. function Particle(material) {
  27933. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  27934. return new Sprite(material);
  27935. }
  27936. function ParticleSystem(geometry, material) {
  27937. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  27938. return new Points(geometry, material);
  27939. }
  27940. function PointCloudMaterial(parameters) {
  27941. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  27942. return new PointsMaterial(parameters);
  27943. }
  27944. function ParticleBasicMaterial(parameters) {
  27945. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  27946. return new PointsMaterial(parameters);
  27947. }
  27948. function ParticleSystemMaterial(parameters) {
  27949. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  27950. return new PointsMaterial(parameters);
  27951. }
  27952. function Vertex(x, y, z) {
  27953. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  27954. return new Vector3(x, y, z);
  27955. } //
  27956. function DynamicBufferAttribute(array, itemSize) {
  27957. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.');
  27958. return new BufferAttribute(array, itemSize).setUsage(DynamicDrawUsage);
  27959. }
  27960. function Int8Attribute(array, itemSize) {
  27961. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  27962. return new Int8BufferAttribute(array, itemSize);
  27963. }
  27964. function Uint8Attribute(array, itemSize) {
  27965. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  27966. return new Uint8BufferAttribute(array, itemSize);
  27967. }
  27968. function Uint8ClampedAttribute(array, itemSize) {
  27969. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  27970. return new Uint8ClampedBufferAttribute(array, itemSize);
  27971. }
  27972. function Int16Attribute(array, itemSize) {
  27973. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  27974. return new Int16BufferAttribute(array, itemSize);
  27975. }
  27976. function Uint16Attribute(array, itemSize) {
  27977. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  27978. return new Uint16BufferAttribute(array, itemSize);
  27979. }
  27980. function Int32Attribute(array, itemSize) {
  27981. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  27982. return new Int32BufferAttribute(array, itemSize);
  27983. }
  27984. function Uint32Attribute(array, itemSize) {
  27985. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  27986. return new Uint32BufferAttribute(array, itemSize);
  27987. }
  27988. function Float32Attribute(array, itemSize) {
  27989. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  27990. return new Float32BufferAttribute(array, itemSize);
  27991. }
  27992. function Float64Attribute(array, itemSize) {
  27993. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  27994. return new Float64BufferAttribute(array, itemSize);
  27995. } //
  27996. Curve.create = function (construct, getPoint) {
  27997. console.log('THREE.Curve.create() has been deprecated');
  27998. construct.prototype = Object.create(Curve.prototype);
  27999. construct.prototype.constructor = construct;
  28000. construct.prototype.getPoint = getPoint;
  28001. return construct;
  28002. }; //
  28003. Path.prototype.fromPoints = function (points) {
  28004. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  28005. return this.setFromPoints(points);
  28006. }; //
  28007. function AxisHelper(size) {
  28008. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  28009. return new AxesHelper(size);
  28010. }
  28011. function BoundingBoxHelper(object, color) {
  28012. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  28013. return new BoxHelper(object, color);
  28014. }
  28015. function EdgesHelper(object, hex) {
  28016. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  28017. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  28018. color: hex !== undefined ? hex : 0xffffff
  28019. }));
  28020. }
  28021. GridHelper.prototype.setColors = function () {
  28022. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  28023. };
  28024. SkeletonHelper.prototype.update = function () {
  28025. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  28026. };
  28027. function WireframeHelper(object, hex) {
  28028. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  28029. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  28030. color: hex !== undefined ? hex : 0xffffff
  28031. }));
  28032. } //
  28033. Loader.prototype.extractUrlBase = function (url) {
  28034. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  28035. return LoaderUtils.extractUrlBase(url);
  28036. };
  28037. Loader.Handlers = {
  28038. add: function () {
  28039. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  28040. },
  28041. get: function () {
  28042. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  28043. }
  28044. };
  28045. function XHRLoader(manager) {
  28046. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  28047. return new FileLoader(manager);
  28048. }
  28049. function BinaryTextureLoader(manager) {
  28050. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  28051. return new DataTextureLoader(manager);
  28052. } //
  28053. Box2.prototype.center = function (optionalTarget) {
  28054. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  28055. return this.getCenter(optionalTarget);
  28056. };
  28057. Box2.prototype.empty = function () {
  28058. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  28059. return this.isEmpty();
  28060. };
  28061. Box2.prototype.isIntersectionBox = function (box) {
  28062. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  28063. return this.intersectsBox(box);
  28064. };
  28065. Box2.prototype.size = function (optionalTarget) {
  28066. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  28067. return this.getSize(optionalTarget);
  28068. }; //
  28069. Box3.prototype.center = function (optionalTarget) {
  28070. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  28071. return this.getCenter(optionalTarget);
  28072. };
  28073. Box3.prototype.empty = function () {
  28074. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  28075. return this.isEmpty();
  28076. };
  28077. Box3.prototype.isIntersectionBox = function (box) {
  28078. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  28079. return this.intersectsBox(box);
  28080. };
  28081. Box3.prototype.isIntersectionSphere = function (sphere) {
  28082. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  28083. return this.intersectsSphere(sphere);
  28084. };
  28085. Box3.prototype.size = function (optionalTarget) {
  28086. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  28087. return this.getSize(optionalTarget);
  28088. }; //
  28089. Sphere.prototype.empty = function () {
  28090. console.warn('THREE.Sphere: .empty() has been renamed to .isEmpty().');
  28091. return this.isEmpty();
  28092. }; //
  28093. Frustum.prototype.setFromMatrix = function (m) {
  28094. console.warn('THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().');
  28095. return this.setFromProjectionMatrix(m);
  28096. }; //
  28097. Line3.prototype.center = function (optionalTarget) {
  28098. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  28099. return this.getCenter(optionalTarget);
  28100. }; //
  28101. Matrix3.prototype.flattenToArrayOffset = function (array, offset) {
  28102. console.warn('THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  28103. return this.toArray(array, offset);
  28104. };
  28105. Matrix3.prototype.multiplyVector3 = function (vector) {
  28106. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  28107. return vector.applyMatrix3(this);
  28108. };
  28109. Matrix3.prototype.multiplyVector3Array = function () {
  28110. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  28111. };
  28112. Matrix3.prototype.applyToBufferAttribute = function (attribute) {
  28113. console.warn('THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.');
  28114. return attribute.applyMatrix3(this);
  28115. };
  28116. Matrix3.prototype.applyToVector3Array = function () {
  28117. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  28118. };
  28119. Matrix3.prototype.getInverse = function (matrix) {
  28120. console.warn('THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  28121. return this.copy(matrix).invert();
  28122. }; //
  28123. Matrix4.prototype.extractPosition = function (m) {
  28124. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  28125. return this.copyPosition(m);
  28126. };
  28127. Matrix4.prototype.flattenToArrayOffset = function (array, offset) {
  28128. console.warn('THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  28129. return this.toArray(array, offset);
  28130. };
  28131. Matrix4.prototype.getPosition = function () {
  28132. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  28133. return new Vector3().setFromMatrixColumn(this, 3);
  28134. };
  28135. Matrix4.prototype.setRotationFromQuaternion = function (q) {
  28136. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  28137. return this.makeRotationFromQuaternion(q);
  28138. };
  28139. Matrix4.prototype.multiplyToArray = function () {
  28140. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  28141. };
  28142. Matrix4.prototype.multiplyVector3 = function (vector) {
  28143. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28144. return vector.applyMatrix4(this);
  28145. };
  28146. Matrix4.prototype.multiplyVector4 = function (vector) {
  28147. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28148. return vector.applyMatrix4(this);
  28149. };
  28150. Matrix4.prototype.multiplyVector3Array = function () {
  28151. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  28152. };
  28153. Matrix4.prototype.rotateAxis = function (v) {
  28154. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  28155. v.transformDirection(this);
  28156. };
  28157. Matrix4.prototype.crossVector = function (vector) {
  28158. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28159. return vector.applyMatrix4(this);
  28160. };
  28161. Matrix4.prototype.translate = function () {
  28162. console.error('THREE.Matrix4: .translate() has been removed.');
  28163. };
  28164. Matrix4.prototype.rotateX = function () {
  28165. console.error('THREE.Matrix4: .rotateX() has been removed.');
  28166. };
  28167. Matrix4.prototype.rotateY = function () {
  28168. console.error('THREE.Matrix4: .rotateY() has been removed.');
  28169. };
  28170. Matrix4.prototype.rotateZ = function () {
  28171. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  28172. };
  28173. Matrix4.prototype.rotateByAxis = function () {
  28174. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  28175. };
  28176. Matrix4.prototype.applyToBufferAttribute = function (attribute) {
  28177. console.warn('THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.');
  28178. return attribute.applyMatrix4(this);
  28179. };
  28180. Matrix4.prototype.applyToVector3Array = function () {
  28181. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  28182. };
  28183. Matrix4.prototype.makeFrustum = function (left, right, bottom, top, near, far) {
  28184. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  28185. return this.makePerspective(left, right, top, bottom, near, far);
  28186. };
  28187. Matrix4.prototype.getInverse = function (matrix) {
  28188. console.warn('THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  28189. return this.copy(matrix).invert();
  28190. }; //
  28191. Plane.prototype.isIntersectionLine = function (line) {
  28192. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  28193. return this.intersectsLine(line);
  28194. }; //
  28195. Quaternion.prototype.multiplyVector3 = function (vector) {
  28196. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  28197. return vector.applyQuaternion(this);
  28198. };
  28199. Quaternion.prototype.inverse = function () {
  28200. console.warn('THREE.Quaternion: .inverse() has been renamed to invert().');
  28201. return this.invert();
  28202. }; //
  28203. Ray.prototype.isIntersectionBox = function (box) {
  28204. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  28205. return this.intersectsBox(box);
  28206. };
  28207. Ray.prototype.isIntersectionPlane = function (plane) {
  28208. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  28209. return this.intersectsPlane(plane);
  28210. };
  28211. Ray.prototype.isIntersectionSphere = function (sphere) {
  28212. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  28213. return this.intersectsSphere(sphere);
  28214. }; //
  28215. Triangle.prototype.area = function () {
  28216. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  28217. return this.getArea();
  28218. };
  28219. Triangle.prototype.barycoordFromPoint = function (point, target) {
  28220. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28221. return this.getBarycoord(point, target);
  28222. };
  28223. Triangle.prototype.midpoint = function (target) {
  28224. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  28225. return this.getMidpoint(target);
  28226. };
  28227. Triangle.prototypenormal = function (target) {
  28228. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28229. return this.getNormal(target);
  28230. };
  28231. Triangle.prototype.plane = function (target) {
  28232. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  28233. return this.getPlane(target);
  28234. };
  28235. Triangle.barycoordFromPoint = function (point, a, b, c, target) {
  28236. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28237. return Triangle.getBarycoord(point, a, b, c, target);
  28238. };
  28239. Triangle.normal = function (a, b, c, target) {
  28240. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28241. return Triangle.getNormal(a, b, c, target);
  28242. }; //
  28243. Shape.prototype.extractAllPoints = function (divisions) {
  28244. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  28245. return this.extractPoints(divisions);
  28246. };
  28247. Shape.prototype.extrude = function (options) {
  28248. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  28249. return new ExtrudeGeometry(this, options);
  28250. };
  28251. Shape.prototype.makeGeometry = function (options) {
  28252. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  28253. return new ShapeGeometry(this, options);
  28254. }; //
  28255. Vector2.prototype.fromAttribute = function (attribute, index, offset) {
  28256. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28257. return this.fromBufferAttribute(attribute, index, offset);
  28258. };
  28259. Vector2.prototype.distanceToManhattan = function (v) {
  28260. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28261. return this.manhattanDistanceTo(v);
  28262. };
  28263. Vector2.prototype.lengthManhattan = function () {
  28264. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  28265. return this.manhattanLength();
  28266. }; //
  28267. Vector3.prototype.setEulerFromRotationMatrix = function () {
  28268. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  28269. };
  28270. Vector3.prototype.setEulerFromQuaternion = function () {
  28271. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  28272. };
  28273. Vector3.prototype.getPositionFromMatrix = function (m) {
  28274. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  28275. return this.setFromMatrixPosition(m);
  28276. };
  28277. Vector3.prototype.getScaleFromMatrix = function (m) {
  28278. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  28279. return this.setFromMatrixScale(m);
  28280. };
  28281. Vector3.prototype.getColumnFromMatrix = function (index, matrix) {
  28282. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  28283. return this.setFromMatrixColumn(matrix, index);
  28284. };
  28285. Vector3.prototype.applyProjection = function (m) {
  28286. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  28287. return this.applyMatrix4(m);
  28288. };
  28289. Vector3.prototype.fromAttribute = function (attribute, index, offset) {
  28290. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28291. return this.fromBufferAttribute(attribute, index, offset);
  28292. };
  28293. Vector3.prototype.distanceToManhattan = function (v) {
  28294. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28295. return this.manhattanDistanceTo(v);
  28296. };
  28297. Vector3.prototype.lengthManhattan = function () {
  28298. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  28299. return this.manhattanLength();
  28300. }; //
  28301. Vector4.prototype.fromAttribute = function (attribute, index, offset) {
  28302. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28303. return this.fromBufferAttribute(attribute, index, offset);
  28304. };
  28305. Vector4.prototype.lengthManhattan = function () {
  28306. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  28307. return this.manhattanLength();
  28308. }; //
  28309. Object3D.prototype.getChildByName = function (name) {
  28310. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  28311. return this.getObjectByName(name);
  28312. };
  28313. Object3D.prototype.renderDepth = function () {
  28314. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  28315. };
  28316. Object3D.prototype.translate = function (distance, axis) {
  28317. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  28318. return this.translateOnAxis(axis, distance);
  28319. };
  28320. Object3D.prototype.getWorldRotation = function () {
  28321. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  28322. };
  28323. Object3D.prototype.applyMatrix = function (matrix) {
  28324. console.warn('THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().');
  28325. return this.applyMatrix4(matrix);
  28326. };
  28327. Object.defineProperties(Object3D.prototype, {
  28328. eulerOrder: {
  28329. get: function () {
  28330. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28331. return this.rotation.order;
  28332. },
  28333. set: function (value) {
  28334. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28335. this.rotation.order = value;
  28336. }
  28337. },
  28338. useQuaternion: {
  28339. get: function () {
  28340. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28341. },
  28342. set: function () {
  28343. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28344. }
  28345. }
  28346. });
  28347. Mesh.prototype.setDrawMode = function () {
  28348. console.error('THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28349. };
  28350. Object.defineProperties(Mesh.prototype, {
  28351. drawMode: {
  28352. get: function () {
  28353. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.');
  28354. return TrianglesDrawMode;
  28355. },
  28356. set: function () {
  28357. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28358. }
  28359. }
  28360. });
  28361. SkinnedMesh.prototype.initBones = function () {
  28362. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  28363. }; //
  28364. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  28365. console.warn('THREE.PerspectiveCamera.setLens is deprecated. ' + 'Use .setFocalLength and .filmGauge for a photographic setup.');
  28366. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  28367. this.setFocalLength(focalLength);
  28368. }; //
  28369. Object.defineProperties(Light.prototype, {
  28370. onlyShadow: {
  28371. set: function () {
  28372. console.warn('THREE.Light: .onlyShadow has been removed.');
  28373. }
  28374. },
  28375. shadowCameraFov: {
  28376. set: function (value) {
  28377. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  28378. this.shadow.camera.fov = value;
  28379. }
  28380. },
  28381. shadowCameraLeft: {
  28382. set: function (value) {
  28383. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  28384. this.shadow.camera.left = value;
  28385. }
  28386. },
  28387. shadowCameraRight: {
  28388. set: function (value) {
  28389. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  28390. this.shadow.camera.right = value;
  28391. }
  28392. },
  28393. shadowCameraTop: {
  28394. set: function (value) {
  28395. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  28396. this.shadow.camera.top = value;
  28397. }
  28398. },
  28399. shadowCameraBottom: {
  28400. set: function (value) {
  28401. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  28402. this.shadow.camera.bottom = value;
  28403. }
  28404. },
  28405. shadowCameraNear: {
  28406. set: function (value) {
  28407. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  28408. this.shadow.camera.near = value;
  28409. }
  28410. },
  28411. shadowCameraFar: {
  28412. set: function (value) {
  28413. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  28414. this.shadow.camera.far = value;
  28415. }
  28416. },
  28417. shadowCameraVisible: {
  28418. set: function () {
  28419. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  28420. }
  28421. },
  28422. shadowBias: {
  28423. set: function (value) {
  28424. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  28425. this.shadow.bias = value;
  28426. }
  28427. },
  28428. shadowDarkness: {
  28429. set: function () {
  28430. console.warn('THREE.Light: .shadowDarkness has been removed.');
  28431. }
  28432. },
  28433. shadowMapWidth: {
  28434. set: function (value) {
  28435. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  28436. this.shadow.mapSize.width = value;
  28437. }
  28438. },
  28439. shadowMapHeight: {
  28440. set: function (value) {
  28441. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  28442. this.shadow.mapSize.height = value;
  28443. }
  28444. }
  28445. }); //
  28446. Object.defineProperties(BufferAttribute.prototype, {
  28447. length: {
  28448. get: function () {
  28449. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  28450. return this.array.length;
  28451. }
  28452. },
  28453. dynamic: {
  28454. get: function () {
  28455. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28456. return this.usage === DynamicDrawUsage;
  28457. },
  28458. set: function () {
  28459. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28460. this.setUsage(DynamicDrawUsage);
  28461. }
  28462. }
  28463. });
  28464. BufferAttribute.prototype.setDynamic = function (value) {
  28465. console.warn('THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28466. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28467. return this;
  28468. };
  28469. BufferAttribute.prototype.copyIndicesArray = function () {
  28470. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  28471. }, BufferAttribute.prototype.setArray = function () {
  28472. console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28473. }; //
  28474. BufferGeometry.prototype.addIndex = function (index) {
  28475. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  28476. this.setIndex(index);
  28477. };
  28478. BufferGeometry.prototype.addAttribute = function (name, attribute) {
  28479. console.warn('THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().');
  28480. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  28481. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  28482. return this.setAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  28483. }
  28484. if (name === 'index') {
  28485. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  28486. this.setIndex(attribute);
  28487. return this;
  28488. }
  28489. return this.setAttribute(name, attribute);
  28490. };
  28491. BufferGeometry.prototype.addDrawCall = function (start, count, indexOffset) {
  28492. if (indexOffset !== undefined) {
  28493. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  28494. }
  28495. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  28496. this.addGroup(start, count);
  28497. };
  28498. BufferGeometry.prototype.clearDrawCalls = function () {
  28499. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  28500. this.clearGroups();
  28501. };
  28502. BufferGeometry.prototype.computeOffsets = function () {
  28503. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  28504. };
  28505. BufferGeometry.prototype.removeAttribute = function (name) {
  28506. console.warn('THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().');
  28507. return this.deleteAttribute(name);
  28508. };
  28509. BufferGeometry.prototype.applyMatrix = function (matrix) {
  28510. console.warn('THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().');
  28511. return this.applyMatrix4(matrix);
  28512. };
  28513. Object.defineProperties(BufferGeometry.prototype, {
  28514. drawcalls: {
  28515. get: function () {
  28516. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  28517. return this.groups;
  28518. }
  28519. },
  28520. offsets: {
  28521. get: function () {
  28522. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  28523. return this.groups;
  28524. }
  28525. }
  28526. });
  28527. InterleavedBuffer.prototype.setDynamic = function (value) {
  28528. console.warn('THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28529. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28530. return this;
  28531. };
  28532. InterleavedBuffer.prototype.setArray = function () {
  28533. console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28534. }; //
  28535. ExtrudeGeometry.prototype.getArrays = function () {
  28536. console.error('THREE.ExtrudeGeometry: .getArrays() has been removed.');
  28537. };
  28538. ExtrudeGeometry.prototype.addShapeList = function () {
  28539. console.error('THREE.ExtrudeGeometry: .addShapeList() has been removed.');
  28540. };
  28541. ExtrudeGeometry.prototype.addShape = function () {
  28542. console.error('THREE.ExtrudeGeometry: .addShape() has been removed.');
  28543. }; //
  28544. Scene.prototype.dispose = function () {
  28545. console.error('THREE.Scene: .dispose() has been removed.');
  28546. }; //
  28547. Uniform.prototype.onUpdate = function () {
  28548. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  28549. return this;
  28550. }; //
  28551. Object.defineProperties(Material.prototype, {
  28552. wrapAround: {
  28553. get: function () {
  28554. console.warn('THREE.Material: .wrapAround has been removed.');
  28555. },
  28556. set: function () {
  28557. console.warn('THREE.Material: .wrapAround has been removed.');
  28558. }
  28559. },
  28560. overdraw: {
  28561. get: function () {
  28562. console.warn('THREE.Material: .overdraw has been removed.');
  28563. },
  28564. set: function () {
  28565. console.warn('THREE.Material: .overdraw has been removed.');
  28566. }
  28567. },
  28568. wrapRGB: {
  28569. get: function () {
  28570. console.warn('THREE.Material: .wrapRGB has been removed.');
  28571. return new Color();
  28572. }
  28573. },
  28574. shading: {
  28575. get: function () {
  28576. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28577. },
  28578. set: function (value) {
  28579. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28580. this.flatShading = value === FlatShading;
  28581. }
  28582. },
  28583. stencilMask: {
  28584. get: function () {
  28585. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28586. return this.stencilFuncMask;
  28587. },
  28588. set: function (value) {
  28589. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28590. this.stencilFuncMask = value;
  28591. }
  28592. },
  28593. vertexTangents: {
  28594. get: function () {
  28595. console.warn('THREE.' + this.type + ': .vertexTangents has been removed.');
  28596. },
  28597. set: function () {
  28598. console.warn('THREE.' + this.type + ': .vertexTangents has been removed.');
  28599. }
  28600. }
  28601. });
  28602. Object.defineProperties(ShaderMaterial.prototype, {
  28603. derivatives: {
  28604. get: function () {
  28605. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28606. return this.extensions.derivatives;
  28607. },
  28608. set: function (value) {
  28609. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28610. this.extensions.derivatives = value;
  28611. }
  28612. }
  28613. }); //
  28614. WebGLRenderer.prototype.clearTarget = function (renderTarget, color, depth, stencil) {
  28615. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  28616. this.setRenderTarget(renderTarget);
  28617. this.clear(color, depth, stencil);
  28618. };
  28619. WebGLRenderer.prototype.animate = function (callback) {
  28620. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  28621. this.setAnimationLoop(callback);
  28622. };
  28623. WebGLRenderer.prototype.getCurrentRenderTarget = function () {
  28624. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  28625. return this.getRenderTarget();
  28626. };
  28627. WebGLRenderer.prototype.getMaxAnisotropy = function () {
  28628. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  28629. return this.capabilities.getMaxAnisotropy();
  28630. };
  28631. WebGLRenderer.prototype.getPrecision = function () {
  28632. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  28633. return this.capabilities.precision;
  28634. };
  28635. WebGLRenderer.prototype.resetGLState = function () {
  28636. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  28637. return this.state.reset();
  28638. };
  28639. WebGLRenderer.prototype.supportsFloatTextures = function () {
  28640. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  28641. return this.extensions.get('OES_texture_float');
  28642. };
  28643. WebGLRenderer.prototype.supportsHalfFloatTextures = function () {
  28644. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  28645. return this.extensions.get('OES_texture_half_float');
  28646. };
  28647. WebGLRenderer.prototype.supportsStandardDerivatives = function () {
  28648. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  28649. return this.extensions.get('OES_standard_derivatives');
  28650. };
  28651. WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () {
  28652. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  28653. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  28654. };
  28655. WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () {
  28656. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  28657. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  28658. };
  28659. WebGLRenderer.prototype.supportsBlendMinMax = function () {
  28660. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  28661. return this.extensions.get('EXT_blend_minmax');
  28662. };
  28663. WebGLRenderer.prototype.supportsVertexTextures = function () {
  28664. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  28665. return this.capabilities.vertexTextures;
  28666. };
  28667. WebGLRenderer.prototype.supportsInstancedArrays = function () {
  28668. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  28669. return this.extensions.get('ANGLE_instanced_arrays');
  28670. };
  28671. WebGLRenderer.prototype.enableScissorTest = function (boolean) {
  28672. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  28673. this.setScissorTest(boolean);
  28674. };
  28675. WebGLRenderer.prototype.initMaterial = function () {
  28676. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  28677. };
  28678. WebGLRenderer.prototype.addPrePlugin = function () {
  28679. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  28680. };
  28681. WebGLRenderer.prototype.addPostPlugin = function () {
  28682. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  28683. };
  28684. WebGLRenderer.prototype.updateShadowMap = function () {
  28685. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  28686. };
  28687. WebGLRenderer.prototype.setFaceCulling = function () {
  28688. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  28689. };
  28690. WebGLRenderer.prototype.allocTextureUnit = function () {
  28691. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  28692. };
  28693. WebGLRenderer.prototype.setTexture = function () {
  28694. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  28695. };
  28696. WebGLRenderer.prototype.setTexture2D = function () {
  28697. console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
  28698. };
  28699. WebGLRenderer.prototype.setTextureCube = function () {
  28700. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  28701. };
  28702. WebGLRenderer.prototype.getActiveMipMapLevel = function () {
  28703. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  28704. return this.getActiveMipmapLevel();
  28705. };
  28706. Object.defineProperties(WebGLRenderer.prototype, {
  28707. shadowMapEnabled: {
  28708. get: function () {
  28709. return this.shadowMap.enabled;
  28710. },
  28711. set: function (value) {
  28712. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  28713. this.shadowMap.enabled = value;
  28714. }
  28715. },
  28716. shadowMapType: {
  28717. get: function () {
  28718. return this.shadowMap.type;
  28719. },
  28720. set: function (value) {
  28721. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  28722. this.shadowMap.type = value;
  28723. }
  28724. },
  28725. shadowMapCullFace: {
  28726. get: function () {
  28727. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  28728. return undefined;
  28729. },
  28730. set: function () {
  28731. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  28732. }
  28733. },
  28734. context: {
  28735. get: function () {
  28736. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  28737. return this.getContext();
  28738. }
  28739. },
  28740. vr: {
  28741. get: function () {
  28742. console.warn('THREE.WebGLRenderer: .vr has been renamed to .xr');
  28743. return this.xr;
  28744. }
  28745. },
  28746. gammaInput: {
  28747. get: function () {
  28748. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  28749. return false;
  28750. },
  28751. set: function () {
  28752. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  28753. }
  28754. },
  28755. gammaOutput: {
  28756. get: function () {
  28757. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  28758. return false;
  28759. },
  28760. set: function (value) {
  28761. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  28762. this.outputEncoding = value === true ? sRGBEncoding : LinearEncoding;
  28763. }
  28764. },
  28765. toneMappingWhitePoint: {
  28766. get: function () {
  28767. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  28768. return 1.0;
  28769. },
  28770. set: function () {
  28771. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  28772. }
  28773. }
  28774. });
  28775. Object.defineProperties(WebGLShadowMap.prototype, {
  28776. cullFace: {
  28777. get: function () {
  28778. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  28779. return undefined;
  28780. },
  28781. set: function () {
  28782. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  28783. }
  28784. },
  28785. renderReverseSided: {
  28786. get: function () {
  28787. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  28788. return undefined;
  28789. },
  28790. set: function () {
  28791. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  28792. }
  28793. },
  28794. renderSingleSided: {
  28795. get: function () {
  28796. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  28797. return undefined;
  28798. },
  28799. set: function () {
  28800. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  28801. }
  28802. }
  28803. });
  28804. function WebGLRenderTargetCube(width, height, options) {
  28805. console.warn('THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).');
  28806. return new WebGLCubeRenderTarget(width, options);
  28807. } //
  28808. Object.defineProperties(WebGLRenderTarget.prototype, {
  28809. wrapS: {
  28810. get: function () {
  28811. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  28812. return this.texture.wrapS;
  28813. },
  28814. set: function (value) {
  28815. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  28816. this.texture.wrapS = value;
  28817. }
  28818. },
  28819. wrapT: {
  28820. get: function () {
  28821. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  28822. return this.texture.wrapT;
  28823. },
  28824. set: function (value) {
  28825. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  28826. this.texture.wrapT = value;
  28827. }
  28828. },
  28829. magFilter: {
  28830. get: function () {
  28831. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  28832. return this.texture.magFilter;
  28833. },
  28834. set: function (value) {
  28835. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  28836. this.texture.magFilter = value;
  28837. }
  28838. },
  28839. minFilter: {
  28840. get: function () {
  28841. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  28842. return this.texture.minFilter;
  28843. },
  28844. set: function (value) {
  28845. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  28846. this.texture.minFilter = value;
  28847. }
  28848. },
  28849. anisotropy: {
  28850. get: function () {
  28851. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  28852. return this.texture.anisotropy;
  28853. },
  28854. set: function (value) {
  28855. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  28856. this.texture.anisotropy = value;
  28857. }
  28858. },
  28859. offset: {
  28860. get: function () {
  28861. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  28862. return this.texture.offset;
  28863. },
  28864. set: function (value) {
  28865. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  28866. this.texture.offset = value;
  28867. }
  28868. },
  28869. repeat: {
  28870. get: function () {
  28871. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  28872. return this.texture.repeat;
  28873. },
  28874. set: function (value) {
  28875. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  28876. this.texture.repeat = value;
  28877. }
  28878. },
  28879. format: {
  28880. get: function () {
  28881. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  28882. return this.texture.format;
  28883. },
  28884. set: function (value) {
  28885. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  28886. this.texture.format = value;
  28887. }
  28888. },
  28889. type: {
  28890. get: function () {
  28891. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  28892. return this.texture.type;
  28893. },
  28894. set: function (value) {
  28895. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  28896. this.texture.type = value;
  28897. }
  28898. },
  28899. generateMipmaps: {
  28900. get: function () {
  28901. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  28902. return this.texture.generateMipmaps;
  28903. },
  28904. set: function (value) {
  28905. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  28906. this.texture.generateMipmaps = value;
  28907. }
  28908. }
  28909. }); //
  28910. Audio.prototype.load = function (file) {
  28911. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  28912. const scope = this;
  28913. const audioLoader = new AudioLoader();
  28914. audioLoader.load(file, function (buffer) {
  28915. scope.setBuffer(buffer);
  28916. });
  28917. return this;
  28918. };
  28919. AudioAnalyser.prototype.getData = function () {
  28920. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  28921. return this.getFrequencyData();
  28922. }; //
  28923. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  28924. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  28925. return this.update(renderer, scene);
  28926. };
  28927. CubeCamera.prototype.clear = function (renderer, color, depth, stencil) {
  28928. console.warn('THREE.CubeCamera: .clear() is now .renderTarget.clear().');
  28929. return this.renderTarget.clear(renderer, color, depth, stencil);
  28930. };
  28931. ImageUtils.crossOrigin = undefined;
  28932. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  28933. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  28934. const loader = new TextureLoader();
  28935. loader.setCrossOrigin(this.crossOrigin);
  28936. const texture = loader.load(url, onLoad, undefined, onError);
  28937. if (mapping) texture.mapping = mapping;
  28938. return texture;
  28939. };
  28940. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  28941. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  28942. const loader = new CubeTextureLoader();
  28943. loader.setCrossOrigin(this.crossOrigin);
  28944. const texture = loader.load(urls, onLoad, undefined, onError);
  28945. if (mapping) texture.mapping = mapping;
  28946. return texture;
  28947. };
  28948. ImageUtils.loadCompressedTexture = function () {
  28949. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  28950. };
  28951. ImageUtils.loadCompressedTextureCube = function () {
  28952. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  28953. }; //
  28954. function CanvasRenderer() {
  28955. console.error('THREE.CanvasRenderer has been removed');
  28956. } //
  28957. function JSONLoader() {
  28958. console.error('THREE.JSONLoader has been removed.');
  28959. } //
  28960. const SceneUtils = {
  28961. createMultiMaterialObject: function () {
  28962. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28963. },
  28964. detach: function () {
  28965. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28966. },
  28967. attach: function () {
  28968. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28969. }
  28970. }; //
  28971. function LensFlare() {
  28972. console.error('THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js');
  28973. }
  28974. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  28975. /* eslint-disable no-undef */
  28976. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  28977. detail: {
  28978. revision: REVISION
  28979. }
  28980. }));
  28981. /* eslint-enable no-undef */
  28982. }
  28983. if (typeof window !== 'undefined') {
  28984. if (window.__THREE__) {
  28985. console.warn('WARNING: Multiple instances of Three.js being imported.');
  28986. } else {
  28987. window.__THREE__ = REVISION;
  28988. }
  28989. }
  28990. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  28991. exports.AddEquation = AddEquation;
  28992. exports.AddOperation = AddOperation;
  28993. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  28994. exports.AdditiveBlending = AdditiveBlending;
  28995. exports.AlphaFormat = AlphaFormat;
  28996. exports.AlwaysDepth = AlwaysDepth;
  28997. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  28998. exports.AmbientLight = AmbientLight;
  28999. exports.AmbientLightProbe = AmbientLightProbe;
  29000. exports.AnimationClip = AnimationClip;
  29001. exports.AnimationLoader = AnimationLoader;
  29002. exports.AnimationMixer = AnimationMixer;
  29003. exports.AnimationObjectGroup = AnimationObjectGroup;
  29004. exports.AnimationUtils = AnimationUtils;
  29005. exports.ArcCurve = ArcCurve;
  29006. exports.ArrayCamera = ArrayCamera;
  29007. exports.ArrowHelper = ArrowHelper;
  29008. exports.Audio = Audio;
  29009. exports.AudioAnalyser = AudioAnalyser;
  29010. exports.AudioContext = AudioContext;
  29011. exports.AudioListener = AudioListener;
  29012. exports.AudioLoader = AudioLoader;
  29013. exports.AxesHelper = AxesHelper;
  29014. exports.AxisHelper = AxisHelper;
  29015. exports.BackSide = BackSide;
  29016. exports.BasicDepthPacking = BasicDepthPacking;
  29017. exports.BasicShadowMap = BasicShadowMap;
  29018. exports.BinaryTextureLoader = BinaryTextureLoader;
  29019. exports.Bone = Bone;
  29020. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  29021. exports.BoundingBoxHelper = BoundingBoxHelper;
  29022. exports.Box2 = Box2;
  29023. exports.Box3 = Box3;
  29024. exports.Box3Helper = Box3Helper;
  29025. exports.BoxBufferGeometry = BoxGeometry;
  29026. exports.BoxGeometry = BoxGeometry;
  29027. exports.BoxHelper = BoxHelper;
  29028. exports.BufferAttribute = BufferAttribute;
  29029. exports.BufferGeometry = BufferGeometry;
  29030. exports.BufferGeometryLoader = BufferGeometryLoader;
  29031. exports.ByteType = ByteType;
  29032. exports.Cache = Cache;
  29033. exports.Camera = Camera;
  29034. exports.CameraHelper = CameraHelper;
  29035. exports.CanvasRenderer = CanvasRenderer;
  29036. exports.CanvasTexture = CanvasTexture;
  29037. exports.CatmullRomCurve3 = CatmullRomCurve3;
  29038. exports.CineonToneMapping = CineonToneMapping;
  29039. exports.CircleBufferGeometry = CircleGeometry;
  29040. exports.CircleGeometry = CircleGeometry;
  29041. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  29042. exports.Clock = Clock;
  29043. exports.Color = Color;
  29044. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  29045. exports.CompressedTexture = CompressedTexture;
  29046. exports.CompressedTextureLoader = CompressedTextureLoader;
  29047. exports.ConeBufferGeometry = ConeGeometry;
  29048. exports.ConeGeometry = ConeGeometry;
  29049. exports.CubeCamera = CubeCamera;
  29050. exports.CubeReflectionMapping = CubeReflectionMapping;
  29051. exports.CubeRefractionMapping = CubeRefractionMapping;
  29052. exports.CubeTexture = CubeTexture;
  29053. exports.CubeTextureLoader = CubeTextureLoader;
  29054. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  29055. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  29056. exports.CubicBezierCurve = CubicBezierCurve;
  29057. exports.CubicBezierCurve3 = CubicBezierCurve3;
  29058. exports.CubicInterpolant = CubicInterpolant;
  29059. exports.CullFaceBack = CullFaceBack;
  29060. exports.CullFaceFront = CullFaceFront;
  29061. exports.CullFaceFrontBack = CullFaceFrontBack;
  29062. exports.CullFaceNone = CullFaceNone;
  29063. exports.Curve = Curve;
  29064. exports.CurvePath = CurvePath;
  29065. exports.CustomBlending = CustomBlending;
  29066. exports.CustomToneMapping = CustomToneMapping;
  29067. exports.CylinderBufferGeometry = CylinderGeometry;
  29068. exports.CylinderGeometry = CylinderGeometry;
  29069. exports.Cylindrical = Cylindrical;
  29070. exports.DataTexture = DataTexture;
  29071. exports.DataTexture2DArray = DataTexture2DArray;
  29072. exports.DataTexture3D = DataTexture3D;
  29073. exports.DataTextureLoader = DataTextureLoader;
  29074. exports.DataUtils = DataUtils;
  29075. exports.DecrementStencilOp = DecrementStencilOp;
  29076. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  29077. exports.DefaultLoadingManager = DefaultLoadingManager;
  29078. exports.DepthFormat = DepthFormat;
  29079. exports.DepthStencilFormat = DepthStencilFormat;
  29080. exports.DepthTexture = DepthTexture;
  29081. exports.DirectionalLight = DirectionalLight;
  29082. exports.DirectionalLightHelper = DirectionalLightHelper;
  29083. exports.DiscreteInterpolant = DiscreteInterpolant;
  29084. exports.DodecahedronBufferGeometry = DodecahedronGeometry;
  29085. exports.DodecahedronGeometry = DodecahedronGeometry;
  29086. exports.DoubleSide = DoubleSide;
  29087. exports.DstAlphaFactor = DstAlphaFactor;
  29088. exports.DstColorFactor = DstColorFactor;
  29089. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  29090. exports.DynamicCopyUsage = DynamicCopyUsage;
  29091. exports.DynamicDrawUsage = DynamicDrawUsage;
  29092. exports.DynamicReadUsage = DynamicReadUsage;
  29093. exports.EdgesGeometry = EdgesGeometry;
  29094. exports.EdgesHelper = EdgesHelper;
  29095. exports.EllipseCurve = EllipseCurve;
  29096. exports.EqualDepth = EqualDepth;
  29097. exports.EqualStencilFunc = EqualStencilFunc;
  29098. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  29099. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  29100. exports.Euler = Euler;
  29101. exports.EventDispatcher = EventDispatcher;
  29102. exports.ExtrudeBufferGeometry = ExtrudeGeometry;
  29103. exports.ExtrudeGeometry = ExtrudeGeometry;
  29104. exports.FaceColors = FaceColors;
  29105. exports.FileLoader = FileLoader;
  29106. exports.FlatShading = FlatShading;
  29107. exports.Float16BufferAttribute = Float16BufferAttribute;
  29108. exports.Float32Attribute = Float32Attribute;
  29109. exports.Float32BufferAttribute = Float32BufferAttribute;
  29110. exports.Float64Attribute = Float64Attribute;
  29111. exports.Float64BufferAttribute = Float64BufferAttribute;
  29112. exports.FloatType = FloatType;
  29113. exports.Fog = Fog;
  29114. exports.FogExp2 = FogExp2;
  29115. exports.Font = Font;
  29116. exports.FontLoader = FontLoader;
  29117. exports.FrontSide = FrontSide;
  29118. exports.Frustum = Frustum;
  29119. exports.GLBufferAttribute = GLBufferAttribute;
  29120. exports.GLSL1 = GLSL1;
  29121. exports.GLSL3 = GLSL3;
  29122. exports.GammaEncoding = GammaEncoding;
  29123. exports.GreaterDepth = GreaterDepth;
  29124. exports.GreaterEqualDepth = GreaterEqualDepth;
  29125. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  29126. exports.GreaterStencilFunc = GreaterStencilFunc;
  29127. exports.GridHelper = GridHelper;
  29128. exports.Group = Group;
  29129. exports.HalfFloatType = HalfFloatType;
  29130. exports.HemisphereLight = HemisphereLight;
  29131. exports.HemisphereLightHelper = HemisphereLightHelper;
  29132. exports.HemisphereLightProbe = HemisphereLightProbe;
  29133. exports.IcosahedronBufferGeometry = IcosahedronGeometry;
  29134. exports.IcosahedronGeometry = IcosahedronGeometry;
  29135. exports.ImageBitmapLoader = ImageBitmapLoader;
  29136. exports.ImageLoader = ImageLoader;
  29137. exports.ImageUtils = ImageUtils;
  29138. exports.ImmediateRenderObject = ImmediateRenderObject;
  29139. exports.IncrementStencilOp = IncrementStencilOp;
  29140. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  29141. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  29142. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  29143. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  29144. exports.InstancedMesh = InstancedMesh;
  29145. exports.Int16Attribute = Int16Attribute;
  29146. exports.Int16BufferAttribute = Int16BufferAttribute;
  29147. exports.Int32Attribute = Int32Attribute;
  29148. exports.Int32BufferAttribute = Int32BufferAttribute;
  29149. exports.Int8Attribute = Int8Attribute;
  29150. exports.Int8BufferAttribute = Int8BufferAttribute;
  29151. exports.IntType = IntType;
  29152. exports.InterleavedBuffer = InterleavedBuffer;
  29153. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  29154. exports.Interpolant = Interpolant;
  29155. exports.InterpolateDiscrete = InterpolateDiscrete;
  29156. exports.InterpolateLinear = InterpolateLinear;
  29157. exports.InterpolateSmooth = InterpolateSmooth;
  29158. exports.InvertStencilOp = InvertStencilOp;
  29159. exports.JSONLoader = JSONLoader;
  29160. exports.KeepStencilOp = KeepStencilOp;
  29161. exports.KeyframeTrack = KeyframeTrack;
  29162. exports.LOD = LOD;
  29163. exports.LatheBufferGeometry = LatheGeometry;
  29164. exports.LatheGeometry = LatheGeometry;
  29165. exports.Layers = Layers;
  29166. exports.LensFlare = LensFlare;
  29167. exports.LessDepth = LessDepth;
  29168. exports.LessEqualDepth = LessEqualDepth;
  29169. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  29170. exports.LessStencilFunc = LessStencilFunc;
  29171. exports.Light = Light;
  29172. exports.LightProbe = LightProbe;
  29173. exports.Line = Line;
  29174. exports.Line3 = Line3;
  29175. exports.LineBasicMaterial = LineBasicMaterial;
  29176. exports.LineCurve = LineCurve;
  29177. exports.LineCurve3 = LineCurve3;
  29178. exports.LineDashedMaterial = LineDashedMaterial;
  29179. exports.LineLoop = LineLoop;
  29180. exports.LinePieces = LinePieces;
  29181. exports.LineSegments = LineSegments;
  29182. exports.LineStrip = LineStrip;
  29183. exports.LinearEncoding = LinearEncoding;
  29184. exports.LinearFilter = LinearFilter;
  29185. exports.LinearInterpolant = LinearInterpolant;
  29186. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  29187. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  29188. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  29189. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  29190. exports.LinearToneMapping = LinearToneMapping;
  29191. exports.Loader = Loader;
  29192. exports.LoaderUtils = LoaderUtils;
  29193. exports.LoadingManager = LoadingManager;
  29194. exports.LogLuvEncoding = LogLuvEncoding;
  29195. exports.LoopOnce = LoopOnce;
  29196. exports.LoopPingPong = LoopPingPong;
  29197. exports.LoopRepeat = LoopRepeat;
  29198. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  29199. exports.LuminanceFormat = LuminanceFormat;
  29200. exports.MOUSE = MOUSE;
  29201. exports.Material = Material;
  29202. exports.MaterialLoader = MaterialLoader;
  29203. exports.Math = MathUtils;
  29204. exports.MathUtils = MathUtils;
  29205. exports.Matrix3 = Matrix3;
  29206. exports.Matrix4 = Matrix4;
  29207. exports.MaxEquation = MaxEquation;
  29208. exports.Mesh = Mesh;
  29209. exports.MeshBasicMaterial = MeshBasicMaterial;
  29210. exports.MeshDepthMaterial = MeshDepthMaterial;
  29211. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  29212. exports.MeshFaceMaterial = MeshFaceMaterial;
  29213. exports.MeshLambertMaterial = MeshLambertMaterial;
  29214. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  29215. exports.MeshNormalMaterial = MeshNormalMaterial;
  29216. exports.MeshPhongMaterial = MeshPhongMaterial;
  29217. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  29218. exports.MeshStandardMaterial = MeshStandardMaterial;
  29219. exports.MeshToonMaterial = MeshToonMaterial;
  29220. exports.MinEquation = MinEquation;
  29221. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  29222. exports.MixOperation = MixOperation;
  29223. exports.MultiMaterial = MultiMaterial;
  29224. exports.MultiplyBlending = MultiplyBlending;
  29225. exports.MultiplyOperation = MultiplyOperation;
  29226. exports.NearestFilter = NearestFilter;
  29227. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  29228. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  29229. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  29230. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  29231. exports.NeverDepth = NeverDepth;
  29232. exports.NeverStencilFunc = NeverStencilFunc;
  29233. exports.NoBlending = NoBlending;
  29234. exports.NoColors = NoColors;
  29235. exports.NoToneMapping = NoToneMapping;
  29236. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  29237. exports.NormalBlending = NormalBlending;
  29238. exports.NotEqualDepth = NotEqualDepth;
  29239. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  29240. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  29241. exports.Object3D = Object3D;
  29242. exports.ObjectLoader = ObjectLoader;
  29243. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  29244. exports.OctahedronBufferGeometry = OctahedronGeometry;
  29245. exports.OctahedronGeometry = OctahedronGeometry;
  29246. exports.OneFactor = OneFactor;
  29247. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  29248. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  29249. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  29250. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  29251. exports.OrthographicCamera = OrthographicCamera;
  29252. exports.PCFShadowMap = PCFShadowMap;
  29253. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  29254. exports.PMREMGenerator = PMREMGenerator;
  29255. exports.ParametricBufferGeometry = ParametricGeometry;
  29256. exports.ParametricGeometry = ParametricGeometry;
  29257. exports.Particle = Particle;
  29258. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  29259. exports.ParticleSystem = ParticleSystem;
  29260. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  29261. exports.Path = Path;
  29262. exports.PerspectiveCamera = PerspectiveCamera;
  29263. exports.Plane = Plane;
  29264. exports.PlaneBufferGeometry = PlaneGeometry;
  29265. exports.PlaneGeometry = PlaneGeometry;
  29266. exports.PlaneHelper = PlaneHelper;
  29267. exports.PointCloud = PointCloud;
  29268. exports.PointCloudMaterial = PointCloudMaterial;
  29269. exports.PointLight = PointLight;
  29270. exports.PointLightHelper = PointLightHelper;
  29271. exports.Points = Points;
  29272. exports.PointsMaterial = PointsMaterial;
  29273. exports.PolarGridHelper = PolarGridHelper;
  29274. exports.PolyhedronBufferGeometry = PolyhedronGeometry;
  29275. exports.PolyhedronGeometry = PolyhedronGeometry;
  29276. exports.PositionalAudio = PositionalAudio;
  29277. exports.PropertyBinding = PropertyBinding;
  29278. exports.PropertyMixer = PropertyMixer;
  29279. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  29280. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  29281. exports.Quaternion = Quaternion;
  29282. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  29283. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  29284. exports.REVISION = REVISION;
  29285. exports.RGBADepthPacking = RGBADepthPacking;
  29286. exports.RGBAFormat = RGBAFormat;
  29287. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  29288. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  29289. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  29290. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  29291. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  29292. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  29293. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  29294. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  29295. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  29296. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  29297. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  29298. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  29299. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  29300. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  29301. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  29302. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  29303. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  29304. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  29305. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  29306. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  29307. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  29308. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  29309. exports.RGBDEncoding = RGBDEncoding;
  29310. exports.RGBEEncoding = RGBEEncoding;
  29311. exports.RGBEFormat = RGBEFormat;
  29312. exports.RGBFormat = RGBFormat;
  29313. exports.RGBIntegerFormat = RGBIntegerFormat;
  29314. exports.RGBM16Encoding = RGBM16Encoding;
  29315. exports.RGBM7Encoding = RGBM7Encoding;
  29316. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  29317. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  29318. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  29319. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  29320. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  29321. exports.RGFormat = RGFormat;
  29322. exports.RGIntegerFormat = RGIntegerFormat;
  29323. exports.RawShaderMaterial = RawShaderMaterial;
  29324. exports.Ray = Ray;
  29325. exports.Raycaster = Raycaster;
  29326. exports.RectAreaLight = RectAreaLight;
  29327. exports.RedFormat = RedFormat;
  29328. exports.RedIntegerFormat = RedIntegerFormat;
  29329. exports.ReinhardToneMapping = ReinhardToneMapping;
  29330. exports.RepeatWrapping = RepeatWrapping;
  29331. exports.ReplaceStencilOp = ReplaceStencilOp;
  29332. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  29333. exports.RingBufferGeometry = RingGeometry;
  29334. exports.RingGeometry = RingGeometry;
  29335. exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
  29336. exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
  29337. exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
  29338. exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
  29339. exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
  29340. exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
  29341. exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
  29342. exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
  29343. exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
  29344. exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
  29345. exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
  29346. exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
  29347. exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
  29348. exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
  29349. exports.Scene = Scene;
  29350. exports.SceneUtils = SceneUtils;
  29351. exports.ShaderChunk = ShaderChunk;
  29352. exports.ShaderLib = ShaderLib;
  29353. exports.ShaderMaterial = ShaderMaterial;
  29354. exports.ShadowMaterial = ShadowMaterial;
  29355. exports.Shape = Shape;
  29356. exports.ShapeBufferGeometry = ShapeGeometry;
  29357. exports.ShapeGeometry = ShapeGeometry;
  29358. exports.ShapePath = ShapePath;
  29359. exports.ShapeUtils = ShapeUtils;
  29360. exports.ShortType = ShortType;
  29361. exports.Skeleton = Skeleton;
  29362. exports.SkeletonHelper = SkeletonHelper;
  29363. exports.SkinnedMesh = SkinnedMesh;
  29364. exports.SmoothShading = SmoothShading;
  29365. exports.Sphere = Sphere;
  29366. exports.SphereBufferGeometry = SphereGeometry;
  29367. exports.SphereGeometry = SphereGeometry;
  29368. exports.Spherical = Spherical;
  29369. exports.SphericalHarmonics3 = SphericalHarmonics3;
  29370. exports.SplineCurve = SplineCurve;
  29371. exports.SpotLight = SpotLight;
  29372. exports.SpotLightHelper = SpotLightHelper;
  29373. exports.Sprite = Sprite;
  29374. exports.SpriteMaterial = SpriteMaterial;
  29375. exports.SrcAlphaFactor = SrcAlphaFactor;
  29376. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  29377. exports.SrcColorFactor = SrcColorFactor;
  29378. exports.StaticCopyUsage = StaticCopyUsage;
  29379. exports.StaticDrawUsage = StaticDrawUsage;
  29380. exports.StaticReadUsage = StaticReadUsage;
  29381. exports.StereoCamera = StereoCamera;
  29382. exports.StreamCopyUsage = StreamCopyUsage;
  29383. exports.StreamDrawUsage = StreamDrawUsage;
  29384. exports.StreamReadUsage = StreamReadUsage;
  29385. exports.StringKeyframeTrack = StringKeyframeTrack;
  29386. exports.SubtractEquation = SubtractEquation;
  29387. exports.SubtractiveBlending = SubtractiveBlending;
  29388. exports.TOUCH = TOUCH;
  29389. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  29390. exports.TetrahedronBufferGeometry = TetrahedronGeometry;
  29391. exports.TetrahedronGeometry = TetrahedronGeometry;
  29392. exports.TextBufferGeometry = TextGeometry;
  29393. exports.TextGeometry = TextGeometry;
  29394. exports.Texture = Texture;
  29395. exports.TextureLoader = TextureLoader;
  29396. exports.TorusBufferGeometry = TorusGeometry;
  29397. exports.TorusGeometry = TorusGeometry;
  29398. exports.TorusKnotBufferGeometry = TorusKnotGeometry;
  29399. exports.TorusKnotGeometry = TorusKnotGeometry;
  29400. exports.Triangle = Triangle;
  29401. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  29402. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  29403. exports.TrianglesDrawMode = TrianglesDrawMode;
  29404. exports.TubeBufferGeometry = TubeGeometry;
  29405. exports.TubeGeometry = TubeGeometry;
  29406. exports.UVMapping = UVMapping;
  29407. exports.Uint16Attribute = Uint16Attribute;
  29408. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  29409. exports.Uint32Attribute = Uint32Attribute;
  29410. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  29411. exports.Uint8Attribute = Uint8Attribute;
  29412. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  29413. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  29414. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  29415. exports.Uniform = Uniform;
  29416. exports.UniformsLib = UniformsLib;
  29417. exports.UniformsUtils = UniformsUtils;
  29418. exports.UnsignedByteType = UnsignedByteType;
  29419. exports.UnsignedInt248Type = UnsignedInt248Type;
  29420. exports.UnsignedIntType = UnsignedIntType;
  29421. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  29422. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  29423. exports.UnsignedShort565Type = UnsignedShort565Type;
  29424. exports.UnsignedShortType = UnsignedShortType;
  29425. exports.VSMShadowMap = VSMShadowMap;
  29426. exports.Vector2 = Vector2;
  29427. exports.Vector3 = Vector3;
  29428. exports.Vector4 = Vector4;
  29429. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  29430. exports.Vertex = Vertex;
  29431. exports.VertexColors = VertexColors;
  29432. exports.VideoTexture = VideoTexture;
  29433. exports.WebGL1Renderer = WebGL1Renderer;
  29434. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  29435. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  29436. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  29437. exports.WebGLRenderTarget = WebGLRenderTarget;
  29438. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  29439. exports.WebGLRenderer = WebGLRenderer;
  29440. exports.WebGLUtils = WebGLUtils;
  29441. exports.WireframeGeometry = WireframeGeometry;
  29442. exports.WireframeHelper = WireframeHelper;
  29443. exports.WrapAroundEnding = WrapAroundEnding;
  29444. exports.XHRLoader = XHRLoader;
  29445. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  29446. exports.ZeroFactor = ZeroFactor;
  29447. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  29448. exports.ZeroStencilOp = ZeroStencilOp;
  29449. exports.sRGBEncoding = sRGBEncoding;
  29450. Object.defineProperty(exports, '__esModule', { value: true });
  29451. })));
粤ICP备19079148号