three.js 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414
  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 float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\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\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = specularColor * 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 dotVH = saturate( dot( geometry.viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float NoH ) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float NoV, float NoL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( NoL + NoV - NoL * NoV ) ) );\n}\nvec3 BRDF_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 max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}";
  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\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularTintFactor = specularTint;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARTINTMAP\n\t\t\tspecularTintFactor *= specularTintMapTexelToLinear( texture2D( specularTintMap, vUv ) ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularTintFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( ior - 1.0 ) / ( ior + 1.0 ) ) * specularTintFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 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\tfloat specularF90;\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 ), 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.specularF90, 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;\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\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationTint;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( vec3 n, vec3 v, float thickness, float ior, mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( float roughness, float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec3 getTransmissionSample( vec2 fragCoord, float roughness, float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod ).rgb;\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod ).rgb;\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( vec3 radiance, float transmissionDistance, vec3 attenuationColor, float attenuationDistance ) {\n\t\tif ( attenuationDistance == 0.0 ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\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 meshnormal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}";
  7909. var meshnormal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  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 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 vec3 vWorldPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}";
  7914. 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}";
  7915. 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}";
  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. meshnormal_frag: meshnormal_frag,
  8042. meshnormal_vert: meshnormal_vert,
  8043. meshphong_frag: meshphong_frag,
  8044. meshphong_vert: meshphong_vert,
  8045. meshphysical_frag: meshphysical_frag,
  8046. meshphysical_vert: meshphysical_vert,
  8047. meshtoon_frag: meshtoon_frag,
  8048. meshtoon_vert: meshtoon_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.meshnormal_vert,
  8436. fragmentShader: ShaderChunk.meshnormal_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. scene.background = background;
  9567. }
  9568. _textureToCubeUV(texture, cubeUVRenderTarget) {
  9569. const renderer = this._renderer;
  9570. if (texture.isCubeTexture) {
  9571. if (this._cubemapShader == null) {
  9572. this._cubemapShader = _getCubemapShader();
  9573. }
  9574. } else {
  9575. if (this._equirectShader == null) {
  9576. this._equirectShader = _getEquirectShader();
  9577. }
  9578. }
  9579. const material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  9580. const mesh = new Mesh(_lodPlanes[0], material);
  9581. const uniforms = material.uniforms;
  9582. uniforms['envMap'].value = texture;
  9583. if (!texture.isCubeTexture) {
  9584. uniforms['texelSize'].value.set(1.0 / texture.image.width, 1.0 / texture.image.height);
  9585. }
  9586. uniforms['inputEncoding'].value = ENCODINGS[texture.encoding];
  9587. uniforms['outputEncoding'].value = ENCODINGS[cubeUVRenderTarget.texture.encoding];
  9588. _setViewport(cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX);
  9589. renderer.setRenderTarget(cubeUVRenderTarget);
  9590. renderer.render(mesh, _flatCamera);
  9591. }
  9592. _applyPMREM(cubeUVRenderTarget) {
  9593. const renderer = this._renderer;
  9594. const autoClear = renderer.autoClear;
  9595. renderer.autoClear = false;
  9596. for (let i = 1; i < TOTAL_LODS; i++) {
  9597. const sigma = Math.sqrt(_sigmas[i] * _sigmas[i] - _sigmas[i - 1] * _sigmas[i - 1]);
  9598. const poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  9599. this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  9600. }
  9601. renderer.autoClear = autoClear;
  9602. }
  9603. /**
  9604. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9605. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9606. * the blur latitudinally (around the poles), and then longitudinally (towards
  9607. * the poles) to approximate the orthogonally-separable blur. It is least
  9608. * accurate at the poles, but still does a decent job.
  9609. */
  9610. _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  9611. const pingPongRenderTarget = this._pingPongRenderTarget;
  9612. this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  9613. this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  9614. }
  9615. _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  9616. const renderer = this._renderer;
  9617. const blurMaterial = this._blurMaterial;
  9618. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  9619. console.error('blur direction must be either latitudinal or longitudinal!');
  9620. } // Number of standard deviations at which to cut off the discrete approximation.
  9621. const STANDARD_DEVIATIONS = 3;
  9622. const blurMesh = new Mesh(_lodPlanes[lodOut], blurMaterial);
  9623. const blurUniforms = blurMaterial.uniforms;
  9624. const pixels = _sizeLods[lodIn] - 1;
  9625. const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  9626. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9627. const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  9628. if (samples > MAX_SAMPLES) {
  9629. console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
  9630. }
  9631. const weights = [];
  9632. let sum = 0;
  9633. for (let i = 0; i < MAX_SAMPLES; ++i) {
  9634. const x = i / sigmaPixels;
  9635. const weight = Math.exp(-x * x / 2);
  9636. weights.push(weight);
  9637. if (i == 0) {
  9638. sum += weight;
  9639. } else if (i < samples) {
  9640. sum += 2 * weight;
  9641. }
  9642. }
  9643. for (let i = 0; i < weights.length; i++) {
  9644. weights[i] = weights[i] / sum;
  9645. }
  9646. blurUniforms['envMap'].value = targetIn.texture;
  9647. blurUniforms['samples'].value = samples;
  9648. blurUniforms['weights'].value = weights;
  9649. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  9650. if (poleAxis) {
  9651. blurUniforms['poleAxis'].value = poleAxis;
  9652. }
  9653. blurUniforms['dTheta'].value = radiansPerPixel;
  9654. blurUniforms['mipInt'].value = LOD_MAX - lodIn;
  9655. blurUniforms['inputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  9656. blurUniforms['outputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  9657. const outputSize = _sizeLods[lodOut];
  9658. const x = 3 * Math.max(0, SIZE_MAX - 2 * outputSize);
  9659. const y = (lodOut === 0 ? 0 : 2 * SIZE_MAX) + 2 * outputSize * (lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0);
  9660. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  9661. renderer.setRenderTarget(targetOut);
  9662. renderer.render(blurMesh, _flatCamera);
  9663. }
  9664. }
  9665. function _isLDR(texture) {
  9666. if (texture === undefined || texture.type !== UnsignedByteType) return false;
  9667. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  9668. }
  9669. function _createPlanes() {
  9670. const _lodPlanes = [];
  9671. const _sizeLods = [];
  9672. const _sigmas = [];
  9673. let lod = LOD_MAX;
  9674. for (let i = 0; i < TOTAL_LODS; i++) {
  9675. const sizeLod = Math.pow(2, lod);
  9676. _sizeLods.push(sizeLod);
  9677. let sigma = 1.0 / sizeLod;
  9678. if (i > LOD_MAX - LOD_MIN) {
  9679. sigma = EXTRA_LOD_SIGMA[i - LOD_MAX + LOD_MIN - 1];
  9680. } else if (i == 0) {
  9681. sigma = 0;
  9682. }
  9683. _sigmas.push(sigma);
  9684. const texelSize = 1.0 / (sizeLod - 1);
  9685. const min = -texelSize / 2;
  9686. const max = 1 + texelSize / 2;
  9687. const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  9688. const cubeFaces = 6;
  9689. const vertices = 6;
  9690. const positionSize = 3;
  9691. const uvSize = 2;
  9692. const faceIndexSize = 1;
  9693. const position = new Float32Array(positionSize * vertices * cubeFaces);
  9694. const uv = new Float32Array(uvSize * vertices * cubeFaces);
  9695. const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  9696. for (let face = 0; face < cubeFaces; face++) {
  9697. const x = face % 3 * 2 / 3 - 1;
  9698. const y = face > 2 ? 0 : -1;
  9699. 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];
  9700. position.set(coordinates, positionSize * vertices * face);
  9701. uv.set(uv1, uvSize * vertices * face);
  9702. const fill = [face, face, face, face, face, face];
  9703. faceIndex.set(fill, faceIndexSize * vertices * face);
  9704. }
  9705. const planes = new BufferGeometry();
  9706. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  9707. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  9708. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  9709. _lodPlanes.push(planes);
  9710. if (lod > LOD_MIN) {
  9711. lod--;
  9712. }
  9713. }
  9714. return {
  9715. _lodPlanes,
  9716. _sizeLods,
  9717. _sigmas
  9718. };
  9719. }
  9720. function _createRenderTarget(params) {
  9721. const cubeUVRenderTarget = new WebGLRenderTarget(3 * SIZE_MAX, 3 * SIZE_MAX, params);
  9722. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9723. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9724. cubeUVRenderTarget.scissorTest = true;
  9725. return cubeUVRenderTarget;
  9726. }
  9727. function _setViewport(target, x, y, width, height) {
  9728. target.viewport.set(x, y, width, height);
  9729. target.scissor.set(x, y, width, height);
  9730. }
  9731. function _getBlurShader(maxSamples) {
  9732. const weights = new Float32Array(maxSamples);
  9733. const poleAxis = new Vector3(0, 1, 0);
  9734. const shaderMaterial = new RawShaderMaterial({
  9735. name: 'SphericalGaussianBlur',
  9736. defines: {
  9737. 'n': maxSamples
  9738. },
  9739. uniforms: {
  9740. 'envMap': {
  9741. value: null
  9742. },
  9743. 'samples': {
  9744. value: 1
  9745. },
  9746. 'weights': {
  9747. value: weights
  9748. },
  9749. 'latitudinal': {
  9750. value: false
  9751. },
  9752. 'dTheta': {
  9753. value: 0
  9754. },
  9755. 'mipInt': {
  9756. value: 0
  9757. },
  9758. 'poleAxis': {
  9759. value: poleAxis
  9760. },
  9761. 'inputEncoding': {
  9762. value: ENCODINGS[LinearEncoding]
  9763. },
  9764. 'outputEncoding': {
  9765. value: ENCODINGS[LinearEncoding]
  9766. }
  9767. },
  9768. vertexShader: _getCommonVertexShader(),
  9769. fragmentShader:
  9770. /* glsl */
  9771. `
  9772. precision mediump float;
  9773. precision mediump int;
  9774. varying vec3 vOutputDirection;
  9775. uniform sampler2D envMap;
  9776. uniform int samples;
  9777. uniform float weights[ n ];
  9778. uniform bool latitudinal;
  9779. uniform float dTheta;
  9780. uniform float mipInt;
  9781. uniform vec3 poleAxis;
  9782. ${_getEncodings()}
  9783. #define ENVMAP_TYPE_CUBE_UV
  9784. #include <cube_uv_reflection_fragment>
  9785. vec3 getSample( float theta, vec3 axis ) {
  9786. float cosTheta = cos( theta );
  9787. // Rodrigues' axis-angle rotation
  9788. vec3 sampleDirection = vOutputDirection * cosTheta
  9789. + cross( axis, vOutputDirection ) * sin( theta )
  9790. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9791. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  9792. }
  9793. void main() {
  9794. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  9795. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  9796. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  9797. }
  9798. axis = normalize( axis );
  9799. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9800. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  9801. for ( int i = 1; i < n; i++ ) {
  9802. if ( i >= samples ) {
  9803. break;
  9804. }
  9805. float theta = dTheta * float( i );
  9806. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  9807. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  9808. }
  9809. gl_FragColor = linearToOutputTexel( gl_FragColor );
  9810. }
  9811. `,
  9812. blending: NoBlending,
  9813. depthTest: false,
  9814. depthWrite: false
  9815. });
  9816. return shaderMaterial;
  9817. }
  9818. function _getEquirectShader() {
  9819. const texelSize = new Vector2(1, 1);
  9820. const shaderMaterial = new RawShaderMaterial({
  9821. name: 'EquirectangularToCubeUV',
  9822. uniforms: {
  9823. 'envMap': {
  9824. value: null
  9825. },
  9826. 'texelSize': {
  9827. value: texelSize
  9828. },
  9829. 'inputEncoding': {
  9830. value: ENCODINGS[LinearEncoding]
  9831. },
  9832. 'outputEncoding': {
  9833. value: ENCODINGS[LinearEncoding]
  9834. }
  9835. },
  9836. vertexShader: _getCommonVertexShader(),
  9837. fragmentShader:
  9838. /* glsl */
  9839. `
  9840. precision mediump float;
  9841. precision mediump int;
  9842. varying vec3 vOutputDirection;
  9843. uniform sampler2D envMap;
  9844. uniform vec2 texelSize;
  9845. ${_getEncodings()}
  9846. #include <common>
  9847. void main() {
  9848. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9849. vec3 outputDirection = normalize( vOutputDirection );
  9850. vec2 uv = equirectUv( outputDirection );
  9851. vec2 f = fract( uv / texelSize - 0.5 );
  9852. uv -= f * texelSize;
  9853. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9854. uv.x += texelSize.x;
  9855. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9856. uv.y += texelSize.y;
  9857. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9858. uv.x -= texelSize.x;
  9859. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  9860. vec3 tm = mix( tl, tr, f.x );
  9861. vec3 bm = mix( bl, br, f.x );
  9862. gl_FragColor.rgb = mix( tm, bm, f.y );
  9863. gl_FragColor = linearToOutputTexel( gl_FragColor );
  9864. }
  9865. `,
  9866. blending: NoBlending,
  9867. depthTest: false,
  9868. depthWrite: false
  9869. });
  9870. return shaderMaterial;
  9871. }
  9872. function _getCubemapShader() {
  9873. const shaderMaterial = new RawShaderMaterial({
  9874. name: 'CubemapToCubeUV',
  9875. uniforms: {
  9876. 'envMap': {
  9877. value: null
  9878. },
  9879. 'inputEncoding': {
  9880. value: ENCODINGS[LinearEncoding]
  9881. },
  9882. 'outputEncoding': {
  9883. value: ENCODINGS[LinearEncoding]
  9884. }
  9885. },
  9886. vertexShader: _getCommonVertexShader(),
  9887. fragmentShader:
  9888. /* glsl */
  9889. `
  9890. precision mediump float;
  9891. precision mediump int;
  9892. varying vec3 vOutputDirection;
  9893. uniform samplerCube envMap;
  9894. ${_getEncodings()}
  9895. void main() {
  9896. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9897. gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;
  9898. gl_FragColor = linearToOutputTexel( gl_FragColor );
  9899. }
  9900. `,
  9901. blending: NoBlending,
  9902. depthTest: false,
  9903. depthWrite: false
  9904. });
  9905. return shaderMaterial;
  9906. }
  9907. function _getCommonVertexShader() {
  9908. return (
  9909. /* glsl */
  9910. `
  9911. precision mediump float;
  9912. precision mediump int;
  9913. attribute vec3 position;
  9914. attribute vec2 uv;
  9915. attribute float faceIndex;
  9916. varying vec3 vOutputDirection;
  9917. // RH coordinate system; PMREM face-indexing convention
  9918. vec3 getDirection( vec2 uv, float face ) {
  9919. uv = 2.0 * uv - 1.0;
  9920. vec3 direction = vec3( uv, 1.0 );
  9921. if ( face == 0.0 ) {
  9922. direction = direction.zyx; // ( 1, v, u ) pos x
  9923. } else if ( face == 1.0 ) {
  9924. direction = direction.xzy;
  9925. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  9926. } else if ( face == 2.0 ) {
  9927. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  9928. } else if ( face == 3.0 ) {
  9929. direction = direction.zyx;
  9930. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  9931. } else if ( face == 4.0 ) {
  9932. direction = direction.xzy;
  9933. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  9934. } else if ( face == 5.0 ) {
  9935. direction.z *= -1.0; // ( u, v, -1 ) neg z
  9936. }
  9937. return direction;
  9938. }
  9939. void main() {
  9940. vOutputDirection = getDirection( uv, faceIndex );
  9941. gl_Position = vec4( position, 1.0 );
  9942. }
  9943. `
  9944. );
  9945. }
  9946. function _getEncodings() {
  9947. return (
  9948. /* glsl */
  9949. `
  9950. uniform int inputEncoding;
  9951. uniform int outputEncoding;
  9952. #include <encodings_pars_fragment>
  9953. vec4 inputTexelToLinear( vec4 value ) {
  9954. if ( inputEncoding == 0 ) {
  9955. return value;
  9956. } else if ( inputEncoding == 1 ) {
  9957. return sRGBToLinear( value );
  9958. } else if ( inputEncoding == 2 ) {
  9959. return RGBEToLinear( value );
  9960. } else if ( inputEncoding == 3 ) {
  9961. return RGBMToLinear( value, 7.0 );
  9962. } else if ( inputEncoding == 4 ) {
  9963. return RGBMToLinear( value, 16.0 );
  9964. } else if ( inputEncoding == 5 ) {
  9965. return RGBDToLinear( value, 256.0 );
  9966. } else {
  9967. return GammaToLinear( value, 2.2 );
  9968. }
  9969. }
  9970. vec4 linearToOutputTexel( vec4 value ) {
  9971. if ( outputEncoding == 0 ) {
  9972. return value;
  9973. } else if ( outputEncoding == 1 ) {
  9974. return LinearTosRGB( value );
  9975. } else if ( outputEncoding == 2 ) {
  9976. return LinearToRGBE( value );
  9977. } else if ( outputEncoding == 3 ) {
  9978. return LinearToRGBM( value, 7.0 );
  9979. } else if ( outputEncoding == 4 ) {
  9980. return LinearToRGBM( value, 16.0 );
  9981. } else if ( outputEncoding == 5 ) {
  9982. return LinearToRGBD( value, 256.0 );
  9983. } else {
  9984. return LinearToGamma( value, 2.2 );
  9985. }
  9986. }
  9987. vec4 envMapTexelToLinear( vec4 color ) {
  9988. return inputTexelToLinear( color );
  9989. }
  9990. `
  9991. );
  9992. }
  9993. function WebGLCubeUVMaps(renderer) {
  9994. let cubeUVmaps = new WeakMap();
  9995. let pmremGenerator = null;
  9996. function get(texture) {
  9997. if (texture && texture.isTexture && texture.isRenderTargetTexture === false) {
  9998. const mapping = texture.mapping;
  9999. const isEquirectMap = mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping;
  10000. const isCubeMap = mapping === CubeReflectionMapping || mapping === CubeRefractionMapping;
  10001. if (isEquirectMap || isCubeMap) {
  10002. // equirect/cube map to cubeUV conversion
  10003. if (cubeUVmaps.has(texture)) {
  10004. return cubeUVmaps.get(texture).texture;
  10005. } else {
  10006. const image = texture.image;
  10007. if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) {
  10008. const currentRenderTarget = renderer.getRenderTarget();
  10009. if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer);
  10010. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture);
  10011. cubeUVmaps.set(texture, renderTarget);
  10012. renderer.setRenderTarget(currentRenderTarget);
  10013. texture.addEventListener('dispose', onTextureDispose);
  10014. return renderTarget.texture;
  10015. } else {
  10016. // image not yet ready. try the conversion next frame
  10017. return null;
  10018. }
  10019. }
  10020. }
  10021. }
  10022. return texture;
  10023. }
  10024. function isCubeTextureComplete(image) {
  10025. let count = 0;
  10026. const length = 6;
  10027. for (let i = 0; i < length; i++) {
  10028. if (image[i] !== undefined) count++;
  10029. }
  10030. return count === length;
  10031. }
  10032. function onTextureDispose(event) {
  10033. const texture = event.target;
  10034. texture.removeEventListener('dispose', onTextureDispose);
  10035. const cubemapUV = cubeUVmaps.get(texture);
  10036. if (cubemapUV !== undefined) {
  10037. cubemapUV.delete(texture);
  10038. cubemapUV.dispose();
  10039. }
  10040. }
  10041. function dispose() {
  10042. cubeUVmaps = new WeakMap();
  10043. if (pmremGenerator !== null) {
  10044. pmremGenerator.dispose();
  10045. pmremGenerator = null;
  10046. }
  10047. }
  10048. return {
  10049. get: get,
  10050. dispose: dispose
  10051. };
  10052. }
  10053. function WebGLExtensions(gl) {
  10054. const extensions = {};
  10055. function getExtension(name) {
  10056. if (extensions[name] !== undefined) {
  10057. return extensions[name];
  10058. }
  10059. let extension;
  10060. switch (name) {
  10061. case 'WEBGL_depth_texture':
  10062. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  10063. break;
  10064. case 'EXT_texture_filter_anisotropic':
  10065. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  10066. break;
  10067. case 'WEBGL_compressed_texture_s3tc':
  10068. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10069. break;
  10070. case 'WEBGL_compressed_texture_pvrtc':
  10071. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10072. break;
  10073. default:
  10074. extension = gl.getExtension(name);
  10075. }
  10076. extensions[name] = extension;
  10077. return extension;
  10078. }
  10079. return {
  10080. has: function (name) {
  10081. return getExtension(name) !== null;
  10082. },
  10083. init: function (capabilities) {
  10084. if (capabilities.isWebGL2) {
  10085. getExtension('EXT_color_buffer_float');
  10086. } else {
  10087. getExtension('WEBGL_depth_texture');
  10088. getExtension('OES_texture_float');
  10089. getExtension('OES_texture_half_float');
  10090. getExtension('OES_texture_half_float_linear');
  10091. getExtension('OES_standard_derivatives');
  10092. getExtension('OES_element_index_uint');
  10093. getExtension('OES_vertex_array_object');
  10094. getExtension('ANGLE_instanced_arrays');
  10095. }
  10096. getExtension('OES_texture_float_linear');
  10097. getExtension('EXT_color_buffer_half_float');
  10098. },
  10099. get: function (name) {
  10100. const extension = getExtension(name);
  10101. if (extension === null) {
  10102. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  10103. }
  10104. return extension;
  10105. }
  10106. };
  10107. }
  10108. function WebGLGeometries(gl, attributes, info, bindingStates) {
  10109. const geometries = {};
  10110. const wireframeAttributes = new WeakMap();
  10111. function onGeometryDispose(event) {
  10112. const geometry = event.target;
  10113. if (geometry.index !== null) {
  10114. attributes.remove(geometry.index);
  10115. }
  10116. for (const name in geometry.attributes) {
  10117. attributes.remove(geometry.attributes[name]);
  10118. }
  10119. geometry.removeEventListener('dispose', onGeometryDispose);
  10120. delete geometries[geometry.id];
  10121. const attribute = wireframeAttributes.get(geometry);
  10122. if (attribute) {
  10123. attributes.remove(attribute);
  10124. wireframeAttributes.delete(geometry);
  10125. }
  10126. bindingStates.releaseStatesOfGeometry(geometry);
  10127. if (geometry.isInstancedBufferGeometry === true) {
  10128. delete geometry._maxInstanceCount;
  10129. } //
  10130. info.memory.geometries--;
  10131. }
  10132. function get(object, geometry) {
  10133. if (geometries[geometry.id] === true) return geometry;
  10134. geometry.addEventListener('dispose', onGeometryDispose);
  10135. geometries[geometry.id] = true;
  10136. info.memory.geometries++;
  10137. return geometry;
  10138. }
  10139. function update(geometry) {
  10140. const geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates.
  10141. for (const name in geometryAttributes) {
  10142. attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER);
  10143. } // morph targets
  10144. const morphAttributes = geometry.morphAttributes;
  10145. for (const name in morphAttributes) {
  10146. const array = morphAttributes[name];
  10147. for (let i = 0, l = array.length; i < l; i++) {
  10148. attributes.update(array[i], gl.ARRAY_BUFFER);
  10149. }
  10150. }
  10151. }
  10152. function updateWireframeAttribute(geometry) {
  10153. const indices = [];
  10154. const geometryIndex = geometry.index;
  10155. const geometryPosition = geometry.attributes.position;
  10156. let version = 0;
  10157. if (geometryIndex !== null) {
  10158. const array = geometryIndex.array;
  10159. version = geometryIndex.version;
  10160. for (let i = 0, l = array.length; i < l; i += 3) {
  10161. const a = array[i + 0];
  10162. const b = array[i + 1];
  10163. const c = array[i + 2];
  10164. indices.push(a, b, b, c, c, a);
  10165. }
  10166. } else {
  10167. const array = geometryPosition.array;
  10168. version = geometryPosition.version;
  10169. for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  10170. const a = i + 0;
  10171. const b = i + 1;
  10172. const c = i + 2;
  10173. indices.push(a, b, b, c, c, a);
  10174. }
  10175. }
  10176. const attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  10177. attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
  10178. //
  10179. const previousAttribute = wireframeAttributes.get(geometry);
  10180. if (previousAttribute) attributes.remove(previousAttribute); //
  10181. wireframeAttributes.set(geometry, attribute);
  10182. }
  10183. function getWireframeAttribute(geometry) {
  10184. const currentAttribute = wireframeAttributes.get(geometry);
  10185. if (currentAttribute) {
  10186. const geometryIndex = geometry.index;
  10187. if (geometryIndex !== null) {
  10188. // if the attribute is obsolete, create a new one
  10189. if (currentAttribute.version < geometryIndex.version) {
  10190. updateWireframeAttribute(geometry);
  10191. }
  10192. }
  10193. } else {
  10194. updateWireframeAttribute(geometry);
  10195. }
  10196. return wireframeAttributes.get(geometry);
  10197. }
  10198. return {
  10199. get: get,
  10200. update: update,
  10201. getWireframeAttribute: getWireframeAttribute
  10202. };
  10203. }
  10204. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  10205. const isWebGL2 = capabilities.isWebGL2;
  10206. let mode;
  10207. function setMode(value) {
  10208. mode = value;
  10209. }
  10210. let type, bytesPerElement;
  10211. function setIndex(value) {
  10212. type = value.type;
  10213. bytesPerElement = value.bytesPerElement;
  10214. }
  10215. function render(start, count) {
  10216. gl.drawElements(mode, count, type, start * bytesPerElement);
  10217. info.update(count, mode, 1);
  10218. }
  10219. function renderInstances(start, count, primcount) {
  10220. if (primcount === 0) return;
  10221. let extension, methodName;
  10222. if (isWebGL2) {
  10223. extension = gl;
  10224. methodName = 'drawElementsInstanced';
  10225. } else {
  10226. extension = extensions.get('ANGLE_instanced_arrays');
  10227. methodName = 'drawElementsInstancedANGLE';
  10228. if (extension === null) {
  10229. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  10230. return;
  10231. }
  10232. }
  10233. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  10234. info.update(count, mode, primcount);
  10235. } //
  10236. this.setMode = setMode;
  10237. this.setIndex = setIndex;
  10238. this.render = render;
  10239. this.renderInstances = renderInstances;
  10240. }
  10241. function WebGLInfo(gl) {
  10242. const memory = {
  10243. geometries: 0,
  10244. textures: 0
  10245. };
  10246. const render = {
  10247. frame: 0,
  10248. calls: 0,
  10249. triangles: 0,
  10250. points: 0,
  10251. lines: 0
  10252. };
  10253. function update(count, mode, instanceCount) {
  10254. render.calls++;
  10255. switch (mode) {
  10256. case gl.TRIANGLES:
  10257. render.triangles += instanceCount * (count / 3);
  10258. break;
  10259. case gl.LINES:
  10260. render.lines += instanceCount * (count / 2);
  10261. break;
  10262. case gl.LINE_STRIP:
  10263. render.lines += instanceCount * (count - 1);
  10264. break;
  10265. case gl.LINE_LOOP:
  10266. render.lines += instanceCount * count;
  10267. break;
  10268. case gl.POINTS:
  10269. render.points += instanceCount * count;
  10270. break;
  10271. default:
  10272. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  10273. break;
  10274. }
  10275. }
  10276. function reset() {
  10277. render.frame++;
  10278. render.calls = 0;
  10279. render.triangles = 0;
  10280. render.points = 0;
  10281. render.lines = 0;
  10282. }
  10283. return {
  10284. memory: memory,
  10285. render: render,
  10286. programs: null,
  10287. autoReset: true,
  10288. reset: reset,
  10289. update: update
  10290. };
  10291. }
  10292. function numericalSort(a, b) {
  10293. return a[0] - b[0];
  10294. }
  10295. function absNumericalSort(a, b) {
  10296. return Math.abs(b[1]) - Math.abs(a[1]);
  10297. }
  10298. function WebGLMorphtargets(gl) {
  10299. const influencesList = {};
  10300. const morphInfluences = new Float32Array(8);
  10301. const workInfluences = [];
  10302. for (let i = 0; i < 8; i++) {
  10303. workInfluences[i] = [i, 0];
  10304. }
  10305. function update(object, geometry, material, program) {
  10306. const objectInfluences = object.morphTargetInfluences; // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10307. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10308. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10309. let influences = influencesList[geometry.id];
  10310. if (influences === undefined || influences.length !== length) {
  10311. // initialise list
  10312. influences = [];
  10313. for (let i = 0; i < length; i++) {
  10314. influences[i] = [i, 0];
  10315. }
  10316. influencesList[geometry.id] = influences;
  10317. } // Collect influences
  10318. for (let i = 0; i < length; i++) {
  10319. const influence = influences[i];
  10320. influence[0] = i;
  10321. influence[1] = objectInfluences[i];
  10322. }
  10323. influences.sort(absNumericalSort);
  10324. for (let i = 0; i < 8; i++) {
  10325. if (i < length && influences[i][1]) {
  10326. workInfluences[i][0] = influences[i][0];
  10327. workInfluences[i][1] = influences[i][1];
  10328. } else {
  10329. workInfluences[i][0] = Number.MAX_SAFE_INTEGER;
  10330. workInfluences[i][1] = 0;
  10331. }
  10332. }
  10333. workInfluences.sort(numericalSort);
  10334. const morphTargets = geometry.morphAttributes.position;
  10335. const morphNormals = geometry.morphAttributes.normal;
  10336. let morphInfluencesSum = 0;
  10337. for (let i = 0; i < 8; i++) {
  10338. const influence = workInfluences[i];
  10339. const index = influence[0];
  10340. const value = influence[1];
  10341. if (index !== Number.MAX_SAFE_INTEGER && value) {
  10342. if (morphTargets && geometry.getAttribute('morphTarget' + i) !== morphTargets[index]) {
  10343. geometry.setAttribute('morphTarget' + i, morphTargets[index]);
  10344. }
  10345. if (morphNormals && geometry.getAttribute('morphNormal' + i) !== morphNormals[index]) {
  10346. geometry.setAttribute('morphNormal' + i, morphNormals[index]);
  10347. }
  10348. morphInfluences[i] = value;
  10349. morphInfluencesSum += value;
  10350. } else {
  10351. if (morphTargets && geometry.hasAttribute('morphTarget' + i) === true) {
  10352. geometry.deleteAttribute('morphTarget' + i);
  10353. }
  10354. if (morphNormals && geometry.hasAttribute('morphNormal' + i) === true) {
  10355. geometry.deleteAttribute('morphNormal' + i);
  10356. }
  10357. morphInfluences[i] = 0;
  10358. }
  10359. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10360. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10361. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10362. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10363. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10364. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  10365. }
  10366. return {
  10367. update: update
  10368. };
  10369. }
  10370. function WebGLObjects(gl, geometries, attributes, info) {
  10371. let updateMap = new WeakMap();
  10372. function update(object) {
  10373. const frame = info.render.frame;
  10374. const geometry = object.geometry;
  10375. const buffergeometry = geometries.get(object, geometry); // Update once per frame
  10376. if (updateMap.get(buffergeometry) !== frame) {
  10377. geometries.update(buffergeometry);
  10378. updateMap.set(buffergeometry, frame);
  10379. }
  10380. if (object.isInstancedMesh) {
  10381. if (object.hasEventListener('dispose', onInstancedMeshDispose) === false) {
  10382. object.addEventListener('dispose', onInstancedMeshDispose);
  10383. }
  10384. attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER);
  10385. if (object.instanceColor !== null) {
  10386. attributes.update(object.instanceColor, gl.ARRAY_BUFFER);
  10387. }
  10388. }
  10389. return buffergeometry;
  10390. }
  10391. function dispose() {
  10392. updateMap = new WeakMap();
  10393. }
  10394. function onInstancedMeshDispose(event) {
  10395. const instancedMesh = event.target;
  10396. instancedMesh.removeEventListener('dispose', onInstancedMeshDispose);
  10397. attributes.remove(instancedMesh.instanceMatrix);
  10398. if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor);
  10399. }
  10400. return {
  10401. update: update,
  10402. dispose: dispose
  10403. };
  10404. }
  10405. class DataTexture2DArray extends Texture {
  10406. constructor(data = null, width = 1, height = 1, depth = 1) {
  10407. super(null);
  10408. this.image = {
  10409. data,
  10410. width,
  10411. height,
  10412. depth
  10413. };
  10414. this.magFilter = NearestFilter;
  10415. this.minFilter = NearestFilter;
  10416. this.wrapR = ClampToEdgeWrapping;
  10417. this.generateMipmaps = false;
  10418. this.flipY = false;
  10419. this.unpackAlignment = 1;
  10420. this.needsUpdate = true;
  10421. }
  10422. }
  10423. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  10424. class DataTexture3D extends Texture {
  10425. constructor(data = null, width = 1, height = 1, depth = 1) {
  10426. // We're going to add .setXXX() methods for setting properties later.
  10427. // Users can still set in DataTexture3D directly.
  10428. //
  10429. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  10430. // texture.anisotropy = 16;
  10431. //
  10432. // See #14839
  10433. super(null);
  10434. this.image = {
  10435. data,
  10436. width,
  10437. height,
  10438. depth
  10439. };
  10440. this.magFilter = NearestFilter;
  10441. this.minFilter = NearestFilter;
  10442. this.wrapR = ClampToEdgeWrapping;
  10443. this.generateMipmaps = false;
  10444. this.flipY = false;
  10445. this.unpackAlignment = 1;
  10446. this.needsUpdate = true;
  10447. }
  10448. }
  10449. DataTexture3D.prototype.isDataTexture3D = true;
  10450. /**
  10451. * Uniforms of a program.
  10452. * Those form a tree structure with a special top-level container for the root,
  10453. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10454. *
  10455. *
  10456. * Properties of inner nodes including the top-level container:
  10457. *
  10458. * .seq - array of nested uniforms
  10459. * .map - nested uniforms by name
  10460. *
  10461. *
  10462. * Methods of all nodes except the top-level container:
  10463. *
  10464. * .setValue( gl, value, [textures] )
  10465. *
  10466. * uploads a uniform value(s)
  10467. * the 'textures' parameter is needed for sampler uniforms
  10468. *
  10469. *
  10470. * Static methods of the top-level container (textures factorizations):
  10471. *
  10472. * .upload( gl, seq, values, textures )
  10473. *
  10474. * sets uniforms in 'seq' to 'values[id].value'
  10475. *
  10476. * .seqWithValue( seq, values ) : filteredSeq
  10477. *
  10478. * filters 'seq' entries with corresponding entry in values
  10479. *
  10480. *
  10481. * Methods of the top-level container (textures factorizations):
  10482. *
  10483. * .setValue( gl, name, value, textures )
  10484. *
  10485. * sets uniform with name 'name' to 'value'
  10486. *
  10487. * .setOptional( gl, obj, prop )
  10488. *
  10489. * like .set for an optional property of the object
  10490. *
  10491. */
  10492. const emptyTexture = new Texture();
  10493. const emptyTexture2dArray = new DataTexture2DArray();
  10494. const emptyTexture3d = new DataTexture3D();
  10495. const emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  10496. // Array Caches (provide typed arrays for temporary by size)
  10497. const arrayCacheF32 = [];
  10498. const arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  10499. const mat4array = new Float32Array(16);
  10500. const mat3array = new Float32Array(9);
  10501. const mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  10502. function flatten(array, nBlocks, blockSize) {
  10503. const firstElem = array[0];
  10504. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  10505. // see http://jacksondunstan.com/articles/983
  10506. const n = nBlocks * blockSize;
  10507. let r = arrayCacheF32[n];
  10508. if (r === undefined) {
  10509. r = new Float32Array(n);
  10510. arrayCacheF32[n] = r;
  10511. }
  10512. if (nBlocks !== 0) {
  10513. firstElem.toArray(r, 0);
  10514. for (let i = 1, offset = 0; i !== nBlocks; ++i) {
  10515. offset += blockSize;
  10516. array[i].toArray(r, offset);
  10517. }
  10518. }
  10519. return r;
  10520. }
  10521. function arraysEqual(a, b) {
  10522. if (a.length !== b.length) return false;
  10523. for (let i = 0, l = a.length; i < l; i++) {
  10524. if (a[i] !== b[i]) return false;
  10525. }
  10526. return true;
  10527. }
  10528. function copyArray(a, b) {
  10529. for (let i = 0, l = b.length; i < l; i++) {
  10530. a[i] = b[i];
  10531. }
  10532. } // Texture unit allocation
  10533. function allocTexUnits(textures, n) {
  10534. let r = arrayCacheI32[n];
  10535. if (r === undefined) {
  10536. r = new Int32Array(n);
  10537. arrayCacheI32[n] = r;
  10538. }
  10539. for (let i = 0; i !== n; ++i) {
  10540. r[i] = textures.allocateTextureUnit();
  10541. }
  10542. return r;
  10543. } // --- Setters ---
  10544. // Note: Defining these methods externally, because they come in a bunch
  10545. // and this way their names minify.
  10546. // Single scalar
  10547. function setValueV1f(gl, v) {
  10548. const cache = this.cache;
  10549. if (cache[0] === v) return;
  10550. gl.uniform1f(this.addr, v);
  10551. cache[0] = v;
  10552. } // Single float vector (from flat array or THREE.VectorN)
  10553. function setValueV2f(gl, v) {
  10554. const cache = this.cache;
  10555. if (v.x !== undefined) {
  10556. if (cache[0] !== v.x || cache[1] !== v.y) {
  10557. gl.uniform2f(this.addr, v.x, v.y);
  10558. cache[0] = v.x;
  10559. cache[1] = v.y;
  10560. }
  10561. } else {
  10562. if (arraysEqual(cache, v)) return;
  10563. gl.uniform2fv(this.addr, v);
  10564. copyArray(cache, v);
  10565. }
  10566. }
  10567. function setValueV3f(gl, v) {
  10568. const cache = this.cache;
  10569. if (v.x !== undefined) {
  10570. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  10571. gl.uniform3f(this.addr, v.x, v.y, v.z);
  10572. cache[0] = v.x;
  10573. cache[1] = v.y;
  10574. cache[2] = v.z;
  10575. }
  10576. } else if (v.r !== undefined) {
  10577. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  10578. gl.uniform3f(this.addr, v.r, v.g, v.b);
  10579. cache[0] = v.r;
  10580. cache[1] = v.g;
  10581. cache[2] = v.b;
  10582. }
  10583. } else {
  10584. if (arraysEqual(cache, v)) return;
  10585. gl.uniform3fv(this.addr, v);
  10586. copyArray(cache, v);
  10587. }
  10588. }
  10589. function setValueV4f(gl, v) {
  10590. const cache = this.cache;
  10591. if (v.x !== undefined) {
  10592. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  10593. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  10594. cache[0] = v.x;
  10595. cache[1] = v.y;
  10596. cache[2] = v.z;
  10597. cache[3] = v.w;
  10598. }
  10599. } else {
  10600. if (arraysEqual(cache, v)) return;
  10601. gl.uniform4fv(this.addr, v);
  10602. copyArray(cache, v);
  10603. }
  10604. } // Single matrix (from flat array or THREE.MatrixN)
  10605. function setValueM2(gl, v) {
  10606. const cache = this.cache;
  10607. const elements = v.elements;
  10608. if (elements === undefined) {
  10609. if (arraysEqual(cache, v)) return;
  10610. gl.uniformMatrix2fv(this.addr, false, v);
  10611. copyArray(cache, v);
  10612. } else {
  10613. if (arraysEqual(cache, elements)) return;
  10614. mat2array.set(elements);
  10615. gl.uniformMatrix2fv(this.addr, false, mat2array);
  10616. copyArray(cache, elements);
  10617. }
  10618. }
  10619. function setValueM3(gl, v) {
  10620. const cache = this.cache;
  10621. const elements = v.elements;
  10622. if (elements === undefined) {
  10623. if (arraysEqual(cache, v)) return;
  10624. gl.uniformMatrix3fv(this.addr, false, v);
  10625. copyArray(cache, v);
  10626. } else {
  10627. if (arraysEqual(cache, elements)) return;
  10628. mat3array.set(elements);
  10629. gl.uniformMatrix3fv(this.addr, false, mat3array);
  10630. copyArray(cache, elements);
  10631. }
  10632. }
  10633. function setValueM4(gl, v) {
  10634. const cache = this.cache;
  10635. const elements = v.elements;
  10636. if (elements === undefined) {
  10637. if (arraysEqual(cache, v)) return;
  10638. gl.uniformMatrix4fv(this.addr, false, v);
  10639. copyArray(cache, v);
  10640. } else {
  10641. if (arraysEqual(cache, elements)) return;
  10642. mat4array.set(elements);
  10643. gl.uniformMatrix4fv(this.addr, false, mat4array);
  10644. copyArray(cache, elements);
  10645. }
  10646. } // Single integer / boolean
  10647. function setValueV1i(gl, v) {
  10648. const cache = this.cache;
  10649. if (cache[0] === v) return;
  10650. gl.uniform1i(this.addr, v);
  10651. cache[0] = v;
  10652. } // Single integer / boolean vector (from flat array)
  10653. function setValueV2i(gl, v) {
  10654. const cache = this.cache;
  10655. if (arraysEqual(cache, v)) return;
  10656. gl.uniform2iv(this.addr, v);
  10657. copyArray(cache, v);
  10658. }
  10659. function setValueV3i(gl, v) {
  10660. const cache = this.cache;
  10661. if (arraysEqual(cache, v)) return;
  10662. gl.uniform3iv(this.addr, v);
  10663. copyArray(cache, v);
  10664. }
  10665. function setValueV4i(gl, v) {
  10666. const cache = this.cache;
  10667. if (arraysEqual(cache, v)) return;
  10668. gl.uniform4iv(this.addr, v);
  10669. copyArray(cache, v);
  10670. } // Single unsigned integer
  10671. function setValueV1ui(gl, v) {
  10672. const cache = this.cache;
  10673. if (cache[0] === v) return;
  10674. gl.uniform1ui(this.addr, v);
  10675. cache[0] = v;
  10676. } // Single unsigned integer vector (from flat array)
  10677. function setValueV2ui(gl, v) {
  10678. const cache = this.cache;
  10679. if (arraysEqual(cache, v)) return;
  10680. gl.uniform2uiv(this.addr, v);
  10681. copyArray(cache, v);
  10682. }
  10683. function setValueV3ui(gl, v) {
  10684. const cache = this.cache;
  10685. if (arraysEqual(cache, v)) return;
  10686. gl.uniform3uiv(this.addr, v);
  10687. copyArray(cache, v);
  10688. }
  10689. function setValueV4ui(gl, v) {
  10690. const cache = this.cache;
  10691. if (arraysEqual(cache, v)) return;
  10692. gl.uniform4uiv(this.addr, v);
  10693. copyArray(cache, v);
  10694. } // Single texture (2D / Cube)
  10695. function setValueT1(gl, v, textures) {
  10696. const cache = this.cache;
  10697. const unit = textures.allocateTextureUnit();
  10698. if (cache[0] !== unit) {
  10699. gl.uniform1i(this.addr, unit);
  10700. cache[0] = unit;
  10701. }
  10702. textures.safeSetTexture2D(v || emptyTexture, unit);
  10703. }
  10704. function setValueT3D1(gl, v, textures) {
  10705. const cache = this.cache;
  10706. const unit = textures.allocateTextureUnit();
  10707. if (cache[0] !== unit) {
  10708. gl.uniform1i(this.addr, unit);
  10709. cache[0] = unit;
  10710. }
  10711. textures.setTexture3D(v || emptyTexture3d, unit);
  10712. }
  10713. function setValueT6(gl, v, textures) {
  10714. const cache = this.cache;
  10715. const unit = textures.allocateTextureUnit();
  10716. if (cache[0] !== unit) {
  10717. gl.uniform1i(this.addr, unit);
  10718. cache[0] = unit;
  10719. }
  10720. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  10721. }
  10722. function setValueT2DArray1(gl, v, textures) {
  10723. const cache = this.cache;
  10724. const unit = textures.allocateTextureUnit();
  10725. if (cache[0] !== unit) {
  10726. gl.uniform1i(this.addr, unit);
  10727. cache[0] = unit;
  10728. }
  10729. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  10730. } // Helper to pick the right setter for the singular case
  10731. function getSingularSetter(type) {
  10732. switch (type) {
  10733. case 0x1406:
  10734. return setValueV1f;
  10735. // FLOAT
  10736. case 0x8b50:
  10737. return setValueV2f;
  10738. // _VEC2
  10739. case 0x8b51:
  10740. return setValueV3f;
  10741. // _VEC3
  10742. case 0x8b52:
  10743. return setValueV4f;
  10744. // _VEC4
  10745. case 0x8b5a:
  10746. return setValueM2;
  10747. // _MAT2
  10748. case 0x8b5b:
  10749. return setValueM3;
  10750. // _MAT3
  10751. case 0x8b5c:
  10752. return setValueM4;
  10753. // _MAT4
  10754. case 0x1404:
  10755. case 0x8b56:
  10756. return setValueV1i;
  10757. // INT, BOOL
  10758. case 0x8b53:
  10759. case 0x8b57:
  10760. return setValueV2i;
  10761. // _VEC2
  10762. case 0x8b54:
  10763. case 0x8b58:
  10764. return setValueV3i;
  10765. // _VEC3
  10766. case 0x8b55:
  10767. case 0x8b59:
  10768. return setValueV4i;
  10769. // _VEC4
  10770. case 0x1405:
  10771. return setValueV1ui;
  10772. // UINT
  10773. case 0x8dc6:
  10774. return setValueV2ui;
  10775. // _VEC2
  10776. case 0x8dc7:
  10777. return setValueV3ui;
  10778. // _VEC3
  10779. case 0x8dc8:
  10780. return setValueV4ui;
  10781. // _VEC4
  10782. case 0x8b5e: // SAMPLER_2D
  10783. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10784. case 0x8dca: // INT_SAMPLER_2D
  10785. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10786. case 0x8b62:
  10787. // SAMPLER_2D_SHADOW
  10788. return setValueT1;
  10789. case 0x8b5f: // SAMPLER_3D
  10790. case 0x8dcb: // INT_SAMPLER_3D
  10791. case 0x8dd3:
  10792. // UNSIGNED_INT_SAMPLER_3D
  10793. return setValueT3D1;
  10794. case 0x8b60: // SAMPLER_CUBE
  10795. case 0x8dcc: // INT_SAMPLER_CUBE
  10796. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10797. case 0x8dc5:
  10798. // SAMPLER_CUBE_SHADOW
  10799. return setValueT6;
  10800. case 0x8dc1: // SAMPLER_2D_ARRAY
  10801. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10802. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10803. case 0x8dc4:
  10804. // SAMPLER_2D_ARRAY_SHADOW
  10805. return setValueT2DArray1;
  10806. }
  10807. } // Array of scalars
  10808. function setValueV1fArray(gl, v) {
  10809. gl.uniform1fv(this.addr, v);
  10810. } // Array of vectors (from flat array or array of THREE.VectorN)
  10811. function setValueV2fArray(gl, v) {
  10812. const data = flatten(v, this.size, 2);
  10813. gl.uniform2fv(this.addr, data);
  10814. }
  10815. function setValueV3fArray(gl, v) {
  10816. const data = flatten(v, this.size, 3);
  10817. gl.uniform3fv(this.addr, data);
  10818. }
  10819. function setValueV4fArray(gl, v) {
  10820. const data = flatten(v, this.size, 4);
  10821. gl.uniform4fv(this.addr, data);
  10822. } // Array of matrices (from flat array or array of THREE.MatrixN)
  10823. function setValueM2Array(gl, v) {
  10824. const data = flatten(v, this.size, 4);
  10825. gl.uniformMatrix2fv(this.addr, false, data);
  10826. }
  10827. function setValueM3Array(gl, v) {
  10828. const data = flatten(v, this.size, 9);
  10829. gl.uniformMatrix3fv(this.addr, false, data);
  10830. }
  10831. function setValueM4Array(gl, v) {
  10832. const data = flatten(v, this.size, 16);
  10833. gl.uniformMatrix4fv(this.addr, false, data);
  10834. } // Array of integer / boolean
  10835. function setValueV1iArray(gl, v) {
  10836. gl.uniform1iv(this.addr, v);
  10837. } // Array of integer / boolean vectors (from flat array)
  10838. function setValueV2iArray(gl, v) {
  10839. gl.uniform2iv(this.addr, v);
  10840. }
  10841. function setValueV3iArray(gl, v) {
  10842. gl.uniform3iv(this.addr, v);
  10843. }
  10844. function setValueV4iArray(gl, v) {
  10845. gl.uniform4iv(this.addr, v);
  10846. } // Array of unsigned integer
  10847. function setValueV1uiArray(gl, v) {
  10848. gl.uniform1uiv(this.addr, v);
  10849. } // Array of unsigned integer vectors (from flat array)
  10850. function setValueV2uiArray(gl, v) {
  10851. gl.uniform2uiv(this.addr, v);
  10852. }
  10853. function setValueV3uiArray(gl, v) {
  10854. gl.uniform3uiv(this.addr, v);
  10855. }
  10856. function setValueV4uiArray(gl, v) {
  10857. gl.uniform4uiv(this.addr, v);
  10858. } // Array of textures (2D / Cube)
  10859. function setValueT1Array(gl, v, textures) {
  10860. const n = v.length;
  10861. const units = allocTexUnits(textures, n);
  10862. gl.uniform1iv(this.addr, units);
  10863. for (let i = 0; i !== n; ++i) {
  10864. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  10865. }
  10866. }
  10867. function setValueT6Array(gl, v, textures) {
  10868. const n = v.length;
  10869. const units = allocTexUnits(textures, n);
  10870. gl.uniform1iv(this.addr, units);
  10871. for (let i = 0; i !== n; ++i) {
  10872. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  10873. }
  10874. } // Helper to pick the right setter for a pure (bottom-level) array
  10875. function getPureArraySetter(type) {
  10876. switch (type) {
  10877. case 0x1406:
  10878. return setValueV1fArray;
  10879. // FLOAT
  10880. case 0x8b50:
  10881. return setValueV2fArray;
  10882. // _VEC2
  10883. case 0x8b51:
  10884. return setValueV3fArray;
  10885. // _VEC3
  10886. case 0x8b52:
  10887. return setValueV4fArray;
  10888. // _VEC4
  10889. case 0x8b5a:
  10890. return setValueM2Array;
  10891. // _MAT2
  10892. case 0x8b5b:
  10893. return setValueM3Array;
  10894. // _MAT3
  10895. case 0x8b5c:
  10896. return setValueM4Array;
  10897. // _MAT4
  10898. case 0x1404:
  10899. case 0x8b56:
  10900. return setValueV1iArray;
  10901. // INT, BOOL
  10902. case 0x8b53:
  10903. case 0x8b57:
  10904. return setValueV2iArray;
  10905. // _VEC2
  10906. case 0x8b54:
  10907. case 0x8b58:
  10908. return setValueV3iArray;
  10909. // _VEC3
  10910. case 0x8b55:
  10911. case 0x8b59:
  10912. return setValueV4iArray;
  10913. // _VEC4
  10914. case 0x1405:
  10915. return setValueV1uiArray;
  10916. // UINT
  10917. case 0x8dc6:
  10918. return setValueV2uiArray;
  10919. // _VEC2
  10920. case 0x8dc7:
  10921. return setValueV3uiArray;
  10922. // _VEC3
  10923. case 0x8dc8:
  10924. return setValueV4uiArray;
  10925. // _VEC4
  10926. case 0x8b5e: // SAMPLER_2D
  10927. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10928. case 0x8dca: // INT_SAMPLER_2D
  10929. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10930. case 0x8b62:
  10931. // SAMPLER_2D_SHADOW
  10932. return setValueT1Array;
  10933. case 0x8b60: // SAMPLER_CUBE
  10934. case 0x8dcc: // INT_SAMPLER_CUBE
  10935. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10936. case 0x8dc5:
  10937. // SAMPLER_CUBE_SHADOW
  10938. return setValueT6Array;
  10939. }
  10940. } // --- Uniform Classes ---
  10941. function SingleUniform(id, activeInfo, addr) {
  10942. this.id = id;
  10943. this.addr = addr;
  10944. this.cache = [];
  10945. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  10946. }
  10947. function PureArrayUniform(id, activeInfo, addr) {
  10948. this.id = id;
  10949. this.addr = addr;
  10950. this.cache = [];
  10951. this.size = activeInfo.size;
  10952. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  10953. }
  10954. PureArrayUniform.prototype.updateCache = function (data) {
  10955. const cache = this.cache;
  10956. if (data instanceof Float32Array && cache.length !== data.length) {
  10957. this.cache = new Float32Array(data.length);
  10958. }
  10959. copyArray(cache, data);
  10960. };
  10961. function StructuredUniform(id) {
  10962. this.id = id;
  10963. this.seq = [];
  10964. this.map = {};
  10965. }
  10966. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  10967. const seq = this.seq;
  10968. for (let i = 0, n = seq.length; i !== n; ++i) {
  10969. const u = seq[i];
  10970. u.setValue(gl, value[u.id], textures);
  10971. }
  10972. }; // --- Top-level ---
  10973. // Parser - builds up the property tree from the path strings
  10974. const RePathPart = /(\w+)(\])?(\[|\.)?/g; // extracts
  10975. // - the identifier (member name or array index)
  10976. // - followed by an optional right bracket (found when array index)
  10977. // - followed by an optional left bracket or dot (type of subscript)
  10978. //
  10979. // Note: These portions can be read in a non-overlapping fashion and
  10980. // allow straightforward parsing of the hierarchy that WebGL encodes
  10981. // in the uniform names.
  10982. function addUniform(container, uniformObject) {
  10983. container.seq.push(uniformObject);
  10984. container.map[uniformObject.id] = uniformObject;
  10985. }
  10986. function parseUniform(activeInfo, addr, container) {
  10987. const path = activeInfo.name,
  10988. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  10989. RePathPart.lastIndex = 0;
  10990. while (true) {
  10991. const match = RePathPart.exec(path),
  10992. matchEnd = RePathPart.lastIndex;
  10993. let id = match[1];
  10994. const idIsIndex = match[2] === ']',
  10995. subscript = match[3];
  10996. if (idIsIndex) id = id | 0; // convert to integer
  10997. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  10998. // bare name or "pure" bottom-level array "[0]" suffix
  10999. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  11000. break;
  11001. } else {
  11002. // step into inner node / create it in case it doesn't exist
  11003. const map = container.map;
  11004. let next = map[id];
  11005. if (next === undefined) {
  11006. next = new StructuredUniform(id);
  11007. addUniform(container, next);
  11008. }
  11009. container = next;
  11010. }
  11011. }
  11012. } // Root Container
  11013. function WebGLUniforms(gl, program) {
  11014. this.seq = [];
  11015. this.map = {};
  11016. const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  11017. for (let i = 0; i < n; ++i) {
  11018. const info = gl.getActiveUniform(program, i),
  11019. addr = gl.getUniformLocation(program, info.name);
  11020. parseUniform(info, addr, this);
  11021. }
  11022. }
  11023. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  11024. const u = this.map[name];
  11025. if (u !== undefined) u.setValue(gl, value, textures);
  11026. };
  11027. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  11028. const v = object[name];
  11029. if (v !== undefined) this.setValue(gl, name, v);
  11030. }; // Static interface
  11031. WebGLUniforms.upload = function (gl, seq, values, textures) {
  11032. for (let i = 0, n = seq.length; i !== n; ++i) {
  11033. const u = seq[i],
  11034. v = values[u.id];
  11035. if (v.needsUpdate !== false) {
  11036. // note: always updating when .needsUpdate is undefined
  11037. u.setValue(gl, v.value, textures);
  11038. }
  11039. }
  11040. };
  11041. WebGLUniforms.seqWithValue = function (seq, values) {
  11042. const r = [];
  11043. for (let i = 0, n = seq.length; i !== n; ++i) {
  11044. const u = seq[i];
  11045. if (u.id in values) r.push(u);
  11046. }
  11047. return r;
  11048. };
  11049. function WebGLShader(gl, type, string) {
  11050. const shader = gl.createShader(type);
  11051. gl.shaderSource(shader, string);
  11052. gl.compileShader(shader);
  11053. return shader;
  11054. }
  11055. let programIdCount = 0;
  11056. function addLineNumbers(string) {
  11057. const lines = string.split('\n');
  11058. for (let i = 0; i < lines.length; i++) {
  11059. lines[i] = i + 1 + ': ' + lines[i];
  11060. }
  11061. return lines.join('\n');
  11062. }
  11063. function getEncodingComponents(encoding) {
  11064. switch (encoding) {
  11065. case LinearEncoding:
  11066. return ['Linear', '( value )'];
  11067. case sRGBEncoding:
  11068. return ['sRGB', '( value )'];
  11069. case RGBEEncoding:
  11070. return ['RGBE', '( value )'];
  11071. case RGBM7Encoding:
  11072. return ['RGBM', '( value, 7.0 )'];
  11073. case RGBM16Encoding:
  11074. return ['RGBM', '( value, 16.0 )'];
  11075. case RGBDEncoding:
  11076. return ['RGBD', '( value, 256.0 )'];
  11077. case GammaEncoding:
  11078. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  11079. case LogLuvEncoding:
  11080. return ['LogLuv', '( value )'];
  11081. default:
  11082. console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
  11083. return ['Linear', '( value )'];
  11084. }
  11085. }
  11086. function getShaderErrors(gl, shader, type) {
  11087. const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  11088. const errors = gl.getShaderInfoLog(shader).trim();
  11089. if (status && errors === '') return ''; // --enable-privileged-webgl-extension
  11090. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11091. return type.toUpperCase() + '\n\n' + errors + '\n\n' + addLineNumbers(gl.getShaderSource(shader));
  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() + ' - ' + 'VALIDATE_STATUS ' + gl.getProgramParameter(program, gl.VALIDATE_STATUS) + '\n\n' + 'Program Info Log: ' + programLog + '\n' + vertexErrors + '\n' + fragmentErrors);
  11321. } else if (programLog !== '') {
  11322. console.warn('THREE.WebGLProgram: Program Info Log:', 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. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23095. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  23096. return this.intensity * Math.PI;
  23097. }
  23098. set power(power) {
  23099. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23100. this.intensity = power / Math.PI;
  23101. }
  23102. dispose() {
  23103. this.shadow.dispose();
  23104. }
  23105. copy(source) {
  23106. super.copy(source);
  23107. this.distance = source.distance;
  23108. this.angle = source.angle;
  23109. this.penumbra = source.penumbra;
  23110. this.decay = source.decay;
  23111. this.target = source.target.clone();
  23112. this.shadow = source.shadow.clone();
  23113. return this;
  23114. }
  23115. }
  23116. SpotLight.prototype.isSpotLight = true;
  23117. const _projScreenMatrix = /*@__PURE__*/new Matrix4();
  23118. const _lightPositionWorld = /*@__PURE__*/new Vector3();
  23119. const _lookTarget = /*@__PURE__*/new Vector3();
  23120. class PointLightShadow extends LightShadow {
  23121. constructor() {
  23122. super(new PerspectiveCamera(90, 1, 0.5, 500));
  23123. this._frameExtents = new Vector2(4, 2);
  23124. this._viewportCount = 6;
  23125. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  23126. // following orientation:
  23127. //
  23128. // xzXZ
  23129. // y Y
  23130. //
  23131. // X - Positive x direction
  23132. // x - Negative x direction
  23133. // Y - Positive y direction
  23134. // y - Negative y direction
  23135. // Z - Positive z direction
  23136. // z - Negative z direction
  23137. // positive X
  23138. new Vector4(2, 1, 1, 1), // negative X
  23139. new Vector4(0, 1, 1, 1), // positive Z
  23140. new Vector4(3, 1, 1, 1), // negative Z
  23141. new Vector4(1, 1, 1, 1), // positive Y
  23142. new Vector4(3, 0, 1, 1), // negative Y
  23143. new Vector4(1, 0, 1, 1)];
  23144. 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)];
  23145. 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)];
  23146. }
  23147. updateMatrices(light, viewportIndex = 0) {
  23148. const camera = this.camera;
  23149. const shadowMatrix = this.matrix;
  23150. const far = light.distance || camera.far;
  23151. if (far !== camera.far) {
  23152. camera.far = far;
  23153. camera.updateProjectionMatrix();
  23154. }
  23155. _lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23156. camera.position.copy(_lightPositionWorld);
  23157. _lookTarget.copy(camera.position);
  23158. _lookTarget.add(this._cubeDirections[viewportIndex]);
  23159. camera.up.copy(this._cubeUps[viewportIndex]);
  23160. camera.lookAt(_lookTarget);
  23161. camera.updateMatrixWorld();
  23162. shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z);
  23163. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  23164. this._frustum.setFromProjectionMatrix(_projScreenMatrix);
  23165. }
  23166. }
  23167. PointLightShadow.prototype.isPointLightShadow = true;
  23168. class PointLight extends Light {
  23169. constructor(color, intensity, distance = 0, decay = 1) {
  23170. super(color, intensity);
  23171. this.type = 'PointLight';
  23172. this.distance = distance;
  23173. this.decay = decay; // for physically correct lights, should be 2.
  23174. this.shadow = new PointLightShadow();
  23175. }
  23176. get power() {
  23177. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23178. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  23179. return this.intensity * 4 * Math.PI;
  23180. }
  23181. set power(power) {
  23182. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23183. this.intensity = power / (4 * Math.PI);
  23184. }
  23185. dispose() {
  23186. this.shadow.dispose();
  23187. }
  23188. copy(source) {
  23189. super.copy(source);
  23190. this.distance = source.distance;
  23191. this.decay = source.decay;
  23192. this.shadow = source.shadow.clone();
  23193. return this;
  23194. }
  23195. }
  23196. PointLight.prototype.isPointLight = true;
  23197. class DirectionalLightShadow extends LightShadow {
  23198. constructor() {
  23199. super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  23200. }
  23201. }
  23202. DirectionalLightShadow.prototype.isDirectionalLightShadow = true;
  23203. class DirectionalLight extends Light {
  23204. constructor(color, intensity) {
  23205. super(color, intensity);
  23206. this.type = 'DirectionalLight';
  23207. this.position.copy(Object3D.DefaultUp);
  23208. this.updateMatrix();
  23209. this.target = new Object3D();
  23210. this.shadow = new DirectionalLightShadow();
  23211. }
  23212. dispose() {
  23213. this.shadow.dispose();
  23214. }
  23215. copy(source) {
  23216. super.copy(source);
  23217. this.target = source.target.clone();
  23218. this.shadow = source.shadow.clone();
  23219. return this;
  23220. }
  23221. }
  23222. DirectionalLight.prototype.isDirectionalLight = true;
  23223. class AmbientLight extends Light {
  23224. constructor(color, intensity) {
  23225. super(color, intensity);
  23226. this.type = 'AmbientLight';
  23227. }
  23228. }
  23229. AmbientLight.prototype.isAmbientLight = true;
  23230. class RectAreaLight extends Light {
  23231. constructor(color, intensity, width = 10, height = 10) {
  23232. super(color, intensity);
  23233. this.type = 'RectAreaLight';
  23234. this.width = width;
  23235. this.height = height;
  23236. }
  23237. get power() {
  23238. // compute the light's luminous power (in lumens) from its intensity (in nits)
  23239. return this.intensity * this.width * this.height * Math.PI;
  23240. }
  23241. set power(power) {
  23242. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  23243. this.intensity = power / (this.width * this.height * Math.PI);
  23244. }
  23245. copy(source) {
  23246. super.copy(source);
  23247. this.width = source.width;
  23248. this.height = source.height;
  23249. return this;
  23250. }
  23251. toJSON(meta) {
  23252. const data = super.toJSON(meta);
  23253. data.object.width = this.width;
  23254. data.object.height = this.height;
  23255. return data;
  23256. }
  23257. }
  23258. RectAreaLight.prototype.isRectAreaLight = true;
  23259. /**
  23260. * Primary reference:
  23261. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23262. *
  23263. * Secondary reference:
  23264. * https://www.ppsloan.org/publications/StupidSH36.pdf
  23265. */
  23266. // 3-band SH defined by 9 coefficients
  23267. class SphericalHarmonics3 {
  23268. constructor() {
  23269. this.coefficients = [];
  23270. for (let i = 0; i < 9; i++) {
  23271. this.coefficients.push(new Vector3());
  23272. }
  23273. }
  23274. set(coefficients) {
  23275. for (let i = 0; i < 9; i++) {
  23276. this.coefficients[i].copy(coefficients[i]);
  23277. }
  23278. return this;
  23279. }
  23280. zero() {
  23281. for (let i = 0; i < 9; i++) {
  23282. this.coefficients[i].set(0, 0, 0);
  23283. }
  23284. return this;
  23285. } // get the radiance in the direction of the normal
  23286. // target is a Vector3
  23287. getAt(normal, target) {
  23288. // normal is assumed to be unit length
  23289. const x = normal.x,
  23290. y = normal.y,
  23291. z = normal.z;
  23292. const coeff = this.coefficients; // band 0
  23293. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  23294. target.addScaledVector(coeff[1], 0.488603 * y);
  23295. target.addScaledVector(coeff[2], 0.488603 * z);
  23296. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  23297. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  23298. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  23299. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  23300. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  23301. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  23302. return target;
  23303. } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  23304. // target is a Vector3
  23305. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23306. getIrradianceAt(normal, target) {
  23307. // normal is assumed to be unit length
  23308. const x = normal.x,
  23309. y = normal.y,
  23310. z = normal.z;
  23311. const coeff = this.coefficients; // band 0
  23312. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  23313. // band 1
  23314. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  23315. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  23316. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  23317. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  23318. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  23319. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  23320. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  23321. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  23322. return target;
  23323. }
  23324. add(sh) {
  23325. for (let i = 0; i < 9; i++) {
  23326. this.coefficients[i].add(sh.coefficients[i]);
  23327. }
  23328. return this;
  23329. }
  23330. addScaledSH(sh, s) {
  23331. for (let i = 0; i < 9; i++) {
  23332. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  23333. }
  23334. return this;
  23335. }
  23336. scale(s) {
  23337. for (let i = 0; i < 9; i++) {
  23338. this.coefficients[i].multiplyScalar(s);
  23339. }
  23340. return this;
  23341. }
  23342. lerp(sh, alpha) {
  23343. for (let i = 0; i < 9; i++) {
  23344. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  23345. }
  23346. return this;
  23347. }
  23348. equals(sh) {
  23349. for (let i = 0; i < 9; i++) {
  23350. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  23351. return false;
  23352. }
  23353. }
  23354. return true;
  23355. }
  23356. copy(sh) {
  23357. return this.set(sh.coefficients);
  23358. }
  23359. clone() {
  23360. return new this.constructor().copy(this);
  23361. }
  23362. fromArray(array, offset = 0) {
  23363. const coefficients = this.coefficients;
  23364. for (let i = 0; i < 9; i++) {
  23365. coefficients[i].fromArray(array, offset + i * 3);
  23366. }
  23367. return this;
  23368. }
  23369. toArray(array = [], offset = 0) {
  23370. const coefficients = this.coefficients;
  23371. for (let i = 0; i < 9; i++) {
  23372. coefficients[i].toArray(array, offset + i * 3);
  23373. }
  23374. return array;
  23375. } // evaluate the basis functions
  23376. // shBasis is an Array[ 9 ]
  23377. static getBasisAt(normal, shBasis) {
  23378. // normal is assumed to be unit length
  23379. const x = normal.x,
  23380. y = normal.y,
  23381. z = normal.z; // band 0
  23382. shBasis[0] = 0.282095; // band 1
  23383. shBasis[1] = 0.488603 * y;
  23384. shBasis[2] = 0.488603 * z;
  23385. shBasis[3] = 0.488603 * x; // band 2
  23386. shBasis[4] = 1.092548 * x * y;
  23387. shBasis[5] = 1.092548 * y * z;
  23388. shBasis[6] = 0.315392 * (3 * z * z - 1);
  23389. shBasis[7] = 1.092548 * x * z;
  23390. shBasis[8] = 0.546274 * (x * x - y * y);
  23391. }
  23392. }
  23393. SphericalHarmonics3.prototype.isSphericalHarmonics3 = true;
  23394. class LightProbe extends Light {
  23395. constructor(sh = new SphericalHarmonics3(), intensity = 1) {
  23396. super(undefined, intensity);
  23397. this.sh = sh;
  23398. }
  23399. copy(source) {
  23400. super.copy(source);
  23401. this.sh.copy(source.sh);
  23402. return this;
  23403. }
  23404. fromJSON(json) {
  23405. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  23406. this.sh.fromArray(json.sh);
  23407. return this;
  23408. }
  23409. toJSON(meta) {
  23410. const data = super.toJSON(meta);
  23411. data.object.sh = this.sh.toArray();
  23412. return data;
  23413. }
  23414. }
  23415. LightProbe.prototype.isLightProbe = true;
  23416. class MaterialLoader extends Loader {
  23417. constructor(manager) {
  23418. super(manager);
  23419. this.textures = {};
  23420. }
  23421. load(url, onLoad, onProgress, onError) {
  23422. const scope = this;
  23423. const loader = new FileLoader(scope.manager);
  23424. loader.setPath(scope.path);
  23425. loader.setRequestHeader(scope.requestHeader);
  23426. loader.setWithCredentials(scope.withCredentials);
  23427. loader.load(url, function (text) {
  23428. try {
  23429. onLoad(scope.parse(JSON.parse(text)));
  23430. } catch (e) {
  23431. if (onError) {
  23432. onError(e);
  23433. } else {
  23434. console.error(e);
  23435. }
  23436. scope.manager.itemError(url);
  23437. }
  23438. }, onProgress, onError);
  23439. }
  23440. parse(json) {
  23441. const textures = this.textures;
  23442. function getTexture(name) {
  23443. if (textures[name] === undefined) {
  23444. console.warn('THREE.MaterialLoader: Undefined texture', name);
  23445. }
  23446. return textures[name];
  23447. }
  23448. const material = new Materials[json.type]();
  23449. if (json.uuid !== undefined) material.uuid = json.uuid;
  23450. if (json.name !== undefined) material.name = json.name;
  23451. if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
  23452. if (json.roughness !== undefined) material.roughness = json.roughness;
  23453. if (json.metalness !== undefined) material.metalness = json.metalness;
  23454. if (json.sheen !== undefined) material.sheen = new Color().setHex(json.sheen);
  23455. if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
  23456. if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
  23457. if (json.specularIntensity !== undefined) material.specularIntensity = json.specularIntensity;
  23458. if (json.specularTint !== undefined && material.specularTint !== undefined) material.specularTint.setHex(json.specularTint);
  23459. if (json.shininess !== undefined) material.shininess = json.shininess;
  23460. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  23461. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  23462. if (json.transmission !== undefined) material.transmission = json.transmission;
  23463. if (json.thickness !== undefined) material.thickness = json.thickness;
  23464. if (json.attenuationDistance !== undefined) material.attenuationDistance = json.attenuationDistance;
  23465. if (json.attenuationTint !== undefined && material.attenuationTint !== undefined) material.attenuationTint.setHex(json.attenuationTint);
  23466. if (json.fog !== undefined) material.fog = json.fog;
  23467. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  23468. if (json.blending !== undefined) material.blending = json.blending;
  23469. if (json.combine !== undefined) material.combine = json.combine;
  23470. if (json.side !== undefined) material.side = json.side;
  23471. if (json.shadowSide !== undefined) material.shadowSide = json.shadowSide;
  23472. if (json.opacity !== undefined) material.opacity = json.opacity;
  23473. if (json.transparent !== undefined) material.transparent = json.transparent;
  23474. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  23475. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  23476. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  23477. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  23478. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  23479. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  23480. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  23481. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  23482. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  23483. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  23484. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  23485. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  23486. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  23487. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  23488. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  23489. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  23490. if (json.rotation !== undefined) material.rotation = json.rotation;
  23491. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  23492. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  23493. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  23494. if (json.scale !== undefined) material.scale = json.scale;
  23495. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  23496. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  23497. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  23498. if (json.dithering !== undefined) material.dithering = json.dithering;
  23499. if (json.alphaToCoverage !== undefined) material.alphaToCoverage = json.alphaToCoverage;
  23500. if (json.premultipliedAlpha !== undefined) material.premultipliedAlpha = json.premultipliedAlpha;
  23501. if (json.visible !== undefined) material.visible = json.visible;
  23502. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  23503. if (json.userData !== undefined) material.userData = json.userData;
  23504. if (json.vertexColors !== undefined) {
  23505. if (typeof json.vertexColors === 'number') {
  23506. material.vertexColors = json.vertexColors > 0 ? true : false;
  23507. } else {
  23508. material.vertexColors = json.vertexColors;
  23509. }
  23510. } // Shader Material
  23511. if (json.uniforms !== undefined) {
  23512. for (const name in json.uniforms) {
  23513. const uniform = json.uniforms[name];
  23514. material.uniforms[name] = {};
  23515. switch (uniform.type) {
  23516. case 't':
  23517. material.uniforms[name].value = getTexture(uniform.value);
  23518. break;
  23519. case 'c':
  23520. material.uniforms[name].value = new Color().setHex(uniform.value);
  23521. break;
  23522. case 'v2':
  23523. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  23524. break;
  23525. case 'v3':
  23526. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  23527. break;
  23528. case 'v4':
  23529. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  23530. break;
  23531. case 'm3':
  23532. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  23533. break;
  23534. case 'm4':
  23535. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  23536. break;
  23537. default:
  23538. material.uniforms[name].value = uniform.value;
  23539. }
  23540. }
  23541. }
  23542. if (json.defines !== undefined) material.defines = json.defines;
  23543. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  23544. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  23545. if (json.extensions !== undefined) {
  23546. for (const key in json.extensions) {
  23547. material.extensions[key] = json.extensions[key];
  23548. }
  23549. } // Deprecated
  23550. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  23551. // for PointsMaterial
  23552. if (json.size !== undefined) material.size = json.size;
  23553. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  23554. if (json.map !== undefined) material.map = getTexture(json.map);
  23555. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  23556. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  23557. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  23558. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  23559. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  23560. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  23561. if (json.normalScale !== undefined) {
  23562. let normalScale = json.normalScale;
  23563. if (Array.isArray(normalScale) === false) {
  23564. // Blender exporter used to export a scalar. See #7459
  23565. normalScale = [normalScale, normalScale];
  23566. }
  23567. material.normalScale = new Vector2().fromArray(normalScale);
  23568. }
  23569. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  23570. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  23571. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  23572. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  23573. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  23574. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  23575. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  23576. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  23577. if (json.specularIntensityMap !== undefined) material.specularIntensityMap = getTexture(json.specularIntensityMap);
  23578. if (json.specularTintMap !== undefined) material.specularTintMap = getTexture(json.specularTintMap);
  23579. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  23580. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  23581. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  23582. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  23583. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  23584. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  23585. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  23586. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  23587. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  23588. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  23589. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  23590. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  23591. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  23592. if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
  23593. if (json.thicknessMap !== undefined) material.thicknessMap = getTexture(json.thicknessMap);
  23594. return material;
  23595. }
  23596. setTextures(value) {
  23597. this.textures = value;
  23598. return this;
  23599. }
  23600. }
  23601. class LoaderUtils {
  23602. static decodeText(array) {
  23603. if (typeof TextDecoder !== 'undefined') {
  23604. return new TextDecoder().decode(array);
  23605. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  23606. // throws a "maximum call stack size exceeded" error for large arrays.
  23607. let s = '';
  23608. for (let i = 0, il = array.length; i < il; i++) {
  23609. // Implicitly assumes little-endian.
  23610. s += String.fromCharCode(array[i]);
  23611. }
  23612. try {
  23613. // merges multi-byte utf-8 characters.
  23614. return decodeURIComponent(escape(s));
  23615. } catch (e) {
  23616. // see #16358
  23617. return s;
  23618. }
  23619. }
  23620. static extractUrlBase(url) {
  23621. const index = url.lastIndexOf('/');
  23622. if (index === -1) return './';
  23623. return url.substr(0, index + 1);
  23624. }
  23625. }
  23626. class InstancedBufferGeometry extends BufferGeometry {
  23627. constructor() {
  23628. super();
  23629. this.type = 'InstancedBufferGeometry';
  23630. this.instanceCount = Infinity;
  23631. }
  23632. copy(source) {
  23633. super.copy(source);
  23634. this.instanceCount = source.instanceCount;
  23635. return this;
  23636. }
  23637. clone() {
  23638. return new this.constructor().copy(this);
  23639. }
  23640. toJSON() {
  23641. const data = super.toJSON(this);
  23642. data.instanceCount = this.instanceCount;
  23643. data.isInstancedBufferGeometry = true;
  23644. return data;
  23645. }
  23646. }
  23647. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  23648. class InstancedBufferAttribute extends BufferAttribute {
  23649. constructor(array, itemSize, normalized, meshPerAttribute = 1) {
  23650. if (typeof normalized === 'number') {
  23651. meshPerAttribute = normalized;
  23652. normalized = false;
  23653. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  23654. }
  23655. super(array, itemSize, normalized);
  23656. this.meshPerAttribute = meshPerAttribute;
  23657. }
  23658. copy(source) {
  23659. super.copy(source);
  23660. this.meshPerAttribute = source.meshPerAttribute;
  23661. return this;
  23662. }
  23663. toJSON() {
  23664. const data = super.toJSON();
  23665. data.meshPerAttribute = this.meshPerAttribute;
  23666. data.isInstancedBufferAttribute = true;
  23667. return data;
  23668. }
  23669. }
  23670. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  23671. class BufferGeometryLoader extends Loader {
  23672. constructor(manager) {
  23673. super(manager);
  23674. }
  23675. load(url, onLoad, onProgress, onError) {
  23676. const scope = this;
  23677. const loader = new FileLoader(scope.manager);
  23678. loader.setPath(scope.path);
  23679. loader.setRequestHeader(scope.requestHeader);
  23680. loader.setWithCredentials(scope.withCredentials);
  23681. loader.load(url, function (text) {
  23682. try {
  23683. onLoad(scope.parse(JSON.parse(text)));
  23684. } catch (e) {
  23685. if (onError) {
  23686. onError(e);
  23687. } else {
  23688. console.error(e);
  23689. }
  23690. scope.manager.itemError(url);
  23691. }
  23692. }, onProgress, onError);
  23693. }
  23694. parse(json) {
  23695. const interleavedBufferMap = {};
  23696. const arrayBufferMap = {};
  23697. function getInterleavedBuffer(json, uuid) {
  23698. if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
  23699. const interleavedBuffers = json.interleavedBuffers;
  23700. const interleavedBuffer = interleavedBuffers[uuid];
  23701. const buffer = getArrayBuffer(json, interleavedBuffer.buffer);
  23702. const array = getTypedArray(interleavedBuffer.type, buffer);
  23703. const ib = new InterleavedBuffer(array, interleavedBuffer.stride);
  23704. ib.uuid = interleavedBuffer.uuid;
  23705. interleavedBufferMap[uuid] = ib;
  23706. return ib;
  23707. }
  23708. function getArrayBuffer(json, uuid) {
  23709. if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
  23710. const arrayBuffers = json.arrayBuffers;
  23711. const arrayBuffer = arrayBuffers[uuid];
  23712. const ab = new Uint32Array(arrayBuffer).buffer;
  23713. arrayBufferMap[uuid] = ab;
  23714. return ab;
  23715. }
  23716. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  23717. const index = json.data.index;
  23718. if (index !== undefined) {
  23719. const typedArray = getTypedArray(index.type, index.array);
  23720. geometry.setIndex(new BufferAttribute(typedArray, 1));
  23721. }
  23722. const attributes = json.data.attributes;
  23723. for (const key in attributes) {
  23724. const attribute = attributes[key];
  23725. let bufferAttribute;
  23726. if (attribute.isInterleavedBufferAttribute) {
  23727. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  23728. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  23729. } else {
  23730. const typedArray = getTypedArray(attribute.type, attribute.array);
  23731. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  23732. bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  23733. }
  23734. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  23735. if (attribute.usage !== undefined) bufferAttribute.setUsage(attribute.usage);
  23736. if (attribute.updateRange !== undefined) {
  23737. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  23738. bufferAttribute.updateRange.count = attribute.updateRange.count;
  23739. }
  23740. geometry.setAttribute(key, bufferAttribute);
  23741. }
  23742. const morphAttributes = json.data.morphAttributes;
  23743. if (morphAttributes) {
  23744. for (const key in morphAttributes) {
  23745. const attributeArray = morphAttributes[key];
  23746. const array = [];
  23747. for (let i = 0, il = attributeArray.length; i < il; i++) {
  23748. const attribute = attributeArray[i];
  23749. let bufferAttribute;
  23750. if (attribute.isInterleavedBufferAttribute) {
  23751. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  23752. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  23753. } else {
  23754. const typedArray = getTypedArray(attribute.type, attribute.array);
  23755. bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  23756. }
  23757. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  23758. array.push(bufferAttribute);
  23759. }
  23760. geometry.morphAttributes[key] = array;
  23761. }
  23762. }
  23763. const morphTargetsRelative = json.data.morphTargetsRelative;
  23764. if (morphTargetsRelative) {
  23765. geometry.morphTargetsRelative = true;
  23766. }
  23767. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  23768. if (groups !== undefined) {
  23769. for (let i = 0, n = groups.length; i !== n; ++i) {
  23770. const group = groups[i];
  23771. geometry.addGroup(group.start, group.count, group.materialIndex);
  23772. }
  23773. }
  23774. const boundingSphere = json.data.boundingSphere;
  23775. if (boundingSphere !== undefined) {
  23776. const center = new Vector3();
  23777. if (boundingSphere.center !== undefined) {
  23778. center.fromArray(boundingSphere.center);
  23779. }
  23780. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  23781. }
  23782. if (json.name) geometry.name = json.name;
  23783. if (json.userData) geometry.userData = json.userData;
  23784. return geometry;
  23785. }
  23786. }
  23787. class ObjectLoader extends Loader {
  23788. constructor(manager) {
  23789. super(manager);
  23790. }
  23791. load(url, onLoad, onProgress, onError) {
  23792. const scope = this;
  23793. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  23794. this.resourcePath = this.resourcePath || path;
  23795. const loader = new FileLoader(this.manager);
  23796. loader.setPath(this.path);
  23797. loader.setRequestHeader(this.requestHeader);
  23798. loader.setWithCredentials(this.withCredentials);
  23799. loader.load(url, function (text) {
  23800. let json = null;
  23801. try {
  23802. json = JSON.parse(text);
  23803. } catch (error) {
  23804. if (onError !== undefined) onError(error);
  23805. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  23806. return;
  23807. }
  23808. const metadata = json.metadata;
  23809. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  23810. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  23811. return;
  23812. }
  23813. scope.parse(json, onLoad);
  23814. }, onProgress, onError);
  23815. }
  23816. async loadAsync(url, onProgress) {
  23817. const scope = this;
  23818. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  23819. this.resourcePath = this.resourcePath || path;
  23820. const loader = new FileLoader(this.manager);
  23821. loader.setPath(this.path);
  23822. loader.setRequestHeader(this.requestHeader);
  23823. loader.setWithCredentials(this.withCredentials);
  23824. const text = await loader.loadAsync(url, onProgress);
  23825. const json = JSON.parse(text);
  23826. const metadata = json.metadata;
  23827. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  23828. throw new Error('THREE.ObjectLoader: Can\'t load ' + url);
  23829. }
  23830. return await scope.parseAsync(json);
  23831. }
  23832. parse(json, onLoad) {
  23833. const animations = this.parseAnimations(json.animations);
  23834. const shapes = this.parseShapes(json.shapes);
  23835. const geometries = this.parseGeometries(json.geometries, shapes);
  23836. const images = this.parseImages(json.images, function () {
  23837. if (onLoad !== undefined) onLoad(object);
  23838. });
  23839. const textures = this.parseTextures(json.textures, images);
  23840. const materials = this.parseMaterials(json.materials, textures);
  23841. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  23842. const skeletons = this.parseSkeletons(json.skeletons, object);
  23843. this.bindSkeletons(object, skeletons); //
  23844. if (onLoad !== undefined) {
  23845. let hasImages = false;
  23846. for (const uuid in images) {
  23847. if (images[uuid] instanceof HTMLImageElement) {
  23848. hasImages = true;
  23849. break;
  23850. }
  23851. }
  23852. if (hasImages === false) onLoad(object);
  23853. }
  23854. return object;
  23855. }
  23856. async parseAsync(json) {
  23857. const animations = this.parseAnimations(json.animations);
  23858. const shapes = this.parseShapes(json.shapes);
  23859. const geometries = this.parseGeometries(json.geometries, shapes);
  23860. const images = await this.parseImagesAsync(json.images);
  23861. const textures = this.parseTextures(json.textures, images);
  23862. const materials = this.parseMaterials(json.materials, textures);
  23863. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  23864. const skeletons = this.parseSkeletons(json.skeletons, object);
  23865. this.bindSkeletons(object, skeletons);
  23866. return object;
  23867. }
  23868. parseShapes(json) {
  23869. const shapes = {};
  23870. if (json !== undefined) {
  23871. for (let i = 0, l = json.length; i < l; i++) {
  23872. const shape = new Shape().fromJSON(json[i]);
  23873. shapes[shape.uuid] = shape;
  23874. }
  23875. }
  23876. return shapes;
  23877. }
  23878. parseSkeletons(json, object) {
  23879. const skeletons = {};
  23880. const bones = {}; // generate bone lookup table
  23881. object.traverse(function (child) {
  23882. if (child.isBone) bones[child.uuid] = child;
  23883. }); // create skeletons
  23884. if (json !== undefined) {
  23885. for (let i = 0, l = json.length; i < l; i++) {
  23886. const skeleton = new Skeleton().fromJSON(json[i], bones);
  23887. skeletons[skeleton.uuid] = skeleton;
  23888. }
  23889. }
  23890. return skeletons;
  23891. }
  23892. parseGeometries(json, shapes) {
  23893. const geometries = {};
  23894. if (json !== undefined) {
  23895. const bufferGeometryLoader = new BufferGeometryLoader();
  23896. for (let i = 0, l = json.length; i < l; i++) {
  23897. let geometry;
  23898. const data = json[i];
  23899. switch (data.type) {
  23900. case 'BufferGeometry':
  23901. case 'InstancedBufferGeometry':
  23902. geometry = bufferGeometryLoader.parse(data);
  23903. break;
  23904. case 'Geometry':
  23905. console.error('THREE.ObjectLoader: The legacy Geometry type is no longer supported.');
  23906. break;
  23907. default:
  23908. if (data.type in Geometries) {
  23909. geometry = Geometries[data.type].fromJSON(data, shapes);
  23910. } else {
  23911. console.warn(`THREE.ObjectLoader: Unsupported geometry type "${data.type}"`);
  23912. }
  23913. }
  23914. geometry.uuid = data.uuid;
  23915. if (data.name !== undefined) geometry.name = data.name;
  23916. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  23917. geometries[data.uuid] = geometry;
  23918. }
  23919. }
  23920. return geometries;
  23921. }
  23922. parseMaterials(json, textures) {
  23923. const cache = {}; // MultiMaterial
  23924. const materials = {};
  23925. if (json !== undefined) {
  23926. const loader = new MaterialLoader();
  23927. loader.setTextures(textures);
  23928. for (let i = 0, l = json.length; i < l; i++) {
  23929. const data = json[i];
  23930. if (data.type === 'MultiMaterial') {
  23931. // Deprecated
  23932. const array = [];
  23933. for (let j = 0; j < data.materials.length; j++) {
  23934. const material = data.materials[j];
  23935. if (cache[material.uuid] === undefined) {
  23936. cache[material.uuid] = loader.parse(material);
  23937. }
  23938. array.push(cache[material.uuid]);
  23939. }
  23940. materials[data.uuid] = array;
  23941. } else {
  23942. if (cache[data.uuid] === undefined) {
  23943. cache[data.uuid] = loader.parse(data);
  23944. }
  23945. materials[data.uuid] = cache[data.uuid];
  23946. }
  23947. }
  23948. }
  23949. return materials;
  23950. }
  23951. parseAnimations(json) {
  23952. const animations = {};
  23953. if (json !== undefined) {
  23954. for (let i = 0; i < json.length; i++) {
  23955. const data = json[i];
  23956. const clip = AnimationClip.parse(data);
  23957. animations[clip.uuid] = clip;
  23958. }
  23959. }
  23960. return animations;
  23961. }
  23962. parseImages(json, onLoad) {
  23963. const scope = this;
  23964. const images = {};
  23965. let loader;
  23966. function loadImage(url) {
  23967. scope.manager.itemStart(url);
  23968. return loader.load(url, function () {
  23969. scope.manager.itemEnd(url);
  23970. }, undefined, function () {
  23971. scope.manager.itemError(url);
  23972. scope.manager.itemEnd(url);
  23973. });
  23974. }
  23975. function deserializeImage(image) {
  23976. if (typeof image === 'string') {
  23977. const url = image;
  23978. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  23979. return loadImage(path);
  23980. } else {
  23981. if (image.data) {
  23982. return {
  23983. data: getTypedArray(image.type, image.data),
  23984. width: image.width,
  23985. height: image.height
  23986. };
  23987. } else {
  23988. return null;
  23989. }
  23990. }
  23991. }
  23992. if (json !== undefined && json.length > 0) {
  23993. const manager = new LoadingManager(onLoad);
  23994. loader = new ImageLoader(manager);
  23995. loader.setCrossOrigin(this.crossOrigin);
  23996. for (let i = 0, il = json.length; i < il; i++) {
  23997. const image = json[i];
  23998. const url = image.url;
  23999. if (Array.isArray(url)) {
  24000. // load array of images e.g CubeTexture
  24001. images[image.uuid] = [];
  24002. for (let j = 0, jl = url.length; j < jl; j++) {
  24003. const currentUrl = url[j];
  24004. const deserializedImage = deserializeImage(currentUrl);
  24005. if (deserializedImage !== null) {
  24006. if (deserializedImage instanceof HTMLImageElement) {
  24007. images[image.uuid].push(deserializedImage);
  24008. } else {
  24009. // special case: handle array of data textures for cube textures
  24010. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  24011. }
  24012. }
  24013. }
  24014. } else {
  24015. // load single image
  24016. const deserializedImage = deserializeImage(image.url);
  24017. if (deserializedImage !== null) {
  24018. images[image.uuid] = deserializedImage;
  24019. }
  24020. }
  24021. }
  24022. }
  24023. return images;
  24024. }
  24025. async parseImagesAsync(json) {
  24026. const scope = this;
  24027. const images = {};
  24028. let loader;
  24029. async function deserializeImage(image) {
  24030. if (typeof image === 'string') {
  24031. const url = image;
  24032. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  24033. return await loader.loadAsync(path);
  24034. } else {
  24035. if (image.data) {
  24036. return {
  24037. data: getTypedArray(image.type, image.data),
  24038. width: image.width,
  24039. height: image.height
  24040. };
  24041. } else {
  24042. return null;
  24043. }
  24044. }
  24045. }
  24046. if (json !== undefined && json.length > 0) {
  24047. loader = new ImageLoader(this.manager);
  24048. loader.setCrossOrigin(this.crossOrigin);
  24049. for (let i = 0, il = json.length; i < il; i++) {
  24050. const image = json[i];
  24051. const url = image.url;
  24052. if (Array.isArray(url)) {
  24053. // load array of images e.g CubeTexture
  24054. images[image.uuid] = [];
  24055. for (let j = 0, jl = url.length; j < jl; j++) {
  24056. const currentUrl = url[j];
  24057. const deserializedImage = await deserializeImage(currentUrl);
  24058. if (deserializedImage !== null) {
  24059. if (deserializedImage instanceof HTMLImageElement) {
  24060. images[image.uuid].push(deserializedImage);
  24061. } else {
  24062. // special case: handle array of data textures for cube textures
  24063. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  24064. }
  24065. }
  24066. }
  24067. } else {
  24068. // load single image
  24069. const deserializedImage = await deserializeImage(image.url);
  24070. if (deserializedImage !== null) {
  24071. images[image.uuid] = deserializedImage;
  24072. }
  24073. }
  24074. }
  24075. }
  24076. return images;
  24077. }
  24078. parseTextures(json, images) {
  24079. function parseConstant(value, type) {
  24080. if (typeof value === 'number') return value;
  24081. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  24082. return type[value];
  24083. }
  24084. const textures = {};
  24085. if (json !== undefined) {
  24086. for (let i = 0, l = json.length; i < l; i++) {
  24087. const data = json[i];
  24088. if (data.image === undefined) {
  24089. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  24090. }
  24091. if (images[data.image] === undefined) {
  24092. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  24093. }
  24094. let texture;
  24095. const image = images[data.image];
  24096. if (Array.isArray(image)) {
  24097. texture = new CubeTexture(image);
  24098. if (image.length === 6) texture.needsUpdate = true;
  24099. } else {
  24100. if (image && image.data) {
  24101. texture = new DataTexture(image.data, image.width, image.height);
  24102. } else {
  24103. texture = new Texture(image);
  24104. }
  24105. if (image) texture.needsUpdate = true; // textures can have undefined image data
  24106. }
  24107. texture.uuid = data.uuid;
  24108. if (data.name !== undefined) texture.name = data.name;
  24109. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  24110. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  24111. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  24112. if (data.center !== undefined) texture.center.fromArray(data.center);
  24113. if (data.rotation !== undefined) texture.rotation = data.rotation;
  24114. if (data.wrap !== undefined) {
  24115. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  24116. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  24117. }
  24118. if (data.format !== undefined) texture.format = data.format;
  24119. if (data.type !== undefined) texture.type = data.type;
  24120. if (data.encoding !== undefined) texture.encoding = data.encoding;
  24121. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  24122. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  24123. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  24124. if (data.flipY !== undefined) texture.flipY = data.flipY;
  24125. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  24126. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  24127. textures[data.uuid] = texture;
  24128. }
  24129. }
  24130. return textures;
  24131. }
  24132. parseObject(data, geometries, materials, textures, animations) {
  24133. let object;
  24134. function getGeometry(name) {
  24135. if (geometries[name] === undefined) {
  24136. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  24137. }
  24138. return geometries[name];
  24139. }
  24140. function getMaterial(name) {
  24141. if (name === undefined) return undefined;
  24142. if (Array.isArray(name)) {
  24143. const array = [];
  24144. for (let i = 0, l = name.length; i < l; i++) {
  24145. const uuid = name[i];
  24146. if (materials[uuid] === undefined) {
  24147. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  24148. }
  24149. array.push(materials[uuid]);
  24150. }
  24151. return array;
  24152. }
  24153. if (materials[name] === undefined) {
  24154. console.warn('THREE.ObjectLoader: Undefined material', name);
  24155. }
  24156. return materials[name];
  24157. }
  24158. function getTexture(uuid) {
  24159. if (textures[uuid] === undefined) {
  24160. console.warn('THREE.ObjectLoader: Undefined texture', uuid);
  24161. }
  24162. return textures[uuid];
  24163. }
  24164. let geometry, material;
  24165. switch (data.type) {
  24166. case 'Scene':
  24167. object = new Scene();
  24168. if (data.background !== undefined) {
  24169. if (Number.isInteger(data.background)) {
  24170. object.background = new Color(data.background);
  24171. } else {
  24172. object.background = getTexture(data.background);
  24173. }
  24174. }
  24175. if (data.environment !== undefined) {
  24176. object.environment = getTexture(data.environment);
  24177. }
  24178. if (data.fog !== undefined) {
  24179. if (data.fog.type === 'Fog') {
  24180. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  24181. } else if (data.fog.type === 'FogExp2') {
  24182. object.fog = new FogExp2(data.fog.color, data.fog.density);
  24183. }
  24184. }
  24185. break;
  24186. case 'PerspectiveCamera':
  24187. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  24188. if (data.focus !== undefined) object.focus = data.focus;
  24189. if (data.zoom !== undefined) object.zoom = data.zoom;
  24190. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  24191. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  24192. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24193. break;
  24194. case 'OrthographicCamera':
  24195. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  24196. if (data.zoom !== undefined) object.zoom = data.zoom;
  24197. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24198. break;
  24199. case 'AmbientLight':
  24200. object = new AmbientLight(data.color, data.intensity);
  24201. break;
  24202. case 'DirectionalLight':
  24203. object = new DirectionalLight(data.color, data.intensity);
  24204. break;
  24205. case 'PointLight':
  24206. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  24207. break;
  24208. case 'RectAreaLight':
  24209. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  24210. break;
  24211. case 'SpotLight':
  24212. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  24213. break;
  24214. case 'HemisphereLight':
  24215. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  24216. break;
  24217. case 'LightProbe':
  24218. object = new LightProbe().fromJSON(data);
  24219. break;
  24220. case 'SkinnedMesh':
  24221. geometry = getGeometry(data.geometry);
  24222. material = getMaterial(data.material);
  24223. object = new SkinnedMesh(geometry, material);
  24224. if (data.bindMode !== undefined) object.bindMode = data.bindMode;
  24225. if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
  24226. if (data.skeleton !== undefined) object.skeleton = data.skeleton;
  24227. break;
  24228. case 'Mesh':
  24229. geometry = getGeometry(data.geometry);
  24230. material = getMaterial(data.material);
  24231. object = new Mesh(geometry, material);
  24232. break;
  24233. case 'InstancedMesh':
  24234. geometry = getGeometry(data.geometry);
  24235. material = getMaterial(data.material);
  24236. const count = data.count;
  24237. const instanceMatrix = data.instanceMatrix;
  24238. const instanceColor = data.instanceColor;
  24239. object = new InstancedMesh(geometry, material, count);
  24240. object.instanceMatrix = new BufferAttribute(new Float32Array(instanceMatrix.array), 16);
  24241. if (instanceColor !== undefined) object.instanceColor = new BufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize);
  24242. break;
  24243. case 'LOD':
  24244. object = new LOD();
  24245. break;
  24246. case 'Line':
  24247. object = new Line(getGeometry(data.geometry), getMaterial(data.material));
  24248. break;
  24249. case 'LineLoop':
  24250. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  24251. break;
  24252. case 'LineSegments':
  24253. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  24254. break;
  24255. case 'PointCloud':
  24256. case 'Points':
  24257. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  24258. break;
  24259. case 'Sprite':
  24260. object = new Sprite(getMaterial(data.material));
  24261. break;
  24262. case 'Group':
  24263. object = new Group();
  24264. break;
  24265. case 'Bone':
  24266. object = new Bone();
  24267. break;
  24268. default:
  24269. object = new Object3D();
  24270. }
  24271. object.uuid = data.uuid;
  24272. if (data.name !== undefined) object.name = data.name;
  24273. if (data.matrix !== undefined) {
  24274. object.matrix.fromArray(data.matrix);
  24275. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  24276. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  24277. } else {
  24278. if (data.position !== undefined) object.position.fromArray(data.position);
  24279. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  24280. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  24281. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  24282. }
  24283. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  24284. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  24285. if (data.shadow) {
  24286. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  24287. if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
  24288. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  24289. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  24290. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  24291. }
  24292. if (data.visible !== undefined) object.visible = data.visible;
  24293. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  24294. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  24295. if (data.userData !== undefined) object.userData = data.userData;
  24296. if (data.layers !== undefined) object.layers.mask = data.layers;
  24297. if (data.children !== undefined) {
  24298. const children = data.children;
  24299. for (let i = 0; i < children.length; i++) {
  24300. object.add(this.parseObject(children[i], geometries, materials, textures, animations));
  24301. }
  24302. }
  24303. if (data.animations !== undefined) {
  24304. const objectAnimations = data.animations;
  24305. for (let i = 0; i < objectAnimations.length; i++) {
  24306. const uuid = objectAnimations[i];
  24307. object.animations.push(animations[uuid]);
  24308. }
  24309. }
  24310. if (data.type === 'LOD') {
  24311. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  24312. const levels = data.levels;
  24313. for (let l = 0; l < levels.length; l++) {
  24314. const level = levels[l];
  24315. const child = object.getObjectByProperty('uuid', level.object);
  24316. if (child !== undefined) {
  24317. object.addLevel(child, level.distance);
  24318. }
  24319. }
  24320. }
  24321. return object;
  24322. }
  24323. bindSkeletons(object, skeletons) {
  24324. if (Object.keys(skeletons).length === 0) return;
  24325. object.traverse(function (child) {
  24326. if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
  24327. const skeleton = skeletons[child.skeleton];
  24328. if (skeleton === undefined) {
  24329. console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
  24330. } else {
  24331. child.bind(skeleton, child.bindMatrix);
  24332. }
  24333. }
  24334. });
  24335. }
  24336. /* DEPRECATED */
  24337. setTexturePath(value) {
  24338. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  24339. return this.setResourcePath(value);
  24340. }
  24341. }
  24342. const TEXTURE_MAPPING = {
  24343. UVMapping: UVMapping,
  24344. CubeReflectionMapping: CubeReflectionMapping,
  24345. CubeRefractionMapping: CubeRefractionMapping,
  24346. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  24347. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  24348. CubeUVReflectionMapping: CubeUVReflectionMapping,
  24349. CubeUVRefractionMapping: CubeUVRefractionMapping
  24350. };
  24351. const TEXTURE_WRAPPING = {
  24352. RepeatWrapping: RepeatWrapping,
  24353. ClampToEdgeWrapping: ClampToEdgeWrapping,
  24354. MirroredRepeatWrapping: MirroredRepeatWrapping
  24355. };
  24356. const TEXTURE_FILTER = {
  24357. NearestFilter: NearestFilter,
  24358. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  24359. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  24360. LinearFilter: LinearFilter,
  24361. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  24362. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  24363. };
  24364. class ImageBitmapLoader extends Loader {
  24365. constructor(manager) {
  24366. super(manager);
  24367. if (typeof createImageBitmap === 'undefined') {
  24368. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  24369. }
  24370. if (typeof fetch === 'undefined') {
  24371. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  24372. }
  24373. this.options = {
  24374. premultiplyAlpha: 'none'
  24375. };
  24376. }
  24377. setOptions(options) {
  24378. this.options = options;
  24379. return this;
  24380. }
  24381. load(url, onLoad, onProgress, onError) {
  24382. if (url === undefined) url = '';
  24383. if (this.path !== undefined) url = this.path + url;
  24384. url = this.manager.resolveURL(url);
  24385. const scope = this;
  24386. const cached = Cache.get(url);
  24387. if (cached !== undefined) {
  24388. scope.manager.itemStart(url);
  24389. setTimeout(function () {
  24390. if (onLoad) onLoad(cached);
  24391. scope.manager.itemEnd(url);
  24392. }, 0);
  24393. return cached;
  24394. }
  24395. const fetchOptions = {};
  24396. fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
  24397. fetchOptions.headers = this.requestHeader;
  24398. fetch(url, fetchOptions).then(function (res) {
  24399. return res.blob();
  24400. }).then(function (blob) {
  24401. return createImageBitmap(blob, Object.assign(scope.options, {
  24402. colorSpaceConversion: 'none'
  24403. }));
  24404. }).then(function (imageBitmap) {
  24405. Cache.add(url, imageBitmap);
  24406. if (onLoad) onLoad(imageBitmap);
  24407. scope.manager.itemEnd(url);
  24408. }).catch(function (e) {
  24409. if (onError) onError(e);
  24410. scope.manager.itemError(url);
  24411. scope.manager.itemEnd(url);
  24412. });
  24413. scope.manager.itemStart(url);
  24414. }
  24415. }
  24416. ImageBitmapLoader.prototype.isImageBitmapLoader = true;
  24417. class ShapePath {
  24418. constructor() {
  24419. this.type = 'ShapePath';
  24420. this.color = new Color();
  24421. this.subPaths = [];
  24422. this.currentPath = null;
  24423. }
  24424. moveTo(x, y) {
  24425. this.currentPath = new Path();
  24426. this.subPaths.push(this.currentPath);
  24427. this.currentPath.moveTo(x, y);
  24428. return this;
  24429. }
  24430. lineTo(x, y) {
  24431. this.currentPath.lineTo(x, y);
  24432. return this;
  24433. }
  24434. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  24435. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  24436. return this;
  24437. }
  24438. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  24439. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  24440. return this;
  24441. }
  24442. splineThru(pts) {
  24443. this.currentPath.splineThru(pts);
  24444. return this;
  24445. }
  24446. toShapes(isCCW, noHoles) {
  24447. function toShapesNoHoles(inSubpaths) {
  24448. const shapes = [];
  24449. for (let i = 0, l = inSubpaths.length; i < l; i++) {
  24450. const tmpPath = inSubpaths[i];
  24451. const tmpShape = new Shape();
  24452. tmpShape.curves = tmpPath.curves;
  24453. shapes.push(tmpShape);
  24454. }
  24455. return shapes;
  24456. }
  24457. function isPointInsidePolygon(inPt, inPolygon) {
  24458. const polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  24459. // toggling of inside/outside at every single! intersection point of an edge
  24460. // with the horizontal line through inPt, left of inPt
  24461. // not counting lowerY endpoints of edges and whole edges on that line
  24462. let inside = false;
  24463. for (let p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  24464. let edgeLowPt = inPolygon[p];
  24465. let edgeHighPt = inPolygon[q];
  24466. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  24467. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  24468. if (Math.abs(edgeDy) > Number.EPSILON) {
  24469. // not parallel
  24470. if (edgeDy < 0) {
  24471. edgeLowPt = inPolygon[q];
  24472. edgeDx = -edgeDx;
  24473. edgeHighPt = inPolygon[p];
  24474. edgeDy = -edgeDy;
  24475. }
  24476. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  24477. if (inPt.y === edgeLowPt.y) {
  24478. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  24479. // continue; // no intersection or edgeLowPt => doesn't count !!!
  24480. } else {
  24481. const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  24482. if (perpEdge === 0) return true; // inPt is on contour ?
  24483. if (perpEdge < 0) continue;
  24484. inside = !inside; // true intersection left of inPt
  24485. }
  24486. } else {
  24487. // parallel or collinear
  24488. if (inPt.y !== edgeLowPt.y) continue; // parallel
  24489. // edge lies on the same horizontal line as inPt
  24490. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  24491. // continue;
  24492. }
  24493. }
  24494. return inside;
  24495. }
  24496. const isClockWise = ShapeUtils.isClockWise;
  24497. const subPaths = this.subPaths;
  24498. if (subPaths.length === 0) return [];
  24499. if (noHoles === true) return toShapesNoHoles(subPaths);
  24500. let solid, tmpPath, tmpShape;
  24501. const shapes = [];
  24502. if (subPaths.length === 1) {
  24503. tmpPath = subPaths[0];
  24504. tmpShape = new Shape();
  24505. tmpShape.curves = tmpPath.curves;
  24506. shapes.push(tmpShape);
  24507. return shapes;
  24508. }
  24509. let holesFirst = !isClockWise(subPaths[0].getPoints());
  24510. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  24511. const betterShapeHoles = [];
  24512. const newShapes = [];
  24513. let newShapeHoles = [];
  24514. let mainIdx = 0;
  24515. let tmpPoints;
  24516. newShapes[mainIdx] = undefined;
  24517. newShapeHoles[mainIdx] = [];
  24518. for (let i = 0, l = subPaths.length; i < l; i++) {
  24519. tmpPath = subPaths[i];
  24520. tmpPoints = tmpPath.getPoints();
  24521. solid = isClockWise(tmpPoints);
  24522. solid = isCCW ? !solid : solid;
  24523. if (solid) {
  24524. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  24525. newShapes[mainIdx] = {
  24526. s: new Shape(),
  24527. p: tmpPoints
  24528. };
  24529. newShapes[mainIdx].s.curves = tmpPath.curves;
  24530. if (holesFirst) mainIdx++;
  24531. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  24532. } else {
  24533. newShapeHoles[mainIdx].push({
  24534. h: tmpPath,
  24535. p: tmpPoints[0]
  24536. }); //console.log('ccw', i);
  24537. }
  24538. } // only Holes? -> probably all Shapes with wrong orientation
  24539. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  24540. if (newShapes.length > 1) {
  24541. let ambiguous = false;
  24542. const toChange = [];
  24543. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  24544. betterShapeHoles[sIdx] = [];
  24545. }
  24546. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  24547. const sho = newShapeHoles[sIdx];
  24548. for (let hIdx = 0; hIdx < sho.length; hIdx++) {
  24549. const ho = sho[hIdx];
  24550. let hole_unassigned = true;
  24551. for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  24552. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  24553. if (sIdx !== s2Idx) toChange.push({
  24554. froms: sIdx,
  24555. tos: s2Idx,
  24556. hole: hIdx
  24557. });
  24558. if (hole_unassigned) {
  24559. hole_unassigned = false;
  24560. betterShapeHoles[s2Idx].push(ho);
  24561. } else {
  24562. ambiguous = true;
  24563. }
  24564. }
  24565. }
  24566. if (hole_unassigned) {
  24567. betterShapeHoles[sIdx].push(ho);
  24568. }
  24569. }
  24570. } // console.log("ambiguous: ", ambiguous);
  24571. if (toChange.length > 0) {
  24572. // console.log("to change: ", toChange);
  24573. if (!ambiguous) newShapeHoles = betterShapeHoles;
  24574. }
  24575. }
  24576. let tmpHoles;
  24577. for (let i = 0, il = newShapes.length; i < il; i++) {
  24578. tmpShape = newShapes[i].s;
  24579. shapes.push(tmpShape);
  24580. tmpHoles = newShapeHoles[i];
  24581. for (let j = 0, jl = tmpHoles.length; j < jl; j++) {
  24582. tmpShape.holes.push(tmpHoles[j].h);
  24583. }
  24584. } //console.log("shape", shapes);
  24585. return shapes;
  24586. }
  24587. }
  24588. class Font {
  24589. constructor(data) {
  24590. this.type = 'Font';
  24591. this.data = data;
  24592. }
  24593. generateShapes(text, size = 100) {
  24594. const shapes = [];
  24595. const paths = createPaths(text, size, this.data);
  24596. for (let p = 0, pl = paths.length; p < pl; p++) {
  24597. Array.prototype.push.apply(shapes, paths[p].toShapes());
  24598. }
  24599. return shapes;
  24600. }
  24601. }
  24602. function createPaths(text, size, data) {
  24603. const chars = Array.from(text);
  24604. const scale = size / data.resolution;
  24605. const line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
  24606. const paths = [];
  24607. let offsetX = 0,
  24608. offsetY = 0;
  24609. for (let i = 0; i < chars.length; i++) {
  24610. const char = chars[i];
  24611. if (char === '\n') {
  24612. offsetX = 0;
  24613. offsetY -= line_height;
  24614. } else {
  24615. const ret = createPath(char, scale, offsetX, offsetY, data);
  24616. offsetX += ret.offsetX;
  24617. paths.push(ret.path);
  24618. }
  24619. }
  24620. return paths;
  24621. }
  24622. function createPath(char, scale, offsetX, offsetY, data) {
  24623. const glyph = data.glyphs[char] || data.glyphs['?'];
  24624. if (!glyph) {
  24625. console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
  24626. return;
  24627. }
  24628. const path = new ShapePath();
  24629. let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  24630. if (glyph.o) {
  24631. const outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
  24632. for (let i = 0, l = outline.length; i < l;) {
  24633. const action = outline[i++];
  24634. switch (action) {
  24635. case 'm':
  24636. // moveTo
  24637. x = outline[i++] * scale + offsetX;
  24638. y = outline[i++] * scale + offsetY;
  24639. path.moveTo(x, y);
  24640. break;
  24641. case 'l':
  24642. // lineTo
  24643. x = outline[i++] * scale + offsetX;
  24644. y = outline[i++] * scale + offsetY;
  24645. path.lineTo(x, y);
  24646. break;
  24647. case 'q':
  24648. // quadraticCurveTo
  24649. cpx = outline[i++] * scale + offsetX;
  24650. cpy = outline[i++] * scale + offsetY;
  24651. cpx1 = outline[i++] * scale + offsetX;
  24652. cpy1 = outline[i++] * scale + offsetY;
  24653. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  24654. break;
  24655. case 'b':
  24656. // bezierCurveTo
  24657. cpx = outline[i++] * scale + offsetX;
  24658. cpy = outline[i++] * scale + offsetY;
  24659. cpx1 = outline[i++] * scale + offsetX;
  24660. cpy1 = outline[i++] * scale + offsetY;
  24661. cpx2 = outline[i++] * scale + offsetX;
  24662. cpy2 = outline[i++] * scale + offsetY;
  24663. path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
  24664. break;
  24665. }
  24666. }
  24667. }
  24668. return {
  24669. offsetX: glyph.ha * scale,
  24670. path: path
  24671. };
  24672. }
  24673. Font.prototype.isFont = true;
  24674. class FontLoader extends Loader {
  24675. constructor(manager) {
  24676. super(manager);
  24677. }
  24678. load(url, onLoad, onProgress, onError) {
  24679. const scope = this;
  24680. const loader = new FileLoader(this.manager);
  24681. loader.setPath(this.path);
  24682. loader.setRequestHeader(this.requestHeader);
  24683. loader.setWithCredentials(scope.withCredentials);
  24684. loader.load(url, function (text) {
  24685. let json;
  24686. try {
  24687. json = JSON.parse(text);
  24688. } catch (e) {
  24689. console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
  24690. json = JSON.parse(text.substring(65, text.length - 2));
  24691. }
  24692. const font = scope.parse(json);
  24693. if (onLoad) onLoad(font);
  24694. }, onProgress, onError);
  24695. }
  24696. parse(json) {
  24697. return new Font(json);
  24698. }
  24699. }
  24700. let _context;
  24701. const AudioContext = {
  24702. getContext: function () {
  24703. if (_context === undefined) {
  24704. _context = new (window.AudioContext || window.webkitAudioContext)();
  24705. }
  24706. return _context;
  24707. },
  24708. setContext: function (value) {
  24709. _context = value;
  24710. }
  24711. };
  24712. class AudioLoader extends Loader {
  24713. constructor(manager) {
  24714. super(manager);
  24715. }
  24716. load(url, onLoad, onProgress, onError) {
  24717. const scope = this;
  24718. const loader = new FileLoader(this.manager);
  24719. loader.setResponseType('arraybuffer');
  24720. loader.setPath(this.path);
  24721. loader.setRequestHeader(this.requestHeader);
  24722. loader.setWithCredentials(this.withCredentials);
  24723. loader.load(url, function (buffer) {
  24724. try {
  24725. // Create a copy of the buffer. The `decodeAudioData` method
  24726. // detaches the buffer when complete, preventing reuse.
  24727. const bufferCopy = buffer.slice(0);
  24728. const context = AudioContext.getContext();
  24729. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  24730. onLoad(audioBuffer);
  24731. });
  24732. } catch (e) {
  24733. if (onError) {
  24734. onError(e);
  24735. } else {
  24736. console.error(e);
  24737. }
  24738. scope.manager.itemError(url);
  24739. }
  24740. }, onProgress, onError);
  24741. }
  24742. }
  24743. class HemisphereLightProbe extends LightProbe {
  24744. constructor(skyColor, groundColor, intensity = 1) {
  24745. super(undefined, intensity);
  24746. const color1 = new Color().set(skyColor);
  24747. const color2 = new Color().set(groundColor);
  24748. const sky = new Vector3(color1.r, color1.g, color1.b);
  24749. const ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  24750. const c0 = Math.sqrt(Math.PI);
  24751. const c1 = c0 * Math.sqrt(0.75);
  24752. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  24753. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  24754. }
  24755. }
  24756. HemisphereLightProbe.prototype.isHemisphereLightProbe = true;
  24757. class AmbientLightProbe extends LightProbe {
  24758. constructor(color, intensity = 1) {
  24759. super(undefined, intensity);
  24760. const color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  24761. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  24762. }
  24763. }
  24764. AmbientLightProbe.prototype.isAmbientLightProbe = true;
  24765. const _eyeRight = /*@__PURE__*/new Matrix4();
  24766. const _eyeLeft = /*@__PURE__*/new Matrix4();
  24767. class StereoCamera {
  24768. constructor() {
  24769. this.type = 'StereoCamera';
  24770. this.aspect = 1;
  24771. this.eyeSep = 0.064;
  24772. this.cameraL = new PerspectiveCamera();
  24773. this.cameraL.layers.enable(1);
  24774. this.cameraL.matrixAutoUpdate = false;
  24775. this.cameraR = new PerspectiveCamera();
  24776. this.cameraR.layers.enable(2);
  24777. this.cameraR.matrixAutoUpdate = false;
  24778. this._cache = {
  24779. focus: null,
  24780. fov: null,
  24781. aspect: null,
  24782. near: null,
  24783. far: null,
  24784. zoom: null,
  24785. eyeSep: null
  24786. };
  24787. }
  24788. update(camera) {
  24789. const cache = this._cache;
  24790. 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;
  24791. if (needsUpdate) {
  24792. cache.focus = camera.focus;
  24793. cache.fov = camera.fov;
  24794. cache.aspect = camera.aspect * this.aspect;
  24795. cache.near = camera.near;
  24796. cache.far = camera.far;
  24797. cache.zoom = camera.zoom;
  24798. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  24799. // http://paulbourke.net/stereographics/stereorender/
  24800. const projectionMatrix = camera.projectionMatrix.clone();
  24801. const eyeSepHalf = cache.eyeSep / 2;
  24802. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  24803. const ymax = cache.near * Math.tan(DEG2RAD * cache.fov * 0.5) / cache.zoom;
  24804. let xmin, xmax; // translate xOffset
  24805. _eyeLeft.elements[12] = -eyeSepHalf;
  24806. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  24807. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  24808. xmax = ymax * cache.aspect + eyeSepOnProjection;
  24809. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  24810. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  24811. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  24812. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  24813. xmax = ymax * cache.aspect - eyeSepOnProjection;
  24814. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  24815. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  24816. this.cameraR.projectionMatrix.copy(projectionMatrix);
  24817. }
  24818. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  24819. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  24820. }
  24821. }
  24822. class Clock {
  24823. constructor(autoStart = true) {
  24824. this.autoStart = autoStart;
  24825. this.startTime = 0;
  24826. this.oldTime = 0;
  24827. this.elapsedTime = 0;
  24828. this.running = false;
  24829. }
  24830. start() {
  24831. this.startTime = now();
  24832. this.oldTime = this.startTime;
  24833. this.elapsedTime = 0;
  24834. this.running = true;
  24835. }
  24836. stop() {
  24837. this.getElapsedTime();
  24838. this.running = false;
  24839. this.autoStart = false;
  24840. }
  24841. getElapsedTime() {
  24842. this.getDelta();
  24843. return this.elapsedTime;
  24844. }
  24845. getDelta() {
  24846. let diff = 0;
  24847. if (this.autoStart && !this.running) {
  24848. this.start();
  24849. return 0;
  24850. }
  24851. if (this.running) {
  24852. const newTime = now();
  24853. diff = (newTime - this.oldTime) / 1000;
  24854. this.oldTime = newTime;
  24855. this.elapsedTime += diff;
  24856. }
  24857. return diff;
  24858. }
  24859. }
  24860. function now() {
  24861. return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  24862. }
  24863. const _position$1 = /*@__PURE__*/new Vector3();
  24864. const _quaternion$1 = /*@__PURE__*/new Quaternion();
  24865. const _scale$1 = /*@__PURE__*/new Vector3();
  24866. const _orientation$1 = /*@__PURE__*/new Vector3();
  24867. class AudioListener extends Object3D {
  24868. constructor() {
  24869. super();
  24870. this.type = 'AudioListener';
  24871. this.context = AudioContext.getContext();
  24872. this.gain = this.context.createGain();
  24873. this.gain.connect(this.context.destination);
  24874. this.filter = null;
  24875. this.timeDelta = 0; // private
  24876. this._clock = new Clock();
  24877. }
  24878. getInput() {
  24879. return this.gain;
  24880. }
  24881. removeFilter() {
  24882. if (this.filter !== null) {
  24883. this.gain.disconnect(this.filter);
  24884. this.filter.disconnect(this.context.destination);
  24885. this.gain.connect(this.context.destination);
  24886. this.filter = null;
  24887. }
  24888. return this;
  24889. }
  24890. getFilter() {
  24891. return this.filter;
  24892. }
  24893. setFilter(value) {
  24894. if (this.filter !== null) {
  24895. this.gain.disconnect(this.filter);
  24896. this.filter.disconnect(this.context.destination);
  24897. } else {
  24898. this.gain.disconnect(this.context.destination);
  24899. }
  24900. this.filter = value;
  24901. this.gain.connect(this.filter);
  24902. this.filter.connect(this.context.destination);
  24903. return this;
  24904. }
  24905. getMasterVolume() {
  24906. return this.gain.gain.value;
  24907. }
  24908. setMasterVolume(value) {
  24909. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  24910. return this;
  24911. }
  24912. updateMatrixWorld(force) {
  24913. super.updateMatrixWorld(force);
  24914. const listener = this.context.listener;
  24915. const up = this.up;
  24916. this.timeDelta = this._clock.getDelta();
  24917. this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1);
  24918. _orientation$1.set(0, 0, -1).applyQuaternion(_quaternion$1);
  24919. if (listener.positionX) {
  24920. // code path for Chrome (see #14393)
  24921. const endTime = this.context.currentTime + this.timeDelta;
  24922. listener.positionX.linearRampToValueAtTime(_position$1.x, endTime);
  24923. listener.positionY.linearRampToValueAtTime(_position$1.y, endTime);
  24924. listener.positionZ.linearRampToValueAtTime(_position$1.z, endTime);
  24925. listener.forwardX.linearRampToValueAtTime(_orientation$1.x, endTime);
  24926. listener.forwardY.linearRampToValueAtTime(_orientation$1.y, endTime);
  24927. listener.forwardZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  24928. listener.upX.linearRampToValueAtTime(up.x, endTime);
  24929. listener.upY.linearRampToValueAtTime(up.y, endTime);
  24930. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  24931. } else {
  24932. listener.setPosition(_position$1.x, _position$1.y, _position$1.z);
  24933. listener.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z);
  24934. }
  24935. }
  24936. }
  24937. class Audio extends Object3D {
  24938. constructor(listener) {
  24939. super();
  24940. this.type = 'Audio';
  24941. this.listener = listener;
  24942. this.context = listener.context;
  24943. this.gain = this.context.createGain();
  24944. this.gain.connect(listener.getInput());
  24945. this.autoplay = false;
  24946. this.buffer = null;
  24947. this.detune = 0;
  24948. this.loop = false;
  24949. this.loopStart = 0;
  24950. this.loopEnd = 0;
  24951. this.offset = 0;
  24952. this.duration = undefined;
  24953. this.playbackRate = 1;
  24954. this.isPlaying = false;
  24955. this.hasPlaybackControl = true;
  24956. this.source = null;
  24957. this.sourceType = 'empty';
  24958. this._startedAt = 0;
  24959. this._progress = 0;
  24960. this._connected = false;
  24961. this.filters = [];
  24962. }
  24963. getOutput() {
  24964. return this.gain;
  24965. }
  24966. setNodeSource(audioNode) {
  24967. this.hasPlaybackControl = false;
  24968. this.sourceType = 'audioNode';
  24969. this.source = audioNode;
  24970. this.connect();
  24971. return this;
  24972. }
  24973. setMediaElementSource(mediaElement) {
  24974. this.hasPlaybackControl = false;
  24975. this.sourceType = 'mediaNode';
  24976. this.source = this.context.createMediaElementSource(mediaElement);
  24977. this.connect();
  24978. return this;
  24979. }
  24980. setMediaStreamSource(mediaStream) {
  24981. this.hasPlaybackControl = false;
  24982. this.sourceType = 'mediaStreamNode';
  24983. this.source = this.context.createMediaStreamSource(mediaStream);
  24984. this.connect();
  24985. return this;
  24986. }
  24987. setBuffer(audioBuffer) {
  24988. this.buffer = audioBuffer;
  24989. this.sourceType = 'buffer';
  24990. if (this.autoplay) this.play();
  24991. return this;
  24992. }
  24993. play(delay = 0) {
  24994. if (this.isPlaying === true) {
  24995. console.warn('THREE.Audio: Audio is already playing.');
  24996. return;
  24997. }
  24998. if (this.hasPlaybackControl === false) {
  24999. console.warn('THREE.Audio: this Audio has no playback control.');
  25000. return;
  25001. }
  25002. this._startedAt = this.context.currentTime + delay;
  25003. const source = this.context.createBufferSource();
  25004. source.buffer = this.buffer;
  25005. source.loop = this.loop;
  25006. source.loopStart = this.loopStart;
  25007. source.loopEnd = this.loopEnd;
  25008. source.onended = this.onEnded.bind(this);
  25009. source.start(this._startedAt, this._progress + this.offset, this.duration);
  25010. this.isPlaying = true;
  25011. this.source = source;
  25012. this.setDetune(this.detune);
  25013. this.setPlaybackRate(this.playbackRate);
  25014. return this.connect();
  25015. }
  25016. pause() {
  25017. if (this.hasPlaybackControl === false) {
  25018. console.warn('THREE.Audio: this Audio has no playback control.');
  25019. return;
  25020. }
  25021. if (this.isPlaying === true) {
  25022. // update current progress
  25023. this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  25024. if (this.loop === true) {
  25025. // ensure _progress does not exceed duration with looped audios
  25026. this._progress = this._progress % (this.duration || this.buffer.duration);
  25027. }
  25028. this.source.stop();
  25029. this.source.onended = null;
  25030. this.isPlaying = false;
  25031. }
  25032. return this;
  25033. }
  25034. stop() {
  25035. if (this.hasPlaybackControl === false) {
  25036. console.warn('THREE.Audio: this Audio has no playback control.');
  25037. return;
  25038. }
  25039. this._progress = 0;
  25040. this.source.stop();
  25041. this.source.onended = null;
  25042. this.isPlaying = false;
  25043. return this;
  25044. }
  25045. connect() {
  25046. if (this.filters.length > 0) {
  25047. this.source.connect(this.filters[0]);
  25048. for (let i = 1, l = this.filters.length; i < l; i++) {
  25049. this.filters[i - 1].connect(this.filters[i]);
  25050. }
  25051. this.filters[this.filters.length - 1].connect(this.getOutput());
  25052. } else {
  25053. this.source.connect(this.getOutput());
  25054. }
  25055. this._connected = true;
  25056. return this;
  25057. }
  25058. disconnect() {
  25059. if (this.filters.length > 0) {
  25060. this.source.disconnect(this.filters[0]);
  25061. for (let i = 1, l = this.filters.length; i < l; i++) {
  25062. this.filters[i - 1].disconnect(this.filters[i]);
  25063. }
  25064. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  25065. } else {
  25066. this.source.disconnect(this.getOutput());
  25067. }
  25068. this._connected = false;
  25069. return this;
  25070. }
  25071. getFilters() {
  25072. return this.filters;
  25073. }
  25074. setFilters(value) {
  25075. if (!value) value = [];
  25076. if (this._connected === true) {
  25077. this.disconnect();
  25078. this.filters = value.slice();
  25079. this.connect();
  25080. } else {
  25081. this.filters = value.slice();
  25082. }
  25083. return this;
  25084. }
  25085. setDetune(value) {
  25086. this.detune = value;
  25087. if (this.source.detune === undefined) return; // only set detune when available
  25088. if (this.isPlaying === true) {
  25089. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  25090. }
  25091. return this;
  25092. }
  25093. getDetune() {
  25094. return this.detune;
  25095. }
  25096. getFilter() {
  25097. return this.getFilters()[0];
  25098. }
  25099. setFilter(filter) {
  25100. return this.setFilters(filter ? [filter] : []);
  25101. }
  25102. setPlaybackRate(value) {
  25103. if (this.hasPlaybackControl === false) {
  25104. console.warn('THREE.Audio: this Audio has no playback control.');
  25105. return;
  25106. }
  25107. this.playbackRate = value;
  25108. if (this.isPlaying === true) {
  25109. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  25110. }
  25111. return this;
  25112. }
  25113. getPlaybackRate() {
  25114. return this.playbackRate;
  25115. }
  25116. onEnded() {
  25117. this.isPlaying = false;
  25118. }
  25119. getLoop() {
  25120. if (this.hasPlaybackControl === false) {
  25121. console.warn('THREE.Audio: this Audio has no playback control.');
  25122. return false;
  25123. }
  25124. return this.loop;
  25125. }
  25126. setLoop(value) {
  25127. if (this.hasPlaybackControl === false) {
  25128. console.warn('THREE.Audio: this Audio has no playback control.');
  25129. return;
  25130. }
  25131. this.loop = value;
  25132. if (this.isPlaying === true) {
  25133. this.source.loop = this.loop;
  25134. }
  25135. return this;
  25136. }
  25137. setLoopStart(value) {
  25138. this.loopStart = value;
  25139. return this;
  25140. }
  25141. setLoopEnd(value) {
  25142. this.loopEnd = value;
  25143. return this;
  25144. }
  25145. getVolume() {
  25146. return this.gain.gain.value;
  25147. }
  25148. setVolume(value) {
  25149. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25150. return this;
  25151. }
  25152. }
  25153. const _position = /*@__PURE__*/new Vector3();
  25154. const _quaternion = /*@__PURE__*/new Quaternion();
  25155. const _scale = /*@__PURE__*/new Vector3();
  25156. const _orientation = /*@__PURE__*/new Vector3();
  25157. class PositionalAudio extends Audio {
  25158. constructor(listener) {
  25159. super(listener);
  25160. this.panner = this.context.createPanner();
  25161. this.panner.panningModel = 'HRTF';
  25162. this.panner.connect(this.gain);
  25163. }
  25164. getOutput() {
  25165. return this.panner;
  25166. }
  25167. getRefDistance() {
  25168. return this.panner.refDistance;
  25169. }
  25170. setRefDistance(value) {
  25171. this.panner.refDistance = value;
  25172. return this;
  25173. }
  25174. getRolloffFactor() {
  25175. return this.panner.rolloffFactor;
  25176. }
  25177. setRolloffFactor(value) {
  25178. this.panner.rolloffFactor = value;
  25179. return this;
  25180. }
  25181. getDistanceModel() {
  25182. return this.panner.distanceModel;
  25183. }
  25184. setDistanceModel(value) {
  25185. this.panner.distanceModel = value;
  25186. return this;
  25187. }
  25188. getMaxDistance() {
  25189. return this.panner.maxDistance;
  25190. }
  25191. setMaxDistance(value) {
  25192. this.panner.maxDistance = value;
  25193. return this;
  25194. }
  25195. setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25196. this.panner.coneInnerAngle = coneInnerAngle;
  25197. this.panner.coneOuterAngle = coneOuterAngle;
  25198. this.panner.coneOuterGain = coneOuterGain;
  25199. return this;
  25200. }
  25201. updateMatrixWorld(force) {
  25202. super.updateMatrixWorld(force);
  25203. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  25204. this.matrixWorld.decompose(_position, _quaternion, _scale);
  25205. _orientation.set(0, 0, 1).applyQuaternion(_quaternion);
  25206. const panner = this.panner;
  25207. if (panner.positionX) {
  25208. // code path for Chrome and Firefox (see #14393)
  25209. const endTime = this.context.currentTime + this.listener.timeDelta;
  25210. panner.positionX.linearRampToValueAtTime(_position.x, endTime);
  25211. panner.positionY.linearRampToValueAtTime(_position.y, endTime);
  25212. panner.positionZ.linearRampToValueAtTime(_position.z, endTime);
  25213. panner.orientationX.linearRampToValueAtTime(_orientation.x, endTime);
  25214. panner.orientationY.linearRampToValueAtTime(_orientation.y, endTime);
  25215. panner.orientationZ.linearRampToValueAtTime(_orientation.z, endTime);
  25216. } else {
  25217. panner.setPosition(_position.x, _position.y, _position.z);
  25218. panner.setOrientation(_orientation.x, _orientation.y, _orientation.z);
  25219. }
  25220. }
  25221. }
  25222. class AudioAnalyser {
  25223. constructor(audio, fftSize = 2048) {
  25224. this.analyser = audio.context.createAnalyser();
  25225. this.analyser.fftSize = fftSize;
  25226. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  25227. audio.getOutput().connect(this.analyser);
  25228. }
  25229. getFrequencyData() {
  25230. this.analyser.getByteFrequencyData(this.data);
  25231. return this.data;
  25232. }
  25233. getAverageFrequency() {
  25234. let value = 0;
  25235. const data = this.getFrequencyData();
  25236. for (let i = 0; i < data.length; i++) {
  25237. value += data[i];
  25238. }
  25239. return value / data.length;
  25240. }
  25241. }
  25242. class PropertyMixer {
  25243. constructor(binding, typeName, valueSize) {
  25244. this.binding = binding;
  25245. this.valueSize = valueSize;
  25246. let mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  25247. //
  25248. // interpolators can use .buffer as their .result
  25249. // the data then goes to 'incoming'
  25250. //
  25251. // 'accu0' and 'accu1' are used frame-interleaved for
  25252. // the cumulative result and are compared to detect
  25253. // changes
  25254. //
  25255. // 'orig' stores the original state of the property
  25256. //
  25257. // 'add' is used for additive cumulative results
  25258. //
  25259. // 'work' is optional and is only present for quaternion types. It is used
  25260. // to store intermediate quaternion multiplication results
  25261. switch (typeName) {
  25262. case 'quaternion':
  25263. mixFunction = this._slerp;
  25264. mixFunctionAdditive = this._slerpAdditive;
  25265. setIdentity = this._setAdditiveIdentityQuaternion;
  25266. this.buffer = new Float64Array(valueSize * 6);
  25267. this._workIndex = 5;
  25268. break;
  25269. case 'string':
  25270. case 'bool':
  25271. mixFunction = this._select; // Use the regular mix function and for additive on these types,
  25272. // additive is not relevant for non-numeric types
  25273. mixFunctionAdditive = this._select;
  25274. setIdentity = this._setAdditiveIdentityOther;
  25275. this.buffer = new Array(valueSize * 5);
  25276. break;
  25277. default:
  25278. mixFunction = this._lerp;
  25279. mixFunctionAdditive = this._lerpAdditive;
  25280. setIdentity = this._setAdditiveIdentityNumeric;
  25281. this.buffer = new Float64Array(valueSize * 5);
  25282. }
  25283. this._mixBufferRegion = mixFunction;
  25284. this._mixBufferRegionAdditive = mixFunctionAdditive;
  25285. this._setIdentity = setIdentity;
  25286. this._origIndex = 3;
  25287. this._addIndex = 4;
  25288. this.cumulativeWeight = 0;
  25289. this.cumulativeWeightAdditive = 0;
  25290. this.useCount = 0;
  25291. this.referenceCount = 0;
  25292. } // accumulate data in the 'incoming' region into 'accu<i>'
  25293. accumulate(accuIndex, weight) {
  25294. // note: happily accumulating nothing when weight = 0, the caller knows
  25295. // the weight and shouldn't have made the call in the first place
  25296. const buffer = this.buffer,
  25297. stride = this.valueSize,
  25298. offset = accuIndex * stride + stride;
  25299. let currentWeight = this.cumulativeWeight;
  25300. if (currentWeight === 0) {
  25301. // accuN := incoming * weight
  25302. for (let i = 0; i !== stride; ++i) {
  25303. buffer[offset + i] = buffer[i];
  25304. }
  25305. currentWeight = weight;
  25306. } else {
  25307. // accuN := accuN + incoming * weight
  25308. currentWeight += weight;
  25309. const mix = weight / currentWeight;
  25310. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  25311. }
  25312. this.cumulativeWeight = currentWeight;
  25313. } // accumulate data in the 'incoming' region into 'add'
  25314. accumulateAdditive(weight) {
  25315. const buffer = this.buffer,
  25316. stride = this.valueSize,
  25317. offset = stride * this._addIndex;
  25318. if (this.cumulativeWeightAdditive === 0) {
  25319. // add = identity
  25320. this._setIdentity();
  25321. } // add := add + incoming * weight
  25322. this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
  25323. this.cumulativeWeightAdditive += weight;
  25324. } // apply the state of 'accu<i>' to the binding when accus differ
  25325. apply(accuIndex) {
  25326. const stride = this.valueSize,
  25327. buffer = this.buffer,
  25328. offset = accuIndex * stride + stride,
  25329. weight = this.cumulativeWeight,
  25330. weightAdditive = this.cumulativeWeightAdditive,
  25331. binding = this.binding;
  25332. this.cumulativeWeight = 0;
  25333. this.cumulativeWeightAdditive = 0;
  25334. if (weight < 1) {
  25335. // accuN := accuN + original * ( 1 - cumulativeWeight )
  25336. const originalValueOffset = stride * this._origIndex;
  25337. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  25338. }
  25339. if (weightAdditive > 0) {
  25340. // accuN := accuN + additive accuN
  25341. this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
  25342. }
  25343. for (let i = stride, e = stride + stride; i !== e; ++i) {
  25344. if (buffer[i] !== buffer[i + stride]) {
  25345. // value has changed -> update scene graph
  25346. binding.setValue(buffer, offset);
  25347. break;
  25348. }
  25349. }
  25350. } // remember the state of the bound property and copy it to both accus
  25351. saveOriginalState() {
  25352. const binding = this.binding;
  25353. const buffer = this.buffer,
  25354. stride = this.valueSize,
  25355. originalValueOffset = stride * this._origIndex;
  25356. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  25357. for (let i = stride, e = originalValueOffset; i !== e; ++i) {
  25358. buffer[i] = buffer[originalValueOffset + i % stride];
  25359. } // Add to identity for additive
  25360. this._setIdentity();
  25361. this.cumulativeWeight = 0;
  25362. this.cumulativeWeightAdditive = 0;
  25363. } // apply the state previously taken via 'saveOriginalState' to the binding
  25364. restoreOriginalState() {
  25365. const originalValueOffset = this.valueSize * 3;
  25366. this.binding.setValue(this.buffer, originalValueOffset);
  25367. }
  25368. _setAdditiveIdentityNumeric() {
  25369. const startIndex = this._addIndex * this.valueSize;
  25370. const endIndex = startIndex + this.valueSize;
  25371. for (let i = startIndex; i < endIndex; i++) {
  25372. this.buffer[i] = 0;
  25373. }
  25374. }
  25375. _setAdditiveIdentityQuaternion() {
  25376. this._setAdditiveIdentityNumeric();
  25377. this.buffer[this._addIndex * this.valueSize + 3] = 1;
  25378. }
  25379. _setAdditiveIdentityOther() {
  25380. const startIndex = this._origIndex * this.valueSize;
  25381. const targetIndex = this._addIndex * this.valueSize;
  25382. for (let i = 0; i < this.valueSize; i++) {
  25383. this.buffer[targetIndex + i] = this.buffer[startIndex + i];
  25384. }
  25385. } // mix functions
  25386. _select(buffer, dstOffset, srcOffset, t, stride) {
  25387. if (t >= 0.5) {
  25388. for (let i = 0; i !== stride; ++i) {
  25389. buffer[dstOffset + i] = buffer[srcOffset + i];
  25390. }
  25391. }
  25392. }
  25393. _slerp(buffer, dstOffset, srcOffset, t) {
  25394. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  25395. }
  25396. _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  25397. const workOffset = this._workIndex * stride; // Store result in intermediate buffer offset
  25398. Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
  25399. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
  25400. }
  25401. _lerp(buffer, dstOffset, srcOffset, t, stride) {
  25402. const s = 1 - t;
  25403. for (let i = 0; i !== stride; ++i) {
  25404. const j = dstOffset + i;
  25405. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  25406. }
  25407. }
  25408. _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  25409. for (let i = 0; i !== stride; ++i) {
  25410. const j = dstOffset + i;
  25411. buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
  25412. }
  25413. }
  25414. }
  25415. // Characters [].:/ are reserved for track binding syntax.
  25416. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  25417. const _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  25418. // only latin characters, and the unicode \p{L} is not yet supported. So
  25419. // instead, we exclude reserved characters and match everything else.
  25420. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  25421. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  25422. // be matched to parse the rest of the track name.
  25423. const _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  25424. const _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  25425. // characters. Accessor may contain any character except closing bracket.
  25426. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  25427. // contain any non-bracket characters.
  25428. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  25429. const _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  25430. const _supportedObjectNames = ['material', 'materials', 'bones'];
  25431. class Composite {
  25432. constructor(targetGroup, path, optionalParsedPath) {
  25433. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  25434. this._targetGroup = targetGroup;
  25435. this._bindings = targetGroup.subscribe_(path, parsedPath);
  25436. }
  25437. getValue(array, offset) {
  25438. this.bind(); // bind all binding
  25439. const firstValidIndex = this._targetGroup.nCachedObjects_,
  25440. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  25441. if (binding !== undefined) binding.getValue(array, offset);
  25442. }
  25443. setValue(array, offset) {
  25444. const bindings = this._bindings;
  25445. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25446. bindings[i].setValue(array, offset);
  25447. }
  25448. }
  25449. bind() {
  25450. const bindings = this._bindings;
  25451. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25452. bindings[i].bind();
  25453. }
  25454. }
  25455. unbind() {
  25456. const bindings = this._bindings;
  25457. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25458. bindings[i].unbind();
  25459. }
  25460. }
  25461. } // Note: This class uses a State pattern on a per-method basis:
  25462. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  25463. // prototype version of these methods with one that represents
  25464. // the bound state. When the property is not found, the methods
  25465. // become no-ops.
  25466. class PropertyBinding {
  25467. constructor(rootNode, path, parsedPath) {
  25468. this.path = path;
  25469. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  25470. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  25471. this.rootNode = rootNode; // initial state of these methods that calls 'bind'
  25472. this.getValue = this._getValue_unbound;
  25473. this.setValue = this._setValue_unbound;
  25474. }
  25475. static create(root, path, parsedPath) {
  25476. if (!(root && root.isAnimationObjectGroup)) {
  25477. return new PropertyBinding(root, path, parsedPath);
  25478. } else {
  25479. return new PropertyBinding.Composite(root, path, parsedPath);
  25480. }
  25481. }
  25482. /**
  25483. * Replaces spaces with underscores and removes unsupported characters from
  25484. * node names, to ensure compatibility with parseTrackName().
  25485. *
  25486. * @param {string} name Node name to be sanitized.
  25487. * @return {string}
  25488. */
  25489. static sanitizeNodeName(name) {
  25490. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  25491. }
  25492. static parseTrackName(trackName) {
  25493. const matches = _trackRe.exec(trackName);
  25494. if (!matches) {
  25495. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  25496. }
  25497. const results = {
  25498. // directoryName: matches[ 1 ], // (tschw) currently unused
  25499. nodeName: matches[2],
  25500. objectName: matches[3],
  25501. objectIndex: matches[4],
  25502. propertyName: matches[5],
  25503. // required
  25504. propertyIndex: matches[6]
  25505. };
  25506. const lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  25507. if (lastDot !== undefined && lastDot !== -1) {
  25508. const objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
  25509. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  25510. // 'bar' could be the objectName, or part of a nodeName (which can
  25511. // include '.' characters).
  25512. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  25513. results.nodeName = results.nodeName.substring(0, lastDot);
  25514. results.objectName = objectName;
  25515. }
  25516. }
  25517. if (results.propertyName === null || results.propertyName.length === 0) {
  25518. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  25519. }
  25520. return results;
  25521. }
  25522. static findNode(root, nodeName) {
  25523. if (!nodeName || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  25524. return root;
  25525. } // search into skeleton bones.
  25526. if (root.skeleton) {
  25527. const bone = root.skeleton.getBoneByName(nodeName);
  25528. if (bone !== undefined) {
  25529. return bone;
  25530. }
  25531. } // search into node subtree.
  25532. if (root.children) {
  25533. const searchNodeSubtree = function (children) {
  25534. for (let i = 0; i < children.length; i++) {
  25535. const childNode = children[i];
  25536. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  25537. return childNode;
  25538. }
  25539. const result = searchNodeSubtree(childNode.children);
  25540. if (result) return result;
  25541. }
  25542. return null;
  25543. };
  25544. const subTreeNode = searchNodeSubtree(root.children);
  25545. if (subTreeNode) {
  25546. return subTreeNode;
  25547. }
  25548. }
  25549. return null;
  25550. } // these are used to "bind" a nonexistent property
  25551. _getValue_unavailable() {}
  25552. _setValue_unavailable() {} // Getters
  25553. _getValue_direct(buffer, offset) {
  25554. buffer[offset] = this.targetObject[this.propertyName];
  25555. }
  25556. _getValue_array(buffer, offset) {
  25557. const source = this.resolvedProperty;
  25558. for (let i = 0, n = source.length; i !== n; ++i) {
  25559. buffer[offset++] = source[i];
  25560. }
  25561. }
  25562. _getValue_arrayElement(buffer, offset) {
  25563. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  25564. }
  25565. _getValue_toArray(buffer, offset) {
  25566. this.resolvedProperty.toArray(buffer, offset);
  25567. } // Direct
  25568. _setValue_direct(buffer, offset) {
  25569. this.targetObject[this.propertyName] = buffer[offset];
  25570. }
  25571. _setValue_direct_setNeedsUpdate(buffer, offset) {
  25572. this.targetObject[this.propertyName] = buffer[offset];
  25573. this.targetObject.needsUpdate = true;
  25574. }
  25575. _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  25576. this.targetObject[this.propertyName] = buffer[offset];
  25577. this.targetObject.matrixWorldNeedsUpdate = true;
  25578. } // EntireArray
  25579. _setValue_array(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. }
  25585. _setValue_array_setNeedsUpdate(buffer, offset) {
  25586. const dest = this.resolvedProperty;
  25587. for (let i = 0, n = dest.length; i !== n; ++i) {
  25588. dest[i] = buffer[offset++];
  25589. }
  25590. this.targetObject.needsUpdate = true;
  25591. }
  25592. _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  25593. const dest = this.resolvedProperty;
  25594. for (let i = 0, n = dest.length; i !== n; ++i) {
  25595. dest[i] = buffer[offset++];
  25596. }
  25597. this.targetObject.matrixWorldNeedsUpdate = true;
  25598. } // ArrayElement
  25599. _setValue_arrayElement(buffer, offset) {
  25600. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25601. }
  25602. _setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  25603. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25604. this.targetObject.needsUpdate = true;
  25605. }
  25606. _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  25607. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25608. this.targetObject.matrixWorldNeedsUpdate = true;
  25609. } // HasToFromArray
  25610. _setValue_fromArray(buffer, offset) {
  25611. this.resolvedProperty.fromArray(buffer, offset);
  25612. }
  25613. _setValue_fromArray_setNeedsUpdate(buffer, offset) {
  25614. this.resolvedProperty.fromArray(buffer, offset);
  25615. this.targetObject.needsUpdate = true;
  25616. }
  25617. _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  25618. this.resolvedProperty.fromArray(buffer, offset);
  25619. this.targetObject.matrixWorldNeedsUpdate = true;
  25620. }
  25621. _getValue_unbound(targetArray, offset) {
  25622. this.bind();
  25623. this.getValue(targetArray, offset);
  25624. }
  25625. _setValue_unbound(sourceArray, offset) {
  25626. this.bind();
  25627. this.setValue(sourceArray, offset);
  25628. } // create getter / setter pair for a property in the scene graph
  25629. bind() {
  25630. let targetObject = this.node;
  25631. const parsedPath = this.parsedPath;
  25632. const objectName = parsedPath.objectName;
  25633. const propertyName = parsedPath.propertyName;
  25634. let propertyIndex = parsedPath.propertyIndex;
  25635. if (!targetObject) {
  25636. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  25637. this.node = targetObject;
  25638. } // set fail state so we can just 'return' on error
  25639. this.getValue = this._getValue_unavailable;
  25640. this.setValue = this._setValue_unavailable; // ensure there is a value node
  25641. if (!targetObject) {
  25642. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  25643. return;
  25644. }
  25645. if (objectName) {
  25646. let objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  25647. switch (objectName) {
  25648. case 'materials':
  25649. if (!targetObject.material) {
  25650. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  25651. return;
  25652. }
  25653. if (!targetObject.material.materials) {
  25654. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  25655. return;
  25656. }
  25657. targetObject = targetObject.material.materials;
  25658. break;
  25659. case 'bones':
  25660. if (!targetObject.skeleton) {
  25661. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  25662. return;
  25663. } // potential future optimization: skip this if propertyIndex is already an integer
  25664. // and convert the integer string to a true integer.
  25665. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  25666. for (let i = 0; i < targetObject.length; i++) {
  25667. if (targetObject[i].name === objectIndex) {
  25668. objectIndex = i;
  25669. break;
  25670. }
  25671. }
  25672. break;
  25673. default:
  25674. if (targetObject[objectName] === undefined) {
  25675. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  25676. return;
  25677. }
  25678. targetObject = targetObject[objectName];
  25679. }
  25680. if (objectIndex !== undefined) {
  25681. if (targetObject[objectIndex] === undefined) {
  25682. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  25683. return;
  25684. }
  25685. targetObject = targetObject[objectIndex];
  25686. }
  25687. } // resolve property
  25688. const nodeProperty = targetObject[propertyName];
  25689. if (nodeProperty === undefined) {
  25690. const nodeName = parsedPath.nodeName;
  25691. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  25692. return;
  25693. } // determine versioning scheme
  25694. let versioning = this.Versioning.None;
  25695. this.targetObject = targetObject;
  25696. if (targetObject.needsUpdate !== undefined) {
  25697. // material
  25698. versioning = this.Versioning.NeedsUpdate;
  25699. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  25700. // node transform
  25701. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  25702. } // determine how the property gets bound
  25703. let bindingType = this.BindingType.Direct;
  25704. if (propertyIndex !== undefined) {
  25705. // access a sub element of the property array (only primitives are supported right now)
  25706. if (propertyName === 'morphTargetInfluences') {
  25707. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  25708. // support resolving morphTarget names into indices.
  25709. if (!targetObject.geometry) {
  25710. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  25711. return;
  25712. }
  25713. if (targetObject.geometry.isBufferGeometry) {
  25714. if (!targetObject.geometry.morphAttributes) {
  25715. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  25716. return;
  25717. }
  25718. if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
  25719. propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
  25720. }
  25721. } else {
  25722. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this);
  25723. return;
  25724. }
  25725. }
  25726. bindingType = this.BindingType.ArrayElement;
  25727. this.resolvedProperty = nodeProperty;
  25728. this.propertyIndex = propertyIndex;
  25729. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  25730. // must use copy for Object3D.Euler/Quaternion
  25731. bindingType = this.BindingType.HasFromToArray;
  25732. this.resolvedProperty = nodeProperty;
  25733. } else if (Array.isArray(nodeProperty)) {
  25734. bindingType = this.BindingType.EntireArray;
  25735. this.resolvedProperty = nodeProperty;
  25736. } else {
  25737. this.propertyName = propertyName;
  25738. } // select getter / setter
  25739. this.getValue = this.GetterByBindingType[bindingType];
  25740. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  25741. }
  25742. unbind() {
  25743. this.node = null; // back to the prototype version of getValue / setValue
  25744. // note: avoiding to mutate the shape of 'this' via 'delete'
  25745. this.getValue = this._getValue_unbound;
  25746. this.setValue = this._setValue_unbound;
  25747. }
  25748. }
  25749. PropertyBinding.Composite = Composite;
  25750. PropertyBinding.prototype.BindingType = {
  25751. Direct: 0,
  25752. EntireArray: 1,
  25753. ArrayElement: 2,
  25754. HasFromToArray: 3
  25755. };
  25756. PropertyBinding.prototype.Versioning = {
  25757. None: 0,
  25758. NeedsUpdate: 1,
  25759. MatrixWorldNeedsUpdate: 2
  25760. };
  25761. PropertyBinding.prototype.GetterByBindingType = [PropertyBinding.prototype._getValue_direct, PropertyBinding.prototype._getValue_array, PropertyBinding.prototype._getValue_arrayElement, PropertyBinding.prototype._getValue_toArray];
  25762. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [[// Direct
  25763. PropertyBinding.prototype._setValue_direct, PropertyBinding.prototype._setValue_direct_setNeedsUpdate, PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate], [// EntireArray
  25764. PropertyBinding.prototype._setValue_array, PropertyBinding.prototype._setValue_array_setNeedsUpdate, PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate], [// ArrayElement
  25765. PropertyBinding.prototype._setValue_arrayElement, PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate], [// HasToFromArray
  25766. PropertyBinding.prototype._setValue_fromArray, PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];
  25767. /**
  25768. *
  25769. * A group of objects that receives a shared animation state.
  25770. *
  25771. * Usage:
  25772. *
  25773. * - Add objects you would otherwise pass as 'root' to the
  25774. * constructor or the .clipAction method of AnimationMixer.
  25775. *
  25776. * - Instead pass this object as 'root'.
  25777. *
  25778. * - You can also add and remove objects later when the mixer
  25779. * is running.
  25780. *
  25781. * Note:
  25782. *
  25783. * Objects of this class appear as one object to the mixer,
  25784. * so cache control of the individual objects must be done
  25785. * on the group.
  25786. *
  25787. * Limitation:
  25788. *
  25789. * - The animated properties must be compatible among the
  25790. * all objects in the group.
  25791. *
  25792. * - A single property can either be controlled through a
  25793. * target group or directly, but not both.
  25794. */
  25795. class AnimationObjectGroup {
  25796. constructor() {
  25797. this.uuid = generateUUID(); // cached objects followed by the active ones
  25798. this._objects = Array.prototype.slice.call(arguments);
  25799. this.nCachedObjects_ = 0; // threshold
  25800. // note: read by PropertyBinding.Composite
  25801. const indices = {};
  25802. this._indicesByUUID = indices; // for bookkeeping
  25803. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25804. indices[arguments[i].uuid] = i;
  25805. }
  25806. this._paths = []; // inside: string
  25807. this._parsedPaths = []; // inside: { we don't care, here }
  25808. this._bindings = []; // inside: Array< PropertyBinding >
  25809. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  25810. const scope = this;
  25811. this.stats = {
  25812. objects: {
  25813. get total() {
  25814. return scope._objects.length;
  25815. },
  25816. get inUse() {
  25817. return this.total - scope.nCachedObjects_;
  25818. }
  25819. },
  25820. get bindingsPerObject() {
  25821. return scope._bindings.length;
  25822. }
  25823. };
  25824. }
  25825. add() {
  25826. const objects = this._objects,
  25827. indicesByUUID = this._indicesByUUID,
  25828. paths = this._paths,
  25829. parsedPaths = this._parsedPaths,
  25830. bindings = this._bindings,
  25831. nBindings = bindings.length;
  25832. let knownObject = undefined,
  25833. nObjects = objects.length,
  25834. nCachedObjects = this.nCachedObjects_;
  25835. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25836. const object = arguments[i],
  25837. uuid = object.uuid;
  25838. let index = indicesByUUID[uuid];
  25839. if (index === undefined) {
  25840. // unknown object -> add it to the ACTIVE region
  25841. index = nObjects++;
  25842. indicesByUUID[uuid] = index;
  25843. objects.push(object); // accounting is done, now do the same for all bindings
  25844. for (let j = 0, m = nBindings; j !== m; ++j) {
  25845. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  25846. }
  25847. } else if (index < nCachedObjects) {
  25848. knownObject = objects[index]; // move existing object to the ACTIVE region
  25849. const firstActiveIndex = --nCachedObjects,
  25850. lastCachedObject = objects[firstActiveIndex];
  25851. indicesByUUID[lastCachedObject.uuid] = index;
  25852. objects[index] = lastCachedObject;
  25853. indicesByUUID[uuid] = firstActiveIndex;
  25854. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  25855. for (let j = 0, m = nBindings; j !== m; ++j) {
  25856. const bindingsForPath = bindings[j],
  25857. lastCached = bindingsForPath[firstActiveIndex];
  25858. let binding = bindingsForPath[index];
  25859. bindingsForPath[index] = lastCached;
  25860. if (binding === undefined) {
  25861. // since we do not bother to create new bindings
  25862. // for objects that are cached, the binding may
  25863. // or may not exist
  25864. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  25865. }
  25866. bindingsForPath[firstActiveIndex] = binding;
  25867. }
  25868. } else if (objects[index] !== knownObject) {
  25869. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  25870. } // else the object is already where we want it to be
  25871. } // for arguments
  25872. this.nCachedObjects_ = nCachedObjects;
  25873. }
  25874. remove() {
  25875. const objects = this._objects,
  25876. indicesByUUID = this._indicesByUUID,
  25877. bindings = this._bindings,
  25878. nBindings = bindings.length;
  25879. let nCachedObjects = this.nCachedObjects_;
  25880. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25881. const object = arguments[i],
  25882. uuid = object.uuid,
  25883. index = indicesByUUID[uuid];
  25884. if (index !== undefined && index >= nCachedObjects) {
  25885. // move existing object into the CACHED region
  25886. const lastCachedIndex = nCachedObjects++,
  25887. firstActiveObject = objects[lastCachedIndex];
  25888. indicesByUUID[firstActiveObject.uuid] = index;
  25889. objects[index] = firstActiveObject;
  25890. indicesByUUID[uuid] = lastCachedIndex;
  25891. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  25892. for (let j = 0, m = nBindings; j !== m; ++j) {
  25893. const bindingsForPath = bindings[j],
  25894. firstActive = bindingsForPath[lastCachedIndex],
  25895. binding = bindingsForPath[index];
  25896. bindingsForPath[index] = firstActive;
  25897. bindingsForPath[lastCachedIndex] = binding;
  25898. }
  25899. }
  25900. } // for arguments
  25901. this.nCachedObjects_ = nCachedObjects;
  25902. } // remove & forget
  25903. uncache() {
  25904. const objects = this._objects,
  25905. indicesByUUID = this._indicesByUUID,
  25906. bindings = this._bindings,
  25907. nBindings = bindings.length;
  25908. let nCachedObjects = this.nCachedObjects_,
  25909. nObjects = objects.length;
  25910. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25911. const object = arguments[i],
  25912. uuid = object.uuid,
  25913. index = indicesByUUID[uuid];
  25914. if (index !== undefined) {
  25915. delete indicesByUUID[uuid];
  25916. if (index < nCachedObjects) {
  25917. // object is cached, shrink the CACHED region
  25918. const firstActiveIndex = --nCachedObjects,
  25919. lastCachedObject = objects[firstActiveIndex],
  25920. lastIndex = --nObjects,
  25921. lastObject = objects[lastIndex]; // last cached object takes this object's place
  25922. indicesByUUID[lastCachedObject.uuid] = index;
  25923. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  25924. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  25925. objects[firstActiveIndex] = lastObject;
  25926. objects.pop(); // accounting is done, now do the same for all bindings
  25927. for (let j = 0, m = nBindings; j !== m; ++j) {
  25928. const bindingsForPath = bindings[j],
  25929. lastCached = bindingsForPath[firstActiveIndex],
  25930. last = bindingsForPath[lastIndex];
  25931. bindingsForPath[index] = lastCached;
  25932. bindingsForPath[firstActiveIndex] = last;
  25933. bindingsForPath.pop();
  25934. }
  25935. } else {
  25936. // object is active, just swap with the last and pop
  25937. const lastIndex = --nObjects,
  25938. lastObject = objects[lastIndex];
  25939. if (lastIndex > 0) {
  25940. indicesByUUID[lastObject.uuid] = index;
  25941. }
  25942. objects[index] = lastObject;
  25943. objects.pop(); // accounting is done, now do the same for all bindings
  25944. for (let j = 0, m = nBindings; j !== m; ++j) {
  25945. const bindingsForPath = bindings[j];
  25946. bindingsForPath[index] = bindingsForPath[lastIndex];
  25947. bindingsForPath.pop();
  25948. }
  25949. } // cached or active
  25950. } // if object is known
  25951. } // for arguments
  25952. this.nCachedObjects_ = nCachedObjects;
  25953. } // Internal interface used by befriended PropertyBinding.Composite:
  25954. subscribe_(path, parsedPath) {
  25955. // returns an array of bindings for the given path that is changed
  25956. // according to the contained objects in the group
  25957. const indicesByPath = this._bindingsIndicesByPath;
  25958. let index = indicesByPath[path];
  25959. const bindings = this._bindings;
  25960. if (index !== undefined) return bindings[index];
  25961. const paths = this._paths,
  25962. parsedPaths = this._parsedPaths,
  25963. objects = this._objects,
  25964. nObjects = objects.length,
  25965. nCachedObjects = this.nCachedObjects_,
  25966. bindingsForPath = new Array(nObjects);
  25967. index = bindings.length;
  25968. indicesByPath[path] = index;
  25969. paths.push(path);
  25970. parsedPaths.push(parsedPath);
  25971. bindings.push(bindingsForPath);
  25972. for (let i = nCachedObjects, n = objects.length; i !== n; ++i) {
  25973. const object = objects[i];
  25974. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  25975. }
  25976. return bindingsForPath;
  25977. }
  25978. unsubscribe_(path) {
  25979. // tells the group to forget about a property path and no longer
  25980. // update the array previously obtained with 'subscribe_'
  25981. const indicesByPath = this._bindingsIndicesByPath,
  25982. index = indicesByPath[path];
  25983. if (index !== undefined) {
  25984. const paths = this._paths,
  25985. parsedPaths = this._parsedPaths,
  25986. bindings = this._bindings,
  25987. lastBindingsIndex = bindings.length - 1,
  25988. lastBindings = bindings[lastBindingsIndex],
  25989. lastBindingsPath = path[lastBindingsIndex];
  25990. indicesByPath[lastBindingsPath] = index;
  25991. bindings[index] = lastBindings;
  25992. bindings.pop();
  25993. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  25994. parsedPaths.pop();
  25995. paths[index] = paths[lastBindingsIndex];
  25996. paths.pop();
  25997. }
  25998. }
  25999. }
  26000. AnimationObjectGroup.prototype.isAnimationObjectGroup = true;
  26001. class AnimationAction {
  26002. constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) {
  26003. this._mixer = mixer;
  26004. this._clip = clip;
  26005. this._localRoot = localRoot;
  26006. this.blendMode = blendMode;
  26007. const tracks = clip.tracks,
  26008. nTracks = tracks.length,
  26009. interpolants = new Array(nTracks);
  26010. const interpolantSettings = {
  26011. endingStart: ZeroCurvatureEnding,
  26012. endingEnd: ZeroCurvatureEnding
  26013. };
  26014. for (let i = 0; i !== nTracks; ++i) {
  26015. const interpolant = tracks[i].createInterpolant(null);
  26016. interpolants[i] = interpolant;
  26017. interpolant.settings = interpolantSettings;
  26018. }
  26019. this._interpolantSettings = interpolantSettings;
  26020. this._interpolants = interpolants; // bound by the mixer
  26021. // inside: PropertyMixer (managed by the mixer)
  26022. this._propertyBindings = new Array(nTracks);
  26023. this._cacheIndex = null; // for the memory manager
  26024. this._byClipCacheIndex = null; // for the memory manager
  26025. this._timeScaleInterpolant = null;
  26026. this._weightInterpolant = null;
  26027. this.loop = LoopRepeat;
  26028. this._loopCount = -1; // global mixer time when the action is to be started
  26029. // it's set back to 'null' upon start of the action
  26030. this._startTime = null; // scaled local time of the action
  26031. // gets clamped or wrapped to 0..clip.duration according to loop
  26032. this.time = 0;
  26033. this.timeScale = 1;
  26034. this._effectiveTimeScale = 1;
  26035. this.weight = 1;
  26036. this._effectiveWeight = 1;
  26037. this.repetitions = Infinity; // no. of repetitions when looping
  26038. this.paused = false; // true -> zero effective time scale
  26039. this.enabled = true; // false -> zero effective weight
  26040. this.clampWhenFinished = false; // keep feeding the last frame?
  26041. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  26042. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  26043. } // State & Scheduling
  26044. play() {
  26045. this._mixer._activateAction(this);
  26046. return this;
  26047. }
  26048. stop() {
  26049. this._mixer._deactivateAction(this);
  26050. return this.reset();
  26051. }
  26052. reset() {
  26053. this.paused = false;
  26054. this.enabled = true;
  26055. this.time = 0; // restart clip
  26056. this._loopCount = -1; // forget previous loops
  26057. this._startTime = null; // forget scheduling
  26058. return this.stopFading().stopWarping();
  26059. }
  26060. isRunning() {
  26061. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  26062. } // return true when play has been called
  26063. isScheduled() {
  26064. return this._mixer._isActiveAction(this);
  26065. }
  26066. startAt(time) {
  26067. this._startTime = time;
  26068. return this;
  26069. }
  26070. setLoop(mode, repetitions) {
  26071. this.loop = mode;
  26072. this.repetitions = repetitions;
  26073. return this;
  26074. } // Weight
  26075. // set the weight stopping any scheduled fading
  26076. // although .enabled = false yields an effective weight of zero, this
  26077. // method does *not* change .enabled, because it would be confusing
  26078. setEffectiveWeight(weight) {
  26079. this.weight = weight; // note: same logic as when updated at runtime
  26080. this._effectiveWeight = this.enabled ? weight : 0;
  26081. return this.stopFading();
  26082. } // return the weight considering fading and .enabled
  26083. getEffectiveWeight() {
  26084. return this._effectiveWeight;
  26085. }
  26086. fadeIn(duration) {
  26087. return this._scheduleFading(duration, 0, 1);
  26088. }
  26089. fadeOut(duration) {
  26090. return this._scheduleFading(duration, 1, 0);
  26091. }
  26092. crossFadeFrom(fadeOutAction, duration, warp) {
  26093. fadeOutAction.fadeOut(duration);
  26094. this.fadeIn(duration);
  26095. if (warp) {
  26096. const fadeInDuration = this._clip.duration,
  26097. fadeOutDuration = fadeOutAction._clip.duration,
  26098. startEndRatio = fadeOutDuration / fadeInDuration,
  26099. endStartRatio = fadeInDuration / fadeOutDuration;
  26100. fadeOutAction.warp(1.0, startEndRatio, duration);
  26101. this.warp(endStartRatio, 1.0, duration);
  26102. }
  26103. return this;
  26104. }
  26105. crossFadeTo(fadeInAction, duration, warp) {
  26106. return fadeInAction.crossFadeFrom(this, duration, warp);
  26107. }
  26108. stopFading() {
  26109. const weightInterpolant = this._weightInterpolant;
  26110. if (weightInterpolant !== null) {
  26111. this._weightInterpolant = null;
  26112. this._mixer._takeBackControlInterpolant(weightInterpolant);
  26113. }
  26114. return this;
  26115. } // Time Scale Control
  26116. // set the time scale stopping any scheduled warping
  26117. // although .paused = true yields an effective time scale of zero, this
  26118. // method does *not* change .paused, because it would be confusing
  26119. setEffectiveTimeScale(timeScale) {
  26120. this.timeScale = timeScale;
  26121. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  26122. return this.stopWarping();
  26123. } // return the time scale considering warping and .paused
  26124. getEffectiveTimeScale() {
  26125. return this._effectiveTimeScale;
  26126. }
  26127. setDuration(duration) {
  26128. this.timeScale = this._clip.duration / duration;
  26129. return this.stopWarping();
  26130. }
  26131. syncWith(action) {
  26132. this.time = action.time;
  26133. this.timeScale = action.timeScale;
  26134. return this.stopWarping();
  26135. }
  26136. halt(duration) {
  26137. return this.warp(this._effectiveTimeScale, 0, duration);
  26138. }
  26139. warp(startTimeScale, endTimeScale, duration) {
  26140. const mixer = this._mixer,
  26141. now = mixer.time,
  26142. timeScale = this.timeScale;
  26143. let interpolant = this._timeScaleInterpolant;
  26144. if (interpolant === null) {
  26145. interpolant = mixer._lendControlInterpolant();
  26146. this._timeScaleInterpolant = interpolant;
  26147. }
  26148. const times = interpolant.parameterPositions,
  26149. values = interpolant.sampleValues;
  26150. times[0] = now;
  26151. times[1] = now + duration;
  26152. values[0] = startTimeScale / timeScale;
  26153. values[1] = endTimeScale / timeScale;
  26154. return this;
  26155. }
  26156. stopWarping() {
  26157. const timeScaleInterpolant = this._timeScaleInterpolant;
  26158. if (timeScaleInterpolant !== null) {
  26159. this._timeScaleInterpolant = null;
  26160. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  26161. }
  26162. return this;
  26163. } // Object Accessors
  26164. getMixer() {
  26165. return this._mixer;
  26166. }
  26167. getClip() {
  26168. return this._clip;
  26169. }
  26170. getRoot() {
  26171. return this._localRoot || this._mixer._root;
  26172. } // Interna
  26173. _update(time, deltaTime, timeDirection, accuIndex) {
  26174. // called by the mixer
  26175. if (!this.enabled) {
  26176. // call ._updateWeight() to update ._effectiveWeight
  26177. this._updateWeight(time);
  26178. return;
  26179. }
  26180. const startTime = this._startTime;
  26181. if (startTime !== null) {
  26182. // check for scheduled start of action
  26183. const timeRunning = (time - startTime) * timeDirection;
  26184. if (timeRunning < 0 || timeDirection === 0) {
  26185. return; // yet to come / don't decide when delta = 0
  26186. } // start
  26187. this._startTime = null; // unschedule
  26188. deltaTime = timeDirection * timeRunning;
  26189. } // apply time scale and advance time
  26190. deltaTime *= this._updateTimeScale(time);
  26191. const clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  26192. // an effective weight of 0
  26193. const weight = this._updateWeight(time);
  26194. if (weight > 0) {
  26195. const interpolants = this._interpolants;
  26196. const propertyMixers = this._propertyBindings;
  26197. switch (this.blendMode) {
  26198. case AdditiveAnimationBlendMode:
  26199. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26200. interpolants[j].evaluate(clipTime);
  26201. propertyMixers[j].accumulateAdditive(weight);
  26202. }
  26203. break;
  26204. case NormalAnimationBlendMode:
  26205. default:
  26206. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26207. interpolants[j].evaluate(clipTime);
  26208. propertyMixers[j].accumulate(accuIndex, weight);
  26209. }
  26210. }
  26211. }
  26212. }
  26213. _updateWeight(time) {
  26214. let weight = 0;
  26215. if (this.enabled) {
  26216. weight = this.weight;
  26217. const interpolant = this._weightInterpolant;
  26218. if (interpolant !== null) {
  26219. const interpolantValue = interpolant.evaluate(time)[0];
  26220. weight *= interpolantValue;
  26221. if (time > interpolant.parameterPositions[1]) {
  26222. this.stopFading();
  26223. if (interpolantValue === 0) {
  26224. // faded out, disable
  26225. this.enabled = false;
  26226. }
  26227. }
  26228. }
  26229. }
  26230. this._effectiveWeight = weight;
  26231. return weight;
  26232. }
  26233. _updateTimeScale(time) {
  26234. let timeScale = 0;
  26235. if (!this.paused) {
  26236. timeScale = this.timeScale;
  26237. const interpolant = this._timeScaleInterpolant;
  26238. if (interpolant !== null) {
  26239. const interpolantValue = interpolant.evaluate(time)[0];
  26240. timeScale *= interpolantValue;
  26241. if (time > interpolant.parameterPositions[1]) {
  26242. this.stopWarping();
  26243. if (timeScale === 0) {
  26244. // motion has halted, pause
  26245. this.paused = true;
  26246. } else {
  26247. // warp done - apply final time scale
  26248. this.timeScale = timeScale;
  26249. }
  26250. }
  26251. }
  26252. }
  26253. this._effectiveTimeScale = timeScale;
  26254. return timeScale;
  26255. }
  26256. _updateTime(deltaTime) {
  26257. const duration = this._clip.duration;
  26258. const loop = this.loop;
  26259. let time = this.time + deltaTime;
  26260. let loopCount = this._loopCount;
  26261. const pingPong = loop === LoopPingPong;
  26262. if (deltaTime === 0) {
  26263. if (loopCount === -1) return time;
  26264. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  26265. }
  26266. if (loop === LoopOnce) {
  26267. if (loopCount === -1) {
  26268. // just started
  26269. this._loopCount = 0;
  26270. this._setEndings(true, true, false);
  26271. }
  26272. handle_stop: {
  26273. if (time >= duration) {
  26274. time = duration;
  26275. } else if (time < 0) {
  26276. time = 0;
  26277. } else {
  26278. this.time = time;
  26279. break handle_stop;
  26280. }
  26281. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26282. this.time = time;
  26283. this._mixer.dispatchEvent({
  26284. type: 'finished',
  26285. action: this,
  26286. direction: deltaTime < 0 ? -1 : 1
  26287. });
  26288. }
  26289. } else {
  26290. // repetitive Repeat or PingPong
  26291. if (loopCount === -1) {
  26292. // just started
  26293. if (deltaTime >= 0) {
  26294. loopCount = 0;
  26295. this._setEndings(true, this.repetitions === 0, pingPong);
  26296. } else {
  26297. // when looping in reverse direction, the initial
  26298. // transition through zero counts as a repetition,
  26299. // so leave loopCount at -1
  26300. this._setEndings(this.repetitions === 0, true, pingPong);
  26301. }
  26302. }
  26303. if (time >= duration || time < 0) {
  26304. // wrap around
  26305. const loopDelta = Math.floor(time / duration); // signed
  26306. time -= duration * loopDelta;
  26307. loopCount += Math.abs(loopDelta);
  26308. const pending = this.repetitions - loopCount;
  26309. if (pending <= 0) {
  26310. // have to stop (switch state, clamp time, fire event)
  26311. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26312. time = deltaTime > 0 ? duration : 0;
  26313. this.time = time;
  26314. this._mixer.dispatchEvent({
  26315. type: 'finished',
  26316. action: this,
  26317. direction: deltaTime > 0 ? 1 : -1
  26318. });
  26319. } else {
  26320. // keep running
  26321. if (pending === 1) {
  26322. // entering the last round
  26323. const atStart = deltaTime < 0;
  26324. this._setEndings(atStart, !atStart, pingPong);
  26325. } else {
  26326. this._setEndings(false, false, pingPong);
  26327. }
  26328. this._loopCount = loopCount;
  26329. this.time = time;
  26330. this._mixer.dispatchEvent({
  26331. type: 'loop',
  26332. action: this,
  26333. loopDelta: loopDelta
  26334. });
  26335. }
  26336. } else {
  26337. this.time = time;
  26338. }
  26339. if (pingPong && (loopCount & 1) === 1) {
  26340. // invert time for the "pong round"
  26341. return duration - time;
  26342. }
  26343. }
  26344. return time;
  26345. }
  26346. _setEndings(atStart, atEnd, pingPong) {
  26347. const settings = this._interpolantSettings;
  26348. if (pingPong) {
  26349. settings.endingStart = ZeroSlopeEnding;
  26350. settings.endingEnd = ZeroSlopeEnding;
  26351. } else {
  26352. // assuming for LoopOnce atStart == atEnd == true
  26353. if (atStart) {
  26354. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26355. } else {
  26356. settings.endingStart = WrapAroundEnding;
  26357. }
  26358. if (atEnd) {
  26359. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26360. } else {
  26361. settings.endingEnd = WrapAroundEnding;
  26362. }
  26363. }
  26364. }
  26365. _scheduleFading(duration, weightNow, weightThen) {
  26366. const mixer = this._mixer,
  26367. now = mixer.time;
  26368. let interpolant = this._weightInterpolant;
  26369. if (interpolant === null) {
  26370. interpolant = mixer._lendControlInterpolant();
  26371. this._weightInterpolant = interpolant;
  26372. }
  26373. const times = interpolant.parameterPositions,
  26374. values = interpolant.sampleValues;
  26375. times[0] = now;
  26376. values[0] = weightNow;
  26377. times[1] = now + duration;
  26378. values[1] = weightThen;
  26379. return this;
  26380. }
  26381. }
  26382. class AnimationMixer extends EventDispatcher {
  26383. constructor(root) {
  26384. super();
  26385. this._root = root;
  26386. this._initMemoryManager();
  26387. this._accuIndex = 0;
  26388. this.time = 0;
  26389. this.timeScale = 1.0;
  26390. }
  26391. _bindAction(action, prototypeAction) {
  26392. const root = action._localRoot || this._root,
  26393. tracks = action._clip.tracks,
  26394. nTracks = tracks.length,
  26395. bindings = action._propertyBindings,
  26396. interpolants = action._interpolants,
  26397. rootUuid = root.uuid,
  26398. bindingsByRoot = this._bindingsByRootAndName;
  26399. let bindingsByName = bindingsByRoot[rootUuid];
  26400. if (bindingsByName === undefined) {
  26401. bindingsByName = {};
  26402. bindingsByRoot[rootUuid] = bindingsByName;
  26403. }
  26404. for (let i = 0; i !== nTracks; ++i) {
  26405. const track = tracks[i],
  26406. trackName = track.name;
  26407. let binding = bindingsByName[trackName];
  26408. if (binding !== undefined) {
  26409. bindings[i] = binding;
  26410. } else {
  26411. binding = bindings[i];
  26412. if (binding !== undefined) {
  26413. // existing binding, make sure the cache knows
  26414. if (binding._cacheIndex === null) {
  26415. ++binding.referenceCount;
  26416. this._addInactiveBinding(binding, rootUuid, trackName);
  26417. }
  26418. continue;
  26419. }
  26420. const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  26421. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  26422. ++binding.referenceCount;
  26423. this._addInactiveBinding(binding, rootUuid, trackName);
  26424. bindings[i] = binding;
  26425. }
  26426. interpolants[i].resultBuffer = binding.buffer;
  26427. }
  26428. }
  26429. _activateAction(action) {
  26430. if (!this._isActiveAction(action)) {
  26431. if (action._cacheIndex === null) {
  26432. // this action has been forgotten by the cache, but the user
  26433. // appears to be still using it -> rebind
  26434. const rootUuid = (action._localRoot || this._root).uuid,
  26435. clipUuid = action._clip.uuid,
  26436. actionsForClip = this._actionsByClip[clipUuid];
  26437. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  26438. this._addInactiveAction(action, clipUuid, rootUuid);
  26439. }
  26440. const bindings = action._propertyBindings; // increment reference counts / sort out state
  26441. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26442. const binding = bindings[i];
  26443. if (binding.useCount++ === 0) {
  26444. this._lendBinding(binding);
  26445. binding.saveOriginalState();
  26446. }
  26447. }
  26448. this._lendAction(action);
  26449. }
  26450. }
  26451. _deactivateAction(action) {
  26452. if (this._isActiveAction(action)) {
  26453. const bindings = action._propertyBindings; // decrement reference counts / sort out state
  26454. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26455. const binding = bindings[i];
  26456. if (--binding.useCount === 0) {
  26457. binding.restoreOriginalState();
  26458. this._takeBackBinding(binding);
  26459. }
  26460. }
  26461. this._takeBackAction(action);
  26462. }
  26463. } // Memory manager
  26464. _initMemoryManager() {
  26465. this._actions = []; // 'nActiveActions' followed by inactive ones
  26466. this._nActiveActions = 0;
  26467. this._actionsByClip = {}; // inside:
  26468. // {
  26469. // knownActions: Array< AnimationAction > - used as prototypes
  26470. // actionByRoot: AnimationAction - lookup
  26471. // }
  26472. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  26473. this._nActiveBindings = 0;
  26474. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  26475. this._controlInterpolants = []; // same game as above
  26476. this._nActiveControlInterpolants = 0;
  26477. const scope = this;
  26478. this.stats = {
  26479. actions: {
  26480. get total() {
  26481. return scope._actions.length;
  26482. },
  26483. get inUse() {
  26484. return scope._nActiveActions;
  26485. }
  26486. },
  26487. bindings: {
  26488. get total() {
  26489. return scope._bindings.length;
  26490. },
  26491. get inUse() {
  26492. return scope._nActiveBindings;
  26493. }
  26494. },
  26495. controlInterpolants: {
  26496. get total() {
  26497. return scope._controlInterpolants.length;
  26498. },
  26499. get inUse() {
  26500. return scope._nActiveControlInterpolants;
  26501. }
  26502. }
  26503. };
  26504. } // Memory management for AnimationAction objects
  26505. _isActiveAction(action) {
  26506. const index = action._cacheIndex;
  26507. return index !== null && index < this._nActiveActions;
  26508. }
  26509. _addInactiveAction(action, clipUuid, rootUuid) {
  26510. const actions = this._actions,
  26511. actionsByClip = this._actionsByClip;
  26512. let actionsForClip = actionsByClip[clipUuid];
  26513. if (actionsForClip === undefined) {
  26514. actionsForClip = {
  26515. knownActions: [action],
  26516. actionByRoot: {}
  26517. };
  26518. action._byClipCacheIndex = 0;
  26519. actionsByClip[clipUuid] = actionsForClip;
  26520. } else {
  26521. const knownActions = actionsForClip.knownActions;
  26522. action._byClipCacheIndex = knownActions.length;
  26523. knownActions.push(action);
  26524. }
  26525. action._cacheIndex = actions.length;
  26526. actions.push(action);
  26527. actionsForClip.actionByRoot[rootUuid] = action;
  26528. }
  26529. _removeInactiveAction(action) {
  26530. const actions = this._actions,
  26531. lastInactiveAction = actions[actions.length - 1],
  26532. cacheIndex = action._cacheIndex;
  26533. lastInactiveAction._cacheIndex = cacheIndex;
  26534. actions[cacheIndex] = lastInactiveAction;
  26535. actions.pop();
  26536. action._cacheIndex = null;
  26537. const clipUuid = action._clip.uuid,
  26538. actionsByClip = this._actionsByClip,
  26539. actionsForClip = actionsByClip[clipUuid],
  26540. knownActionsForClip = actionsForClip.knownActions,
  26541. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  26542. byClipCacheIndex = action._byClipCacheIndex;
  26543. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  26544. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  26545. knownActionsForClip.pop();
  26546. action._byClipCacheIndex = null;
  26547. const actionByRoot = actionsForClip.actionByRoot,
  26548. rootUuid = (action._localRoot || this._root).uuid;
  26549. delete actionByRoot[rootUuid];
  26550. if (knownActionsForClip.length === 0) {
  26551. delete actionsByClip[clipUuid];
  26552. }
  26553. this._removeInactiveBindingsForAction(action);
  26554. }
  26555. _removeInactiveBindingsForAction(action) {
  26556. const bindings = action._propertyBindings;
  26557. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26558. const binding = bindings[i];
  26559. if (--binding.referenceCount === 0) {
  26560. this._removeInactiveBinding(binding);
  26561. }
  26562. }
  26563. }
  26564. _lendAction(action) {
  26565. // [ active actions | inactive actions ]
  26566. // [ active actions >| inactive actions ]
  26567. // s a
  26568. // <-swap->
  26569. // a s
  26570. const actions = this._actions,
  26571. prevIndex = action._cacheIndex,
  26572. lastActiveIndex = this._nActiveActions++,
  26573. firstInactiveAction = actions[lastActiveIndex];
  26574. action._cacheIndex = lastActiveIndex;
  26575. actions[lastActiveIndex] = action;
  26576. firstInactiveAction._cacheIndex = prevIndex;
  26577. actions[prevIndex] = firstInactiveAction;
  26578. }
  26579. _takeBackAction(action) {
  26580. // [ active actions | inactive actions ]
  26581. // [ active actions |< inactive actions ]
  26582. // a s
  26583. // <-swap->
  26584. // s a
  26585. const actions = this._actions,
  26586. prevIndex = action._cacheIndex,
  26587. firstInactiveIndex = --this._nActiveActions,
  26588. lastActiveAction = actions[firstInactiveIndex];
  26589. action._cacheIndex = firstInactiveIndex;
  26590. actions[firstInactiveIndex] = action;
  26591. lastActiveAction._cacheIndex = prevIndex;
  26592. actions[prevIndex] = lastActiveAction;
  26593. } // Memory management for PropertyMixer objects
  26594. _addInactiveBinding(binding, rootUuid, trackName) {
  26595. const bindingsByRoot = this._bindingsByRootAndName,
  26596. bindings = this._bindings;
  26597. let bindingByName = bindingsByRoot[rootUuid];
  26598. if (bindingByName === undefined) {
  26599. bindingByName = {};
  26600. bindingsByRoot[rootUuid] = bindingByName;
  26601. }
  26602. bindingByName[trackName] = binding;
  26603. binding._cacheIndex = bindings.length;
  26604. bindings.push(binding);
  26605. }
  26606. _removeInactiveBinding(binding) {
  26607. const bindings = this._bindings,
  26608. propBinding = binding.binding,
  26609. rootUuid = propBinding.rootNode.uuid,
  26610. trackName = propBinding.path,
  26611. bindingsByRoot = this._bindingsByRootAndName,
  26612. bindingByName = bindingsByRoot[rootUuid],
  26613. lastInactiveBinding = bindings[bindings.length - 1],
  26614. cacheIndex = binding._cacheIndex;
  26615. lastInactiveBinding._cacheIndex = cacheIndex;
  26616. bindings[cacheIndex] = lastInactiveBinding;
  26617. bindings.pop();
  26618. delete bindingByName[trackName];
  26619. if (Object.keys(bindingByName).length === 0) {
  26620. delete bindingsByRoot[rootUuid];
  26621. }
  26622. }
  26623. _lendBinding(binding) {
  26624. const bindings = this._bindings,
  26625. prevIndex = binding._cacheIndex,
  26626. lastActiveIndex = this._nActiveBindings++,
  26627. firstInactiveBinding = bindings[lastActiveIndex];
  26628. binding._cacheIndex = lastActiveIndex;
  26629. bindings[lastActiveIndex] = binding;
  26630. firstInactiveBinding._cacheIndex = prevIndex;
  26631. bindings[prevIndex] = firstInactiveBinding;
  26632. }
  26633. _takeBackBinding(binding) {
  26634. const bindings = this._bindings,
  26635. prevIndex = binding._cacheIndex,
  26636. firstInactiveIndex = --this._nActiveBindings,
  26637. lastActiveBinding = bindings[firstInactiveIndex];
  26638. binding._cacheIndex = firstInactiveIndex;
  26639. bindings[firstInactiveIndex] = binding;
  26640. lastActiveBinding._cacheIndex = prevIndex;
  26641. bindings[prevIndex] = lastActiveBinding;
  26642. } // Memory management of Interpolants for weight and time scale
  26643. _lendControlInterpolant() {
  26644. const interpolants = this._controlInterpolants,
  26645. lastActiveIndex = this._nActiveControlInterpolants++;
  26646. let interpolant = interpolants[lastActiveIndex];
  26647. if (interpolant === undefined) {
  26648. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  26649. interpolant.__cacheIndex = lastActiveIndex;
  26650. interpolants[lastActiveIndex] = interpolant;
  26651. }
  26652. return interpolant;
  26653. }
  26654. _takeBackControlInterpolant(interpolant) {
  26655. const interpolants = this._controlInterpolants,
  26656. prevIndex = interpolant.__cacheIndex,
  26657. firstInactiveIndex = --this._nActiveControlInterpolants,
  26658. lastActiveInterpolant = interpolants[firstInactiveIndex];
  26659. interpolant.__cacheIndex = firstInactiveIndex;
  26660. interpolants[firstInactiveIndex] = interpolant;
  26661. lastActiveInterpolant.__cacheIndex = prevIndex;
  26662. interpolants[prevIndex] = lastActiveInterpolant;
  26663. } // return an action for a clip optionally using a custom root target
  26664. // object (this method allocates a lot of dynamic memory in case a
  26665. // previously unknown clip/root combination is specified)
  26666. clipAction(clip, optionalRoot, blendMode) {
  26667. const root = optionalRoot || this._root,
  26668. rootUuid = root.uuid;
  26669. let clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
  26670. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  26671. const actionsForClip = this._actionsByClip[clipUuid];
  26672. let prototypeAction = null;
  26673. if (blendMode === undefined) {
  26674. if (clipObject !== null) {
  26675. blendMode = clipObject.blendMode;
  26676. } else {
  26677. blendMode = NormalAnimationBlendMode;
  26678. }
  26679. }
  26680. if (actionsForClip !== undefined) {
  26681. const existingAction = actionsForClip.actionByRoot[rootUuid];
  26682. if (existingAction !== undefined && existingAction.blendMode === blendMode) {
  26683. return existingAction;
  26684. } // we know the clip, so we don't have to parse all
  26685. // the bindings again but can just copy
  26686. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  26687. if (clipObject === null) clipObject = prototypeAction._clip;
  26688. } // clip must be known when specified via string
  26689. if (clipObject === null) return null; // allocate all resources required to run it
  26690. const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
  26691. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  26692. this._addInactiveAction(newAction, clipUuid, rootUuid);
  26693. return newAction;
  26694. } // get an existing action
  26695. existingAction(clip, optionalRoot) {
  26696. const root = optionalRoot || this._root,
  26697. rootUuid = root.uuid,
  26698. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  26699. clipUuid = clipObject ? clipObject.uuid : clip,
  26700. actionsForClip = this._actionsByClip[clipUuid];
  26701. if (actionsForClip !== undefined) {
  26702. return actionsForClip.actionByRoot[rootUuid] || null;
  26703. }
  26704. return null;
  26705. } // deactivates all previously scheduled actions
  26706. stopAllAction() {
  26707. const actions = this._actions,
  26708. nActions = this._nActiveActions;
  26709. for (let i = nActions - 1; i >= 0; --i) {
  26710. actions[i].stop();
  26711. }
  26712. return this;
  26713. } // advance the time and update apply the animation
  26714. update(deltaTime) {
  26715. deltaTime *= this.timeScale;
  26716. const actions = this._actions,
  26717. nActions = this._nActiveActions,
  26718. time = this.time += deltaTime,
  26719. timeDirection = Math.sign(deltaTime),
  26720. accuIndex = this._accuIndex ^= 1; // run active actions
  26721. for (let i = 0; i !== nActions; ++i) {
  26722. const action = actions[i];
  26723. action._update(time, deltaTime, timeDirection, accuIndex);
  26724. } // update scene graph
  26725. const bindings = this._bindings,
  26726. nBindings = this._nActiveBindings;
  26727. for (let i = 0; i !== nBindings; ++i) {
  26728. bindings[i].apply(accuIndex);
  26729. }
  26730. return this;
  26731. } // Allows you to seek to a specific time in an animation.
  26732. setTime(timeInSeconds) {
  26733. this.time = 0; // Zero out time attribute for AnimationMixer object;
  26734. for (let i = 0; i < this._actions.length; i++) {
  26735. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  26736. }
  26737. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  26738. } // return this mixer's root target object
  26739. getRoot() {
  26740. return this._root;
  26741. } // free all resources specific to a particular clip
  26742. uncacheClip(clip) {
  26743. const actions = this._actions,
  26744. clipUuid = clip.uuid,
  26745. actionsByClip = this._actionsByClip,
  26746. actionsForClip = actionsByClip[clipUuid];
  26747. if (actionsForClip !== undefined) {
  26748. // note: just calling _removeInactiveAction would mess up the
  26749. // iteration state and also require updating the state we can
  26750. // just throw away
  26751. const actionsToRemove = actionsForClip.knownActions;
  26752. for (let i = 0, n = actionsToRemove.length; i !== n; ++i) {
  26753. const action = actionsToRemove[i];
  26754. this._deactivateAction(action);
  26755. const cacheIndex = action._cacheIndex,
  26756. lastInactiveAction = actions[actions.length - 1];
  26757. action._cacheIndex = null;
  26758. action._byClipCacheIndex = null;
  26759. lastInactiveAction._cacheIndex = cacheIndex;
  26760. actions[cacheIndex] = lastInactiveAction;
  26761. actions.pop();
  26762. this._removeInactiveBindingsForAction(action);
  26763. }
  26764. delete actionsByClip[clipUuid];
  26765. }
  26766. } // free all resources specific to a particular root target object
  26767. uncacheRoot(root) {
  26768. const rootUuid = root.uuid,
  26769. actionsByClip = this._actionsByClip;
  26770. for (const clipUuid in actionsByClip) {
  26771. const actionByRoot = actionsByClip[clipUuid].actionByRoot,
  26772. action = actionByRoot[rootUuid];
  26773. if (action !== undefined) {
  26774. this._deactivateAction(action);
  26775. this._removeInactiveAction(action);
  26776. }
  26777. }
  26778. const bindingsByRoot = this._bindingsByRootAndName,
  26779. bindingByName = bindingsByRoot[rootUuid];
  26780. if (bindingByName !== undefined) {
  26781. for (const trackName in bindingByName) {
  26782. const binding = bindingByName[trackName];
  26783. binding.restoreOriginalState();
  26784. this._removeInactiveBinding(binding);
  26785. }
  26786. }
  26787. } // remove a targeted clip from the cache
  26788. uncacheAction(clip, optionalRoot) {
  26789. const action = this.existingAction(clip, optionalRoot);
  26790. if (action !== null) {
  26791. this._deactivateAction(action);
  26792. this._removeInactiveAction(action);
  26793. }
  26794. }
  26795. }
  26796. AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array(1);
  26797. class Uniform {
  26798. constructor(value) {
  26799. if (typeof value === 'string') {
  26800. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  26801. value = arguments[1];
  26802. }
  26803. this.value = value;
  26804. }
  26805. clone() {
  26806. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  26807. }
  26808. }
  26809. class InstancedInterleavedBuffer extends InterleavedBuffer {
  26810. constructor(array, stride, meshPerAttribute = 1) {
  26811. super(array, stride);
  26812. this.meshPerAttribute = meshPerAttribute;
  26813. }
  26814. copy(source) {
  26815. super.copy(source);
  26816. this.meshPerAttribute = source.meshPerAttribute;
  26817. return this;
  26818. }
  26819. clone(data) {
  26820. const ib = super.clone(data);
  26821. ib.meshPerAttribute = this.meshPerAttribute;
  26822. return ib;
  26823. }
  26824. toJSON(data) {
  26825. const json = super.toJSON(data);
  26826. json.isInstancedInterleavedBuffer = true;
  26827. json.meshPerAttribute = this.meshPerAttribute;
  26828. return json;
  26829. }
  26830. }
  26831. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  26832. class GLBufferAttribute {
  26833. constructor(buffer, type, itemSize, elementSize, count) {
  26834. this.buffer = buffer;
  26835. this.type = type;
  26836. this.itemSize = itemSize;
  26837. this.elementSize = elementSize;
  26838. this.count = count;
  26839. this.version = 0;
  26840. }
  26841. set needsUpdate(value) {
  26842. if (value === true) this.version++;
  26843. }
  26844. setBuffer(buffer) {
  26845. this.buffer = buffer;
  26846. return this;
  26847. }
  26848. setType(type, elementSize) {
  26849. this.type = type;
  26850. this.elementSize = elementSize;
  26851. return this;
  26852. }
  26853. setItemSize(itemSize) {
  26854. this.itemSize = itemSize;
  26855. return this;
  26856. }
  26857. setCount(count) {
  26858. this.count = count;
  26859. return this;
  26860. }
  26861. }
  26862. GLBufferAttribute.prototype.isGLBufferAttribute = true;
  26863. class Raycaster {
  26864. constructor(origin, direction, near = 0, far = Infinity) {
  26865. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  26866. this.near = near;
  26867. this.far = far;
  26868. this.camera = null;
  26869. this.layers = new Layers();
  26870. this.params = {
  26871. Mesh: {},
  26872. Line: {
  26873. threshold: 1
  26874. },
  26875. LOD: {},
  26876. Points: {
  26877. threshold: 1
  26878. },
  26879. Sprite: {}
  26880. };
  26881. }
  26882. set(origin, direction) {
  26883. // direction is assumed to be normalized (for accurate distance calculations)
  26884. this.ray.set(origin, direction);
  26885. }
  26886. setFromCamera(coords, camera) {
  26887. if (camera && camera.isPerspectiveCamera) {
  26888. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  26889. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  26890. this.camera = camera;
  26891. } else if (camera && camera.isOrthographicCamera) {
  26892. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  26893. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  26894. this.camera = camera;
  26895. } else {
  26896. console.error('THREE.Raycaster: Unsupported camera type: ' + camera.type);
  26897. }
  26898. }
  26899. intersectObject(object, recursive = false, intersects = []) {
  26900. intersectObject(object, this, intersects, recursive);
  26901. intersects.sort(ascSort);
  26902. return intersects;
  26903. }
  26904. intersectObjects(objects, recursive = false, intersects = []) {
  26905. for (let i = 0, l = objects.length; i < l; i++) {
  26906. intersectObject(objects[i], this, intersects, recursive);
  26907. }
  26908. intersects.sort(ascSort);
  26909. return intersects;
  26910. }
  26911. }
  26912. function ascSort(a, b) {
  26913. return a.distance - b.distance;
  26914. }
  26915. function intersectObject(object, raycaster, intersects, recursive) {
  26916. if (object.layers.test(raycaster.layers)) {
  26917. object.raycast(raycaster, intersects);
  26918. }
  26919. if (recursive === true) {
  26920. const children = object.children;
  26921. for (let i = 0, l = children.length; i < l; i++) {
  26922. intersectObject(children[i], raycaster, intersects, true);
  26923. }
  26924. }
  26925. }
  26926. /**
  26927. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  26928. *
  26929. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  26930. * The azimuthal angle (theta) is measured from the positive z-axis.
  26931. */
  26932. class Spherical {
  26933. constructor(radius = 1, phi = 0, theta = 0) {
  26934. this.radius = radius;
  26935. this.phi = phi; // polar angle
  26936. this.theta = theta; // azimuthal angle
  26937. return this;
  26938. }
  26939. set(radius, phi, theta) {
  26940. this.radius = radius;
  26941. this.phi = phi;
  26942. this.theta = theta;
  26943. return this;
  26944. }
  26945. copy(other) {
  26946. this.radius = other.radius;
  26947. this.phi = other.phi;
  26948. this.theta = other.theta;
  26949. return this;
  26950. } // restrict phi to be betwee EPS and PI-EPS
  26951. makeSafe() {
  26952. const EPS = 0.000001;
  26953. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  26954. return this;
  26955. }
  26956. setFromVector3(v) {
  26957. return this.setFromCartesianCoords(v.x, v.y, v.z);
  26958. }
  26959. setFromCartesianCoords(x, y, z) {
  26960. this.radius = Math.sqrt(x * x + y * y + z * z);
  26961. if (this.radius === 0) {
  26962. this.theta = 0;
  26963. this.phi = 0;
  26964. } else {
  26965. this.theta = Math.atan2(x, z);
  26966. this.phi = Math.acos(clamp(y / this.radius, -1, 1));
  26967. }
  26968. return this;
  26969. }
  26970. clone() {
  26971. return new this.constructor().copy(this);
  26972. }
  26973. }
  26974. /**
  26975. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  26976. */
  26977. class Cylindrical {
  26978. constructor(radius = 1, theta = 0, y = 0) {
  26979. this.radius = radius; // distance from the origin to a point in the x-z plane
  26980. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  26981. this.y = y; // height above the x-z plane
  26982. return this;
  26983. }
  26984. set(radius, theta, y) {
  26985. this.radius = radius;
  26986. this.theta = theta;
  26987. this.y = y;
  26988. return this;
  26989. }
  26990. copy(other) {
  26991. this.radius = other.radius;
  26992. this.theta = other.theta;
  26993. this.y = other.y;
  26994. return this;
  26995. }
  26996. setFromVector3(v) {
  26997. return this.setFromCartesianCoords(v.x, v.y, v.z);
  26998. }
  26999. setFromCartesianCoords(x, y, z) {
  27000. this.radius = Math.sqrt(x * x + z * z);
  27001. this.theta = Math.atan2(x, z);
  27002. this.y = y;
  27003. return this;
  27004. }
  27005. clone() {
  27006. return new this.constructor().copy(this);
  27007. }
  27008. }
  27009. const _vector$4 = /*@__PURE__*/new Vector2();
  27010. class Box2 {
  27011. constructor(min = new Vector2(+Infinity, +Infinity), max = new Vector2(-Infinity, -Infinity)) {
  27012. this.min = min;
  27013. this.max = max;
  27014. }
  27015. set(min, max) {
  27016. this.min.copy(min);
  27017. this.max.copy(max);
  27018. return this;
  27019. }
  27020. setFromPoints(points) {
  27021. this.makeEmpty();
  27022. for (let i = 0, il = points.length; i < il; i++) {
  27023. this.expandByPoint(points[i]);
  27024. }
  27025. return this;
  27026. }
  27027. setFromCenterAndSize(center, size) {
  27028. const halfSize = _vector$4.copy(size).multiplyScalar(0.5);
  27029. this.min.copy(center).sub(halfSize);
  27030. this.max.copy(center).add(halfSize);
  27031. return this;
  27032. }
  27033. clone() {
  27034. return new this.constructor().copy(this);
  27035. }
  27036. copy(box) {
  27037. this.min.copy(box.min);
  27038. this.max.copy(box.max);
  27039. return this;
  27040. }
  27041. makeEmpty() {
  27042. this.min.x = this.min.y = +Infinity;
  27043. this.max.x = this.max.y = -Infinity;
  27044. return this;
  27045. }
  27046. isEmpty() {
  27047. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27048. return this.max.x < this.min.x || this.max.y < this.min.y;
  27049. }
  27050. getCenter(target) {
  27051. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  27052. }
  27053. getSize(target) {
  27054. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  27055. }
  27056. expandByPoint(point) {
  27057. this.min.min(point);
  27058. this.max.max(point);
  27059. return this;
  27060. }
  27061. expandByVector(vector) {
  27062. this.min.sub(vector);
  27063. this.max.add(vector);
  27064. return this;
  27065. }
  27066. expandByScalar(scalar) {
  27067. this.min.addScalar(-scalar);
  27068. this.max.addScalar(scalar);
  27069. return this;
  27070. }
  27071. containsPoint(point) {
  27072. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  27073. }
  27074. containsBox(box) {
  27075. 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;
  27076. }
  27077. getParameter(point, target) {
  27078. // This can potentially have a divide by zero if the box
  27079. // has a size dimension of 0.
  27080. 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));
  27081. }
  27082. intersectsBox(box) {
  27083. // using 4 splitting planes to rule out intersections
  27084. 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;
  27085. }
  27086. clampPoint(point, target) {
  27087. return target.copy(point).clamp(this.min, this.max);
  27088. }
  27089. distanceToPoint(point) {
  27090. const clampedPoint = _vector$4.copy(point).clamp(this.min, this.max);
  27091. return clampedPoint.sub(point).length();
  27092. }
  27093. intersect(box) {
  27094. this.min.max(box.min);
  27095. this.max.min(box.max);
  27096. return this;
  27097. }
  27098. union(box) {
  27099. this.min.min(box.min);
  27100. this.max.max(box.max);
  27101. return this;
  27102. }
  27103. translate(offset) {
  27104. this.min.add(offset);
  27105. this.max.add(offset);
  27106. return this;
  27107. }
  27108. equals(box) {
  27109. return box.min.equals(this.min) && box.max.equals(this.max);
  27110. }
  27111. }
  27112. Box2.prototype.isBox2 = true;
  27113. const _startP = /*@__PURE__*/new Vector3();
  27114. const _startEnd = /*@__PURE__*/new Vector3();
  27115. class Line3 {
  27116. constructor(start = new Vector3(), end = new Vector3()) {
  27117. this.start = start;
  27118. this.end = end;
  27119. }
  27120. set(start, end) {
  27121. this.start.copy(start);
  27122. this.end.copy(end);
  27123. return this;
  27124. }
  27125. copy(line) {
  27126. this.start.copy(line.start);
  27127. this.end.copy(line.end);
  27128. return this;
  27129. }
  27130. getCenter(target) {
  27131. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  27132. }
  27133. delta(target) {
  27134. return target.subVectors(this.end, this.start);
  27135. }
  27136. distanceSq() {
  27137. return this.start.distanceToSquared(this.end);
  27138. }
  27139. distance() {
  27140. return this.start.distanceTo(this.end);
  27141. }
  27142. at(t, target) {
  27143. return this.delta(target).multiplyScalar(t).add(this.start);
  27144. }
  27145. closestPointToPointParameter(point, clampToLine) {
  27146. _startP.subVectors(point, this.start);
  27147. _startEnd.subVectors(this.end, this.start);
  27148. const startEnd2 = _startEnd.dot(_startEnd);
  27149. const startEnd_startP = _startEnd.dot(_startP);
  27150. let t = startEnd_startP / startEnd2;
  27151. if (clampToLine) {
  27152. t = clamp(t, 0, 1);
  27153. }
  27154. return t;
  27155. }
  27156. closestPointToPoint(point, clampToLine, target) {
  27157. const t = this.closestPointToPointParameter(point, clampToLine);
  27158. return this.delta(target).multiplyScalar(t).add(this.start);
  27159. }
  27160. applyMatrix4(matrix) {
  27161. this.start.applyMatrix4(matrix);
  27162. this.end.applyMatrix4(matrix);
  27163. return this;
  27164. }
  27165. equals(line) {
  27166. return line.start.equals(this.start) && line.end.equals(this.end);
  27167. }
  27168. clone() {
  27169. return new this.constructor().copy(this);
  27170. }
  27171. }
  27172. class ImmediateRenderObject extends Object3D {
  27173. constructor(material) {
  27174. super();
  27175. this.material = material;
  27176. this.render = function () {};
  27177. this.hasPositions = false;
  27178. this.hasNormals = false;
  27179. this.hasColors = false;
  27180. this.hasUvs = false;
  27181. this.positionArray = null;
  27182. this.normalArray = null;
  27183. this.colorArray = null;
  27184. this.uvArray = null;
  27185. this.count = 0;
  27186. }
  27187. }
  27188. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  27189. const _vector$3 = /*@__PURE__*/new Vector3();
  27190. class SpotLightHelper extends Object3D {
  27191. constructor(light, color) {
  27192. super();
  27193. this.light = light;
  27194. this.light.updateMatrixWorld();
  27195. this.matrix = light.matrixWorld;
  27196. this.matrixAutoUpdate = false;
  27197. this.color = color;
  27198. const geometry = new BufferGeometry();
  27199. 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];
  27200. for (let i = 0, j = 1, l = 32; i < l; i++, j++) {
  27201. const p1 = i / l * Math.PI * 2;
  27202. const p2 = j / l * Math.PI * 2;
  27203. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  27204. }
  27205. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27206. const material = new LineBasicMaterial({
  27207. fog: false,
  27208. toneMapped: false
  27209. });
  27210. this.cone = new LineSegments(geometry, material);
  27211. this.add(this.cone);
  27212. this.update();
  27213. }
  27214. dispose() {
  27215. this.cone.geometry.dispose();
  27216. this.cone.material.dispose();
  27217. }
  27218. update() {
  27219. this.light.updateMatrixWorld();
  27220. const coneLength = this.light.distance ? this.light.distance : 1000;
  27221. const coneWidth = coneLength * Math.tan(this.light.angle);
  27222. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  27223. _vector$3.setFromMatrixPosition(this.light.target.matrixWorld);
  27224. this.cone.lookAt(_vector$3);
  27225. if (this.color !== undefined) {
  27226. this.cone.material.color.set(this.color);
  27227. } else {
  27228. this.cone.material.color.copy(this.light.color);
  27229. }
  27230. }
  27231. }
  27232. const _vector$2 = /*@__PURE__*/new Vector3();
  27233. const _boneMatrix = /*@__PURE__*/new Matrix4();
  27234. const _matrixWorldInv = /*@__PURE__*/new Matrix4();
  27235. class SkeletonHelper extends LineSegments {
  27236. constructor(object) {
  27237. const bones = getBoneList(object);
  27238. const geometry = new BufferGeometry();
  27239. const vertices = [];
  27240. const colors = [];
  27241. const color1 = new Color(0, 0, 1);
  27242. const color2 = new Color(0, 1, 0);
  27243. for (let i = 0; i < bones.length; i++) {
  27244. const bone = bones[i];
  27245. if (bone.parent && bone.parent.isBone) {
  27246. vertices.push(0, 0, 0);
  27247. vertices.push(0, 0, 0);
  27248. colors.push(color1.r, color1.g, color1.b);
  27249. colors.push(color2.r, color2.g, color2.b);
  27250. }
  27251. }
  27252. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27253. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27254. const material = new LineBasicMaterial({
  27255. vertexColors: true,
  27256. depthTest: false,
  27257. depthWrite: false,
  27258. toneMapped: false,
  27259. transparent: true
  27260. });
  27261. super(geometry, material);
  27262. this.type = 'SkeletonHelper';
  27263. this.isSkeletonHelper = true;
  27264. this.root = object;
  27265. this.bones = bones;
  27266. this.matrix = object.matrixWorld;
  27267. this.matrixAutoUpdate = false;
  27268. }
  27269. updateMatrixWorld(force) {
  27270. const bones = this.bones;
  27271. const geometry = this.geometry;
  27272. const position = geometry.getAttribute('position');
  27273. _matrixWorldInv.copy(this.root.matrixWorld).invert();
  27274. for (let i = 0, j = 0; i < bones.length; i++) {
  27275. const bone = bones[i];
  27276. if (bone.parent && bone.parent.isBone) {
  27277. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  27278. _vector$2.setFromMatrixPosition(_boneMatrix);
  27279. position.setXYZ(j, _vector$2.x, _vector$2.y, _vector$2.z);
  27280. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  27281. _vector$2.setFromMatrixPosition(_boneMatrix);
  27282. position.setXYZ(j + 1, _vector$2.x, _vector$2.y, _vector$2.z);
  27283. j += 2;
  27284. }
  27285. }
  27286. geometry.getAttribute('position').needsUpdate = true;
  27287. super.updateMatrixWorld(force);
  27288. }
  27289. }
  27290. function getBoneList(object) {
  27291. const boneList = [];
  27292. if (object && object.isBone) {
  27293. boneList.push(object);
  27294. }
  27295. for (let i = 0; i < object.children.length; i++) {
  27296. boneList.push.apply(boneList, getBoneList(object.children[i]));
  27297. }
  27298. return boneList;
  27299. }
  27300. class PointLightHelper extends Mesh {
  27301. constructor(light, sphereSize, color) {
  27302. const geometry = new SphereGeometry(sphereSize, 4, 2);
  27303. const material = new MeshBasicMaterial({
  27304. wireframe: true,
  27305. fog: false,
  27306. toneMapped: false
  27307. });
  27308. super(geometry, material);
  27309. this.light = light;
  27310. this.light.updateMatrixWorld();
  27311. this.color = color;
  27312. this.type = 'PointLightHelper';
  27313. this.matrix = this.light.matrixWorld;
  27314. this.matrixAutoUpdate = false;
  27315. this.update();
  27316. /*
  27317. // TODO: delete this comment?
  27318. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  27319. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  27320. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  27321. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  27322. const d = light.distance;
  27323. if ( d === 0.0 ) {
  27324. this.lightDistance.visible = false;
  27325. } else {
  27326. this.lightDistance.scale.set( d, d, d );
  27327. }
  27328. this.add( this.lightDistance );
  27329. */
  27330. }
  27331. dispose() {
  27332. this.geometry.dispose();
  27333. this.material.dispose();
  27334. }
  27335. update() {
  27336. if (this.color !== undefined) {
  27337. this.material.color.set(this.color);
  27338. } else {
  27339. this.material.color.copy(this.light.color);
  27340. }
  27341. /*
  27342. const d = this.light.distance;
  27343. if ( d === 0.0 ) {
  27344. this.lightDistance.visible = false;
  27345. } else {
  27346. this.lightDistance.visible = true;
  27347. this.lightDistance.scale.set( d, d, d );
  27348. }
  27349. */
  27350. }
  27351. }
  27352. const _vector$1 = /*@__PURE__*/new Vector3();
  27353. const _color1 = /*@__PURE__*/new Color();
  27354. const _color2 = /*@__PURE__*/new Color();
  27355. class HemisphereLightHelper extends Object3D {
  27356. constructor(light, size, color) {
  27357. super();
  27358. this.light = light;
  27359. this.light.updateMatrixWorld();
  27360. this.matrix = light.matrixWorld;
  27361. this.matrixAutoUpdate = false;
  27362. this.color = color;
  27363. const geometry = new OctahedronGeometry(size);
  27364. geometry.rotateY(Math.PI * 0.5);
  27365. this.material = new MeshBasicMaterial({
  27366. wireframe: true,
  27367. fog: false,
  27368. toneMapped: false
  27369. });
  27370. if (this.color === undefined) this.material.vertexColors = true;
  27371. const position = geometry.getAttribute('position');
  27372. const colors = new Float32Array(position.count * 3);
  27373. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  27374. this.add(new Mesh(geometry, this.material));
  27375. this.update();
  27376. }
  27377. dispose() {
  27378. this.children[0].geometry.dispose();
  27379. this.children[0].material.dispose();
  27380. }
  27381. update() {
  27382. const mesh = this.children[0];
  27383. if (this.color !== undefined) {
  27384. this.material.color.set(this.color);
  27385. } else {
  27386. const colors = mesh.geometry.getAttribute('color');
  27387. _color1.copy(this.light.color);
  27388. _color2.copy(this.light.groundColor);
  27389. for (let i = 0, l = colors.count; i < l; i++) {
  27390. const color = i < l / 2 ? _color1 : _color2;
  27391. colors.setXYZ(i, color.r, color.g, color.b);
  27392. }
  27393. colors.needsUpdate = true;
  27394. }
  27395. mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate());
  27396. }
  27397. }
  27398. class GridHelper extends LineSegments {
  27399. constructor(size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888) {
  27400. color1 = new Color(color1);
  27401. color2 = new Color(color2);
  27402. const center = divisions / 2;
  27403. const step = size / divisions;
  27404. const halfSize = size / 2;
  27405. const vertices = [],
  27406. colors = [];
  27407. for (let i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  27408. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  27409. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  27410. const color = i === center ? color1 : color2;
  27411. color.toArray(colors, j);
  27412. j += 3;
  27413. color.toArray(colors, j);
  27414. j += 3;
  27415. color.toArray(colors, j);
  27416. j += 3;
  27417. color.toArray(colors, j);
  27418. j += 3;
  27419. }
  27420. const geometry = new BufferGeometry();
  27421. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27422. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27423. const material = new LineBasicMaterial({
  27424. vertexColors: true,
  27425. toneMapped: false
  27426. });
  27427. super(geometry, material);
  27428. this.type = 'GridHelper';
  27429. }
  27430. }
  27431. class PolarGridHelper extends LineSegments {
  27432. constructor(radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888) {
  27433. color1 = new Color(color1);
  27434. color2 = new Color(color2);
  27435. const vertices = [];
  27436. const colors = []; // create the radials
  27437. for (let i = 0; i <= radials; i++) {
  27438. const v = i / radials * (Math.PI * 2);
  27439. const x = Math.sin(v) * radius;
  27440. const z = Math.cos(v) * radius;
  27441. vertices.push(0, 0, 0);
  27442. vertices.push(x, 0, z);
  27443. const color = i & 1 ? color1 : color2;
  27444. colors.push(color.r, color.g, color.b);
  27445. colors.push(color.r, color.g, color.b);
  27446. } // create the circles
  27447. for (let i = 0; i <= circles; i++) {
  27448. const color = i & 1 ? color1 : color2;
  27449. const r = radius - radius / circles * i;
  27450. for (let j = 0; j < divisions; j++) {
  27451. // first vertex
  27452. let v = j / divisions * (Math.PI * 2);
  27453. let x = Math.sin(v) * r;
  27454. let z = Math.cos(v) * r;
  27455. vertices.push(x, 0, z);
  27456. colors.push(color.r, color.g, color.b); // second vertex
  27457. v = (j + 1) / divisions * (Math.PI * 2);
  27458. x = Math.sin(v) * r;
  27459. z = Math.cos(v) * r;
  27460. vertices.push(x, 0, z);
  27461. colors.push(color.r, color.g, color.b);
  27462. }
  27463. }
  27464. const geometry = new BufferGeometry();
  27465. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27466. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27467. const material = new LineBasicMaterial({
  27468. vertexColors: true,
  27469. toneMapped: false
  27470. });
  27471. super(geometry, material);
  27472. this.type = 'PolarGridHelper';
  27473. }
  27474. }
  27475. const _v1 = /*@__PURE__*/new Vector3();
  27476. const _v2 = /*@__PURE__*/new Vector3();
  27477. const _v3 = /*@__PURE__*/new Vector3();
  27478. class DirectionalLightHelper extends Object3D {
  27479. constructor(light, size, color) {
  27480. super();
  27481. this.light = light;
  27482. this.light.updateMatrixWorld();
  27483. this.matrix = light.matrixWorld;
  27484. this.matrixAutoUpdate = false;
  27485. this.color = color;
  27486. if (size === undefined) size = 1;
  27487. let geometry = new BufferGeometry();
  27488. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  27489. const material = new LineBasicMaterial({
  27490. fog: false,
  27491. toneMapped: false
  27492. });
  27493. this.lightPlane = new Line(geometry, material);
  27494. this.add(this.lightPlane);
  27495. geometry = new BufferGeometry();
  27496. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  27497. this.targetLine = new Line(geometry, material);
  27498. this.add(this.targetLine);
  27499. this.update();
  27500. }
  27501. dispose() {
  27502. this.lightPlane.geometry.dispose();
  27503. this.lightPlane.material.dispose();
  27504. this.targetLine.geometry.dispose();
  27505. this.targetLine.material.dispose();
  27506. }
  27507. update() {
  27508. _v1.setFromMatrixPosition(this.light.matrixWorld);
  27509. _v2.setFromMatrixPosition(this.light.target.matrixWorld);
  27510. _v3.subVectors(_v2, _v1);
  27511. this.lightPlane.lookAt(_v2);
  27512. if (this.color !== undefined) {
  27513. this.lightPlane.material.color.set(this.color);
  27514. this.targetLine.material.color.set(this.color);
  27515. } else {
  27516. this.lightPlane.material.color.copy(this.light.color);
  27517. this.targetLine.material.color.copy(this.light.color);
  27518. }
  27519. this.targetLine.lookAt(_v2);
  27520. this.targetLine.scale.z = _v3.length();
  27521. }
  27522. }
  27523. const _vector = /*@__PURE__*/new Vector3();
  27524. const _camera = /*@__PURE__*/new Camera();
  27525. /**
  27526. * - shows frustum, line of sight and up of the camera
  27527. * - suitable for fast updates
  27528. * - based on frustum visualization in lightgl.js shadowmap example
  27529. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  27530. */
  27531. class CameraHelper extends LineSegments {
  27532. constructor(camera) {
  27533. const geometry = new BufferGeometry();
  27534. const material = new LineBasicMaterial({
  27535. color: 0xffffff,
  27536. vertexColors: true,
  27537. toneMapped: false
  27538. });
  27539. const vertices = [];
  27540. const colors = [];
  27541. const pointMap = {}; // colors
  27542. const colorFrustum = new Color(0xffaa00);
  27543. const colorCone = new Color(0xff0000);
  27544. const colorUp = new Color(0x00aaff);
  27545. const colorTarget = new Color(0xffffff);
  27546. const colorCross = new Color(0x333333); // near
  27547. addLine('n1', 'n2', colorFrustum);
  27548. addLine('n2', 'n4', colorFrustum);
  27549. addLine('n4', 'n3', colorFrustum);
  27550. addLine('n3', 'n1', colorFrustum); // far
  27551. addLine('f1', 'f2', colorFrustum);
  27552. addLine('f2', 'f4', colorFrustum);
  27553. addLine('f4', 'f3', colorFrustum);
  27554. addLine('f3', 'f1', colorFrustum); // sides
  27555. addLine('n1', 'f1', colorFrustum);
  27556. addLine('n2', 'f2', colorFrustum);
  27557. addLine('n3', 'f3', colorFrustum);
  27558. addLine('n4', 'f4', colorFrustum); // cone
  27559. addLine('p', 'n1', colorCone);
  27560. addLine('p', 'n2', colorCone);
  27561. addLine('p', 'n3', colorCone);
  27562. addLine('p', 'n4', colorCone); // up
  27563. addLine('u1', 'u2', colorUp);
  27564. addLine('u2', 'u3', colorUp);
  27565. addLine('u3', 'u1', colorUp); // target
  27566. addLine('c', 't', colorTarget);
  27567. addLine('p', 'c', colorCross); // cross
  27568. addLine('cn1', 'cn2', colorCross);
  27569. addLine('cn3', 'cn4', colorCross);
  27570. addLine('cf1', 'cf2', colorCross);
  27571. addLine('cf3', 'cf4', colorCross);
  27572. function addLine(a, b, color) {
  27573. addPoint(a, color);
  27574. addPoint(b, color);
  27575. }
  27576. function addPoint(id, color) {
  27577. vertices.push(0, 0, 0);
  27578. colors.push(color.r, color.g, color.b);
  27579. if (pointMap[id] === undefined) {
  27580. pointMap[id] = [];
  27581. }
  27582. pointMap[id].push(vertices.length / 3 - 1);
  27583. }
  27584. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27585. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27586. super(geometry, material);
  27587. this.type = 'CameraHelper';
  27588. this.camera = camera;
  27589. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  27590. this.matrix = camera.matrixWorld;
  27591. this.matrixAutoUpdate = false;
  27592. this.pointMap = pointMap;
  27593. this.update();
  27594. }
  27595. update() {
  27596. const geometry = this.geometry;
  27597. const pointMap = this.pointMap;
  27598. const w = 1,
  27599. h = 1; // we need just camera projection matrix inverse
  27600. // world matrix must be identity
  27601. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  27602. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  27603. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  27604. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  27605. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  27606. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  27607. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  27608. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  27609. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  27610. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  27611. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  27612. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  27613. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  27614. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  27615. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  27616. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  27617. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  27618. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  27619. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  27620. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  27621. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  27622. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  27623. geometry.getAttribute('position').needsUpdate = true;
  27624. }
  27625. dispose() {
  27626. this.geometry.dispose();
  27627. this.material.dispose();
  27628. }
  27629. }
  27630. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  27631. _vector.set(x, y, z).unproject(camera);
  27632. const points = pointMap[point];
  27633. if (points !== undefined) {
  27634. const position = geometry.getAttribute('position');
  27635. for (let i = 0, l = points.length; i < l; i++) {
  27636. position.setXYZ(points[i], _vector.x, _vector.y, _vector.z);
  27637. }
  27638. }
  27639. }
  27640. const _box = /*@__PURE__*/new Box3();
  27641. class BoxHelper extends LineSegments {
  27642. constructor(object, color = 0xffff00) {
  27643. 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]);
  27644. const positions = new Float32Array(8 * 3);
  27645. const geometry = new BufferGeometry();
  27646. geometry.setIndex(new BufferAttribute(indices, 1));
  27647. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  27648. super(geometry, new LineBasicMaterial({
  27649. color: color,
  27650. toneMapped: false
  27651. }));
  27652. this.object = object;
  27653. this.type = 'BoxHelper';
  27654. this.matrixAutoUpdate = false;
  27655. this.update();
  27656. }
  27657. update(object) {
  27658. if (object !== undefined) {
  27659. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  27660. }
  27661. if (this.object !== undefined) {
  27662. _box.setFromObject(this.object);
  27663. }
  27664. if (_box.isEmpty()) return;
  27665. const min = _box.min;
  27666. const max = _box.max;
  27667. /*
  27668. 5____4
  27669. 1/___0/|
  27670. | 6__|_7
  27671. 2/___3/
  27672. 0: max.x, max.y, max.z
  27673. 1: min.x, max.y, max.z
  27674. 2: min.x, min.y, max.z
  27675. 3: max.x, min.y, max.z
  27676. 4: max.x, max.y, min.z
  27677. 5: min.x, max.y, min.z
  27678. 6: min.x, min.y, min.z
  27679. 7: max.x, min.y, min.z
  27680. */
  27681. const position = this.geometry.attributes.position;
  27682. const array = position.array;
  27683. array[0] = max.x;
  27684. array[1] = max.y;
  27685. array[2] = max.z;
  27686. array[3] = min.x;
  27687. array[4] = max.y;
  27688. array[5] = max.z;
  27689. array[6] = min.x;
  27690. array[7] = min.y;
  27691. array[8] = max.z;
  27692. array[9] = max.x;
  27693. array[10] = min.y;
  27694. array[11] = max.z;
  27695. array[12] = max.x;
  27696. array[13] = max.y;
  27697. array[14] = min.z;
  27698. array[15] = min.x;
  27699. array[16] = max.y;
  27700. array[17] = min.z;
  27701. array[18] = min.x;
  27702. array[19] = min.y;
  27703. array[20] = min.z;
  27704. array[21] = max.x;
  27705. array[22] = min.y;
  27706. array[23] = min.z;
  27707. position.needsUpdate = true;
  27708. this.geometry.computeBoundingSphere();
  27709. }
  27710. setFromObject(object) {
  27711. this.object = object;
  27712. this.update();
  27713. return this;
  27714. }
  27715. copy(source) {
  27716. LineSegments.prototype.copy.call(this, source);
  27717. this.object = source.object;
  27718. return this;
  27719. }
  27720. }
  27721. class Box3Helper extends LineSegments {
  27722. constructor(box, color = 0xffff00) {
  27723. 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]);
  27724. 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];
  27725. const geometry = new BufferGeometry();
  27726. geometry.setIndex(new BufferAttribute(indices, 1));
  27727. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27728. super(geometry, new LineBasicMaterial({
  27729. color: color,
  27730. toneMapped: false
  27731. }));
  27732. this.box = box;
  27733. this.type = 'Box3Helper';
  27734. this.geometry.computeBoundingSphere();
  27735. }
  27736. updateMatrixWorld(force) {
  27737. const box = this.box;
  27738. if (box.isEmpty()) return;
  27739. box.getCenter(this.position);
  27740. box.getSize(this.scale);
  27741. this.scale.multiplyScalar(0.5);
  27742. super.updateMatrixWorld(force);
  27743. }
  27744. }
  27745. class PlaneHelper extends Line {
  27746. constructor(plane, size = 1, hex = 0xffff00) {
  27747. const color = hex;
  27748. 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];
  27749. const geometry = new BufferGeometry();
  27750. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27751. geometry.computeBoundingSphere();
  27752. super(geometry, new LineBasicMaterial({
  27753. color: color,
  27754. toneMapped: false
  27755. }));
  27756. this.type = 'PlaneHelper';
  27757. this.plane = plane;
  27758. this.size = size;
  27759. const positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  27760. const geometry2 = new BufferGeometry();
  27761. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  27762. geometry2.computeBoundingSphere();
  27763. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  27764. color: color,
  27765. opacity: 0.2,
  27766. transparent: true,
  27767. depthWrite: false,
  27768. toneMapped: false
  27769. })));
  27770. }
  27771. updateMatrixWorld(force) {
  27772. let scale = -this.plane.constant;
  27773. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  27774. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  27775. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  27776. this.lookAt(this.plane.normal);
  27777. super.updateMatrixWorld(force);
  27778. }
  27779. }
  27780. const _axis = /*@__PURE__*/new Vector3();
  27781. let _lineGeometry, _coneGeometry;
  27782. class ArrowHelper extends Object3D {
  27783. // dir is assumed to be normalized
  27784. 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) {
  27785. super();
  27786. this.type = 'ArrowHelper';
  27787. if (_lineGeometry === undefined) {
  27788. _lineGeometry = new BufferGeometry();
  27789. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  27790. _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1);
  27791. _coneGeometry.translate(0, -0.5, 0);
  27792. }
  27793. this.position.copy(origin);
  27794. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  27795. color: color,
  27796. toneMapped: false
  27797. }));
  27798. this.line.matrixAutoUpdate = false;
  27799. this.add(this.line);
  27800. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  27801. color: color,
  27802. toneMapped: false
  27803. }));
  27804. this.cone.matrixAutoUpdate = false;
  27805. this.add(this.cone);
  27806. this.setDirection(dir);
  27807. this.setLength(length, headLength, headWidth);
  27808. }
  27809. setDirection(dir) {
  27810. // dir is assumed to be normalized
  27811. if (dir.y > 0.99999) {
  27812. this.quaternion.set(0, 0, 0, 1);
  27813. } else if (dir.y < -0.99999) {
  27814. this.quaternion.set(1, 0, 0, 0);
  27815. } else {
  27816. _axis.set(dir.z, 0, -dir.x).normalize();
  27817. const radians = Math.acos(dir.y);
  27818. this.quaternion.setFromAxisAngle(_axis, radians);
  27819. }
  27820. }
  27821. setLength(length, headLength = length * 0.2, headWidth = headLength * 0.2) {
  27822. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  27823. this.line.updateMatrix();
  27824. this.cone.scale.set(headWidth, headLength, headWidth);
  27825. this.cone.position.y = length;
  27826. this.cone.updateMatrix();
  27827. }
  27828. setColor(color) {
  27829. this.line.material.color.set(color);
  27830. this.cone.material.color.set(color);
  27831. }
  27832. copy(source) {
  27833. super.copy(source, false);
  27834. this.line.copy(source.line);
  27835. this.cone.copy(source.cone);
  27836. return this;
  27837. }
  27838. }
  27839. class AxesHelper extends LineSegments {
  27840. constructor(size = 1) {
  27841. const vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  27842. const colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  27843. const geometry = new BufferGeometry();
  27844. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27845. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27846. const material = new LineBasicMaterial({
  27847. vertexColors: true,
  27848. toneMapped: false
  27849. });
  27850. super(geometry, material);
  27851. this.type = 'AxesHelper';
  27852. }
  27853. setColors(xAxisColor, yAxisColor, zAxisColor) {
  27854. const color = new Color();
  27855. const array = this.geometry.attributes.color.array;
  27856. color.set(xAxisColor);
  27857. color.toArray(array, 0);
  27858. color.toArray(array, 3);
  27859. color.set(yAxisColor);
  27860. color.toArray(array, 6);
  27861. color.toArray(array, 9);
  27862. color.set(zAxisColor);
  27863. color.toArray(array, 12);
  27864. color.toArray(array, 15);
  27865. this.geometry.attributes.color.needsUpdate = true;
  27866. return this;
  27867. }
  27868. dispose() {
  27869. this.geometry.dispose();
  27870. this.material.dispose();
  27871. }
  27872. }
  27873. const _floatView = new Float32Array(1);
  27874. const _int32View = new Int32Array(_floatView.buffer);
  27875. class DataUtils {
  27876. // Converts float32 to float16 (stored as uint16 value).
  27877. static toHalfFloat(val) {
  27878. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  27879. /* This method is faster than the OpenEXR implementation (very often
  27880. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  27881. * by James Tursa?s half-precision code. */
  27882. _floatView[0] = val;
  27883. const x = _int32View[0];
  27884. let bits = x >> 16 & 0x8000;
  27885. /* Get the sign */
  27886. let m = x >> 12 & 0x07ff;
  27887. /* Keep one extra bit for rounding */
  27888. const e = x >> 23 & 0xff;
  27889. /* Using int is faster here */
  27890. /* If zero, or denormal, or exponent underflows too much for a denormal
  27891. * half, return signed zero. */
  27892. if (e < 103) return bits;
  27893. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  27894. if (e > 142) {
  27895. bits |= 0x7c00;
  27896. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  27897. * not Inf, so make sure we set one mantissa bit too. */
  27898. bits |= (e == 255 ? 0 : 1) && x & 0x007fffff;
  27899. return bits;
  27900. }
  27901. /* If exponent underflows but not too much, return a denormal */
  27902. if (e < 113) {
  27903. m |= 0x0800;
  27904. /* Extra rounding may overflow and set mantissa to 0 and exponent
  27905. * to 1, which is OK. */
  27906. bits |= (m >> 114 - e) + (m >> 113 - e & 1);
  27907. return bits;
  27908. }
  27909. bits |= e - 112 << 10 | m >> 1;
  27910. /* Extra rounding. An overflow will set mantissa to 0 and increment
  27911. * the exponent, which is OK. */
  27912. bits += m & 1;
  27913. return bits;
  27914. }
  27915. }
  27916. const LineStrip = 0;
  27917. const LinePieces = 1;
  27918. const NoColors = 0;
  27919. const FaceColors = 1;
  27920. const VertexColors = 2;
  27921. function MeshFaceMaterial(materials) {
  27922. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  27923. return materials;
  27924. }
  27925. function MultiMaterial(materials = []) {
  27926. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  27927. materials.isMultiMaterial = true;
  27928. materials.materials = materials;
  27929. materials.clone = function () {
  27930. return materials.slice();
  27931. };
  27932. return materials;
  27933. }
  27934. function PointCloud(geometry, material) {
  27935. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  27936. return new Points(geometry, material);
  27937. }
  27938. function Particle(material) {
  27939. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  27940. return new Sprite(material);
  27941. }
  27942. function ParticleSystem(geometry, material) {
  27943. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  27944. return new Points(geometry, material);
  27945. }
  27946. function PointCloudMaterial(parameters) {
  27947. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  27948. return new PointsMaterial(parameters);
  27949. }
  27950. function ParticleBasicMaterial(parameters) {
  27951. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  27952. return new PointsMaterial(parameters);
  27953. }
  27954. function ParticleSystemMaterial(parameters) {
  27955. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  27956. return new PointsMaterial(parameters);
  27957. }
  27958. function Vertex(x, y, z) {
  27959. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  27960. return new Vector3(x, y, z);
  27961. } //
  27962. function DynamicBufferAttribute(array, itemSize) {
  27963. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.');
  27964. return new BufferAttribute(array, itemSize).setUsage(DynamicDrawUsage);
  27965. }
  27966. function Int8Attribute(array, itemSize) {
  27967. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  27968. return new Int8BufferAttribute(array, itemSize);
  27969. }
  27970. function Uint8Attribute(array, itemSize) {
  27971. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  27972. return new Uint8BufferAttribute(array, itemSize);
  27973. }
  27974. function Uint8ClampedAttribute(array, itemSize) {
  27975. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  27976. return new Uint8ClampedBufferAttribute(array, itemSize);
  27977. }
  27978. function Int16Attribute(array, itemSize) {
  27979. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  27980. return new Int16BufferAttribute(array, itemSize);
  27981. }
  27982. function Uint16Attribute(array, itemSize) {
  27983. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  27984. return new Uint16BufferAttribute(array, itemSize);
  27985. }
  27986. function Int32Attribute(array, itemSize) {
  27987. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  27988. return new Int32BufferAttribute(array, itemSize);
  27989. }
  27990. function Uint32Attribute(array, itemSize) {
  27991. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  27992. return new Uint32BufferAttribute(array, itemSize);
  27993. }
  27994. function Float32Attribute(array, itemSize) {
  27995. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  27996. return new Float32BufferAttribute(array, itemSize);
  27997. }
  27998. function Float64Attribute(array, itemSize) {
  27999. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  28000. return new Float64BufferAttribute(array, itemSize);
  28001. } //
  28002. Curve.create = function (construct, getPoint) {
  28003. console.log('THREE.Curve.create() has been deprecated');
  28004. construct.prototype = Object.create(Curve.prototype);
  28005. construct.prototype.constructor = construct;
  28006. construct.prototype.getPoint = getPoint;
  28007. return construct;
  28008. }; //
  28009. Path.prototype.fromPoints = function (points) {
  28010. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  28011. return this.setFromPoints(points);
  28012. }; //
  28013. function AxisHelper(size) {
  28014. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  28015. return new AxesHelper(size);
  28016. }
  28017. function BoundingBoxHelper(object, color) {
  28018. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  28019. return new BoxHelper(object, color);
  28020. }
  28021. function EdgesHelper(object, hex) {
  28022. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  28023. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  28024. color: hex !== undefined ? hex : 0xffffff
  28025. }));
  28026. }
  28027. GridHelper.prototype.setColors = function () {
  28028. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  28029. };
  28030. SkeletonHelper.prototype.update = function () {
  28031. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  28032. };
  28033. function WireframeHelper(object, hex) {
  28034. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  28035. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  28036. color: hex !== undefined ? hex : 0xffffff
  28037. }));
  28038. } //
  28039. Loader.prototype.extractUrlBase = function (url) {
  28040. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  28041. return LoaderUtils.extractUrlBase(url);
  28042. };
  28043. Loader.Handlers = {
  28044. add: function () {
  28045. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  28046. },
  28047. get: function () {
  28048. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  28049. }
  28050. };
  28051. function XHRLoader(manager) {
  28052. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  28053. return new FileLoader(manager);
  28054. }
  28055. function BinaryTextureLoader(manager) {
  28056. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  28057. return new DataTextureLoader(manager);
  28058. } //
  28059. Box2.prototype.center = function (optionalTarget) {
  28060. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  28061. return this.getCenter(optionalTarget);
  28062. };
  28063. Box2.prototype.empty = function () {
  28064. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  28065. return this.isEmpty();
  28066. };
  28067. Box2.prototype.isIntersectionBox = function (box) {
  28068. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  28069. return this.intersectsBox(box);
  28070. };
  28071. Box2.prototype.size = function (optionalTarget) {
  28072. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  28073. return this.getSize(optionalTarget);
  28074. }; //
  28075. Box3.prototype.center = function (optionalTarget) {
  28076. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  28077. return this.getCenter(optionalTarget);
  28078. };
  28079. Box3.prototype.empty = function () {
  28080. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  28081. return this.isEmpty();
  28082. };
  28083. Box3.prototype.isIntersectionBox = function (box) {
  28084. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  28085. return this.intersectsBox(box);
  28086. };
  28087. Box3.prototype.isIntersectionSphere = function (sphere) {
  28088. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  28089. return this.intersectsSphere(sphere);
  28090. };
  28091. Box3.prototype.size = function (optionalTarget) {
  28092. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  28093. return this.getSize(optionalTarget);
  28094. }; //
  28095. Sphere.prototype.empty = function () {
  28096. console.warn('THREE.Sphere: .empty() has been renamed to .isEmpty().');
  28097. return this.isEmpty();
  28098. }; //
  28099. Frustum.prototype.setFromMatrix = function (m) {
  28100. console.warn('THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().');
  28101. return this.setFromProjectionMatrix(m);
  28102. }; //
  28103. Line3.prototype.center = function (optionalTarget) {
  28104. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  28105. return this.getCenter(optionalTarget);
  28106. }; //
  28107. Matrix3.prototype.flattenToArrayOffset = function (array, offset) {
  28108. console.warn('THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  28109. return this.toArray(array, offset);
  28110. };
  28111. Matrix3.prototype.multiplyVector3 = function (vector) {
  28112. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  28113. return vector.applyMatrix3(this);
  28114. };
  28115. Matrix3.prototype.multiplyVector3Array = function () {
  28116. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  28117. };
  28118. Matrix3.prototype.applyToBufferAttribute = function (attribute) {
  28119. console.warn('THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.');
  28120. return attribute.applyMatrix3(this);
  28121. };
  28122. Matrix3.prototype.applyToVector3Array = function () {
  28123. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  28124. };
  28125. Matrix3.prototype.getInverse = function (matrix) {
  28126. console.warn('THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  28127. return this.copy(matrix).invert();
  28128. }; //
  28129. Matrix4.prototype.extractPosition = function (m) {
  28130. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  28131. return this.copyPosition(m);
  28132. };
  28133. Matrix4.prototype.flattenToArrayOffset = function (array, offset) {
  28134. console.warn('THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  28135. return this.toArray(array, offset);
  28136. };
  28137. Matrix4.prototype.getPosition = function () {
  28138. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  28139. return new Vector3().setFromMatrixColumn(this, 3);
  28140. };
  28141. Matrix4.prototype.setRotationFromQuaternion = function (q) {
  28142. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  28143. return this.makeRotationFromQuaternion(q);
  28144. };
  28145. Matrix4.prototype.multiplyToArray = function () {
  28146. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  28147. };
  28148. Matrix4.prototype.multiplyVector3 = function (vector) {
  28149. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28150. return vector.applyMatrix4(this);
  28151. };
  28152. Matrix4.prototype.multiplyVector4 = function (vector) {
  28153. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28154. return vector.applyMatrix4(this);
  28155. };
  28156. Matrix4.prototype.multiplyVector3Array = function () {
  28157. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  28158. };
  28159. Matrix4.prototype.rotateAxis = function (v) {
  28160. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  28161. v.transformDirection(this);
  28162. };
  28163. Matrix4.prototype.crossVector = function (vector) {
  28164. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28165. return vector.applyMatrix4(this);
  28166. };
  28167. Matrix4.prototype.translate = function () {
  28168. console.error('THREE.Matrix4: .translate() has been removed.');
  28169. };
  28170. Matrix4.prototype.rotateX = function () {
  28171. console.error('THREE.Matrix4: .rotateX() has been removed.');
  28172. };
  28173. Matrix4.prototype.rotateY = function () {
  28174. console.error('THREE.Matrix4: .rotateY() has been removed.');
  28175. };
  28176. Matrix4.prototype.rotateZ = function () {
  28177. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  28178. };
  28179. Matrix4.prototype.rotateByAxis = function () {
  28180. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  28181. };
  28182. Matrix4.prototype.applyToBufferAttribute = function (attribute) {
  28183. console.warn('THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.');
  28184. return attribute.applyMatrix4(this);
  28185. };
  28186. Matrix4.prototype.applyToVector3Array = function () {
  28187. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  28188. };
  28189. Matrix4.prototype.makeFrustum = function (left, right, bottom, top, near, far) {
  28190. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  28191. return this.makePerspective(left, right, top, bottom, near, far);
  28192. };
  28193. Matrix4.prototype.getInverse = function (matrix) {
  28194. console.warn('THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  28195. return this.copy(matrix).invert();
  28196. }; //
  28197. Plane.prototype.isIntersectionLine = function (line) {
  28198. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  28199. return this.intersectsLine(line);
  28200. }; //
  28201. Quaternion.prototype.multiplyVector3 = function (vector) {
  28202. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  28203. return vector.applyQuaternion(this);
  28204. };
  28205. Quaternion.prototype.inverse = function () {
  28206. console.warn('THREE.Quaternion: .inverse() has been renamed to invert().');
  28207. return this.invert();
  28208. }; //
  28209. Ray.prototype.isIntersectionBox = function (box) {
  28210. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  28211. return this.intersectsBox(box);
  28212. };
  28213. Ray.prototype.isIntersectionPlane = function (plane) {
  28214. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  28215. return this.intersectsPlane(plane);
  28216. };
  28217. Ray.prototype.isIntersectionSphere = function (sphere) {
  28218. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  28219. return this.intersectsSphere(sphere);
  28220. }; //
  28221. Triangle.prototype.area = function () {
  28222. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  28223. return this.getArea();
  28224. };
  28225. Triangle.prototype.barycoordFromPoint = function (point, target) {
  28226. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28227. return this.getBarycoord(point, target);
  28228. };
  28229. Triangle.prototype.midpoint = function (target) {
  28230. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  28231. return this.getMidpoint(target);
  28232. };
  28233. Triangle.prototypenormal = function (target) {
  28234. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28235. return this.getNormal(target);
  28236. };
  28237. Triangle.prototype.plane = function (target) {
  28238. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  28239. return this.getPlane(target);
  28240. };
  28241. Triangle.barycoordFromPoint = function (point, a, b, c, target) {
  28242. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28243. return Triangle.getBarycoord(point, a, b, c, target);
  28244. };
  28245. Triangle.normal = function (a, b, c, target) {
  28246. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28247. return Triangle.getNormal(a, b, c, target);
  28248. }; //
  28249. Shape.prototype.extractAllPoints = function (divisions) {
  28250. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  28251. return this.extractPoints(divisions);
  28252. };
  28253. Shape.prototype.extrude = function (options) {
  28254. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  28255. return new ExtrudeGeometry(this, options);
  28256. };
  28257. Shape.prototype.makeGeometry = function (options) {
  28258. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  28259. return new ShapeGeometry(this, options);
  28260. }; //
  28261. Vector2.prototype.fromAttribute = function (attribute, index, offset) {
  28262. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28263. return this.fromBufferAttribute(attribute, index, offset);
  28264. };
  28265. Vector2.prototype.distanceToManhattan = function (v) {
  28266. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28267. return this.manhattanDistanceTo(v);
  28268. };
  28269. Vector2.prototype.lengthManhattan = function () {
  28270. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  28271. return this.manhattanLength();
  28272. }; //
  28273. Vector3.prototype.setEulerFromRotationMatrix = function () {
  28274. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  28275. };
  28276. Vector3.prototype.setEulerFromQuaternion = function () {
  28277. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  28278. };
  28279. Vector3.prototype.getPositionFromMatrix = function (m) {
  28280. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  28281. return this.setFromMatrixPosition(m);
  28282. };
  28283. Vector3.prototype.getScaleFromMatrix = function (m) {
  28284. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  28285. return this.setFromMatrixScale(m);
  28286. };
  28287. Vector3.prototype.getColumnFromMatrix = function (index, matrix) {
  28288. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  28289. return this.setFromMatrixColumn(matrix, index);
  28290. };
  28291. Vector3.prototype.applyProjection = function (m) {
  28292. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  28293. return this.applyMatrix4(m);
  28294. };
  28295. Vector3.prototype.fromAttribute = function (attribute, index, offset) {
  28296. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28297. return this.fromBufferAttribute(attribute, index, offset);
  28298. };
  28299. Vector3.prototype.distanceToManhattan = function (v) {
  28300. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28301. return this.manhattanDistanceTo(v);
  28302. };
  28303. Vector3.prototype.lengthManhattan = function () {
  28304. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  28305. return this.manhattanLength();
  28306. }; //
  28307. Vector4.prototype.fromAttribute = function (attribute, index, offset) {
  28308. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28309. return this.fromBufferAttribute(attribute, index, offset);
  28310. };
  28311. Vector4.prototype.lengthManhattan = function () {
  28312. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  28313. return this.manhattanLength();
  28314. }; //
  28315. Object3D.prototype.getChildByName = function (name) {
  28316. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  28317. return this.getObjectByName(name);
  28318. };
  28319. Object3D.prototype.renderDepth = function () {
  28320. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  28321. };
  28322. Object3D.prototype.translate = function (distance, axis) {
  28323. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  28324. return this.translateOnAxis(axis, distance);
  28325. };
  28326. Object3D.prototype.getWorldRotation = function () {
  28327. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  28328. };
  28329. Object3D.prototype.applyMatrix = function (matrix) {
  28330. console.warn('THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().');
  28331. return this.applyMatrix4(matrix);
  28332. };
  28333. Object.defineProperties(Object3D.prototype, {
  28334. eulerOrder: {
  28335. get: function () {
  28336. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28337. return this.rotation.order;
  28338. },
  28339. set: function (value) {
  28340. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28341. this.rotation.order = value;
  28342. }
  28343. },
  28344. useQuaternion: {
  28345. get: function () {
  28346. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28347. },
  28348. set: function () {
  28349. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28350. }
  28351. }
  28352. });
  28353. Mesh.prototype.setDrawMode = function () {
  28354. console.error('THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28355. };
  28356. Object.defineProperties(Mesh.prototype, {
  28357. drawMode: {
  28358. get: function () {
  28359. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.');
  28360. return TrianglesDrawMode;
  28361. },
  28362. set: function () {
  28363. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28364. }
  28365. }
  28366. });
  28367. SkinnedMesh.prototype.initBones = function () {
  28368. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  28369. }; //
  28370. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  28371. console.warn('THREE.PerspectiveCamera.setLens is deprecated. ' + 'Use .setFocalLength and .filmGauge for a photographic setup.');
  28372. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  28373. this.setFocalLength(focalLength);
  28374. }; //
  28375. Object.defineProperties(Light.prototype, {
  28376. onlyShadow: {
  28377. set: function () {
  28378. console.warn('THREE.Light: .onlyShadow has been removed.');
  28379. }
  28380. },
  28381. shadowCameraFov: {
  28382. set: function (value) {
  28383. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  28384. this.shadow.camera.fov = value;
  28385. }
  28386. },
  28387. shadowCameraLeft: {
  28388. set: function (value) {
  28389. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  28390. this.shadow.camera.left = value;
  28391. }
  28392. },
  28393. shadowCameraRight: {
  28394. set: function (value) {
  28395. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  28396. this.shadow.camera.right = value;
  28397. }
  28398. },
  28399. shadowCameraTop: {
  28400. set: function (value) {
  28401. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  28402. this.shadow.camera.top = value;
  28403. }
  28404. },
  28405. shadowCameraBottom: {
  28406. set: function (value) {
  28407. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  28408. this.shadow.camera.bottom = value;
  28409. }
  28410. },
  28411. shadowCameraNear: {
  28412. set: function (value) {
  28413. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  28414. this.shadow.camera.near = value;
  28415. }
  28416. },
  28417. shadowCameraFar: {
  28418. set: function (value) {
  28419. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  28420. this.shadow.camera.far = value;
  28421. }
  28422. },
  28423. shadowCameraVisible: {
  28424. set: function () {
  28425. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  28426. }
  28427. },
  28428. shadowBias: {
  28429. set: function (value) {
  28430. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  28431. this.shadow.bias = value;
  28432. }
  28433. },
  28434. shadowDarkness: {
  28435. set: function () {
  28436. console.warn('THREE.Light: .shadowDarkness has been removed.');
  28437. }
  28438. },
  28439. shadowMapWidth: {
  28440. set: function (value) {
  28441. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  28442. this.shadow.mapSize.width = value;
  28443. }
  28444. },
  28445. shadowMapHeight: {
  28446. set: function (value) {
  28447. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  28448. this.shadow.mapSize.height = value;
  28449. }
  28450. }
  28451. }); //
  28452. Object.defineProperties(BufferAttribute.prototype, {
  28453. length: {
  28454. get: function () {
  28455. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  28456. return this.array.length;
  28457. }
  28458. },
  28459. dynamic: {
  28460. get: function () {
  28461. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28462. return this.usage === DynamicDrawUsage;
  28463. },
  28464. set: function () {
  28465. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28466. this.setUsage(DynamicDrawUsage);
  28467. }
  28468. }
  28469. });
  28470. BufferAttribute.prototype.setDynamic = function (value) {
  28471. console.warn('THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28472. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28473. return this;
  28474. };
  28475. BufferAttribute.prototype.copyIndicesArray = function () {
  28476. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  28477. }, BufferAttribute.prototype.setArray = function () {
  28478. console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28479. }; //
  28480. BufferGeometry.prototype.addIndex = function (index) {
  28481. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  28482. this.setIndex(index);
  28483. };
  28484. BufferGeometry.prototype.addAttribute = function (name, attribute) {
  28485. console.warn('THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().');
  28486. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  28487. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  28488. return this.setAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  28489. }
  28490. if (name === 'index') {
  28491. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  28492. this.setIndex(attribute);
  28493. return this;
  28494. }
  28495. return this.setAttribute(name, attribute);
  28496. };
  28497. BufferGeometry.prototype.addDrawCall = function (start, count, indexOffset) {
  28498. if (indexOffset !== undefined) {
  28499. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  28500. }
  28501. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  28502. this.addGroup(start, count);
  28503. };
  28504. BufferGeometry.prototype.clearDrawCalls = function () {
  28505. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  28506. this.clearGroups();
  28507. };
  28508. BufferGeometry.prototype.computeOffsets = function () {
  28509. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  28510. };
  28511. BufferGeometry.prototype.removeAttribute = function (name) {
  28512. console.warn('THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().');
  28513. return this.deleteAttribute(name);
  28514. };
  28515. BufferGeometry.prototype.applyMatrix = function (matrix) {
  28516. console.warn('THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().');
  28517. return this.applyMatrix4(matrix);
  28518. };
  28519. Object.defineProperties(BufferGeometry.prototype, {
  28520. drawcalls: {
  28521. get: function () {
  28522. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  28523. return this.groups;
  28524. }
  28525. },
  28526. offsets: {
  28527. get: function () {
  28528. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  28529. return this.groups;
  28530. }
  28531. }
  28532. });
  28533. InterleavedBuffer.prototype.setDynamic = function (value) {
  28534. console.warn('THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28535. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28536. return this;
  28537. };
  28538. InterleavedBuffer.prototype.setArray = function () {
  28539. console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28540. }; //
  28541. ExtrudeGeometry.prototype.getArrays = function () {
  28542. console.error('THREE.ExtrudeGeometry: .getArrays() has been removed.');
  28543. };
  28544. ExtrudeGeometry.prototype.addShapeList = function () {
  28545. console.error('THREE.ExtrudeGeometry: .addShapeList() has been removed.');
  28546. };
  28547. ExtrudeGeometry.prototype.addShape = function () {
  28548. console.error('THREE.ExtrudeGeometry: .addShape() has been removed.');
  28549. }; //
  28550. Scene.prototype.dispose = function () {
  28551. console.error('THREE.Scene: .dispose() has been removed.');
  28552. }; //
  28553. Uniform.prototype.onUpdate = function () {
  28554. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  28555. return this;
  28556. }; //
  28557. Object.defineProperties(Material.prototype, {
  28558. wrapAround: {
  28559. get: function () {
  28560. console.warn('THREE.Material: .wrapAround has been removed.');
  28561. },
  28562. set: function () {
  28563. console.warn('THREE.Material: .wrapAround has been removed.');
  28564. }
  28565. },
  28566. overdraw: {
  28567. get: function () {
  28568. console.warn('THREE.Material: .overdraw has been removed.');
  28569. },
  28570. set: function () {
  28571. console.warn('THREE.Material: .overdraw has been removed.');
  28572. }
  28573. },
  28574. wrapRGB: {
  28575. get: function () {
  28576. console.warn('THREE.Material: .wrapRGB has been removed.');
  28577. return new Color();
  28578. }
  28579. },
  28580. shading: {
  28581. get: function () {
  28582. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28583. },
  28584. set: function (value) {
  28585. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28586. this.flatShading = value === FlatShading;
  28587. }
  28588. },
  28589. stencilMask: {
  28590. get: function () {
  28591. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28592. return this.stencilFuncMask;
  28593. },
  28594. set: function (value) {
  28595. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28596. this.stencilFuncMask = value;
  28597. }
  28598. },
  28599. vertexTangents: {
  28600. get: function () {
  28601. console.warn('THREE.' + this.type + ': .vertexTangents has been removed.');
  28602. },
  28603. set: function () {
  28604. console.warn('THREE.' + this.type + ': .vertexTangents has been removed.');
  28605. }
  28606. }
  28607. });
  28608. Object.defineProperties(ShaderMaterial.prototype, {
  28609. derivatives: {
  28610. get: function () {
  28611. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28612. return this.extensions.derivatives;
  28613. },
  28614. set: function (value) {
  28615. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28616. this.extensions.derivatives = value;
  28617. }
  28618. }
  28619. }); //
  28620. WebGLRenderer.prototype.clearTarget = function (renderTarget, color, depth, stencil) {
  28621. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  28622. this.setRenderTarget(renderTarget);
  28623. this.clear(color, depth, stencil);
  28624. };
  28625. WebGLRenderer.prototype.animate = function (callback) {
  28626. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  28627. this.setAnimationLoop(callback);
  28628. };
  28629. WebGLRenderer.prototype.getCurrentRenderTarget = function () {
  28630. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  28631. return this.getRenderTarget();
  28632. };
  28633. WebGLRenderer.prototype.getMaxAnisotropy = function () {
  28634. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  28635. return this.capabilities.getMaxAnisotropy();
  28636. };
  28637. WebGLRenderer.prototype.getPrecision = function () {
  28638. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  28639. return this.capabilities.precision;
  28640. };
  28641. WebGLRenderer.prototype.resetGLState = function () {
  28642. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  28643. return this.state.reset();
  28644. };
  28645. WebGLRenderer.prototype.supportsFloatTextures = function () {
  28646. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  28647. return this.extensions.get('OES_texture_float');
  28648. };
  28649. WebGLRenderer.prototype.supportsHalfFloatTextures = function () {
  28650. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  28651. return this.extensions.get('OES_texture_half_float');
  28652. };
  28653. WebGLRenderer.prototype.supportsStandardDerivatives = function () {
  28654. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  28655. return this.extensions.get('OES_standard_derivatives');
  28656. };
  28657. WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () {
  28658. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  28659. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  28660. };
  28661. WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () {
  28662. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  28663. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  28664. };
  28665. WebGLRenderer.prototype.supportsBlendMinMax = function () {
  28666. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  28667. return this.extensions.get('EXT_blend_minmax');
  28668. };
  28669. WebGLRenderer.prototype.supportsVertexTextures = function () {
  28670. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  28671. return this.capabilities.vertexTextures;
  28672. };
  28673. WebGLRenderer.prototype.supportsInstancedArrays = function () {
  28674. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  28675. return this.extensions.get('ANGLE_instanced_arrays');
  28676. };
  28677. WebGLRenderer.prototype.enableScissorTest = function (boolean) {
  28678. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  28679. this.setScissorTest(boolean);
  28680. };
  28681. WebGLRenderer.prototype.initMaterial = function () {
  28682. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  28683. };
  28684. WebGLRenderer.prototype.addPrePlugin = function () {
  28685. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  28686. };
  28687. WebGLRenderer.prototype.addPostPlugin = function () {
  28688. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  28689. };
  28690. WebGLRenderer.prototype.updateShadowMap = function () {
  28691. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  28692. };
  28693. WebGLRenderer.prototype.setFaceCulling = function () {
  28694. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  28695. };
  28696. WebGLRenderer.prototype.allocTextureUnit = function () {
  28697. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  28698. };
  28699. WebGLRenderer.prototype.setTexture = function () {
  28700. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  28701. };
  28702. WebGLRenderer.prototype.setTexture2D = function () {
  28703. console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
  28704. };
  28705. WebGLRenderer.prototype.setTextureCube = function () {
  28706. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  28707. };
  28708. WebGLRenderer.prototype.getActiveMipMapLevel = function () {
  28709. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  28710. return this.getActiveMipmapLevel();
  28711. };
  28712. Object.defineProperties(WebGLRenderer.prototype, {
  28713. shadowMapEnabled: {
  28714. get: function () {
  28715. return this.shadowMap.enabled;
  28716. },
  28717. set: function (value) {
  28718. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  28719. this.shadowMap.enabled = value;
  28720. }
  28721. },
  28722. shadowMapType: {
  28723. get: function () {
  28724. return this.shadowMap.type;
  28725. },
  28726. set: function (value) {
  28727. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  28728. this.shadowMap.type = value;
  28729. }
  28730. },
  28731. shadowMapCullFace: {
  28732. get: function () {
  28733. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  28734. return undefined;
  28735. },
  28736. set: function () {
  28737. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  28738. }
  28739. },
  28740. context: {
  28741. get: function () {
  28742. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  28743. return this.getContext();
  28744. }
  28745. },
  28746. vr: {
  28747. get: function () {
  28748. console.warn('THREE.WebGLRenderer: .vr has been renamed to .xr');
  28749. return this.xr;
  28750. }
  28751. },
  28752. gammaInput: {
  28753. get: function () {
  28754. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  28755. return false;
  28756. },
  28757. set: function () {
  28758. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  28759. }
  28760. },
  28761. gammaOutput: {
  28762. get: function () {
  28763. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  28764. return false;
  28765. },
  28766. set: function (value) {
  28767. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  28768. this.outputEncoding = value === true ? sRGBEncoding : LinearEncoding;
  28769. }
  28770. },
  28771. toneMappingWhitePoint: {
  28772. get: function () {
  28773. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  28774. return 1.0;
  28775. },
  28776. set: function () {
  28777. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  28778. }
  28779. }
  28780. });
  28781. Object.defineProperties(WebGLShadowMap.prototype, {
  28782. cullFace: {
  28783. get: function () {
  28784. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  28785. return undefined;
  28786. },
  28787. set: function () {
  28788. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  28789. }
  28790. },
  28791. renderReverseSided: {
  28792. get: function () {
  28793. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  28794. return undefined;
  28795. },
  28796. set: function () {
  28797. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  28798. }
  28799. },
  28800. renderSingleSided: {
  28801. get: function () {
  28802. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  28803. return undefined;
  28804. },
  28805. set: function () {
  28806. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  28807. }
  28808. }
  28809. });
  28810. function WebGLRenderTargetCube(width, height, options) {
  28811. console.warn('THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).');
  28812. return new WebGLCubeRenderTarget(width, options);
  28813. } //
  28814. Object.defineProperties(WebGLRenderTarget.prototype, {
  28815. wrapS: {
  28816. get: function () {
  28817. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  28818. return this.texture.wrapS;
  28819. },
  28820. set: function (value) {
  28821. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  28822. this.texture.wrapS = value;
  28823. }
  28824. },
  28825. wrapT: {
  28826. get: function () {
  28827. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  28828. return this.texture.wrapT;
  28829. },
  28830. set: function (value) {
  28831. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  28832. this.texture.wrapT = value;
  28833. }
  28834. },
  28835. magFilter: {
  28836. get: function () {
  28837. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  28838. return this.texture.magFilter;
  28839. },
  28840. set: function (value) {
  28841. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  28842. this.texture.magFilter = value;
  28843. }
  28844. },
  28845. minFilter: {
  28846. get: function () {
  28847. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  28848. return this.texture.minFilter;
  28849. },
  28850. set: function (value) {
  28851. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  28852. this.texture.minFilter = value;
  28853. }
  28854. },
  28855. anisotropy: {
  28856. get: function () {
  28857. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  28858. return this.texture.anisotropy;
  28859. },
  28860. set: function (value) {
  28861. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  28862. this.texture.anisotropy = value;
  28863. }
  28864. },
  28865. offset: {
  28866. get: function () {
  28867. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  28868. return this.texture.offset;
  28869. },
  28870. set: function (value) {
  28871. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  28872. this.texture.offset = value;
  28873. }
  28874. },
  28875. repeat: {
  28876. get: function () {
  28877. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  28878. return this.texture.repeat;
  28879. },
  28880. set: function (value) {
  28881. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  28882. this.texture.repeat = value;
  28883. }
  28884. },
  28885. format: {
  28886. get: function () {
  28887. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  28888. return this.texture.format;
  28889. },
  28890. set: function (value) {
  28891. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  28892. this.texture.format = value;
  28893. }
  28894. },
  28895. type: {
  28896. get: function () {
  28897. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  28898. return this.texture.type;
  28899. },
  28900. set: function (value) {
  28901. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  28902. this.texture.type = value;
  28903. }
  28904. },
  28905. generateMipmaps: {
  28906. get: function () {
  28907. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  28908. return this.texture.generateMipmaps;
  28909. },
  28910. set: function (value) {
  28911. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  28912. this.texture.generateMipmaps = value;
  28913. }
  28914. }
  28915. }); //
  28916. Audio.prototype.load = function (file) {
  28917. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  28918. const scope = this;
  28919. const audioLoader = new AudioLoader();
  28920. audioLoader.load(file, function (buffer) {
  28921. scope.setBuffer(buffer);
  28922. });
  28923. return this;
  28924. };
  28925. AudioAnalyser.prototype.getData = function () {
  28926. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  28927. return this.getFrequencyData();
  28928. }; //
  28929. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  28930. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  28931. return this.update(renderer, scene);
  28932. };
  28933. CubeCamera.prototype.clear = function (renderer, color, depth, stencil) {
  28934. console.warn('THREE.CubeCamera: .clear() is now .renderTarget.clear().');
  28935. return this.renderTarget.clear(renderer, color, depth, stencil);
  28936. };
  28937. ImageUtils.crossOrigin = undefined;
  28938. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  28939. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  28940. const loader = new TextureLoader();
  28941. loader.setCrossOrigin(this.crossOrigin);
  28942. const texture = loader.load(url, onLoad, undefined, onError);
  28943. if (mapping) texture.mapping = mapping;
  28944. return texture;
  28945. };
  28946. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  28947. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  28948. const loader = new CubeTextureLoader();
  28949. loader.setCrossOrigin(this.crossOrigin);
  28950. const texture = loader.load(urls, onLoad, undefined, onError);
  28951. if (mapping) texture.mapping = mapping;
  28952. return texture;
  28953. };
  28954. ImageUtils.loadCompressedTexture = function () {
  28955. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  28956. };
  28957. ImageUtils.loadCompressedTextureCube = function () {
  28958. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  28959. }; //
  28960. function CanvasRenderer() {
  28961. console.error('THREE.CanvasRenderer has been removed');
  28962. } //
  28963. function JSONLoader() {
  28964. console.error('THREE.JSONLoader has been removed.');
  28965. } //
  28966. const SceneUtils = {
  28967. createMultiMaterialObject: function () {
  28968. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28969. },
  28970. detach: function () {
  28971. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28972. },
  28973. attach: function () {
  28974. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28975. }
  28976. }; //
  28977. function LensFlare() {
  28978. console.error('THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js');
  28979. }
  28980. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  28981. /* eslint-disable no-undef */
  28982. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  28983. detail: {
  28984. revision: REVISION
  28985. }
  28986. }));
  28987. /* eslint-enable no-undef */
  28988. }
  28989. if (typeof window !== 'undefined') {
  28990. if (window.__THREE__) {
  28991. console.warn('WARNING: Multiple instances of Three.js being imported.');
  28992. } else {
  28993. window.__THREE__ = REVISION;
  28994. }
  28995. }
  28996. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  28997. exports.AddEquation = AddEquation;
  28998. exports.AddOperation = AddOperation;
  28999. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  29000. exports.AdditiveBlending = AdditiveBlending;
  29001. exports.AlphaFormat = AlphaFormat;
  29002. exports.AlwaysDepth = AlwaysDepth;
  29003. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  29004. exports.AmbientLight = AmbientLight;
  29005. exports.AmbientLightProbe = AmbientLightProbe;
  29006. exports.AnimationClip = AnimationClip;
  29007. exports.AnimationLoader = AnimationLoader;
  29008. exports.AnimationMixer = AnimationMixer;
  29009. exports.AnimationObjectGroup = AnimationObjectGroup;
  29010. exports.AnimationUtils = AnimationUtils;
  29011. exports.ArcCurve = ArcCurve;
  29012. exports.ArrayCamera = ArrayCamera;
  29013. exports.ArrowHelper = ArrowHelper;
  29014. exports.Audio = Audio;
  29015. exports.AudioAnalyser = AudioAnalyser;
  29016. exports.AudioContext = AudioContext;
  29017. exports.AudioListener = AudioListener;
  29018. exports.AudioLoader = AudioLoader;
  29019. exports.AxesHelper = AxesHelper;
  29020. exports.AxisHelper = AxisHelper;
  29021. exports.BackSide = BackSide;
  29022. exports.BasicDepthPacking = BasicDepthPacking;
  29023. exports.BasicShadowMap = BasicShadowMap;
  29024. exports.BinaryTextureLoader = BinaryTextureLoader;
  29025. exports.Bone = Bone;
  29026. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  29027. exports.BoundingBoxHelper = BoundingBoxHelper;
  29028. exports.Box2 = Box2;
  29029. exports.Box3 = Box3;
  29030. exports.Box3Helper = Box3Helper;
  29031. exports.BoxBufferGeometry = BoxGeometry;
  29032. exports.BoxGeometry = BoxGeometry;
  29033. exports.BoxHelper = BoxHelper;
  29034. exports.BufferAttribute = BufferAttribute;
  29035. exports.BufferGeometry = BufferGeometry;
  29036. exports.BufferGeometryLoader = BufferGeometryLoader;
  29037. exports.ByteType = ByteType;
  29038. exports.Cache = Cache;
  29039. exports.Camera = Camera;
  29040. exports.CameraHelper = CameraHelper;
  29041. exports.CanvasRenderer = CanvasRenderer;
  29042. exports.CanvasTexture = CanvasTexture;
  29043. exports.CatmullRomCurve3 = CatmullRomCurve3;
  29044. exports.CineonToneMapping = CineonToneMapping;
  29045. exports.CircleBufferGeometry = CircleGeometry;
  29046. exports.CircleGeometry = CircleGeometry;
  29047. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  29048. exports.Clock = Clock;
  29049. exports.Color = Color;
  29050. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  29051. exports.CompressedTexture = CompressedTexture;
  29052. exports.CompressedTextureLoader = CompressedTextureLoader;
  29053. exports.ConeBufferGeometry = ConeGeometry;
  29054. exports.ConeGeometry = ConeGeometry;
  29055. exports.CubeCamera = CubeCamera;
  29056. exports.CubeReflectionMapping = CubeReflectionMapping;
  29057. exports.CubeRefractionMapping = CubeRefractionMapping;
  29058. exports.CubeTexture = CubeTexture;
  29059. exports.CubeTextureLoader = CubeTextureLoader;
  29060. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  29061. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  29062. exports.CubicBezierCurve = CubicBezierCurve;
  29063. exports.CubicBezierCurve3 = CubicBezierCurve3;
  29064. exports.CubicInterpolant = CubicInterpolant;
  29065. exports.CullFaceBack = CullFaceBack;
  29066. exports.CullFaceFront = CullFaceFront;
  29067. exports.CullFaceFrontBack = CullFaceFrontBack;
  29068. exports.CullFaceNone = CullFaceNone;
  29069. exports.Curve = Curve;
  29070. exports.CurvePath = CurvePath;
  29071. exports.CustomBlending = CustomBlending;
  29072. exports.CustomToneMapping = CustomToneMapping;
  29073. exports.CylinderBufferGeometry = CylinderGeometry;
  29074. exports.CylinderGeometry = CylinderGeometry;
  29075. exports.Cylindrical = Cylindrical;
  29076. exports.DataTexture = DataTexture;
  29077. exports.DataTexture2DArray = DataTexture2DArray;
  29078. exports.DataTexture3D = DataTexture3D;
  29079. exports.DataTextureLoader = DataTextureLoader;
  29080. exports.DataUtils = DataUtils;
  29081. exports.DecrementStencilOp = DecrementStencilOp;
  29082. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  29083. exports.DefaultLoadingManager = DefaultLoadingManager;
  29084. exports.DepthFormat = DepthFormat;
  29085. exports.DepthStencilFormat = DepthStencilFormat;
  29086. exports.DepthTexture = DepthTexture;
  29087. exports.DirectionalLight = DirectionalLight;
  29088. exports.DirectionalLightHelper = DirectionalLightHelper;
  29089. exports.DiscreteInterpolant = DiscreteInterpolant;
  29090. exports.DodecahedronBufferGeometry = DodecahedronGeometry;
  29091. exports.DodecahedronGeometry = DodecahedronGeometry;
  29092. exports.DoubleSide = DoubleSide;
  29093. exports.DstAlphaFactor = DstAlphaFactor;
  29094. exports.DstColorFactor = DstColorFactor;
  29095. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  29096. exports.DynamicCopyUsage = DynamicCopyUsage;
  29097. exports.DynamicDrawUsage = DynamicDrawUsage;
  29098. exports.DynamicReadUsage = DynamicReadUsage;
  29099. exports.EdgesGeometry = EdgesGeometry;
  29100. exports.EdgesHelper = EdgesHelper;
  29101. exports.EllipseCurve = EllipseCurve;
  29102. exports.EqualDepth = EqualDepth;
  29103. exports.EqualStencilFunc = EqualStencilFunc;
  29104. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  29105. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  29106. exports.Euler = Euler;
  29107. exports.EventDispatcher = EventDispatcher;
  29108. exports.ExtrudeBufferGeometry = ExtrudeGeometry;
  29109. exports.ExtrudeGeometry = ExtrudeGeometry;
  29110. exports.FaceColors = FaceColors;
  29111. exports.FileLoader = FileLoader;
  29112. exports.FlatShading = FlatShading;
  29113. exports.Float16BufferAttribute = Float16BufferAttribute;
  29114. exports.Float32Attribute = Float32Attribute;
  29115. exports.Float32BufferAttribute = Float32BufferAttribute;
  29116. exports.Float64Attribute = Float64Attribute;
  29117. exports.Float64BufferAttribute = Float64BufferAttribute;
  29118. exports.FloatType = FloatType;
  29119. exports.Fog = Fog;
  29120. exports.FogExp2 = FogExp2;
  29121. exports.Font = Font;
  29122. exports.FontLoader = FontLoader;
  29123. exports.FrontSide = FrontSide;
  29124. exports.Frustum = Frustum;
  29125. exports.GLBufferAttribute = GLBufferAttribute;
  29126. exports.GLSL1 = GLSL1;
  29127. exports.GLSL3 = GLSL3;
  29128. exports.GammaEncoding = GammaEncoding;
  29129. exports.GreaterDepth = GreaterDepth;
  29130. exports.GreaterEqualDepth = GreaterEqualDepth;
  29131. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  29132. exports.GreaterStencilFunc = GreaterStencilFunc;
  29133. exports.GridHelper = GridHelper;
  29134. exports.Group = Group;
  29135. exports.HalfFloatType = HalfFloatType;
  29136. exports.HemisphereLight = HemisphereLight;
  29137. exports.HemisphereLightHelper = HemisphereLightHelper;
  29138. exports.HemisphereLightProbe = HemisphereLightProbe;
  29139. exports.IcosahedronBufferGeometry = IcosahedronGeometry;
  29140. exports.IcosahedronGeometry = IcosahedronGeometry;
  29141. exports.ImageBitmapLoader = ImageBitmapLoader;
  29142. exports.ImageLoader = ImageLoader;
  29143. exports.ImageUtils = ImageUtils;
  29144. exports.ImmediateRenderObject = ImmediateRenderObject;
  29145. exports.IncrementStencilOp = IncrementStencilOp;
  29146. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  29147. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  29148. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  29149. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  29150. exports.InstancedMesh = InstancedMesh;
  29151. exports.Int16Attribute = Int16Attribute;
  29152. exports.Int16BufferAttribute = Int16BufferAttribute;
  29153. exports.Int32Attribute = Int32Attribute;
  29154. exports.Int32BufferAttribute = Int32BufferAttribute;
  29155. exports.Int8Attribute = Int8Attribute;
  29156. exports.Int8BufferAttribute = Int8BufferAttribute;
  29157. exports.IntType = IntType;
  29158. exports.InterleavedBuffer = InterleavedBuffer;
  29159. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  29160. exports.Interpolant = Interpolant;
  29161. exports.InterpolateDiscrete = InterpolateDiscrete;
  29162. exports.InterpolateLinear = InterpolateLinear;
  29163. exports.InterpolateSmooth = InterpolateSmooth;
  29164. exports.InvertStencilOp = InvertStencilOp;
  29165. exports.JSONLoader = JSONLoader;
  29166. exports.KeepStencilOp = KeepStencilOp;
  29167. exports.KeyframeTrack = KeyframeTrack;
  29168. exports.LOD = LOD;
  29169. exports.LatheBufferGeometry = LatheGeometry;
  29170. exports.LatheGeometry = LatheGeometry;
  29171. exports.Layers = Layers;
  29172. exports.LensFlare = LensFlare;
  29173. exports.LessDepth = LessDepth;
  29174. exports.LessEqualDepth = LessEqualDepth;
  29175. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  29176. exports.LessStencilFunc = LessStencilFunc;
  29177. exports.Light = Light;
  29178. exports.LightProbe = LightProbe;
  29179. exports.Line = Line;
  29180. exports.Line3 = Line3;
  29181. exports.LineBasicMaterial = LineBasicMaterial;
  29182. exports.LineCurve = LineCurve;
  29183. exports.LineCurve3 = LineCurve3;
  29184. exports.LineDashedMaterial = LineDashedMaterial;
  29185. exports.LineLoop = LineLoop;
  29186. exports.LinePieces = LinePieces;
  29187. exports.LineSegments = LineSegments;
  29188. exports.LineStrip = LineStrip;
  29189. exports.LinearEncoding = LinearEncoding;
  29190. exports.LinearFilter = LinearFilter;
  29191. exports.LinearInterpolant = LinearInterpolant;
  29192. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  29193. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  29194. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  29195. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  29196. exports.LinearToneMapping = LinearToneMapping;
  29197. exports.Loader = Loader;
  29198. exports.LoaderUtils = LoaderUtils;
  29199. exports.LoadingManager = LoadingManager;
  29200. exports.LogLuvEncoding = LogLuvEncoding;
  29201. exports.LoopOnce = LoopOnce;
  29202. exports.LoopPingPong = LoopPingPong;
  29203. exports.LoopRepeat = LoopRepeat;
  29204. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  29205. exports.LuminanceFormat = LuminanceFormat;
  29206. exports.MOUSE = MOUSE;
  29207. exports.Material = Material;
  29208. exports.MaterialLoader = MaterialLoader;
  29209. exports.Math = MathUtils;
  29210. exports.MathUtils = MathUtils;
  29211. exports.Matrix3 = Matrix3;
  29212. exports.Matrix4 = Matrix4;
  29213. exports.MaxEquation = MaxEquation;
  29214. exports.Mesh = Mesh;
  29215. exports.MeshBasicMaterial = MeshBasicMaterial;
  29216. exports.MeshDepthMaterial = MeshDepthMaterial;
  29217. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  29218. exports.MeshFaceMaterial = MeshFaceMaterial;
  29219. exports.MeshLambertMaterial = MeshLambertMaterial;
  29220. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  29221. exports.MeshNormalMaterial = MeshNormalMaterial;
  29222. exports.MeshPhongMaterial = MeshPhongMaterial;
  29223. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  29224. exports.MeshStandardMaterial = MeshStandardMaterial;
  29225. exports.MeshToonMaterial = MeshToonMaterial;
  29226. exports.MinEquation = MinEquation;
  29227. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  29228. exports.MixOperation = MixOperation;
  29229. exports.MultiMaterial = MultiMaterial;
  29230. exports.MultiplyBlending = MultiplyBlending;
  29231. exports.MultiplyOperation = MultiplyOperation;
  29232. exports.NearestFilter = NearestFilter;
  29233. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  29234. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  29235. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  29236. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  29237. exports.NeverDepth = NeverDepth;
  29238. exports.NeverStencilFunc = NeverStencilFunc;
  29239. exports.NoBlending = NoBlending;
  29240. exports.NoColors = NoColors;
  29241. exports.NoToneMapping = NoToneMapping;
  29242. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  29243. exports.NormalBlending = NormalBlending;
  29244. exports.NotEqualDepth = NotEqualDepth;
  29245. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  29246. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  29247. exports.Object3D = Object3D;
  29248. exports.ObjectLoader = ObjectLoader;
  29249. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  29250. exports.OctahedronBufferGeometry = OctahedronGeometry;
  29251. exports.OctahedronGeometry = OctahedronGeometry;
  29252. exports.OneFactor = OneFactor;
  29253. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  29254. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  29255. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  29256. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  29257. exports.OrthographicCamera = OrthographicCamera;
  29258. exports.PCFShadowMap = PCFShadowMap;
  29259. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  29260. exports.PMREMGenerator = PMREMGenerator;
  29261. exports.ParametricBufferGeometry = ParametricGeometry;
  29262. exports.ParametricGeometry = ParametricGeometry;
  29263. exports.Particle = Particle;
  29264. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  29265. exports.ParticleSystem = ParticleSystem;
  29266. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  29267. exports.Path = Path;
  29268. exports.PerspectiveCamera = PerspectiveCamera;
  29269. exports.Plane = Plane;
  29270. exports.PlaneBufferGeometry = PlaneGeometry;
  29271. exports.PlaneGeometry = PlaneGeometry;
  29272. exports.PlaneHelper = PlaneHelper;
  29273. exports.PointCloud = PointCloud;
  29274. exports.PointCloudMaterial = PointCloudMaterial;
  29275. exports.PointLight = PointLight;
  29276. exports.PointLightHelper = PointLightHelper;
  29277. exports.Points = Points;
  29278. exports.PointsMaterial = PointsMaterial;
  29279. exports.PolarGridHelper = PolarGridHelper;
  29280. exports.PolyhedronBufferGeometry = PolyhedronGeometry;
  29281. exports.PolyhedronGeometry = PolyhedronGeometry;
  29282. exports.PositionalAudio = PositionalAudio;
  29283. exports.PropertyBinding = PropertyBinding;
  29284. exports.PropertyMixer = PropertyMixer;
  29285. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  29286. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  29287. exports.Quaternion = Quaternion;
  29288. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  29289. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  29290. exports.REVISION = REVISION;
  29291. exports.RGBADepthPacking = RGBADepthPacking;
  29292. exports.RGBAFormat = RGBAFormat;
  29293. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  29294. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  29295. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  29296. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  29297. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  29298. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  29299. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  29300. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  29301. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  29302. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  29303. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  29304. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  29305. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  29306. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  29307. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  29308. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  29309. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  29310. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  29311. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  29312. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  29313. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  29314. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  29315. exports.RGBDEncoding = RGBDEncoding;
  29316. exports.RGBEEncoding = RGBEEncoding;
  29317. exports.RGBEFormat = RGBEFormat;
  29318. exports.RGBFormat = RGBFormat;
  29319. exports.RGBIntegerFormat = RGBIntegerFormat;
  29320. exports.RGBM16Encoding = RGBM16Encoding;
  29321. exports.RGBM7Encoding = RGBM7Encoding;
  29322. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  29323. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  29324. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  29325. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  29326. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  29327. exports.RGFormat = RGFormat;
  29328. exports.RGIntegerFormat = RGIntegerFormat;
  29329. exports.RawShaderMaterial = RawShaderMaterial;
  29330. exports.Ray = Ray;
  29331. exports.Raycaster = Raycaster;
  29332. exports.RectAreaLight = RectAreaLight;
  29333. exports.RedFormat = RedFormat;
  29334. exports.RedIntegerFormat = RedIntegerFormat;
  29335. exports.ReinhardToneMapping = ReinhardToneMapping;
  29336. exports.RepeatWrapping = RepeatWrapping;
  29337. exports.ReplaceStencilOp = ReplaceStencilOp;
  29338. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  29339. exports.RingBufferGeometry = RingGeometry;
  29340. exports.RingGeometry = RingGeometry;
  29341. exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
  29342. exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
  29343. exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
  29344. exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
  29345. exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
  29346. exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
  29347. exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
  29348. exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
  29349. exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
  29350. exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
  29351. exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
  29352. exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
  29353. exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
  29354. exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
  29355. exports.Scene = Scene;
  29356. exports.SceneUtils = SceneUtils;
  29357. exports.ShaderChunk = ShaderChunk;
  29358. exports.ShaderLib = ShaderLib;
  29359. exports.ShaderMaterial = ShaderMaterial;
  29360. exports.ShadowMaterial = ShadowMaterial;
  29361. exports.Shape = Shape;
  29362. exports.ShapeBufferGeometry = ShapeGeometry;
  29363. exports.ShapeGeometry = ShapeGeometry;
  29364. exports.ShapePath = ShapePath;
  29365. exports.ShapeUtils = ShapeUtils;
  29366. exports.ShortType = ShortType;
  29367. exports.Skeleton = Skeleton;
  29368. exports.SkeletonHelper = SkeletonHelper;
  29369. exports.SkinnedMesh = SkinnedMesh;
  29370. exports.SmoothShading = SmoothShading;
  29371. exports.Sphere = Sphere;
  29372. exports.SphereBufferGeometry = SphereGeometry;
  29373. exports.SphereGeometry = SphereGeometry;
  29374. exports.Spherical = Spherical;
  29375. exports.SphericalHarmonics3 = SphericalHarmonics3;
  29376. exports.SplineCurve = SplineCurve;
  29377. exports.SpotLight = SpotLight;
  29378. exports.SpotLightHelper = SpotLightHelper;
  29379. exports.Sprite = Sprite;
  29380. exports.SpriteMaterial = SpriteMaterial;
  29381. exports.SrcAlphaFactor = SrcAlphaFactor;
  29382. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  29383. exports.SrcColorFactor = SrcColorFactor;
  29384. exports.StaticCopyUsage = StaticCopyUsage;
  29385. exports.StaticDrawUsage = StaticDrawUsage;
  29386. exports.StaticReadUsage = StaticReadUsage;
  29387. exports.StereoCamera = StereoCamera;
  29388. exports.StreamCopyUsage = StreamCopyUsage;
  29389. exports.StreamDrawUsage = StreamDrawUsage;
  29390. exports.StreamReadUsage = StreamReadUsage;
  29391. exports.StringKeyframeTrack = StringKeyframeTrack;
  29392. exports.SubtractEquation = SubtractEquation;
  29393. exports.SubtractiveBlending = SubtractiveBlending;
  29394. exports.TOUCH = TOUCH;
  29395. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  29396. exports.TetrahedronBufferGeometry = TetrahedronGeometry;
  29397. exports.TetrahedronGeometry = TetrahedronGeometry;
  29398. exports.TextBufferGeometry = TextGeometry;
  29399. exports.TextGeometry = TextGeometry;
  29400. exports.Texture = Texture;
  29401. exports.TextureLoader = TextureLoader;
  29402. exports.TorusBufferGeometry = TorusGeometry;
  29403. exports.TorusGeometry = TorusGeometry;
  29404. exports.TorusKnotBufferGeometry = TorusKnotGeometry;
  29405. exports.TorusKnotGeometry = TorusKnotGeometry;
  29406. exports.Triangle = Triangle;
  29407. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  29408. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  29409. exports.TrianglesDrawMode = TrianglesDrawMode;
  29410. exports.TubeBufferGeometry = TubeGeometry;
  29411. exports.TubeGeometry = TubeGeometry;
  29412. exports.UVMapping = UVMapping;
  29413. exports.Uint16Attribute = Uint16Attribute;
  29414. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  29415. exports.Uint32Attribute = Uint32Attribute;
  29416. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  29417. exports.Uint8Attribute = Uint8Attribute;
  29418. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  29419. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  29420. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  29421. exports.Uniform = Uniform;
  29422. exports.UniformsLib = UniformsLib;
  29423. exports.UniformsUtils = UniformsUtils;
  29424. exports.UnsignedByteType = UnsignedByteType;
  29425. exports.UnsignedInt248Type = UnsignedInt248Type;
  29426. exports.UnsignedIntType = UnsignedIntType;
  29427. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  29428. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  29429. exports.UnsignedShort565Type = UnsignedShort565Type;
  29430. exports.UnsignedShortType = UnsignedShortType;
  29431. exports.VSMShadowMap = VSMShadowMap;
  29432. exports.Vector2 = Vector2;
  29433. exports.Vector3 = Vector3;
  29434. exports.Vector4 = Vector4;
  29435. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  29436. exports.Vertex = Vertex;
  29437. exports.VertexColors = VertexColors;
  29438. exports.VideoTexture = VideoTexture;
  29439. exports.WebGL1Renderer = WebGL1Renderer;
  29440. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  29441. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  29442. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  29443. exports.WebGLRenderTarget = WebGLRenderTarget;
  29444. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  29445. exports.WebGLRenderer = WebGLRenderer;
  29446. exports.WebGLUtils = WebGLUtils;
  29447. exports.WireframeGeometry = WireframeGeometry;
  29448. exports.WireframeHelper = WireframeHelper;
  29449. exports.WrapAroundEnding = WrapAroundEnding;
  29450. exports.XHRLoader = XHRLoader;
  29451. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  29452. exports.ZeroFactor = ZeroFactor;
  29453. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  29454. exports.ZeroStencilOp = ZeroStencilOp;
  29455. exports.sRGBEncoding = sRGBEncoding;
  29456. Object.defineProperty(exports, '__esModule', { value: true });
  29457. })));
粤ICP备19079148号