three.js 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280
  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 = '130';
  12. const MOUSE = {
  13. LEFT: 0,
  14. MIDDLE: 1,
  15. RIGHT: 2,
  16. ROTATE: 0,
  17. DOLLY: 1,
  18. PAN: 2
  19. };
  20. const TOUCH = {
  21. ROTATE: 0,
  22. PAN: 1,
  23. DOLLY_PAN: 2,
  24. DOLLY_ROTATE: 3
  25. };
  26. const CullFaceNone = 0;
  27. const CullFaceBack = 1;
  28. const CullFaceFront = 2;
  29. const CullFaceFrontBack = 3;
  30. const BasicShadowMap = 0;
  31. const PCFShadowMap = 1;
  32. const PCFSoftShadowMap = 2;
  33. const VSMShadowMap = 3;
  34. const FrontSide = 0;
  35. const BackSide = 1;
  36. const DoubleSide = 2;
  37. const FlatShading = 1;
  38. const SmoothShading = 2;
  39. const NoBlending = 0;
  40. const NormalBlending = 1;
  41. const AdditiveBlending = 2;
  42. const SubtractiveBlending = 3;
  43. const MultiplyBlending = 4;
  44. const CustomBlending = 5;
  45. const AddEquation = 100;
  46. const SubtractEquation = 101;
  47. const ReverseSubtractEquation = 102;
  48. const MinEquation = 103;
  49. const MaxEquation = 104;
  50. const ZeroFactor = 200;
  51. const OneFactor = 201;
  52. const SrcColorFactor = 202;
  53. const OneMinusSrcColorFactor = 203;
  54. const SrcAlphaFactor = 204;
  55. const OneMinusSrcAlphaFactor = 205;
  56. const DstAlphaFactor = 206;
  57. const OneMinusDstAlphaFactor = 207;
  58. const DstColorFactor = 208;
  59. const OneMinusDstColorFactor = 209;
  60. const SrcAlphaSaturateFactor = 210;
  61. const NeverDepth = 0;
  62. const AlwaysDepth = 1;
  63. const LessDepth = 2;
  64. const LessEqualDepth = 3;
  65. const EqualDepth = 4;
  66. const GreaterEqualDepth = 5;
  67. const GreaterDepth = 6;
  68. const NotEqualDepth = 7;
  69. const MultiplyOperation = 0;
  70. const MixOperation = 1;
  71. const AddOperation = 2;
  72. const NoToneMapping = 0;
  73. const LinearToneMapping = 1;
  74. const ReinhardToneMapping = 2;
  75. const CineonToneMapping = 3;
  76. const ACESFilmicToneMapping = 4;
  77. const CustomToneMapping = 5;
  78. const UVMapping = 300;
  79. const CubeReflectionMapping = 301;
  80. const CubeRefractionMapping = 302;
  81. const EquirectangularReflectionMapping = 303;
  82. const EquirectangularRefractionMapping = 304;
  83. const CubeUVReflectionMapping = 306;
  84. const CubeUVRefractionMapping = 307;
  85. const RepeatWrapping = 1000;
  86. const ClampToEdgeWrapping = 1001;
  87. const MirroredRepeatWrapping = 1002;
  88. const NearestFilter = 1003;
  89. const NearestMipmapNearestFilter = 1004;
  90. const NearestMipMapNearestFilter = 1004;
  91. const NearestMipmapLinearFilter = 1005;
  92. const NearestMipMapLinearFilter = 1005;
  93. const LinearFilter = 1006;
  94. const LinearMipmapNearestFilter = 1007;
  95. const LinearMipMapNearestFilter = 1007;
  96. const LinearMipmapLinearFilter = 1008;
  97. const LinearMipMapLinearFilter = 1008;
  98. const UnsignedByteType = 1009;
  99. const ByteType = 1010;
  100. const ShortType = 1011;
  101. const UnsignedShortType = 1012;
  102. const IntType = 1013;
  103. const UnsignedIntType = 1014;
  104. const FloatType = 1015;
  105. const HalfFloatType = 1016;
  106. const UnsignedShort4444Type = 1017;
  107. const UnsignedShort5551Type = 1018;
  108. const UnsignedShort565Type = 1019;
  109. const UnsignedInt248Type = 1020;
  110. const AlphaFormat = 1021;
  111. const RGBFormat = 1022;
  112. const RGBAFormat = 1023;
  113. const LuminanceFormat = 1024;
  114. const LuminanceAlphaFormat = 1025;
  115. const RGBEFormat = RGBAFormat;
  116. const DepthFormat = 1026;
  117. const DepthStencilFormat = 1027;
  118. const RedFormat = 1028;
  119. const RedIntegerFormat = 1029;
  120. const RGFormat = 1030;
  121. const RGIntegerFormat = 1031;
  122. const RGBIntegerFormat = 1032;
  123. const RGBAIntegerFormat = 1033;
  124. const RGB_S3TC_DXT1_Format = 33776;
  125. const RGBA_S3TC_DXT1_Format = 33777;
  126. const RGBA_S3TC_DXT3_Format = 33778;
  127. const RGBA_S3TC_DXT5_Format = 33779;
  128. const RGB_PVRTC_4BPPV1_Format = 35840;
  129. const RGB_PVRTC_2BPPV1_Format = 35841;
  130. const RGBA_PVRTC_4BPPV1_Format = 35842;
  131. const RGBA_PVRTC_2BPPV1_Format = 35843;
  132. const RGB_ETC1_Format = 36196;
  133. const RGB_ETC2_Format = 37492;
  134. const RGBA_ETC2_EAC_Format = 37496;
  135. const RGBA_ASTC_4x4_Format = 37808;
  136. const RGBA_ASTC_5x4_Format = 37809;
  137. const RGBA_ASTC_5x5_Format = 37810;
  138. const RGBA_ASTC_6x5_Format = 37811;
  139. const RGBA_ASTC_6x6_Format = 37812;
  140. const RGBA_ASTC_8x5_Format = 37813;
  141. const RGBA_ASTC_8x6_Format = 37814;
  142. const RGBA_ASTC_8x8_Format = 37815;
  143. const RGBA_ASTC_10x5_Format = 37816;
  144. const RGBA_ASTC_10x6_Format = 37817;
  145. const RGBA_ASTC_10x8_Format = 37818;
  146. const RGBA_ASTC_10x10_Format = 37819;
  147. const RGBA_ASTC_12x10_Format = 37820;
  148. const RGBA_ASTC_12x12_Format = 37821;
  149. const RGBA_BPTC_Format = 36492;
  150. const SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  151. const SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  152. const SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  153. const SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  154. const SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  155. const SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  156. const SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  157. const SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  158. const SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  159. const SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  160. const SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  161. const SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  162. const SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  163. const SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  164. const LoopOnce = 2200;
  165. const LoopRepeat = 2201;
  166. const LoopPingPong = 2202;
  167. const InterpolateDiscrete = 2300;
  168. const InterpolateLinear = 2301;
  169. const InterpolateSmooth = 2302;
  170. const ZeroCurvatureEnding = 2400;
  171. const ZeroSlopeEnding = 2401;
  172. const WrapAroundEnding = 2402;
  173. const NormalAnimationBlendMode = 2500;
  174. const AdditiveAnimationBlendMode = 2501;
  175. const TrianglesDrawMode = 0;
  176. const TriangleStripDrawMode = 1;
  177. const TriangleFanDrawMode = 2;
  178. const LinearEncoding = 3000;
  179. const sRGBEncoding = 3001;
  180. const GammaEncoding = 3007;
  181. const RGBEEncoding = 3002;
  182. const LogLuvEncoding = 3003;
  183. const RGBM7Encoding = 3004;
  184. const RGBM16Encoding = 3005;
  185. const RGBDEncoding = 3006;
  186. const BasicDepthPacking = 3200;
  187. const RGBADepthPacking = 3201;
  188. const TangentSpaceNormalMap = 0;
  189. const ObjectSpaceNormalMap = 1;
  190. const ZeroStencilOp = 0;
  191. const KeepStencilOp = 7680;
  192. const ReplaceStencilOp = 7681;
  193. const IncrementStencilOp = 7682;
  194. const DecrementStencilOp = 7683;
  195. const IncrementWrapStencilOp = 34055;
  196. const DecrementWrapStencilOp = 34056;
  197. const InvertStencilOp = 5386;
  198. const NeverStencilFunc = 512;
  199. const LessStencilFunc = 513;
  200. const EqualStencilFunc = 514;
  201. const LessEqualStencilFunc = 515;
  202. const GreaterStencilFunc = 516;
  203. const NotEqualStencilFunc = 517;
  204. const GreaterEqualStencilFunc = 518;
  205. const AlwaysStencilFunc = 519;
  206. const StaticDrawUsage = 35044;
  207. const DynamicDrawUsage = 35048;
  208. const StreamDrawUsage = 35040;
  209. const StaticReadUsage = 35045;
  210. const DynamicReadUsage = 35049;
  211. const StreamReadUsage = 35041;
  212. const StaticCopyUsage = 35046;
  213. const DynamicCopyUsage = 35050;
  214. const StreamCopyUsage = 35042;
  215. const GLSL1 = '100';
  216. const GLSL3 = '300 es';
  217. /**
  218. * https://github.com/mrdoob/eventdispatcher.js/
  219. */
  220. class EventDispatcher {
  221. addEventListener(type, listener) {
  222. if (this._listeners === undefined) this._listeners = {};
  223. const listeners = this._listeners;
  224. if (listeners[type] === undefined) {
  225. listeners[type] = [];
  226. }
  227. if (listeners[type].indexOf(listener) === -1) {
  228. listeners[type].push(listener);
  229. }
  230. }
  231. hasEventListener(type, listener) {
  232. if (this._listeners === undefined) return false;
  233. const listeners = this._listeners;
  234. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  235. }
  236. removeEventListener(type, listener) {
  237. if (this._listeners === undefined) return;
  238. const listeners = this._listeners;
  239. const listenerArray = listeners[type];
  240. if (listenerArray !== undefined) {
  241. const index = listenerArray.indexOf(listener);
  242. if (index !== -1) {
  243. listenerArray.splice(index, 1);
  244. }
  245. }
  246. }
  247. dispatchEvent(event) {
  248. if (this._listeners === undefined) return;
  249. const listeners = this._listeners;
  250. const listenerArray = listeners[event.type];
  251. if (listenerArray !== undefined) {
  252. event.target = this; // Make a copy, in case listeners are removed while iterating.
  253. const array = listenerArray.slice(0);
  254. for (let i = 0, l = array.length; i < l; i++) {
  255. array[i].call(this, event);
  256. }
  257. event.target = null;
  258. }
  259. }
  260. }
  261. const _lut = [];
  262. for (let i = 0; i < 256; i++) {
  263. _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
  264. }
  265. let _seed = 1234567;
  266. const DEG2RAD = Math.PI / 180;
  267. const RAD2DEG = 180 / Math.PI; // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  268. function generateUUID() {
  269. const d0 = Math.random() * 0xffffffff | 0;
  270. const d1 = Math.random() * 0xffffffff | 0;
  271. const d2 = Math.random() * 0xffffffff | 0;
  272. const d3 = Math.random() * 0xffffffff | 0;
  273. const uuid = _lut[d0 & 0xff] + _lut[d0 >> 8 & 0xff] + _lut[d0 >> 16 & 0xff] + _lut[d0 >> 24 & 0xff] + '-' + _lut[d1 & 0xff] + _lut[d1 >> 8 & 0xff] + '-' + _lut[d1 >> 16 & 0x0f | 0x40] + _lut[d1 >> 24 & 0xff] + '-' + _lut[d2 & 0x3f | 0x80] + _lut[d2 >> 8 & 0xff] + '-' + _lut[d2 >> 16 & 0xff] + _lut[d2 >> 24 & 0xff] + _lut[d3 & 0xff] + _lut[d3 >> 8 & 0xff] + _lut[d3 >> 16 & 0xff] + _lut[d3 >> 24 & 0xff]; // .toUpperCase() here flattens concatenated strings to save heap memory space.
  274. return uuid.toUpperCase();
  275. }
  276. function clamp(value, min, max) {
  277. return Math.max(min, Math.min(max, value));
  278. } // compute euclidian modulo of m % n
  279. // https://en.wikipedia.org/wiki/Modulo_operation
  280. function euclideanModulo(n, m) {
  281. return (n % m + m) % m;
  282. } // Linear mapping from range <a1, a2> to range <b1, b2>
  283. function mapLinear(x, a1, a2, b1, b2) {
  284. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  285. } // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  286. function inverseLerp(x, y, value) {
  287. if (x !== y) {
  288. return (value - x) / (y - x);
  289. } else {
  290. return 0;
  291. }
  292. } // https://en.wikipedia.org/wiki/Linear_interpolation
  293. function lerp(x, y, t) {
  294. return (1 - t) * x + t * y;
  295. } // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  296. function damp(x, y, lambda, dt) {
  297. return lerp(x, y, 1 - Math.exp(-lambda * dt));
  298. } // https://www.desmos.com/calculator/vcsjnyz7x4
  299. function pingpong(x, length = 1) {
  300. return length - Math.abs(euclideanModulo(x, length * 2) - length);
  301. } // http://en.wikipedia.org/wiki/Smoothstep
  302. function smoothstep(x, min, max) {
  303. if (x <= min) return 0;
  304. if (x >= max) return 1;
  305. x = (x - min) / (max - min);
  306. return x * x * (3 - 2 * x);
  307. }
  308. function smootherstep(x, min, max) {
  309. if (x <= min) return 0;
  310. if (x >= max) return 1;
  311. x = (x - min) / (max - min);
  312. return x * x * x * (x * (x * 6 - 15) + 10);
  313. } // Random integer from <low, high> interval
  314. function randInt(low, high) {
  315. return low + Math.floor(Math.random() * (high - low + 1));
  316. } // Random float from <low, high> interval
  317. function randFloat(low, high) {
  318. return low + Math.random() * (high - low);
  319. } // Random float from <-range/2, range/2> interval
  320. function randFloatSpread(range) {
  321. return range * (0.5 - Math.random());
  322. } // Deterministic pseudo-random float in the interval [ 0, 1 ]
  323. function seededRandom(s) {
  324. if (s !== undefined) _seed = s % 2147483647; // Park-Miller algorithm
  325. _seed = _seed * 16807 % 2147483647;
  326. return (_seed - 1) / 2147483646;
  327. }
  328. function degToRad(degrees) {
  329. return degrees * DEG2RAD;
  330. }
  331. function radToDeg(radians) {
  332. return radians * RAD2DEG;
  333. }
  334. function isPowerOfTwo(value) {
  335. return (value & value - 1) === 0 && value !== 0;
  336. }
  337. function ceilPowerOfTwo(value) {
  338. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  339. }
  340. function floorPowerOfTwo(value) {
  341. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  342. }
  343. function setQuaternionFromProperEuler(q, a, b, c, order) {
  344. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  345. // rotations are applied to the axes in the order specified by 'order'
  346. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  347. // angles are in radians
  348. const cos = Math.cos;
  349. const sin = Math.sin;
  350. const c2 = cos(b / 2);
  351. const s2 = sin(b / 2);
  352. const c13 = cos((a + c) / 2);
  353. const s13 = sin((a + c) / 2);
  354. const c1_3 = cos((a - c) / 2);
  355. const s1_3 = sin((a - c) / 2);
  356. const c3_1 = cos((c - a) / 2);
  357. const s3_1 = sin((c - a) / 2);
  358. switch (order) {
  359. case 'XYX':
  360. q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
  361. break;
  362. case 'YZY':
  363. q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
  364. break;
  365. case 'ZXZ':
  366. q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
  367. break;
  368. case 'XZX':
  369. q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
  370. break;
  371. case 'YXY':
  372. q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
  373. break;
  374. case 'ZYZ':
  375. q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
  376. break;
  377. default:
  378. console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order);
  379. }
  380. }
  381. var MathUtils = /*#__PURE__*/Object.freeze({
  382. __proto__: null,
  383. DEG2RAD: DEG2RAD,
  384. RAD2DEG: RAD2DEG,
  385. generateUUID: generateUUID,
  386. clamp: clamp,
  387. euclideanModulo: euclideanModulo,
  388. mapLinear: mapLinear,
  389. inverseLerp: inverseLerp,
  390. lerp: lerp,
  391. damp: damp,
  392. pingpong: pingpong,
  393. smoothstep: smoothstep,
  394. smootherstep: smootherstep,
  395. randInt: randInt,
  396. randFloat: randFloat,
  397. randFloatSpread: randFloatSpread,
  398. seededRandom: seededRandom,
  399. degToRad: degToRad,
  400. radToDeg: radToDeg,
  401. isPowerOfTwo: isPowerOfTwo,
  402. ceilPowerOfTwo: ceilPowerOfTwo,
  403. floorPowerOfTwo: floorPowerOfTwo,
  404. setQuaternionFromProperEuler: setQuaternionFromProperEuler
  405. });
  406. class Vector2 {
  407. constructor(x = 0, y = 0) {
  408. this.x = x;
  409. this.y = y;
  410. }
  411. get width() {
  412. return this.x;
  413. }
  414. set width(value) {
  415. this.x = value;
  416. }
  417. get height() {
  418. return this.y;
  419. }
  420. set height(value) {
  421. this.y = value;
  422. }
  423. set(x, y) {
  424. this.x = x;
  425. this.y = y;
  426. return this;
  427. }
  428. setScalar(scalar) {
  429. this.x = scalar;
  430. this.y = scalar;
  431. return this;
  432. }
  433. setX(x) {
  434. this.x = x;
  435. return this;
  436. }
  437. setY(y) {
  438. this.y = y;
  439. return this;
  440. }
  441. setComponent(index, value) {
  442. switch (index) {
  443. case 0:
  444. this.x = value;
  445. break;
  446. case 1:
  447. this.y = value;
  448. break;
  449. default:
  450. throw new Error('index is out of range: ' + index);
  451. }
  452. return this;
  453. }
  454. getComponent(index) {
  455. switch (index) {
  456. case 0:
  457. return this.x;
  458. case 1:
  459. return this.y;
  460. default:
  461. throw new Error('index is out of range: ' + index);
  462. }
  463. }
  464. clone() {
  465. return new this.constructor(this.x, this.y);
  466. }
  467. copy(v) {
  468. this.x = v.x;
  469. this.y = v.y;
  470. return this;
  471. }
  472. add(v, w) {
  473. if (w !== undefined) {
  474. console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  475. return this.addVectors(v, w);
  476. }
  477. this.x += v.x;
  478. this.y += v.y;
  479. return this;
  480. }
  481. addScalar(s) {
  482. this.x += s;
  483. this.y += s;
  484. return this;
  485. }
  486. addVectors(a, b) {
  487. this.x = a.x + b.x;
  488. this.y = a.y + b.y;
  489. return this;
  490. }
  491. addScaledVector(v, s) {
  492. this.x += v.x * s;
  493. this.y += v.y * s;
  494. return this;
  495. }
  496. sub(v, w) {
  497. if (w !== undefined) {
  498. console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  499. return this.subVectors(v, w);
  500. }
  501. this.x -= v.x;
  502. this.y -= v.y;
  503. return this;
  504. }
  505. subScalar(s) {
  506. this.x -= s;
  507. this.y -= s;
  508. return this;
  509. }
  510. subVectors(a, b) {
  511. this.x = a.x - b.x;
  512. this.y = a.y - b.y;
  513. return this;
  514. }
  515. multiply(v) {
  516. this.x *= v.x;
  517. this.y *= v.y;
  518. return this;
  519. }
  520. multiplyScalar(scalar) {
  521. this.x *= scalar;
  522. this.y *= scalar;
  523. return this;
  524. }
  525. divide(v) {
  526. this.x /= v.x;
  527. this.y /= v.y;
  528. return this;
  529. }
  530. divideScalar(scalar) {
  531. return this.multiplyScalar(1 / scalar);
  532. }
  533. applyMatrix3(m) {
  534. const x = this.x,
  535. y = this.y;
  536. const e = m.elements;
  537. this.x = e[0] * x + e[3] * y + e[6];
  538. this.y = e[1] * x + e[4] * y + e[7];
  539. return this;
  540. }
  541. min(v) {
  542. this.x = Math.min(this.x, v.x);
  543. this.y = Math.min(this.y, v.y);
  544. return this;
  545. }
  546. max(v) {
  547. this.x = Math.max(this.x, v.x);
  548. this.y = Math.max(this.y, v.y);
  549. return this;
  550. }
  551. clamp(min, max) {
  552. // assumes min < max, componentwise
  553. this.x = Math.max(min.x, Math.min(max.x, this.x));
  554. this.y = Math.max(min.y, Math.min(max.y, this.y));
  555. return this;
  556. }
  557. clampScalar(minVal, maxVal) {
  558. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  559. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  560. return this;
  561. }
  562. clampLength(min, max) {
  563. const length = this.length();
  564. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  565. }
  566. floor() {
  567. this.x = Math.floor(this.x);
  568. this.y = Math.floor(this.y);
  569. return this;
  570. }
  571. ceil() {
  572. this.x = Math.ceil(this.x);
  573. this.y = Math.ceil(this.y);
  574. return this;
  575. }
  576. round() {
  577. this.x = Math.round(this.x);
  578. this.y = Math.round(this.y);
  579. return this;
  580. }
  581. roundToZero() {
  582. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  583. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  584. return this;
  585. }
  586. negate() {
  587. this.x = -this.x;
  588. this.y = -this.y;
  589. return this;
  590. }
  591. dot(v) {
  592. return this.x * v.x + this.y * v.y;
  593. }
  594. cross(v) {
  595. return this.x * v.y - this.y * v.x;
  596. }
  597. lengthSq() {
  598. return this.x * this.x + this.y * this.y;
  599. }
  600. length() {
  601. return Math.sqrt(this.x * this.x + this.y * this.y);
  602. }
  603. manhattanLength() {
  604. return Math.abs(this.x) + Math.abs(this.y);
  605. }
  606. normalize() {
  607. return this.divideScalar(this.length() || 1);
  608. }
  609. angle() {
  610. // computes the angle in radians with respect to the positive x-axis
  611. const angle = Math.atan2(-this.y, -this.x) + Math.PI;
  612. return angle;
  613. }
  614. distanceTo(v) {
  615. return Math.sqrt(this.distanceToSquared(v));
  616. }
  617. distanceToSquared(v) {
  618. const dx = this.x - v.x,
  619. dy = this.y - v.y;
  620. return dx * dx + dy * dy;
  621. }
  622. manhattanDistanceTo(v) {
  623. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  624. }
  625. setLength(length) {
  626. return this.normalize().multiplyScalar(length);
  627. }
  628. lerp(v, alpha) {
  629. this.x += (v.x - this.x) * alpha;
  630. this.y += (v.y - this.y) * alpha;
  631. return this;
  632. }
  633. lerpVectors(v1, v2, alpha) {
  634. this.x = v1.x + (v2.x - v1.x) * alpha;
  635. this.y = v1.y + (v2.y - v1.y) * alpha;
  636. return this;
  637. }
  638. equals(v) {
  639. return v.x === this.x && v.y === this.y;
  640. }
  641. fromArray(array, offset = 0) {
  642. this.x = array[offset];
  643. this.y = array[offset + 1];
  644. return this;
  645. }
  646. toArray(array = [], offset = 0) {
  647. array[offset] = this.x;
  648. array[offset + 1] = this.y;
  649. return array;
  650. }
  651. fromBufferAttribute(attribute, index, offset) {
  652. if (offset !== undefined) {
  653. console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
  654. }
  655. this.x = attribute.getX(index);
  656. this.y = attribute.getY(index);
  657. return this;
  658. }
  659. rotateAround(center, angle) {
  660. const c = Math.cos(angle),
  661. s = Math.sin(angle);
  662. const x = this.x - center.x;
  663. const y = this.y - center.y;
  664. this.x = x * c - y * s + center.x;
  665. this.y = x * s + y * c + center.y;
  666. return this;
  667. }
  668. random() {
  669. this.x = Math.random();
  670. this.y = Math.random();
  671. return this;
  672. }
  673. }
  674. Vector2.prototype.isVector2 = true;
  675. class Matrix3 {
  676. constructor() {
  677. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  678. if (arguments.length > 0) {
  679. console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
  680. }
  681. }
  682. set(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  683. const te = this.elements;
  684. te[0] = n11;
  685. te[1] = n21;
  686. te[2] = n31;
  687. te[3] = n12;
  688. te[4] = n22;
  689. te[5] = n32;
  690. te[6] = n13;
  691. te[7] = n23;
  692. te[8] = n33;
  693. return this;
  694. }
  695. identity() {
  696. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  697. return this;
  698. }
  699. copy(m) {
  700. const te = this.elements;
  701. const me = m.elements;
  702. te[0] = me[0];
  703. te[1] = me[1];
  704. te[2] = me[2];
  705. te[3] = me[3];
  706. te[4] = me[4];
  707. te[5] = me[5];
  708. te[6] = me[6];
  709. te[7] = me[7];
  710. te[8] = me[8];
  711. return this;
  712. }
  713. extractBasis(xAxis, yAxis, zAxis) {
  714. xAxis.setFromMatrix3Column(this, 0);
  715. yAxis.setFromMatrix3Column(this, 1);
  716. zAxis.setFromMatrix3Column(this, 2);
  717. return this;
  718. }
  719. setFromMatrix4(m) {
  720. const me = m.elements;
  721. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  722. return this;
  723. }
  724. multiply(m) {
  725. return this.multiplyMatrices(this, m);
  726. }
  727. premultiply(m) {
  728. return this.multiplyMatrices(m, this);
  729. }
  730. multiplyMatrices(a, b) {
  731. const ae = a.elements;
  732. const be = b.elements;
  733. const te = this.elements;
  734. const a11 = ae[0],
  735. a12 = ae[3],
  736. a13 = ae[6];
  737. const a21 = ae[1],
  738. a22 = ae[4],
  739. a23 = ae[7];
  740. const a31 = ae[2],
  741. a32 = ae[5],
  742. a33 = ae[8];
  743. const b11 = be[0],
  744. b12 = be[3],
  745. b13 = be[6];
  746. const b21 = be[1],
  747. b22 = be[4],
  748. b23 = be[7];
  749. const b31 = be[2],
  750. b32 = be[5],
  751. b33 = be[8];
  752. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  753. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  754. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  755. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  756. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  757. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  758. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  759. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  760. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  761. return this;
  762. }
  763. multiplyScalar(s) {
  764. const te = this.elements;
  765. te[0] *= s;
  766. te[3] *= s;
  767. te[6] *= s;
  768. te[1] *= s;
  769. te[4] *= s;
  770. te[7] *= s;
  771. te[2] *= s;
  772. te[5] *= s;
  773. te[8] *= s;
  774. return this;
  775. }
  776. determinant() {
  777. const te = this.elements;
  778. const a = te[0],
  779. b = te[1],
  780. c = te[2],
  781. d = te[3],
  782. e = te[4],
  783. f = te[5],
  784. g = te[6],
  785. h = te[7],
  786. i = te[8];
  787. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  788. }
  789. invert() {
  790. const te = this.elements,
  791. n11 = te[0],
  792. n21 = te[1],
  793. n31 = te[2],
  794. n12 = te[3],
  795. n22 = te[4],
  796. n32 = te[5],
  797. n13 = te[6],
  798. n23 = te[7],
  799. n33 = te[8],
  800. t11 = n33 * n22 - n32 * n23,
  801. t12 = n32 * n13 - n33 * n12,
  802. t13 = n23 * n12 - n22 * n13,
  803. det = n11 * t11 + n21 * t12 + n31 * t13;
  804. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  805. const detInv = 1 / det;
  806. te[0] = t11 * detInv;
  807. te[1] = (n31 * n23 - n33 * n21) * detInv;
  808. te[2] = (n32 * n21 - n31 * n22) * detInv;
  809. te[3] = t12 * detInv;
  810. te[4] = (n33 * n11 - n31 * n13) * detInv;
  811. te[5] = (n31 * n12 - n32 * n11) * detInv;
  812. te[6] = t13 * detInv;
  813. te[7] = (n21 * n13 - n23 * n11) * detInv;
  814. te[8] = (n22 * n11 - n21 * n12) * detInv;
  815. return this;
  816. }
  817. transpose() {
  818. let tmp;
  819. const m = this.elements;
  820. tmp = m[1];
  821. m[1] = m[3];
  822. m[3] = tmp;
  823. tmp = m[2];
  824. m[2] = m[6];
  825. m[6] = tmp;
  826. tmp = m[5];
  827. m[5] = m[7];
  828. m[7] = tmp;
  829. return this;
  830. }
  831. getNormalMatrix(matrix4) {
  832. return this.setFromMatrix4(matrix4).invert().transpose();
  833. }
  834. transposeIntoArray(r) {
  835. const m = this.elements;
  836. r[0] = m[0];
  837. r[1] = m[3];
  838. r[2] = m[6];
  839. r[3] = m[1];
  840. r[4] = m[4];
  841. r[5] = m[7];
  842. r[6] = m[2];
  843. r[7] = m[5];
  844. r[8] = m[8];
  845. return this;
  846. }
  847. setUvTransform(tx, ty, sx, sy, rotation, cx, cy) {
  848. const c = Math.cos(rotation);
  849. const s = Math.sin(rotation);
  850. this.set(sx * c, sx * s, -sx * (c * cx + s * cy) + cx + tx, -sy * s, sy * c, -sy * (-s * cx + c * cy) + cy + ty, 0, 0, 1);
  851. return this;
  852. }
  853. scale(sx, sy) {
  854. const te = this.elements;
  855. te[0] *= sx;
  856. te[3] *= sx;
  857. te[6] *= sx;
  858. te[1] *= sy;
  859. te[4] *= sy;
  860. te[7] *= sy;
  861. return this;
  862. }
  863. rotate(theta) {
  864. const c = Math.cos(theta);
  865. const s = Math.sin(theta);
  866. const te = this.elements;
  867. const a11 = te[0],
  868. a12 = te[3],
  869. a13 = te[6];
  870. const a21 = te[1],
  871. a22 = te[4],
  872. a23 = te[7];
  873. te[0] = c * a11 + s * a21;
  874. te[3] = c * a12 + s * a22;
  875. te[6] = c * a13 + s * a23;
  876. te[1] = -s * a11 + c * a21;
  877. te[4] = -s * a12 + c * a22;
  878. te[7] = -s * a13 + c * a23;
  879. return this;
  880. }
  881. translate(tx, ty) {
  882. const te = this.elements;
  883. te[0] += tx * te[2];
  884. te[3] += tx * te[5];
  885. te[6] += tx * te[8];
  886. te[1] += ty * te[2];
  887. te[4] += ty * te[5];
  888. te[7] += ty * te[8];
  889. return this;
  890. }
  891. equals(matrix) {
  892. const te = this.elements;
  893. const me = matrix.elements;
  894. for (let i = 0; i < 9; i++) {
  895. if (te[i] !== me[i]) return false;
  896. }
  897. return true;
  898. }
  899. fromArray(array, offset = 0) {
  900. for (let i = 0; i < 9; i++) {
  901. this.elements[i] = array[i + offset];
  902. }
  903. return this;
  904. }
  905. toArray(array = [], offset = 0) {
  906. const te = this.elements;
  907. array[offset] = te[0];
  908. array[offset + 1] = te[1];
  909. array[offset + 2] = te[2];
  910. array[offset + 3] = te[3];
  911. array[offset + 4] = te[4];
  912. array[offset + 5] = te[5];
  913. array[offset + 6] = te[6];
  914. array[offset + 7] = te[7];
  915. array[offset + 8] = te[8];
  916. return array;
  917. }
  918. clone() {
  919. return new this.constructor().fromArray(this.elements);
  920. }
  921. }
  922. Matrix3.prototype.isMatrix3 = true;
  923. let _canvas;
  924. class ImageUtils {
  925. static getDataURL(image) {
  926. if (/^data:/i.test(image.src)) {
  927. return image.src;
  928. }
  929. if (typeof HTMLCanvasElement == 'undefined') {
  930. return image.src;
  931. }
  932. let canvas;
  933. if (image instanceof HTMLCanvasElement) {
  934. canvas = image;
  935. } else {
  936. if (_canvas === undefined) _canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  937. _canvas.width = image.width;
  938. _canvas.height = image.height;
  939. const context = _canvas.getContext('2d');
  940. if (image instanceof ImageData) {
  941. context.putImageData(image, 0, 0);
  942. } else {
  943. context.drawImage(image, 0, 0, image.width, image.height);
  944. }
  945. canvas = _canvas;
  946. }
  947. if (canvas.width > 2048 || canvas.height > 2048) {
  948. console.warn('THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image);
  949. return canvas.toDataURL('image/jpeg', 0.6);
  950. } else {
  951. return canvas.toDataURL('image/png');
  952. }
  953. }
  954. }
  955. let textureId = 0;
  956. class Texture extends EventDispatcher {
  957. constructor(image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = 1, encoding = LinearEncoding) {
  958. super();
  959. Object.defineProperty(this, 'id', {
  960. value: textureId++
  961. });
  962. this.uuid = generateUUID();
  963. this.name = '';
  964. this.image = image;
  965. this.mipmaps = [];
  966. this.mapping = mapping;
  967. this.wrapS = wrapS;
  968. this.wrapT = wrapT;
  969. this.magFilter = magFilter;
  970. this.minFilter = minFilter;
  971. this.anisotropy = anisotropy;
  972. this.format = format;
  973. this.internalFormat = null;
  974. this.type = type;
  975. this.offset = new Vector2(0, 0);
  976. this.repeat = new Vector2(1, 1);
  977. this.center = new Vector2(0, 0);
  978. this.rotation = 0;
  979. this.matrixAutoUpdate = true;
  980. this.matrix = new Matrix3();
  981. this.generateMipmaps = true;
  982. this.premultiplyAlpha = false;
  983. this.flipY = true;
  984. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  985. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  986. //
  987. // Also changing the encoding after already used by a Material will not automatically make the Material
  988. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  989. this.encoding = encoding;
  990. this.version = 0;
  991. this.onUpdate = null;
  992. }
  993. updateMatrix() {
  994. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  995. }
  996. clone() {
  997. return new this.constructor().copy(this);
  998. }
  999. copy(source) {
  1000. this.name = source.name;
  1001. this.image = source.image;
  1002. this.mipmaps = source.mipmaps.slice(0);
  1003. this.mapping = source.mapping;
  1004. this.wrapS = source.wrapS;
  1005. this.wrapT = source.wrapT;
  1006. this.magFilter = source.magFilter;
  1007. this.minFilter = source.minFilter;
  1008. this.anisotropy = source.anisotropy;
  1009. this.format = source.format;
  1010. this.internalFormat = source.internalFormat;
  1011. this.type = source.type;
  1012. this.offset.copy(source.offset);
  1013. this.repeat.copy(source.repeat);
  1014. this.center.copy(source.center);
  1015. this.rotation = source.rotation;
  1016. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1017. this.matrix.copy(source.matrix);
  1018. this.generateMipmaps = source.generateMipmaps;
  1019. this.premultiplyAlpha = source.premultiplyAlpha;
  1020. this.flipY = source.flipY;
  1021. this.unpackAlignment = source.unpackAlignment;
  1022. this.encoding = source.encoding;
  1023. return this;
  1024. }
  1025. toJSON(meta) {
  1026. const isRootObject = meta === undefined || typeof meta === 'string';
  1027. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  1028. return meta.textures[this.uuid];
  1029. }
  1030. const output = {
  1031. metadata: {
  1032. version: 4.5,
  1033. type: 'Texture',
  1034. generator: 'Texture.toJSON'
  1035. },
  1036. uuid: this.uuid,
  1037. name: this.name,
  1038. mapping: this.mapping,
  1039. repeat: [this.repeat.x, this.repeat.y],
  1040. offset: [this.offset.x, this.offset.y],
  1041. center: [this.center.x, this.center.y],
  1042. rotation: this.rotation,
  1043. wrap: [this.wrapS, this.wrapT],
  1044. format: this.format,
  1045. type: this.type,
  1046. encoding: this.encoding,
  1047. minFilter: this.minFilter,
  1048. magFilter: this.magFilter,
  1049. anisotropy: this.anisotropy,
  1050. flipY: this.flipY,
  1051. premultiplyAlpha: this.premultiplyAlpha,
  1052. unpackAlignment: this.unpackAlignment
  1053. };
  1054. if (this.image !== undefined) {
  1055. // TODO: Move to THREE.Image
  1056. const image = this.image;
  1057. if (image.uuid === undefined) {
  1058. image.uuid = generateUUID(); // UGH
  1059. }
  1060. if (!isRootObject && meta.images[image.uuid] === undefined) {
  1061. let url;
  1062. if (Array.isArray(image)) {
  1063. // process array of images e.g. CubeTexture
  1064. url = [];
  1065. for (let i = 0, l = image.length; i < l; i++) {
  1066. // check cube texture with data textures
  1067. if (image[i].isDataTexture) {
  1068. url.push(serializeImage(image[i].image));
  1069. } else {
  1070. url.push(serializeImage(image[i]));
  1071. }
  1072. }
  1073. } else {
  1074. // process single image
  1075. url = serializeImage(image);
  1076. }
  1077. meta.images[image.uuid] = {
  1078. uuid: image.uuid,
  1079. url: url
  1080. };
  1081. }
  1082. output.image = image.uuid;
  1083. }
  1084. if (!isRootObject) {
  1085. meta.textures[this.uuid] = output;
  1086. }
  1087. return output;
  1088. }
  1089. dispose() {
  1090. this.dispatchEvent({
  1091. type: 'dispose'
  1092. });
  1093. }
  1094. transformUv(uv) {
  1095. if (this.mapping !== UVMapping) return uv;
  1096. uv.applyMatrix3(this.matrix);
  1097. if (uv.x < 0 || uv.x > 1) {
  1098. switch (this.wrapS) {
  1099. case RepeatWrapping:
  1100. uv.x = uv.x - Math.floor(uv.x);
  1101. break;
  1102. case ClampToEdgeWrapping:
  1103. uv.x = uv.x < 0 ? 0 : 1;
  1104. break;
  1105. case MirroredRepeatWrapping:
  1106. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  1107. uv.x = Math.ceil(uv.x) - uv.x;
  1108. } else {
  1109. uv.x = uv.x - Math.floor(uv.x);
  1110. }
  1111. break;
  1112. }
  1113. }
  1114. if (uv.y < 0 || uv.y > 1) {
  1115. switch (this.wrapT) {
  1116. case RepeatWrapping:
  1117. uv.y = uv.y - Math.floor(uv.y);
  1118. break;
  1119. case ClampToEdgeWrapping:
  1120. uv.y = uv.y < 0 ? 0 : 1;
  1121. break;
  1122. case MirroredRepeatWrapping:
  1123. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  1124. uv.y = Math.ceil(uv.y) - uv.y;
  1125. } else {
  1126. uv.y = uv.y - Math.floor(uv.y);
  1127. }
  1128. break;
  1129. }
  1130. }
  1131. if (this.flipY) {
  1132. uv.y = 1 - uv.y;
  1133. }
  1134. return uv;
  1135. }
  1136. set needsUpdate(value) {
  1137. if (value === true) this.version++;
  1138. }
  1139. }
  1140. Texture.DEFAULT_IMAGE = undefined;
  1141. Texture.DEFAULT_MAPPING = UVMapping;
  1142. Texture.prototype.isTexture = true;
  1143. function serializeImage(image) {
  1144. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  1145. // default images
  1146. return ImageUtils.getDataURL(image);
  1147. } else {
  1148. if (image.data) {
  1149. // images of DataTexture
  1150. return {
  1151. data: Array.prototype.slice.call(image.data),
  1152. width: image.width,
  1153. height: image.height,
  1154. type: image.data.constructor.name
  1155. };
  1156. } else {
  1157. console.warn('THREE.Texture: Unable to serialize Texture.');
  1158. return {};
  1159. }
  1160. }
  1161. }
  1162. class Vector4 {
  1163. constructor(x = 0, y = 0, z = 0, w = 1) {
  1164. this.x = x;
  1165. this.y = y;
  1166. this.z = z;
  1167. this.w = w;
  1168. }
  1169. get width() {
  1170. return this.z;
  1171. }
  1172. set width(value) {
  1173. this.z = value;
  1174. }
  1175. get height() {
  1176. return this.w;
  1177. }
  1178. set height(value) {
  1179. this.w = value;
  1180. }
  1181. set(x, y, z, w) {
  1182. this.x = x;
  1183. this.y = y;
  1184. this.z = z;
  1185. this.w = w;
  1186. return this;
  1187. }
  1188. setScalar(scalar) {
  1189. this.x = scalar;
  1190. this.y = scalar;
  1191. this.z = scalar;
  1192. this.w = scalar;
  1193. return this;
  1194. }
  1195. setX(x) {
  1196. this.x = x;
  1197. return this;
  1198. }
  1199. setY(y) {
  1200. this.y = y;
  1201. return this;
  1202. }
  1203. setZ(z) {
  1204. this.z = z;
  1205. return this;
  1206. }
  1207. setW(w) {
  1208. this.w = w;
  1209. return this;
  1210. }
  1211. setComponent(index, value) {
  1212. switch (index) {
  1213. case 0:
  1214. this.x = value;
  1215. break;
  1216. case 1:
  1217. this.y = value;
  1218. break;
  1219. case 2:
  1220. this.z = value;
  1221. break;
  1222. case 3:
  1223. this.w = value;
  1224. break;
  1225. default:
  1226. throw new Error('index is out of range: ' + index);
  1227. }
  1228. return this;
  1229. }
  1230. getComponent(index) {
  1231. switch (index) {
  1232. case 0:
  1233. return this.x;
  1234. case 1:
  1235. return this.y;
  1236. case 2:
  1237. return this.z;
  1238. case 3:
  1239. return this.w;
  1240. default:
  1241. throw new Error('index is out of range: ' + index);
  1242. }
  1243. }
  1244. clone() {
  1245. return new this.constructor(this.x, this.y, this.z, this.w);
  1246. }
  1247. copy(v) {
  1248. this.x = v.x;
  1249. this.y = v.y;
  1250. this.z = v.z;
  1251. this.w = v.w !== undefined ? v.w : 1;
  1252. return this;
  1253. }
  1254. add(v, w) {
  1255. if (w !== undefined) {
  1256. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  1257. return this.addVectors(v, w);
  1258. }
  1259. this.x += v.x;
  1260. this.y += v.y;
  1261. this.z += v.z;
  1262. this.w += v.w;
  1263. return this;
  1264. }
  1265. addScalar(s) {
  1266. this.x += s;
  1267. this.y += s;
  1268. this.z += s;
  1269. this.w += s;
  1270. return this;
  1271. }
  1272. addVectors(a, b) {
  1273. this.x = a.x + b.x;
  1274. this.y = a.y + b.y;
  1275. this.z = a.z + b.z;
  1276. this.w = a.w + b.w;
  1277. return this;
  1278. }
  1279. addScaledVector(v, s) {
  1280. this.x += v.x * s;
  1281. this.y += v.y * s;
  1282. this.z += v.z * s;
  1283. this.w += v.w * s;
  1284. return this;
  1285. }
  1286. sub(v, w) {
  1287. if (w !== undefined) {
  1288. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  1289. return this.subVectors(v, w);
  1290. }
  1291. this.x -= v.x;
  1292. this.y -= v.y;
  1293. this.z -= v.z;
  1294. this.w -= v.w;
  1295. return this;
  1296. }
  1297. subScalar(s) {
  1298. this.x -= s;
  1299. this.y -= s;
  1300. this.z -= s;
  1301. this.w -= s;
  1302. return this;
  1303. }
  1304. subVectors(a, b) {
  1305. this.x = a.x - b.x;
  1306. this.y = a.y - b.y;
  1307. this.z = a.z - b.z;
  1308. this.w = a.w - b.w;
  1309. return this;
  1310. }
  1311. multiply(v) {
  1312. this.x *= v.x;
  1313. this.y *= v.y;
  1314. this.z *= v.z;
  1315. this.w *= v.w;
  1316. return this;
  1317. }
  1318. multiplyScalar(scalar) {
  1319. this.x *= scalar;
  1320. this.y *= scalar;
  1321. this.z *= scalar;
  1322. this.w *= scalar;
  1323. return this;
  1324. }
  1325. applyMatrix4(m) {
  1326. const x = this.x,
  1327. y = this.y,
  1328. z = this.z,
  1329. w = this.w;
  1330. const e = m.elements;
  1331. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1332. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1333. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1334. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1335. return this;
  1336. }
  1337. divideScalar(scalar) {
  1338. return this.multiplyScalar(1 / scalar);
  1339. }
  1340. setAxisAngleFromQuaternion(q) {
  1341. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1342. // q is assumed to be normalized
  1343. this.w = 2 * Math.acos(q.w);
  1344. const s = Math.sqrt(1 - q.w * q.w);
  1345. if (s < 0.0001) {
  1346. this.x = 1;
  1347. this.y = 0;
  1348. this.z = 0;
  1349. } else {
  1350. this.x = q.x / s;
  1351. this.y = q.y / s;
  1352. this.z = q.z / s;
  1353. }
  1354. return this;
  1355. }
  1356. setAxisAngleFromRotationMatrix(m) {
  1357. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1358. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1359. let angle, x, y, z; // variables for result
  1360. const epsilon = 0.01,
  1361. // margin to allow for rounding errors
  1362. epsilon2 = 0.1,
  1363. // margin to distinguish between 0 and 180 degrees
  1364. te = m.elements,
  1365. m11 = te[0],
  1366. m12 = te[4],
  1367. m13 = te[8],
  1368. m21 = te[1],
  1369. m22 = te[5],
  1370. m23 = te[9],
  1371. m31 = te[2],
  1372. m32 = te[6],
  1373. m33 = te[10];
  1374. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  1375. // singularity found
  1376. // first check for identity matrix which must have +1 for all terms
  1377. // in leading diagonal and zero in other terms
  1378. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  1379. // this singularity is identity matrix so angle = 0
  1380. this.set(1, 0, 0, 0);
  1381. return this; // zero angle, arbitrary axis
  1382. } // otherwise this singularity is angle = 180
  1383. angle = Math.PI;
  1384. const xx = (m11 + 1) / 2;
  1385. const yy = (m22 + 1) / 2;
  1386. const zz = (m33 + 1) / 2;
  1387. const xy = (m12 + m21) / 4;
  1388. const xz = (m13 + m31) / 4;
  1389. const yz = (m23 + m32) / 4;
  1390. if (xx > yy && xx > zz) {
  1391. // m11 is the largest diagonal term
  1392. if (xx < epsilon) {
  1393. x = 0;
  1394. y = 0.707106781;
  1395. z = 0.707106781;
  1396. } else {
  1397. x = Math.sqrt(xx);
  1398. y = xy / x;
  1399. z = xz / x;
  1400. }
  1401. } else if (yy > zz) {
  1402. // m22 is the largest diagonal term
  1403. if (yy < epsilon) {
  1404. x = 0.707106781;
  1405. y = 0;
  1406. z = 0.707106781;
  1407. } else {
  1408. y = Math.sqrt(yy);
  1409. x = xy / y;
  1410. z = yz / y;
  1411. }
  1412. } else {
  1413. // m33 is the largest diagonal term so base result on this
  1414. if (zz < epsilon) {
  1415. x = 0.707106781;
  1416. y = 0.707106781;
  1417. z = 0;
  1418. } else {
  1419. z = Math.sqrt(zz);
  1420. x = xz / z;
  1421. y = yz / z;
  1422. }
  1423. }
  1424. this.set(x, y, z, angle);
  1425. return this; // return 180 deg rotation
  1426. } // as we have reached here there are no singularities so we can handle normally
  1427. let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  1428. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1429. // caught by singularity test above, but I've left it in just in case
  1430. this.x = (m32 - m23) / s;
  1431. this.y = (m13 - m31) / s;
  1432. this.z = (m21 - m12) / s;
  1433. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  1434. return this;
  1435. }
  1436. min(v) {
  1437. this.x = Math.min(this.x, v.x);
  1438. this.y = Math.min(this.y, v.y);
  1439. this.z = Math.min(this.z, v.z);
  1440. this.w = Math.min(this.w, v.w);
  1441. return this;
  1442. }
  1443. max(v) {
  1444. this.x = Math.max(this.x, v.x);
  1445. this.y = Math.max(this.y, v.y);
  1446. this.z = Math.max(this.z, v.z);
  1447. this.w = Math.max(this.w, v.w);
  1448. return this;
  1449. }
  1450. clamp(min, max) {
  1451. // assumes min < max, componentwise
  1452. this.x = Math.max(min.x, Math.min(max.x, this.x));
  1453. this.y = Math.max(min.y, Math.min(max.y, this.y));
  1454. this.z = Math.max(min.z, Math.min(max.z, this.z));
  1455. this.w = Math.max(min.w, Math.min(max.w, this.w));
  1456. return this;
  1457. }
  1458. clampScalar(minVal, maxVal) {
  1459. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  1460. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  1461. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  1462. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  1463. return this;
  1464. }
  1465. clampLength(min, max) {
  1466. const length = this.length();
  1467. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  1468. }
  1469. floor() {
  1470. this.x = Math.floor(this.x);
  1471. this.y = Math.floor(this.y);
  1472. this.z = Math.floor(this.z);
  1473. this.w = Math.floor(this.w);
  1474. return this;
  1475. }
  1476. ceil() {
  1477. this.x = Math.ceil(this.x);
  1478. this.y = Math.ceil(this.y);
  1479. this.z = Math.ceil(this.z);
  1480. this.w = Math.ceil(this.w);
  1481. return this;
  1482. }
  1483. round() {
  1484. this.x = Math.round(this.x);
  1485. this.y = Math.round(this.y);
  1486. this.z = Math.round(this.z);
  1487. this.w = Math.round(this.w);
  1488. return this;
  1489. }
  1490. roundToZero() {
  1491. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  1492. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  1493. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  1494. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  1495. return this;
  1496. }
  1497. negate() {
  1498. this.x = -this.x;
  1499. this.y = -this.y;
  1500. this.z = -this.z;
  1501. this.w = -this.w;
  1502. return this;
  1503. }
  1504. dot(v) {
  1505. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1506. }
  1507. lengthSq() {
  1508. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1509. }
  1510. length() {
  1511. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1512. }
  1513. manhattanLength() {
  1514. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  1515. }
  1516. normalize() {
  1517. return this.divideScalar(this.length() || 1);
  1518. }
  1519. setLength(length) {
  1520. return this.normalize().multiplyScalar(length);
  1521. }
  1522. lerp(v, alpha) {
  1523. this.x += (v.x - this.x) * alpha;
  1524. this.y += (v.y - this.y) * alpha;
  1525. this.z += (v.z - this.z) * alpha;
  1526. this.w += (v.w - this.w) * alpha;
  1527. return this;
  1528. }
  1529. lerpVectors(v1, v2, alpha) {
  1530. this.x = v1.x + (v2.x - v1.x) * alpha;
  1531. this.y = v1.y + (v2.y - v1.y) * alpha;
  1532. this.z = v1.z + (v2.z - v1.z) * alpha;
  1533. this.w = v1.w + (v2.w - v1.w) * alpha;
  1534. return this;
  1535. }
  1536. equals(v) {
  1537. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  1538. }
  1539. fromArray(array, offset = 0) {
  1540. this.x = array[offset];
  1541. this.y = array[offset + 1];
  1542. this.z = array[offset + 2];
  1543. this.w = array[offset + 3];
  1544. return this;
  1545. }
  1546. toArray(array = [], offset = 0) {
  1547. array[offset] = this.x;
  1548. array[offset + 1] = this.y;
  1549. array[offset + 2] = this.z;
  1550. array[offset + 3] = this.w;
  1551. return array;
  1552. }
  1553. fromBufferAttribute(attribute, index, offset) {
  1554. if (offset !== undefined) {
  1555. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  1556. }
  1557. this.x = attribute.getX(index);
  1558. this.y = attribute.getY(index);
  1559. this.z = attribute.getZ(index);
  1560. this.w = attribute.getW(index);
  1561. return this;
  1562. }
  1563. random() {
  1564. this.x = Math.random();
  1565. this.y = Math.random();
  1566. this.z = Math.random();
  1567. this.w = Math.random();
  1568. return this;
  1569. }
  1570. }
  1571. Vector4.prototype.isVector4 = true;
  1572. /*
  1573. In options, we can specify:
  1574. * Texture parameters for an auto-generated target texture
  1575. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1576. */
  1577. class WebGLRenderTarget extends EventDispatcher {
  1578. constructor(width, height, options = {}) {
  1579. super();
  1580. this.width = width;
  1581. this.height = height;
  1582. this.depth = 1;
  1583. this.scissor = new Vector4(0, 0, width, height);
  1584. this.scissorTest = false;
  1585. this.viewport = new Vector4(0, 0, width, height);
  1586. this.texture = new Texture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  1587. this.texture.image = {
  1588. width: width,
  1589. height: height,
  1590. depth: 1
  1591. };
  1592. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  1593. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  1594. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1595. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  1596. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1597. }
  1598. setTexture(texture) {
  1599. texture.image = {
  1600. width: this.width,
  1601. height: this.height,
  1602. depth: this.depth
  1603. };
  1604. this.texture = texture;
  1605. }
  1606. setSize(width, height, depth = 1) {
  1607. if (this.width !== width || this.height !== height || this.depth !== depth) {
  1608. this.width = width;
  1609. this.height = height;
  1610. this.depth = depth;
  1611. this.texture.image.width = width;
  1612. this.texture.image.height = height;
  1613. this.texture.image.depth = depth;
  1614. this.dispose();
  1615. }
  1616. this.viewport.set(0, 0, width, height);
  1617. this.scissor.set(0, 0, width, height);
  1618. }
  1619. clone() {
  1620. return new this.constructor().copy(this);
  1621. }
  1622. copy(source) {
  1623. this.width = source.width;
  1624. this.height = source.height;
  1625. this.depth = source.depth;
  1626. this.viewport.copy(source.viewport);
  1627. this.texture = source.texture.clone();
  1628. this.texture.image = { ...this.texture.image
  1629. }; // See #20328.
  1630. this.depthBuffer = source.depthBuffer;
  1631. this.stencilBuffer = source.stencilBuffer;
  1632. this.depthTexture = source.depthTexture;
  1633. return this;
  1634. }
  1635. dispose() {
  1636. this.dispatchEvent({
  1637. type: 'dispose'
  1638. });
  1639. }
  1640. }
  1641. WebGLRenderTarget.prototype.isWebGLRenderTarget = true;
  1642. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  1643. constructor(width, height, count) {
  1644. super(width, height);
  1645. const texture = this.texture;
  1646. this.texture = [];
  1647. for (let i = 0; i < count; i++) {
  1648. this.texture[i] = texture.clone();
  1649. }
  1650. }
  1651. setSize(width, height, depth = 1) {
  1652. if (this.width !== width || this.height !== height || this.depth !== depth) {
  1653. this.width = width;
  1654. this.height = height;
  1655. this.depth = depth;
  1656. for (let i = 0, il = this.texture.length; i < il; i++) {
  1657. this.texture[i].image.width = width;
  1658. this.texture[i].image.height = height;
  1659. this.texture[i].image.depth = depth;
  1660. }
  1661. this.dispose();
  1662. }
  1663. this.viewport.set(0, 0, width, height);
  1664. this.scissor.set(0, 0, width, height);
  1665. return this;
  1666. }
  1667. copy(source) {
  1668. this.dispose();
  1669. this.width = source.width;
  1670. this.height = source.height;
  1671. this.depth = source.depth;
  1672. this.viewport.set(0, 0, this.width, this.height);
  1673. this.scissor.set(0, 0, this.width, this.height);
  1674. this.depthBuffer = source.depthBuffer;
  1675. this.stencilBuffer = source.stencilBuffer;
  1676. this.depthTexture = source.depthTexture;
  1677. this.texture.length = 0;
  1678. for (let i = 0, il = source.texture.length; i < il; i++) {
  1679. this.texture[i] = source.texture[i].clone();
  1680. }
  1681. return this;
  1682. }
  1683. }
  1684. WebGLMultipleRenderTargets.prototype.isWebGLMultipleRenderTargets = true;
  1685. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  1686. constructor(width, height, options) {
  1687. super(width, height, options);
  1688. this.samples = 4;
  1689. }
  1690. copy(source) {
  1691. super.copy.call(this, source);
  1692. this.samples = source.samples;
  1693. return this;
  1694. }
  1695. }
  1696. WebGLMultisampleRenderTarget.prototype.isWebGLMultisampleRenderTarget = true;
  1697. class Quaternion {
  1698. constructor(x = 0, y = 0, z = 0, w = 1) {
  1699. this._x = x;
  1700. this._y = y;
  1701. this._z = z;
  1702. this._w = w;
  1703. }
  1704. static slerp(qa, qb, qm, t) {
  1705. console.warn('THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead.');
  1706. return qm.slerpQuaternions(qa, qb, t);
  1707. }
  1708. static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  1709. // fuzz-free, array-based Quaternion SLERP operation
  1710. let x0 = src0[srcOffset0 + 0],
  1711. y0 = src0[srcOffset0 + 1],
  1712. z0 = src0[srcOffset0 + 2],
  1713. w0 = src0[srcOffset0 + 3];
  1714. const x1 = src1[srcOffset1 + 0],
  1715. y1 = src1[srcOffset1 + 1],
  1716. z1 = src1[srcOffset1 + 2],
  1717. w1 = src1[srcOffset1 + 3];
  1718. if (t === 0) {
  1719. dst[dstOffset + 0] = x0;
  1720. dst[dstOffset + 1] = y0;
  1721. dst[dstOffset + 2] = z0;
  1722. dst[dstOffset + 3] = w0;
  1723. return;
  1724. }
  1725. if (t === 1) {
  1726. dst[dstOffset + 0] = x1;
  1727. dst[dstOffset + 1] = y1;
  1728. dst[dstOffset + 2] = z1;
  1729. dst[dstOffset + 3] = w1;
  1730. return;
  1731. }
  1732. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  1733. let s = 1 - t;
  1734. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1735. dir = cos >= 0 ? 1 : -1,
  1736. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  1737. if (sqrSin > Number.EPSILON) {
  1738. const sin = Math.sqrt(sqrSin),
  1739. len = Math.atan2(sin, cos * dir);
  1740. s = Math.sin(s * len) / sin;
  1741. t = Math.sin(t * len) / sin;
  1742. }
  1743. const tDir = t * dir;
  1744. x0 = x0 * s + x1 * tDir;
  1745. y0 = y0 * s + y1 * tDir;
  1746. z0 = z0 * s + z1 * tDir;
  1747. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  1748. if (s === 1 - t) {
  1749. const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  1750. x0 *= f;
  1751. y0 *= f;
  1752. z0 *= f;
  1753. w0 *= f;
  1754. }
  1755. }
  1756. dst[dstOffset] = x0;
  1757. dst[dstOffset + 1] = y0;
  1758. dst[dstOffset + 2] = z0;
  1759. dst[dstOffset + 3] = w0;
  1760. }
  1761. static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
  1762. const x0 = src0[srcOffset0];
  1763. const y0 = src0[srcOffset0 + 1];
  1764. const z0 = src0[srcOffset0 + 2];
  1765. const w0 = src0[srcOffset0 + 3];
  1766. const x1 = src1[srcOffset1];
  1767. const y1 = src1[srcOffset1 + 1];
  1768. const z1 = src1[srcOffset1 + 2];
  1769. const w1 = src1[srcOffset1 + 3];
  1770. dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  1771. dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  1772. dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  1773. dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  1774. return dst;
  1775. }
  1776. get x() {
  1777. return this._x;
  1778. }
  1779. set x(value) {
  1780. this._x = value;
  1781. this._onChangeCallback();
  1782. }
  1783. get y() {
  1784. return this._y;
  1785. }
  1786. set y(value) {
  1787. this._y = value;
  1788. this._onChangeCallback();
  1789. }
  1790. get z() {
  1791. return this._z;
  1792. }
  1793. set z(value) {
  1794. this._z = value;
  1795. this._onChangeCallback();
  1796. }
  1797. get w() {
  1798. return this._w;
  1799. }
  1800. set w(value) {
  1801. this._w = value;
  1802. this._onChangeCallback();
  1803. }
  1804. set(x, y, z, w) {
  1805. this._x = x;
  1806. this._y = y;
  1807. this._z = z;
  1808. this._w = w;
  1809. this._onChangeCallback();
  1810. return this;
  1811. }
  1812. clone() {
  1813. return new this.constructor(this._x, this._y, this._z, this._w);
  1814. }
  1815. copy(quaternion) {
  1816. this._x = quaternion.x;
  1817. this._y = quaternion.y;
  1818. this._z = quaternion.z;
  1819. this._w = quaternion.w;
  1820. this._onChangeCallback();
  1821. return this;
  1822. }
  1823. setFromEuler(euler, update) {
  1824. if (!(euler && euler.isEuler)) {
  1825. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  1826. }
  1827. const x = euler._x,
  1828. y = euler._y,
  1829. z = euler._z,
  1830. order = euler._order; // http://www.mathworks.com/matlabcentral/fileexchange/
  1831. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1832. // content/SpinCalc.m
  1833. const cos = Math.cos;
  1834. const sin = Math.sin;
  1835. const c1 = cos(x / 2);
  1836. const c2 = cos(y / 2);
  1837. const c3 = cos(z / 2);
  1838. const s1 = sin(x / 2);
  1839. const s2 = sin(y / 2);
  1840. const s3 = sin(z / 2);
  1841. switch (order) {
  1842. case 'XYZ':
  1843. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1844. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1845. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1846. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1847. break;
  1848. case 'YXZ':
  1849. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1850. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1851. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1852. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1853. break;
  1854. case 'ZXY':
  1855. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1856. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1857. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1858. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1859. break;
  1860. case 'ZYX':
  1861. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1862. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1863. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1864. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1865. break;
  1866. case 'YZX':
  1867. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1868. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1869. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1870. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1871. break;
  1872. case 'XZY':
  1873. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1874. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1875. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1876. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1877. break;
  1878. default:
  1879. console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
  1880. }
  1881. if (update !== false) this._onChangeCallback();
  1882. return this;
  1883. }
  1884. setFromAxisAngle(axis, angle) {
  1885. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1886. // assumes axis is normalized
  1887. const halfAngle = angle / 2,
  1888. s = Math.sin(halfAngle);
  1889. this._x = axis.x * s;
  1890. this._y = axis.y * s;
  1891. this._z = axis.z * s;
  1892. this._w = Math.cos(halfAngle);
  1893. this._onChangeCallback();
  1894. return this;
  1895. }
  1896. setFromRotationMatrix(m) {
  1897. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1898. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1899. const te = m.elements,
  1900. m11 = te[0],
  1901. m12 = te[4],
  1902. m13 = te[8],
  1903. m21 = te[1],
  1904. m22 = te[5],
  1905. m23 = te[9],
  1906. m31 = te[2],
  1907. m32 = te[6],
  1908. m33 = te[10],
  1909. trace = m11 + m22 + m33;
  1910. if (trace > 0) {
  1911. const s = 0.5 / Math.sqrt(trace + 1.0);
  1912. this._w = 0.25 / s;
  1913. this._x = (m32 - m23) * s;
  1914. this._y = (m13 - m31) * s;
  1915. this._z = (m21 - m12) * s;
  1916. } else if (m11 > m22 && m11 > m33) {
  1917. const s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1918. this._w = (m32 - m23) / s;
  1919. this._x = 0.25 * s;
  1920. this._y = (m12 + m21) / s;
  1921. this._z = (m13 + m31) / s;
  1922. } else if (m22 > m33) {
  1923. const s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1924. this._w = (m13 - m31) / s;
  1925. this._x = (m12 + m21) / s;
  1926. this._y = 0.25 * s;
  1927. this._z = (m23 + m32) / s;
  1928. } else {
  1929. const s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1930. this._w = (m21 - m12) / s;
  1931. this._x = (m13 + m31) / s;
  1932. this._y = (m23 + m32) / s;
  1933. this._z = 0.25 * s;
  1934. }
  1935. this._onChangeCallback();
  1936. return this;
  1937. }
  1938. setFromUnitVectors(vFrom, vTo) {
  1939. // assumes direction vectors vFrom and vTo are normalized
  1940. let r = vFrom.dot(vTo) + 1;
  1941. if (r < Number.EPSILON) {
  1942. // vFrom and vTo point in opposite directions
  1943. r = 0;
  1944. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  1945. this._x = -vFrom.y;
  1946. this._y = vFrom.x;
  1947. this._z = 0;
  1948. this._w = r;
  1949. } else {
  1950. this._x = 0;
  1951. this._y = -vFrom.z;
  1952. this._z = vFrom.y;
  1953. this._w = r;
  1954. }
  1955. } else {
  1956. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  1957. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  1958. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  1959. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  1960. this._w = r;
  1961. }
  1962. return this.normalize();
  1963. }
  1964. angleTo(q) {
  1965. return 2 * Math.acos(Math.abs(clamp(this.dot(q), -1, 1)));
  1966. }
  1967. rotateTowards(q, step) {
  1968. const angle = this.angleTo(q);
  1969. if (angle === 0) return this;
  1970. const t = Math.min(1, step / angle);
  1971. this.slerp(q, t);
  1972. return this;
  1973. }
  1974. identity() {
  1975. return this.set(0, 0, 0, 1);
  1976. }
  1977. invert() {
  1978. // quaternion is assumed to have unit length
  1979. return this.conjugate();
  1980. }
  1981. conjugate() {
  1982. this._x *= -1;
  1983. this._y *= -1;
  1984. this._z *= -1;
  1985. this._onChangeCallback();
  1986. return this;
  1987. }
  1988. dot(v) {
  1989. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1990. }
  1991. lengthSq() {
  1992. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1993. }
  1994. length() {
  1995. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  1996. }
  1997. normalize() {
  1998. let l = this.length();
  1999. if (l === 0) {
  2000. this._x = 0;
  2001. this._y = 0;
  2002. this._z = 0;
  2003. this._w = 1;
  2004. } else {
  2005. l = 1 / l;
  2006. this._x = this._x * l;
  2007. this._y = this._y * l;
  2008. this._z = this._z * l;
  2009. this._w = this._w * l;
  2010. }
  2011. this._onChangeCallback();
  2012. return this;
  2013. }
  2014. multiply(q, p) {
  2015. if (p !== undefined) {
  2016. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  2017. return this.multiplyQuaternions(q, p);
  2018. }
  2019. return this.multiplyQuaternions(this, q);
  2020. }
  2021. premultiply(q) {
  2022. return this.multiplyQuaternions(q, this);
  2023. }
  2024. multiplyQuaternions(a, b) {
  2025. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2026. const qax = a._x,
  2027. qay = a._y,
  2028. qaz = a._z,
  2029. qaw = a._w;
  2030. const qbx = b._x,
  2031. qby = b._y,
  2032. qbz = b._z,
  2033. qbw = b._w;
  2034. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2035. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2036. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2037. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2038. this._onChangeCallback();
  2039. return this;
  2040. }
  2041. slerp(qb, t) {
  2042. if (t === 0) return this;
  2043. if (t === 1) return this.copy(qb);
  2044. const x = this._x,
  2045. y = this._y,
  2046. z = this._z,
  2047. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2048. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2049. if (cosHalfTheta < 0) {
  2050. this._w = -qb._w;
  2051. this._x = -qb._x;
  2052. this._y = -qb._y;
  2053. this._z = -qb._z;
  2054. cosHalfTheta = -cosHalfTheta;
  2055. } else {
  2056. this.copy(qb);
  2057. }
  2058. if (cosHalfTheta >= 1.0) {
  2059. this._w = w;
  2060. this._x = x;
  2061. this._y = y;
  2062. this._z = z;
  2063. return this;
  2064. }
  2065. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2066. if (sqrSinHalfTheta <= Number.EPSILON) {
  2067. const s = 1 - t;
  2068. this._w = s * w + t * this._w;
  2069. this._x = s * x + t * this._x;
  2070. this._y = s * y + t * this._y;
  2071. this._z = s * z + t * this._z;
  2072. this.normalize();
  2073. this._onChangeCallback();
  2074. return this;
  2075. }
  2076. const sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2077. const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2078. const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2079. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2080. this._w = w * ratioA + this._w * ratioB;
  2081. this._x = x * ratioA + this._x * ratioB;
  2082. this._y = y * ratioA + this._y * ratioB;
  2083. this._z = z * ratioA + this._z * ratioB;
  2084. this._onChangeCallback();
  2085. return this;
  2086. }
  2087. slerpQuaternions(qa, qb, t) {
  2088. this.copy(qa).slerp(qb, t);
  2089. }
  2090. equals(quaternion) {
  2091. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2092. }
  2093. fromArray(array, offset = 0) {
  2094. this._x = array[offset];
  2095. this._y = array[offset + 1];
  2096. this._z = array[offset + 2];
  2097. this._w = array[offset + 3];
  2098. this._onChangeCallback();
  2099. return this;
  2100. }
  2101. toArray(array = [], offset = 0) {
  2102. array[offset] = this._x;
  2103. array[offset + 1] = this._y;
  2104. array[offset + 2] = this._z;
  2105. array[offset + 3] = this._w;
  2106. return array;
  2107. }
  2108. fromBufferAttribute(attribute, index) {
  2109. this._x = attribute.getX(index);
  2110. this._y = attribute.getY(index);
  2111. this._z = attribute.getZ(index);
  2112. this._w = attribute.getW(index);
  2113. return this;
  2114. }
  2115. _onChange(callback) {
  2116. this._onChangeCallback = callback;
  2117. return this;
  2118. }
  2119. _onChangeCallback() {}
  2120. }
  2121. Quaternion.prototype.isQuaternion = true;
  2122. class Vector3 {
  2123. constructor(x = 0, y = 0, z = 0) {
  2124. this.x = x;
  2125. this.y = y;
  2126. this.z = z;
  2127. }
  2128. set(x, y, z) {
  2129. if (z === undefined) z = this.z; // sprite.scale.set(x,y)
  2130. this.x = x;
  2131. this.y = y;
  2132. this.z = z;
  2133. return this;
  2134. }
  2135. setScalar(scalar) {
  2136. this.x = scalar;
  2137. this.y = scalar;
  2138. this.z = scalar;
  2139. return this;
  2140. }
  2141. setX(x) {
  2142. this.x = x;
  2143. return this;
  2144. }
  2145. setY(y) {
  2146. this.y = y;
  2147. return this;
  2148. }
  2149. setZ(z) {
  2150. this.z = z;
  2151. return this;
  2152. }
  2153. setComponent(index, value) {
  2154. switch (index) {
  2155. case 0:
  2156. this.x = value;
  2157. break;
  2158. case 1:
  2159. this.y = value;
  2160. break;
  2161. case 2:
  2162. this.z = value;
  2163. break;
  2164. default:
  2165. throw new Error('index is out of range: ' + index);
  2166. }
  2167. return this;
  2168. }
  2169. getComponent(index) {
  2170. switch (index) {
  2171. case 0:
  2172. return this.x;
  2173. case 1:
  2174. return this.y;
  2175. case 2:
  2176. return this.z;
  2177. default:
  2178. throw new Error('index is out of range: ' + index);
  2179. }
  2180. }
  2181. clone() {
  2182. return new this.constructor(this.x, this.y, this.z);
  2183. }
  2184. copy(v) {
  2185. this.x = v.x;
  2186. this.y = v.y;
  2187. this.z = v.z;
  2188. return this;
  2189. }
  2190. add(v, w) {
  2191. if (w !== undefined) {
  2192. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2193. return this.addVectors(v, w);
  2194. }
  2195. this.x += v.x;
  2196. this.y += v.y;
  2197. this.z += v.z;
  2198. return this;
  2199. }
  2200. addScalar(s) {
  2201. this.x += s;
  2202. this.y += s;
  2203. this.z += s;
  2204. return this;
  2205. }
  2206. addVectors(a, b) {
  2207. this.x = a.x + b.x;
  2208. this.y = a.y + b.y;
  2209. this.z = a.z + b.z;
  2210. return this;
  2211. }
  2212. addScaledVector(v, s) {
  2213. this.x += v.x * s;
  2214. this.y += v.y * s;
  2215. this.z += v.z * s;
  2216. return this;
  2217. }
  2218. sub(v, w) {
  2219. if (w !== undefined) {
  2220. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2221. return this.subVectors(v, w);
  2222. }
  2223. this.x -= v.x;
  2224. this.y -= v.y;
  2225. this.z -= v.z;
  2226. return this;
  2227. }
  2228. subScalar(s) {
  2229. this.x -= s;
  2230. this.y -= s;
  2231. this.z -= s;
  2232. return this;
  2233. }
  2234. subVectors(a, b) {
  2235. this.x = a.x - b.x;
  2236. this.y = a.y - b.y;
  2237. this.z = a.z - b.z;
  2238. return this;
  2239. }
  2240. multiply(v, w) {
  2241. if (w !== undefined) {
  2242. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  2243. return this.multiplyVectors(v, w);
  2244. }
  2245. this.x *= v.x;
  2246. this.y *= v.y;
  2247. this.z *= v.z;
  2248. return this;
  2249. }
  2250. multiplyScalar(scalar) {
  2251. this.x *= scalar;
  2252. this.y *= scalar;
  2253. this.z *= scalar;
  2254. return this;
  2255. }
  2256. multiplyVectors(a, b) {
  2257. this.x = a.x * b.x;
  2258. this.y = a.y * b.y;
  2259. this.z = a.z * b.z;
  2260. return this;
  2261. }
  2262. applyEuler(euler) {
  2263. if (!(euler && euler.isEuler)) {
  2264. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2265. }
  2266. return this.applyQuaternion(_quaternion$4.setFromEuler(euler));
  2267. }
  2268. applyAxisAngle(axis, angle) {
  2269. return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle));
  2270. }
  2271. applyMatrix3(m) {
  2272. const x = this.x,
  2273. y = this.y,
  2274. z = this.z;
  2275. const e = m.elements;
  2276. this.x = e[0] * x + e[3] * y + e[6] * z;
  2277. this.y = e[1] * x + e[4] * y + e[7] * z;
  2278. this.z = e[2] * x + e[5] * y + e[8] * z;
  2279. return this;
  2280. }
  2281. applyNormalMatrix(m) {
  2282. return this.applyMatrix3(m).normalize();
  2283. }
  2284. applyMatrix4(m) {
  2285. const x = this.x,
  2286. y = this.y,
  2287. z = this.z;
  2288. const e = m.elements;
  2289. const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2290. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2291. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2292. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2293. return this;
  2294. }
  2295. applyQuaternion(q) {
  2296. const x = this.x,
  2297. y = this.y,
  2298. z = this.z;
  2299. const qx = q.x,
  2300. qy = q.y,
  2301. qz = q.z,
  2302. qw = q.w; // calculate quat * vector
  2303. const ix = qw * x + qy * z - qz * y;
  2304. const iy = qw * y + qz * x - qx * z;
  2305. const iz = qw * z + qx * y - qy * x;
  2306. const iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  2307. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2308. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2309. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2310. return this;
  2311. }
  2312. project(camera) {
  2313. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  2314. }
  2315. unproject(camera) {
  2316. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  2317. }
  2318. transformDirection(m) {
  2319. // input: THREE.Matrix4 affine matrix
  2320. // vector interpreted as a direction
  2321. const x = this.x,
  2322. y = this.y,
  2323. z = this.z;
  2324. const e = m.elements;
  2325. this.x = e[0] * x + e[4] * y + e[8] * z;
  2326. this.y = e[1] * x + e[5] * y + e[9] * z;
  2327. this.z = e[2] * x + e[6] * y + e[10] * z;
  2328. return this.normalize();
  2329. }
  2330. divide(v) {
  2331. this.x /= v.x;
  2332. this.y /= v.y;
  2333. this.z /= v.z;
  2334. return this;
  2335. }
  2336. divideScalar(scalar) {
  2337. return this.multiplyScalar(1 / scalar);
  2338. }
  2339. min(v) {
  2340. this.x = Math.min(this.x, v.x);
  2341. this.y = Math.min(this.y, v.y);
  2342. this.z = Math.min(this.z, v.z);
  2343. return this;
  2344. }
  2345. max(v) {
  2346. this.x = Math.max(this.x, v.x);
  2347. this.y = Math.max(this.y, v.y);
  2348. this.z = Math.max(this.z, v.z);
  2349. return this;
  2350. }
  2351. clamp(min, max) {
  2352. // assumes min < max, componentwise
  2353. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2354. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2355. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2356. return this;
  2357. }
  2358. clampScalar(minVal, maxVal) {
  2359. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2360. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2361. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2362. return this;
  2363. }
  2364. clampLength(min, max) {
  2365. const length = this.length();
  2366. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2367. }
  2368. floor() {
  2369. this.x = Math.floor(this.x);
  2370. this.y = Math.floor(this.y);
  2371. this.z = Math.floor(this.z);
  2372. return this;
  2373. }
  2374. ceil() {
  2375. this.x = Math.ceil(this.x);
  2376. this.y = Math.ceil(this.y);
  2377. this.z = Math.ceil(this.z);
  2378. return this;
  2379. }
  2380. round() {
  2381. this.x = Math.round(this.x);
  2382. this.y = Math.round(this.y);
  2383. this.z = Math.round(this.z);
  2384. return this;
  2385. }
  2386. roundToZero() {
  2387. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2388. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2389. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2390. return this;
  2391. }
  2392. negate() {
  2393. this.x = -this.x;
  2394. this.y = -this.y;
  2395. this.z = -this.z;
  2396. return this;
  2397. }
  2398. dot(v) {
  2399. return this.x * v.x + this.y * v.y + this.z * v.z;
  2400. } // TODO lengthSquared?
  2401. lengthSq() {
  2402. return this.x * this.x + this.y * this.y + this.z * this.z;
  2403. }
  2404. length() {
  2405. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2406. }
  2407. manhattanLength() {
  2408. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  2409. }
  2410. normalize() {
  2411. return this.divideScalar(this.length() || 1);
  2412. }
  2413. setLength(length) {
  2414. return this.normalize().multiplyScalar(length);
  2415. }
  2416. lerp(v, alpha) {
  2417. this.x += (v.x - this.x) * alpha;
  2418. this.y += (v.y - this.y) * alpha;
  2419. this.z += (v.z - this.z) * alpha;
  2420. return this;
  2421. }
  2422. lerpVectors(v1, v2, alpha) {
  2423. this.x = v1.x + (v2.x - v1.x) * alpha;
  2424. this.y = v1.y + (v2.y - v1.y) * alpha;
  2425. this.z = v1.z + (v2.z - v1.z) * alpha;
  2426. return this;
  2427. }
  2428. cross(v, w) {
  2429. if (w !== undefined) {
  2430. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  2431. return this.crossVectors(v, w);
  2432. }
  2433. return this.crossVectors(this, v);
  2434. }
  2435. crossVectors(a, b) {
  2436. const ax = a.x,
  2437. ay = a.y,
  2438. az = a.z;
  2439. const bx = b.x,
  2440. by = b.y,
  2441. bz = b.z;
  2442. this.x = ay * bz - az * by;
  2443. this.y = az * bx - ax * bz;
  2444. this.z = ax * by - ay * bx;
  2445. return this;
  2446. }
  2447. projectOnVector(v) {
  2448. const denominator = v.lengthSq();
  2449. if (denominator === 0) return this.set(0, 0, 0);
  2450. const scalar = v.dot(this) / denominator;
  2451. return this.copy(v).multiplyScalar(scalar);
  2452. }
  2453. projectOnPlane(planeNormal) {
  2454. _vector$c.copy(this).projectOnVector(planeNormal);
  2455. return this.sub(_vector$c);
  2456. }
  2457. reflect(normal) {
  2458. // reflect incident vector off plane orthogonal to normal
  2459. // normal is assumed to have unit length
  2460. return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal)));
  2461. }
  2462. angleTo(v) {
  2463. const denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  2464. if (denominator === 0) return Math.PI / 2;
  2465. const theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  2466. return Math.acos(clamp(theta, -1, 1));
  2467. }
  2468. distanceTo(v) {
  2469. return Math.sqrt(this.distanceToSquared(v));
  2470. }
  2471. distanceToSquared(v) {
  2472. const dx = this.x - v.x,
  2473. dy = this.y - v.y,
  2474. dz = this.z - v.z;
  2475. return dx * dx + dy * dy + dz * dz;
  2476. }
  2477. manhattanDistanceTo(v) {
  2478. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  2479. }
  2480. setFromSpherical(s) {
  2481. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  2482. }
  2483. setFromSphericalCoords(radius, phi, theta) {
  2484. const sinPhiRadius = Math.sin(phi) * radius;
  2485. this.x = sinPhiRadius * Math.sin(theta);
  2486. this.y = Math.cos(phi) * radius;
  2487. this.z = sinPhiRadius * Math.cos(theta);
  2488. return this;
  2489. }
  2490. setFromCylindrical(c) {
  2491. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  2492. }
  2493. setFromCylindricalCoords(radius, theta, y) {
  2494. this.x = radius * Math.sin(theta);
  2495. this.y = y;
  2496. this.z = radius * Math.cos(theta);
  2497. return this;
  2498. }
  2499. setFromMatrixPosition(m) {
  2500. const e = m.elements;
  2501. this.x = e[12];
  2502. this.y = e[13];
  2503. this.z = e[14];
  2504. return this;
  2505. }
  2506. setFromMatrixScale(m) {
  2507. const sx = this.setFromMatrixColumn(m, 0).length();
  2508. const sy = this.setFromMatrixColumn(m, 1).length();
  2509. const sz = this.setFromMatrixColumn(m, 2).length();
  2510. this.x = sx;
  2511. this.y = sy;
  2512. this.z = sz;
  2513. return this;
  2514. }
  2515. setFromMatrixColumn(m, index) {
  2516. return this.fromArray(m.elements, index * 4);
  2517. }
  2518. setFromMatrix3Column(m, index) {
  2519. return this.fromArray(m.elements, index * 3);
  2520. }
  2521. equals(v) {
  2522. return v.x === this.x && v.y === this.y && v.z === this.z;
  2523. }
  2524. fromArray(array, offset = 0) {
  2525. this.x = array[offset];
  2526. this.y = array[offset + 1];
  2527. this.z = array[offset + 2];
  2528. return this;
  2529. }
  2530. toArray(array = [], offset = 0) {
  2531. array[offset] = this.x;
  2532. array[offset + 1] = this.y;
  2533. array[offset + 2] = this.z;
  2534. return array;
  2535. }
  2536. fromBufferAttribute(attribute, index, offset) {
  2537. if (offset !== undefined) {
  2538. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  2539. }
  2540. this.x = attribute.getX(index);
  2541. this.y = attribute.getY(index);
  2542. this.z = attribute.getZ(index);
  2543. return this;
  2544. }
  2545. random() {
  2546. this.x = Math.random();
  2547. this.y = Math.random();
  2548. this.z = Math.random();
  2549. return this;
  2550. }
  2551. }
  2552. Vector3.prototype.isVector3 = true;
  2553. const _vector$c = /*@__PURE__*/new Vector3();
  2554. const _quaternion$4 = /*@__PURE__*/new Quaternion();
  2555. class Box3 {
  2556. constructor(min = new Vector3(+Infinity, +Infinity, +Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity)) {
  2557. this.min = min;
  2558. this.max = max;
  2559. }
  2560. set(min, max) {
  2561. this.min.copy(min);
  2562. this.max.copy(max);
  2563. return this;
  2564. }
  2565. setFromArray(array) {
  2566. let minX = +Infinity;
  2567. let minY = +Infinity;
  2568. let minZ = +Infinity;
  2569. let maxX = -Infinity;
  2570. let maxY = -Infinity;
  2571. let maxZ = -Infinity;
  2572. for (let i = 0, l = array.length; i < l; i += 3) {
  2573. const x = array[i];
  2574. const y = array[i + 1];
  2575. const z = array[i + 2];
  2576. if (x < minX) minX = x;
  2577. if (y < minY) minY = y;
  2578. if (z < minZ) minZ = z;
  2579. if (x > maxX) maxX = x;
  2580. if (y > maxY) maxY = y;
  2581. if (z > maxZ) maxZ = z;
  2582. }
  2583. this.min.set(minX, minY, minZ);
  2584. this.max.set(maxX, maxY, maxZ);
  2585. return this;
  2586. }
  2587. setFromBufferAttribute(attribute) {
  2588. let minX = +Infinity;
  2589. let minY = +Infinity;
  2590. let minZ = +Infinity;
  2591. let maxX = -Infinity;
  2592. let maxY = -Infinity;
  2593. let maxZ = -Infinity;
  2594. for (let i = 0, l = attribute.count; i < l; i++) {
  2595. const x = attribute.getX(i);
  2596. const y = attribute.getY(i);
  2597. const z = attribute.getZ(i);
  2598. if (x < minX) minX = x;
  2599. if (y < minY) minY = y;
  2600. if (z < minZ) minZ = z;
  2601. if (x > maxX) maxX = x;
  2602. if (y > maxY) maxY = y;
  2603. if (z > maxZ) maxZ = z;
  2604. }
  2605. this.min.set(minX, minY, minZ);
  2606. this.max.set(maxX, maxY, maxZ);
  2607. return this;
  2608. }
  2609. setFromPoints(points) {
  2610. this.makeEmpty();
  2611. for (let i = 0, il = points.length; i < il; i++) {
  2612. this.expandByPoint(points[i]);
  2613. }
  2614. return this;
  2615. }
  2616. setFromCenterAndSize(center, size) {
  2617. const halfSize = _vector$b.copy(size).multiplyScalar(0.5);
  2618. this.min.copy(center).sub(halfSize);
  2619. this.max.copy(center).add(halfSize);
  2620. return this;
  2621. }
  2622. setFromObject(object) {
  2623. this.makeEmpty();
  2624. return this.expandByObject(object);
  2625. }
  2626. clone() {
  2627. return new this.constructor().copy(this);
  2628. }
  2629. copy(box) {
  2630. this.min.copy(box.min);
  2631. this.max.copy(box.max);
  2632. return this;
  2633. }
  2634. makeEmpty() {
  2635. this.min.x = this.min.y = this.min.z = +Infinity;
  2636. this.max.x = this.max.y = this.max.z = -Infinity;
  2637. return this;
  2638. }
  2639. isEmpty() {
  2640. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2641. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  2642. }
  2643. getCenter(target) {
  2644. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  2645. }
  2646. getSize(target) {
  2647. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  2648. }
  2649. expandByPoint(point) {
  2650. this.min.min(point);
  2651. this.max.max(point);
  2652. return this;
  2653. }
  2654. expandByVector(vector) {
  2655. this.min.sub(vector);
  2656. this.max.add(vector);
  2657. return this;
  2658. }
  2659. expandByScalar(scalar) {
  2660. this.min.addScalar(-scalar);
  2661. this.max.addScalar(scalar);
  2662. return this;
  2663. }
  2664. expandByObject(object) {
  2665. // Computes the world-axis-aligned bounding box of an object (including its children),
  2666. // accounting for both the object's, and children's, world transforms
  2667. object.updateWorldMatrix(false, false);
  2668. const geometry = object.geometry;
  2669. if (geometry !== undefined) {
  2670. if (geometry.boundingBox === null) {
  2671. geometry.computeBoundingBox();
  2672. }
  2673. _box$3.copy(geometry.boundingBox);
  2674. _box$3.applyMatrix4(object.matrixWorld);
  2675. this.union(_box$3);
  2676. }
  2677. const children = object.children;
  2678. for (let i = 0, l = children.length; i < l; i++) {
  2679. this.expandByObject(children[i]);
  2680. }
  2681. return this;
  2682. }
  2683. containsPoint(point) {
  2684. 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;
  2685. }
  2686. containsBox(box) {
  2687. 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;
  2688. }
  2689. getParameter(point, target) {
  2690. // This can potentially have a divide by zero if the box
  2691. // has a size dimension of 0.
  2692. 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));
  2693. }
  2694. intersectsBox(box) {
  2695. // using 6 splitting planes to rule out intersections.
  2696. 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;
  2697. }
  2698. intersectsSphere(sphere) {
  2699. // Find the point on the AABB closest to the sphere center.
  2700. this.clampPoint(sphere.center, _vector$b); // If that point is inside the sphere, the AABB and sphere intersect.
  2701. return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  2702. }
  2703. intersectsPlane(plane) {
  2704. // We compute the minimum and maximum dot product values. If those values
  2705. // are on the same side (back or front) of the plane, then there is no intersection.
  2706. let min, max;
  2707. if (plane.normal.x > 0) {
  2708. min = plane.normal.x * this.min.x;
  2709. max = plane.normal.x * this.max.x;
  2710. } else {
  2711. min = plane.normal.x * this.max.x;
  2712. max = plane.normal.x * this.min.x;
  2713. }
  2714. if (plane.normal.y > 0) {
  2715. min += plane.normal.y * this.min.y;
  2716. max += plane.normal.y * this.max.y;
  2717. } else {
  2718. min += plane.normal.y * this.max.y;
  2719. max += plane.normal.y * this.min.y;
  2720. }
  2721. if (plane.normal.z > 0) {
  2722. min += plane.normal.z * this.min.z;
  2723. max += plane.normal.z * this.max.z;
  2724. } else {
  2725. min += plane.normal.z * this.max.z;
  2726. max += plane.normal.z * this.min.z;
  2727. }
  2728. return min <= -plane.constant && max >= -plane.constant;
  2729. }
  2730. intersectsTriangle(triangle) {
  2731. if (this.isEmpty()) {
  2732. return false;
  2733. } // compute box center and extents
  2734. this.getCenter(_center);
  2735. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  2736. _v0$2.subVectors(triangle.a, _center);
  2737. _v1$7.subVectors(triangle.b, _center);
  2738. _v2$3.subVectors(triangle.c, _center); // compute edge vectors for triangle
  2739. _f0.subVectors(_v1$7, _v0$2);
  2740. _f1.subVectors(_v2$3, _v1$7);
  2741. _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
  2742. // 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
  2743. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2744. 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];
  2745. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  2746. return false;
  2747. } // test 3 face normals from the aabb
  2748. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  2749. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  2750. return false;
  2751. } // finally testing the face normal of the triangle
  2752. // use already existing triangle edge vectors here
  2753. _triangleNormal.crossVectors(_f0, _f1);
  2754. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  2755. return satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents);
  2756. }
  2757. clampPoint(point, target) {
  2758. return target.copy(point).clamp(this.min, this.max);
  2759. }
  2760. distanceToPoint(point) {
  2761. const clampedPoint = _vector$b.copy(point).clamp(this.min, this.max);
  2762. return clampedPoint.sub(point).length();
  2763. }
  2764. getBoundingSphere(target) {
  2765. this.getCenter(target.center);
  2766. target.radius = this.getSize(_vector$b).length() * 0.5;
  2767. return target;
  2768. }
  2769. intersect(box) {
  2770. this.min.max(box.min);
  2771. 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.
  2772. if (this.isEmpty()) this.makeEmpty();
  2773. return this;
  2774. }
  2775. union(box) {
  2776. this.min.min(box.min);
  2777. this.max.max(box.max);
  2778. return this;
  2779. }
  2780. applyMatrix4(matrix) {
  2781. // transform of empty box is an empty box.
  2782. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2783. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  2784. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  2785. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  2786. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  2787. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  2788. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  2789. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  2790. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  2791. this.setFromPoints(_points);
  2792. return this;
  2793. }
  2794. translate(offset) {
  2795. this.min.add(offset);
  2796. this.max.add(offset);
  2797. return this;
  2798. }
  2799. equals(box) {
  2800. return box.min.equals(this.min) && box.max.equals(this.max);
  2801. }
  2802. }
  2803. Box3.prototype.isBox3 = true;
  2804. 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()];
  2805. const _vector$b = /*@__PURE__*/new Vector3();
  2806. const _box$3 = /*@__PURE__*/new Box3(); // triangle centered vertices
  2807. const _v0$2 = /*@__PURE__*/new Vector3();
  2808. const _v1$7 = /*@__PURE__*/new Vector3();
  2809. const _v2$3 = /*@__PURE__*/new Vector3(); // triangle edge vectors
  2810. const _f0 = /*@__PURE__*/new Vector3();
  2811. const _f1 = /*@__PURE__*/new Vector3();
  2812. const _f2 = /*@__PURE__*/new Vector3();
  2813. const _center = /*@__PURE__*/new Vector3();
  2814. const _extents = /*@__PURE__*/new Vector3();
  2815. const _triangleNormal = /*@__PURE__*/new Vector3();
  2816. const _testAxis = /*@__PURE__*/new Vector3();
  2817. function satForAxes(axes, v0, v1, v2, extents) {
  2818. for (let i = 0, j = axes.length - 3; i <= j; i += 3) {
  2819. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  2820. 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
  2821. const p0 = v0.dot(_testAxis);
  2822. const p1 = v1.dot(_testAxis);
  2823. const p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  2824. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  2825. // points of the projected triangle are outside the projected half-length of the aabb
  2826. // the axis is seperating and we can exit
  2827. return false;
  2828. }
  2829. }
  2830. return true;
  2831. }
  2832. const _box$2 = /*@__PURE__*/new Box3();
  2833. const _v1$6 = /*@__PURE__*/new Vector3();
  2834. const _toFarthestPoint = /*@__PURE__*/new Vector3();
  2835. const _toPoint = /*@__PURE__*/new Vector3();
  2836. class Sphere {
  2837. constructor(center = new Vector3(), radius = -1) {
  2838. this.center = center;
  2839. this.radius = radius;
  2840. }
  2841. set(center, radius) {
  2842. this.center.copy(center);
  2843. this.radius = radius;
  2844. return this;
  2845. }
  2846. setFromPoints(points, optionalCenter) {
  2847. const center = this.center;
  2848. if (optionalCenter !== undefined) {
  2849. center.copy(optionalCenter);
  2850. } else {
  2851. _box$2.setFromPoints(points).getCenter(center);
  2852. }
  2853. let maxRadiusSq = 0;
  2854. for (let i = 0, il = points.length; i < il; i++) {
  2855. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  2856. }
  2857. this.radius = Math.sqrt(maxRadiusSq);
  2858. return this;
  2859. }
  2860. copy(sphere) {
  2861. this.center.copy(sphere.center);
  2862. this.radius = sphere.radius;
  2863. return this;
  2864. }
  2865. isEmpty() {
  2866. return this.radius < 0;
  2867. }
  2868. makeEmpty() {
  2869. this.center.set(0, 0, 0);
  2870. this.radius = -1;
  2871. return this;
  2872. }
  2873. containsPoint(point) {
  2874. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  2875. }
  2876. distanceToPoint(point) {
  2877. return point.distanceTo(this.center) - this.radius;
  2878. }
  2879. intersectsSphere(sphere) {
  2880. const radiusSum = this.radius + sphere.radius;
  2881. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  2882. }
  2883. intersectsBox(box) {
  2884. return box.intersectsSphere(this);
  2885. }
  2886. intersectsPlane(plane) {
  2887. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  2888. }
  2889. clampPoint(point, target) {
  2890. const deltaLengthSq = this.center.distanceToSquared(point);
  2891. target.copy(point);
  2892. if (deltaLengthSq > this.radius * this.radius) {
  2893. target.sub(this.center).normalize();
  2894. target.multiplyScalar(this.radius).add(this.center);
  2895. }
  2896. return target;
  2897. }
  2898. getBoundingBox(target) {
  2899. if (this.isEmpty()) {
  2900. // Empty sphere produces empty bounding box
  2901. target.makeEmpty();
  2902. return target;
  2903. }
  2904. target.set(this.center, this.center);
  2905. target.expandByScalar(this.radius);
  2906. return target;
  2907. }
  2908. applyMatrix4(matrix) {
  2909. this.center.applyMatrix4(matrix);
  2910. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2911. return this;
  2912. }
  2913. translate(offset) {
  2914. this.center.add(offset);
  2915. return this;
  2916. }
  2917. expandByPoint(point) {
  2918. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  2919. _toPoint.subVectors(point, this.center);
  2920. const lengthSq = _toPoint.lengthSq();
  2921. if (lengthSq > this.radius * this.radius) {
  2922. const length = Math.sqrt(lengthSq);
  2923. const missingRadiusHalf = (length - this.radius) * 0.5; // Nudge this sphere towards the target point. Add half the missing distance to radius,
  2924. // and the other half to position. This gives a tighter enclosure, instead of if
  2925. // the whole missing distance were just added to radius.
  2926. this.center.add(_toPoint.multiplyScalar(missingRadiusHalf / length));
  2927. this.radius += missingRadiusHalf;
  2928. }
  2929. return this;
  2930. }
  2931. union(sphere) {
  2932. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  2933. // To enclose another sphere into this sphere, we only need to enclose two points:
  2934. // 1) Enclose the farthest point on the other sphere into this sphere.
  2935. // 2) Enclose the opposite point of the farthest point into this sphere.
  2936. _toFarthestPoint.subVectors(sphere.center, this.center).normalize().multiplyScalar(sphere.radius);
  2937. this.expandByPoint(_v1$6.copy(sphere.center).add(_toFarthestPoint));
  2938. this.expandByPoint(_v1$6.copy(sphere.center).sub(_toFarthestPoint));
  2939. return this;
  2940. }
  2941. equals(sphere) {
  2942. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  2943. }
  2944. clone() {
  2945. return new this.constructor().copy(this);
  2946. }
  2947. }
  2948. const _vector$a = /*@__PURE__*/new Vector3();
  2949. const _segCenter = /*@__PURE__*/new Vector3();
  2950. const _segDir = /*@__PURE__*/new Vector3();
  2951. const _diff = /*@__PURE__*/new Vector3();
  2952. const _edge1 = /*@__PURE__*/new Vector3();
  2953. const _edge2 = /*@__PURE__*/new Vector3();
  2954. const _normal$1 = /*@__PURE__*/new Vector3();
  2955. class Ray {
  2956. constructor(origin = new Vector3(), direction = new Vector3(0, 0, -1)) {
  2957. this.origin = origin;
  2958. this.direction = direction;
  2959. }
  2960. set(origin, direction) {
  2961. this.origin.copy(origin);
  2962. this.direction.copy(direction);
  2963. return this;
  2964. }
  2965. copy(ray) {
  2966. this.origin.copy(ray.origin);
  2967. this.direction.copy(ray.direction);
  2968. return this;
  2969. }
  2970. at(t, target) {
  2971. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  2972. }
  2973. lookAt(v) {
  2974. this.direction.copy(v).sub(this.origin).normalize();
  2975. return this;
  2976. }
  2977. recast(t) {
  2978. this.origin.copy(this.at(t, _vector$a));
  2979. return this;
  2980. }
  2981. closestPointToPoint(point, target) {
  2982. target.subVectors(point, this.origin);
  2983. const directionDistance = target.dot(this.direction);
  2984. if (directionDistance < 0) {
  2985. return target.copy(this.origin);
  2986. }
  2987. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  2988. }
  2989. distanceToPoint(point) {
  2990. return Math.sqrt(this.distanceSqToPoint(point));
  2991. }
  2992. distanceSqToPoint(point) {
  2993. const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  2994. if (directionDistance < 0) {
  2995. return this.origin.distanceToSquared(point);
  2996. }
  2997. _vector$a.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  2998. return _vector$a.distanceToSquared(point);
  2999. }
  3000. distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  3001. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3002. // It returns the min distance between the ray and the segment
  3003. // defined by v0 and v1
  3004. // It can also set two optional targets :
  3005. // - The closest point on the ray
  3006. // - The closest point on the segment
  3007. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  3008. _segDir.copy(v1).sub(v0).normalize();
  3009. _diff.copy(this.origin).sub(_segCenter);
  3010. const segExtent = v0.distanceTo(v1) * 0.5;
  3011. const a01 = -this.direction.dot(_segDir);
  3012. const b0 = _diff.dot(this.direction);
  3013. const b1 = -_diff.dot(_segDir);
  3014. const c = _diff.lengthSq();
  3015. const det = Math.abs(1 - a01 * a01);
  3016. let s0, s1, sqrDist, extDet;
  3017. if (det > 0) {
  3018. // The ray and segment are not parallel.
  3019. s0 = a01 * b1 - b0;
  3020. s1 = a01 * b0 - b1;
  3021. extDet = segExtent * det;
  3022. if (s0 >= 0) {
  3023. if (s1 >= -extDet) {
  3024. if (s1 <= extDet) {
  3025. // region 0
  3026. // Minimum at interior points of ray and segment.
  3027. const invDet = 1 / det;
  3028. s0 *= invDet;
  3029. s1 *= invDet;
  3030. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  3031. } else {
  3032. // region 1
  3033. s1 = segExtent;
  3034. s0 = Math.max(0, -(a01 * s1 + b0));
  3035. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3036. }
  3037. } else {
  3038. // region 5
  3039. s1 = -segExtent;
  3040. s0 = Math.max(0, -(a01 * s1 + b0));
  3041. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3042. }
  3043. } else {
  3044. if (s1 <= -extDet) {
  3045. // region 4
  3046. s0 = Math.max(0, -(-a01 * segExtent + b0));
  3047. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3048. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3049. } else if (s1 <= extDet) {
  3050. // region 3
  3051. s0 = 0;
  3052. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  3053. sqrDist = s1 * (s1 + 2 * b1) + c;
  3054. } else {
  3055. // region 2
  3056. s0 = Math.max(0, -(a01 * segExtent + b0));
  3057. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3058. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3059. }
  3060. }
  3061. } else {
  3062. // Ray and segment are parallel.
  3063. s1 = a01 > 0 ? -segExtent : segExtent;
  3064. s0 = Math.max(0, -(a01 * s1 + b0));
  3065. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3066. }
  3067. if (optionalPointOnRay) {
  3068. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  3069. }
  3070. if (optionalPointOnSegment) {
  3071. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  3072. }
  3073. return sqrDist;
  3074. }
  3075. intersectSphere(sphere, target) {
  3076. _vector$a.subVectors(sphere.center, this.origin);
  3077. const tca = _vector$a.dot(this.direction);
  3078. const d2 = _vector$a.dot(_vector$a) - tca * tca;
  3079. const radius2 = sphere.radius * sphere.radius;
  3080. if (d2 > radius2) return null;
  3081. const thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  3082. const t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  3083. const t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  3084. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  3085. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3086. // in order to always return an intersect point that is in front of the ray.
  3087. 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
  3088. return this.at(t0, target);
  3089. }
  3090. intersectsSphere(sphere) {
  3091. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  3092. }
  3093. distanceToPlane(plane) {
  3094. const denominator = plane.normal.dot(this.direction);
  3095. if (denominator === 0) {
  3096. // line is coplanar, return origin
  3097. if (plane.distanceToPoint(this.origin) === 0) {
  3098. return 0;
  3099. } // Null is preferable to undefined since undefined means.... it is undefined
  3100. return null;
  3101. }
  3102. const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  3103. return t >= 0 ? t : null;
  3104. }
  3105. intersectPlane(plane, target) {
  3106. const t = this.distanceToPlane(plane);
  3107. if (t === null) {
  3108. return null;
  3109. }
  3110. return this.at(t, target);
  3111. }
  3112. intersectsPlane(plane) {
  3113. // check if the ray lies on the plane first
  3114. const distToPoint = plane.distanceToPoint(this.origin);
  3115. if (distToPoint === 0) {
  3116. return true;
  3117. }
  3118. const denominator = plane.normal.dot(this.direction);
  3119. if (denominator * distToPoint < 0) {
  3120. return true;
  3121. } // ray origin is behind the plane (and is pointing behind it)
  3122. return false;
  3123. }
  3124. intersectBox(box, target) {
  3125. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3126. const invdirx = 1 / this.direction.x,
  3127. invdiry = 1 / this.direction.y,
  3128. invdirz = 1 / this.direction.z;
  3129. const origin = this.origin;
  3130. if (invdirx >= 0) {
  3131. tmin = (box.min.x - origin.x) * invdirx;
  3132. tmax = (box.max.x - origin.x) * invdirx;
  3133. } else {
  3134. tmin = (box.max.x - origin.x) * invdirx;
  3135. tmax = (box.min.x - origin.x) * invdirx;
  3136. }
  3137. if (invdiry >= 0) {
  3138. tymin = (box.min.y - origin.y) * invdiry;
  3139. tymax = (box.max.y - origin.y) * invdiry;
  3140. } else {
  3141. tymin = (box.max.y - origin.y) * invdiry;
  3142. tymax = (box.min.y - origin.y) * invdiry;
  3143. }
  3144. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  3145. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3146. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  3147. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  3148. if (invdirz >= 0) {
  3149. tzmin = (box.min.z - origin.z) * invdirz;
  3150. tzmax = (box.max.z - origin.z) * invdirz;
  3151. } else {
  3152. tzmin = (box.max.z - origin.z) * invdirz;
  3153. tzmax = (box.min.z - origin.z) * invdirz;
  3154. }
  3155. if (tmin > tzmax || tzmin > tmax) return null;
  3156. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  3157. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  3158. if (tmax < 0) return null;
  3159. return this.at(tmin >= 0 ? tmin : tmax, target);
  3160. }
  3161. intersectsBox(box) {
  3162. return this.intersectBox(box, _vector$a) !== null;
  3163. }
  3164. intersectTriangle(a, b, c, backfaceCulling, target) {
  3165. // Compute the offset origin, edges, and normal.
  3166. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3167. _edge1.subVectors(b, a);
  3168. _edge2.subVectors(c, a);
  3169. _normal$1.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3170. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3171. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3172. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3173. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3174. let DdN = this.direction.dot(_normal$1);
  3175. let sign;
  3176. if (DdN > 0) {
  3177. if (backfaceCulling) return null;
  3178. sign = 1;
  3179. } else if (DdN < 0) {
  3180. sign = -1;
  3181. DdN = -DdN;
  3182. } else {
  3183. return null;
  3184. }
  3185. _diff.subVectors(this.origin, a);
  3186. const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  3187. if (DdQxE2 < 0) {
  3188. return null;
  3189. }
  3190. const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  3191. if (DdE1xQ < 0) {
  3192. return null;
  3193. } // b1+b2 > 1, no intersection
  3194. if (DdQxE2 + DdE1xQ > DdN) {
  3195. return null;
  3196. } // Line intersects triangle, check if ray does.
  3197. const QdN = -sign * _diff.dot(_normal$1); // t < 0, no intersection
  3198. if (QdN < 0) {
  3199. return null;
  3200. } // Ray intersects triangle.
  3201. return this.at(QdN / DdN, target);
  3202. }
  3203. applyMatrix4(matrix4) {
  3204. this.origin.applyMatrix4(matrix4);
  3205. this.direction.transformDirection(matrix4);
  3206. return this;
  3207. }
  3208. equals(ray) {
  3209. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  3210. }
  3211. clone() {
  3212. return new this.constructor().copy(this);
  3213. }
  3214. }
  3215. class Matrix4 {
  3216. constructor() {
  3217. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  3218. if (arguments.length > 0) {
  3219. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  3220. }
  3221. }
  3222. set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  3223. const te = this.elements;
  3224. te[0] = n11;
  3225. te[4] = n12;
  3226. te[8] = n13;
  3227. te[12] = n14;
  3228. te[1] = n21;
  3229. te[5] = n22;
  3230. te[9] = n23;
  3231. te[13] = n24;
  3232. te[2] = n31;
  3233. te[6] = n32;
  3234. te[10] = n33;
  3235. te[14] = n34;
  3236. te[3] = n41;
  3237. te[7] = n42;
  3238. te[11] = n43;
  3239. te[15] = n44;
  3240. return this;
  3241. }
  3242. identity() {
  3243. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3244. return this;
  3245. }
  3246. clone() {
  3247. return new Matrix4().fromArray(this.elements);
  3248. }
  3249. copy(m) {
  3250. const te = this.elements;
  3251. const me = m.elements;
  3252. te[0] = me[0];
  3253. te[1] = me[1];
  3254. te[2] = me[2];
  3255. te[3] = me[3];
  3256. te[4] = me[4];
  3257. te[5] = me[5];
  3258. te[6] = me[6];
  3259. te[7] = me[7];
  3260. te[8] = me[8];
  3261. te[9] = me[9];
  3262. te[10] = me[10];
  3263. te[11] = me[11];
  3264. te[12] = me[12];
  3265. te[13] = me[13];
  3266. te[14] = me[14];
  3267. te[15] = me[15];
  3268. return this;
  3269. }
  3270. copyPosition(m) {
  3271. const te = this.elements,
  3272. me = m.elements;
  3273. te[12] = me[12];
  3274. te[13] = me[13];
  3275. te[14] = me[14];
  3276. return this;
  3277. }
  3278. setFromMatrix3(m) {
  3279. const me = m.elements;
  3280. 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);
  3281. return this;
  3282. }
  3283. extractBasis(xAxis, yAxis, zAxis) {
  3284. xAxis.setFromMatrixColumn(this, 0);
  3285. yAxis.setFromMatrixColumn(this, 1);
  3286. zAxis.setFromMatrixColumn(this, 2);
  3287. return this;
  3288. }
  3289. makeBasis(xAxis, yAxis, zAxis) {
  3290. 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);
  3291. return this;
  3292. }
  3293. extractRotation(m) {
  3294. // this method does not support reflection matrices
  3295. const te = this.elements;
  3296. const me = m.elements;
  3297. const scaleX = 1 / _v1$5.setFromMatrixColumn(m, 0).length();
  3298. const scaleY = 1 / _v1$5.setFromMatrixColumn(m, 1).length();
  3299. const scaleZ = 1 / _v1$5.setFromMatrixColumn(m, 2).length();
  3300. te[0] = me[0] * scaleX;
  3301. te[1] = me[1] * scaleX;
  3302. te[2] = me[2] * scaleX;
  3303. te[3] = 0;
  3304. te[4] = me[4] * scaleY;
  3305. te[5] = me[5] * scaleY;
  3306. te[6] = me[6] * scaleY;
  3307. te[7] = 0;
  3308. te[8] = me[8] * scaleZ;
  3309. te[9] = me[9] * scaleZ;
  3310. te[10] = me[10] * scaleZ;
  3311. te[11] = 0;
  3312. te[12] = 0;
  3313. te[13] = 0;
  3314. te[14] = 0;
  3315. te[15] = 1;
  3316. return this;
  3317. }
  3318. makeRotationFromEuler(euler) {
  3319. if (!(euler && euler.isEuler)) {
  3320. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  3321. }
  3322. const te = this.elements;
  3323. const x = euler.x,
  3324. y = euler.y,
  3325. z = euler.z;
  3326. const a = Math.cos(x),
  3327. b = Math.sin(x);
  3328. const c = Math.cos(y),
  3329. d = Math.sin(y);
  3330. const e = Math.cos(z),
  3331. f = Math.sin(z);
  3332. if (euler.order === 'XYZ') {
  3333. const ae = a * e,
  3334. af = a * f,
  3335. be = b * e,
  3336. bf = b * f;
  3337. te[0] = c * e;
  3338. te[4] = -c * f;
  3339. te[8] = d;
  3340. te[1] = af + be * d;
  3341. te[5] = ae - bf * d;
  3342. te[9] = -b * c;
  3343. te[2] = bf - ae * d;
  3344. te[6] = be + af * d;
  3345. te[10] = a * c;
  3346. } else if (euler.order === 'YXZ') {
  3347. const ce = c * e,
  3348. cf = c * f,
  3349. de = d * e,
  3350. df = d * f;
  3351. te[0] = ce + df * b;
  3352. te[4] = de * b - cf;
  3353. te[8] = a * d;
  3354. te[1] = a * f;
  3355. te[5] = a * e;
  3356. te[9] = -b;
  3357. te[2] = cf * b - de;
  3358. te[6] = df + ce * b;
  3359. te[10] = a * c;
  3360. } else if (euler.order === 'ZXY') {
  3361. const ce = c * e,
  3362. cf = c * f,
  3363. de = d * e,
  3364. df = d * f;
  3365. te[0] = ce - df * b;
  3366. te[4] = -a * f;
  3367. te[8] = de + cf * b;
  3368. te[1] = cf + de * b;
  3369. te[5] = a * e;
  3370. te[9] = df - ce * b;
  3371. te[2] = -a * d;
  3372. te[6] = b;
  3373. te[10] = a * c;
  3374. } else if (euler.order === 'ZYX') {
  3375. const ae = a * e,
  3376. af = a * f,
  3377. be = b * e,
  3378. bf = b * f;
  3379. te[0] = c * e;
  3380. te[4] = be * d - af;
  3381. te[8] = ae * d + bf;
  3382. te[1] = c * f;
  3383. te[5] = bf * d + ae;
  3384. te[9] = af * d - be;
  3385. te[2] = -d;
  3386. te[6] = b * c;
  3387. te[10] = a * c;
  3388. } else if (euler.order === 'YZX') {
  3389. const ac = a * c,
  3390. ad = a * d,
  3391. bc = b * c,
  3392. bd = b * d;
  3393. te[0] = c * e;
  3394. te[4] = bd - ac * f;
  3395. te[8] = bc * f + ad;
  3396. te[1] = f;
  3397. te[5] = a * e;
  3398. te[9] = -b * e;
  3399. te[2] = -d * e;
  3400. te[6] = ad * f + bc;
  3401. te[10] = ac - bd * f;
  3402. } else if (euler.order === 'XZY') {
  3403. const ac = a * c,
  3404. ad = a * d,
  3405. bc = b * c,
  3406. bd = b * d;
  3407. te[0] = c * e;
  3408. te[4] = -f;
  3409. te[8] = d * e;
  3410. te[1] = ac * f + bd;
  3411. te[5] = a * e;
  3412. te[9] = ad * f - bc;
  3413. te[2] = bc * f - ad;
  3414. te[6] = b * e;
  3415. te[10] = bd * f + ac;
  3416. } // bottom row
  3417. te[3] = 0;
  3418. te[7] = 0;
  3419. te[11] = 0; // last column
  3420. te[12] = 0;
  3421. te[13] = 0;
  3422. te[14] = 0;
  3423. te[15] = 1;
  3424. return this;
  3425. }
  3426. makeRotationFromQuaternion(q) {
  3427. return this.compose(_zero, q, _one);
  3428. }
  3429. lookAt(eye, target, up) {
  3430. const te = this.elements;
  3431. _z.subVectors(eye, target);
  3432. if (_z.lengthSq() === 0) {
  3433. // eye and target are in the same position
  3434. _z.z = 1;
  3435. }
  3436. _z.normalize();
  3437. _x.crossVectors(up, _z);
  3438. if (_x.lengthSq() === 0) {
  3439. // up and z are parallel
  3440. if (Math.abs(up.z) === 1) {
  3441. _z.x += 0.0001;
  3442. } else {
  3443. _z.z += 0.0001;
  3444. }
  3445. _z.normalize();
  3446. _x.crossVectors(up, _z);
  3447. }
  3448. _x.normalize();
  3449. _y.crossVectors(_z, _x);
  3450. te[0] = _x.x;
  3451. te[4] = _y.x;
  3452. te[8] = _z.x;
  3453. te[1] = _x.y;
  3454. te[5] = _y.y;
  3455. te[9] = _z.y;
  3456. te[2] = _x.z;
  3457. te[6] = _y.z;
  3458. te[10] = _z.z;
  3459. return this;
  3460. }
  3461. multiply(m, n) {
  3462. if (n !== undefined) {
  3463. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  3464. return this.multiplyMatrices(m, n);
  3465. }
  3466. return this.multiplyMatrices(this, m);
  3467. }
  3468. premultiply(m) {
  3469. return this.multiplyMatrices(m, this);
  3470. }
  3471. multiplyMatrices(a, b) {
  3472. const ae = a.elements;
  3473. const be = b.elements;
  3474. const te = this.elements;
  3475. const a11 = ae[0],
  3476. a12 = ae[4],
  3477. a13 = ae[8],
  3478. a14 = ae[12];
  3479. const a21 = ae[1],
  3480. a22 = ae[5],
  3481. a23 = ae[9],
  3482. a24 = ae[13];
  3483. const a31 = ae[2],
  3484. a32 = ae[6],
  3485. a33 = ae[10],
  3486. a34 = ae[14];
  3487. const a41 = ae[3],
  3488. a42 = ae[7],
  3489. a43 = ae[11],
  3490. a44 = ae[15];
  3491. const b11 = be[0],
  3492. b12 = be[4],
  3493. b13 = be[8],
  3494. b14 = be[12];
  3495. const b21 = be[1],
  3496. b22 = be[5],
  3497. b23 = be[9],
  3498. b24 = be[13];
  3499. const b31 = be[2],
  3500. b32 = be[6],
  3501. b33 = be[10],
  3502. b34 = be[14];
  3503. const b41 = be[3],
  3504. b42 = be[7],
  3505. b43 = be[11],
  3506. b44 = be[15];
  3507. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3508. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3509. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3510. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3511. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3512. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3513. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3514. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3515. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3516. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3517. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3518. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3519. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3520. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3521. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3522. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3523. return this;
  3524. }
  3525. multiplyScalar(s) {
  3526. const te = this.elements;
  3527. te[0] *= s;
  3528. te[4] *= s;
  3529. te[8] *= s;
  3530. te[12] *= s;
  3531. te[1] *= s;
  3532. te[5] *= s;
  3533. te[9] *= s;
  3534. te[13] *= s;
  3535. te[2] *= s;
  3536. te[6] *= s;
  3537. te[10] *= s;
  3538. te[14] *= s;
  3539. te[3] *= s;
  3540. te[7] *= s;
  3541. te[11] *= s;
  3542. te[15] *= s;
  3543. return this;
  3544. }
  3545. determinant() {
  3546. const te = this.elements;
  3547. const n11 = te[0],
  3548. n12 = te[4],
  3549. n13 = te[8],
  3550. n14 = te[12];
  3551. const n21 = te[1],
  3552. n22 = te[5],
  3553. n23 = te[9],
  3554. n24 = te[13];
  3555. const n31 = te[2],
  3556. n32 = te[6],
  3557. n33 = te[10],
  3558. n34 = te[14];
  3559. const n41 = te[3],
  3560. n42 = te[7],
  3561. n43 = te[11],
  3562. n44 = te[15]; //TODO: make this more efficient
  3563. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3564. 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);
  3565. }
  3566. transpose() {
  3567. const te = this.elements;
  3568. let tmp;
  3569. tmp = te[1];
  3570. te[1] = te[4];
  3571. te[4] = tmp;
  3572. tmp = te[2];
  3573. te[2] = te[8];
  3574. te[8] = tmp;
  3575. tmp = te[6];
  3576. te[6] = te[9];
  3577. te[9] = tmp;
  3578. tmp = te[3];
  3579. te[3] = te[12];
  3580. te[12] = tmp;
  3581. tmp = te[7];
  3582. te[7] = te[13];
  3583. te[13] = tmp;
  3584. tmp = te[11];
  3585. te[11] = te[14];
  3586. te[14] = tmp;
  3587. return this;
  3588. }
  3589. setPosition(x, y, z) {
  3590. const te = this.elements;
  3591. if (x.isVector3) {
  3592. te[12] = x.x;
  3593. te[13] = x.y;
  3594. te[14] = x.z;
  3595. } else {
  3596. te[12] = x;
  3597. te[13] = y;
  3598. te[14] = z;
  3599. }
  3600. return this;
  3601. }
  3602. invert() {
  3603. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3604. const te = this.elements,
  3605. n11 = te[0],
  3606. n21 = te[1],
  3607. n31 = te[2],
  3608. n41 = te[3],
  3609. n12 = te[4],
  3610. n22 = te[5],
  3611. n32 = te[6],
  3612. n42 = te[7],
  3613. n13 = te[8],
  3614. n23 = te[9],
  3615. n33 = te[10],
  3616. n43 = te[11],
  3617. n14 = te[12],
  3618. n24 = te[13],
  3619. n34 = te[14],
  3620. n44 = te[15],
  3621. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3622. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3623. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3624. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3625. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3626. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  3627. const detInv = 1 / det;
  3628. te[0] = t11 * detInv;
  3629. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  3630. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  3631. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  3632. te[4] = t12 * detInv;
  3633. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  3634. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  3635. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  3636. te[8] = t13 * detInv;
  3637. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  3638. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  3639. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  3640. te[12] = t14 * detInv;
  3641. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  3642. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  3643. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  3644. return this;
  3645. }
  3646. scale(v) {
  3647. const te = this.elements;
  3648. const x = v.x,
  3649. y = v.y,
  3650. z = v.z;
  3651. te[0] *= x;
  3652. te[4] *= y;
  3653. te[8] *= z;
  3654. te[1] *= x;
  3655. te[5] *= y;
  3656. te[9] *= z;
  3657. te[2] *= x;
  3658. te[6] *= y;
  3659. te[10] *= z;
  3660. te[3] *= x;
  3661. te[7] *= y;
  3662. te[11] *= z;
  3663. return this;
  3664. }
  3665. getMaxScaleOnAxis() {
  3666. const te = this.elements;
  3667. const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  3668. const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  3669. const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  3670. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  3671. }
  3672. makeTranslation(x, y, z) {
  3673. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  3674. return this;
  3675. }
  3676. makeRotationX(theta) {
  3677. const c = Math.cos(theta),
  3678. s = Math.sin(theta);
  3679. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  3680. return this;
  3681. }
  3682. makeRotationY(theta) {
  3683. const c = Math.cos(theta),
  3684. s = Math.sin(theta);
  3685. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  3686. return this;
  3687. }
  3688. makeRotationZ(theta) {
  3689. const c = Math.cos(theta),
  3690. s = Math.sin(theta);
  3691. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3692. return this;
  3693. }
  3694. makeRotationAxis(axis, angle) {
  3695. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3696. const c = Math.cos(angle);
  3697. const s = Math.sin(angle);
  3698. const t = 1 - c;
  3699. const x = axis.x,
  3700. y = axis.y,
  3701. z = axis.z;
  3702. const tx = t * x,
  3703. ty = t * y;
  3704. 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);
  3705. return this;
  3706. }
  3707. makeScale(x, y, z) {
  3708. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  3709. return this;
  3710. }
  3711. makeShear(xy, xz, yx, yz, zx, zy) {
  3712. this.set(1, yx, zx, 0, xy, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1);
  3713. return this;
  3714. }
  3715. compose(position, quaternion, scale) {
  3716. const te = this.elements;
  3717. const x = quaternion._x,
  3718. y = quaternion._y,
  3719. z = quaternion._z,
  3720. w = quaternion._w;
  3721. const x2 = x + x,
  3722. y2 = y + y,
  3723. z2 = z + z;
  3724. const xx = x * x2,
  3725. xy = x * y2,
  3726. xz = x * z2;
  3727. const yy = y * y2,
  3728. yz = y * z2,
  3729. zz = z * z2;
  3730. const wx = w * x2,
  3731. wy = w * y2,
  3732. wz = w * z2;
  3733. const sx = scale.x,
  3734. sy = scale.y,
  3735. sz = scale.z;
  3736. te[0] = (1 - (yy + zz)) * sx;
  3737. te[1] = (xy + wz) * sx;
  3738. te[2] = (xz - wy) * sx;
  3739. te[3] = 0;
  3740. te[4] = (xy - wz) * sy;
  3741. te[5] = (1 - (xx + zz)) * sy;
  3742. te[6] = (yz + wx) * sy;
  3743. te[7] = 0;
  3744. te[8] = (xz + wy) * sz;
  3745. te[9] = (yz - wx) * sz;
  3746. te[10] = (1 - (xx + yy)) * sz;
  3747. te[11] = 0;
  3748. te[12] = position.x;
  3749. te[13] = position.y;
  3750. te[14] = position.z;
  3751. te[15] = 1;
  3752. return this;
  3753. }
  3754. decompose(position, quaternion, scale) {
  3755. const te = this.elements;
  3756. let sx = _v1$5.set(te[0], te[1], te[2]).length();
  3757. const sy = _v1$5.set(te[4], te[5], te[6]).length();
  3758. const sz = _v1$5.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  3759. const det = this.determinant();
  3760. if (det < 0) sx = -sx;
  3761. position.x = te[12];
  3762. position.y = te[13];
  3763. position.z = te[14]; // scale the rotation part
  3764. _m1$2.copy(this);
  3765. const invSX = 1 / sx;
  3766. const invSY = 1 / sy;
  3767. const invSZ = 1 / sz;
  3768. _m1$2.elements[0] *= invSX;
  3769. _m1$2.elements[1] *= invSX;
  3770. _m1$2.elements[2] *= invSX;
  3771. _m1$2.elements[4] *= invSY;
  3772. _m1$2.elements[5] *= invSY;
  3773. _m1$2.elements[6] *= invSY;
  3774. _m1$2.elements[8] *= invSZ;
  3775. _m1$2.elements[9] *= invSZ;
  3776. _m1$2.elements[10] *= invSZ;
  3777. quaternion.setFromRotationMatrix(_m1$2);
  3778. scale.x = sx;
  3779. scale.y = sy;
  3780. scale.z = sz;
  3781. return this;
  3782. }
  3783. makePerspective(left, right, top, bottom, near, far) {
  3784. if (far === undefined) {
  3785. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  3786. }
  3787. const te = this.elements;
  3788. const x = 2 * near / (right - left);
  3789. const y = 2 * near / (top - bottom);
  3790. const a = (right + left) / (right - left);
  3791. const b = (top + bottom) / (top - bottom);
  3792. const c = -(far + near) / (far - near);
  3793. const d = -2 * far * near / (far - near);
  3794. te[0] = x;
  3795. te[4] = 0;
  3796. te[8] = a;
  3797. te[12] = 0;
  3798. te[1] = 0;
  3799. te[5] = y;
  3800. te[9] = b;
  3801. te[13] = 0;
  3802. te[2] = 0;
  3803. te[6] = 0;
  3804. te[10] = c;
  3805. te[14] = d;
  3806. te[3] = 0;
  3807. te[7] = 0;
  3808. te[11] = -1;
  3809. te[15] = 0;
  3810. return this;
  3811. }
  3812. makeOrthographic(left, right, top, bottom, near, far) {
  3813. const te = this.elements;
  3814. const w = 1.0 / (right - left);
  3815. const h = 1.0 / (top - bottom);
  3816. const p = 1.0 / (far - near);
  3817. const x = (right + left) * w;
  3818. const y = (top + bottom) * h;
  3819. const z = (far + near) * p;
  3820. te[0] = 2 * w;
  3821. te[4] = 0;
  3822. te[8] = 0;
  3823. te[12] = -x;
  3824. te[1] = 0;
  3825. te[5] = 2 * h;
  3826. te[9] = 0;
  3827. te[13] = -y;
  3828. te[2] = 0;
  3829. te[6] = 0;
  3830. te[10] = -2 * p;
  3831. te[14] = -z;
  3832. te[3] = 0;
  3833. te[7] = 0;
  3834. te[11] = 0;
  3835. te[15] = 1;
  3836. return this;
  3837. }
  3838. equals(matrix) {
  3839. const te = this.elements;
  3840. const me = matrix.elements;
  3841. for (let i = 0; i < 16; i++) {
  3842. if (te[i] !== me[i]) return false;
  3843. }
  3844. return true;
  3845. }
  3846. fromArray(array, offset = 0) {
  3847. for (let i = 0; i < 16; i++) {
  3848. this.elements[i] = array[i + offset];
  3849. }
  3850. return this;
  3851. }
  3852. toArray(array = [], offset = 0) {
  3853. const te = this.elements;
  3854. array[offset] = te[0];
  3855. array[offset + 1] = te[1];
  3856. array[offset + 2] = te[2];
  3857. array[offset + 3] = te[3];
  3858. array[offset + 4] = te[4];
  3859. array[offset + 5] = te[5];
  3860. array[offset + 6] = te[6];
  3861. array[offset + 7] = te[7];
  3862. array[offset + 8] = te[8];
  3863. array[offset + 9] = te[9];
  3864. array[offset + 10] = te[10];
  3865. array[offset + 11] = te[11];
  3866. array[offset + 12] = te[12];
  3867. array[offset + 13] = te[13];
  3868. array[offset + 14] = te[14];
  3869. array[offset + 15] = te[15];
  3870. return array;
  3871. }
  3872. }
  3873. Matrix4.prototype.isMatrix4 = true;
  3874. const _v1$5 = /*@__PURE__*/new Vector3();
  3875. const _m1$2 = /*@__PURE__*/new Matrix4();
  3876. const _zero = /*@__PURE__*/new Vector3(0, 0, 0);
  3877. const _one = /*@__PURE__*/new Vector3(1, 1, 1);
  3878. const _x = /*@__PURE__*/new Vector3();
  3879. const _y = /*@__PURE__*/new Vector3();
  3880. const _z = /*@__PURE__*/new Vector3();
  3881. const _matrix$1 = /*@__PURE__*/new Matrix4();
  3882. const _quaternion$3 = /*@__PURE__*/new Quaternion();
  3883. class Euler {
  3884. constructor(x = 0, y = 0, z = 0, order = Euler.DefaultOrder) {
  3885. this._x = x;
  3886. this._y = y;
  3887. this._z = z;
  3888. this._order = order;
  3889. }
  3890. get x() {
  3891. return this._x;
  3892. }
  3893. set x(value) {
  3894. this._x = value;
  3895. this._onChangeCallback();
  3896. }
  3897. get y() {
  3898. return this._y;
  3899. }
  3900. set y(value) {
  3901. this._y = value;
  3902. this._onChangeCallback();
  3903. }
  3904. get z() {
  3905. return this._z;
  3906. }
  3907. set z(value) {
  3908. this._z = value;
  3909. this._onChangeCallback();
  3910. }
  3911. get order() {
  3912. return this._order;
  3913. }
  3914. set order(value) {
  3915. this._order = value;
  3916. this._onChangeCallback();
  3917. }
  3918. set(x, y, z, order = this._order) {
  3919. this._x = x;
  3920. this._y = y;
  3921. this._z = z;
  3922. this._order = order;
  3923. this._onChangeCallback();
  3924. return this;
  3925. }
  3926. clone() {
  3927. return new this.constructor(this._x, this._y, this._z, this._order);
  3928. }
  3929. copy(euler) {
  3930. this._x = euler._x;
  3931. this._y = euler._y;
  3932. this._z = euler._z;
  3933. this._order = euler._order;
  3934. this._onChangeCallback();
  3935. return this;
  3936. }
  3937. setFromRotationMatrix(m, order = this._order, update = true) {
  3938. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3939. const te = m.elements;
  3940. const m11 = te[0],
  3941. m12 = te[4],
  3942. m13 = te[8];
  3943. const m21 = te[1],
  3944. m22 = te[5],
  3945. m23 = te[9];
  3946. const m31 = te[2],
  3947. m32 = te[6],
  3948. m33 = te[10];
  3949. switch (order) {
  3950. case 'XYZ':
  3951. this._y = Math.asin(clamp(m13, -1, 1));
  3952. if (Math.abs(m13) < 0.9999999) {
  3953. this._x = Math.atan2(-m23, m33);
  3954. this._z = Math.atan2(-m12, m11);
  3955. } else {
  3956. this._x = Math.atan2(m32, m22);
  3957. this._z = 0;
  3958. }
  3959. break;
  3960. case 'YXZ':
  3961. this._x = Math.asin(-clamp(m23, -1, 1));
  3962. if (Math.abs(m23) < 0.9999999) {
  3963. this._y = Math.atan2(m13, m33);
  3964. this._z = Math.atan2(m21, m22);
  3965. } else {
  3966. this._y = Math.atan2(-m31, m11);
  3967. this._z = 0;
  3968. }
  3969. break;
  3970. case 'ZXY':
  3971. this._x = Math.asin(clamp(m32, -1, 1));
  3972. if (Math.abs(m32) < 0.9999999) {
  3973. this._y = Math.atan2(-m31, m33);
  3974. this._z = Math.atan2(-m12, m22);
  3975. } else {
  3976. this._y = 0;
  3977. this._z = Math.atan2(m21, m11);
  3978. }
  3979. break;
  3980. case 'ZYX':
  3981. this._y = Math.asin(-clamp(m31, -1, 1));
  3982. if (Math.abs(m31) < 0.9999999) {
  3983. this._x = Math.atan2(m32, m33);
  3984. this._z = Math.atan2(m21, m11);
  3985. } else {
  3986. this._x = 0;
  3987. this._z = Math.atan2(-m12, m22);
  3988. }
  3989. break;
  3990. case 'YZX':
  3991. this._z = Math.asin(clamp(m21, -1, 1));
  3992. if (Math.abs(m21) < 0.9999999) {
  3993. this._x = Math.atan2(-m23, m22);
  3994. this._y = Math.atan2(-m31, m11);
  3995. } else {
  3996. this._x = 0;
  3997. this._y = Math.atan2(m13, m33);
  3998. }
  3999. break;
  4000. case 'XZY':
  4001. this._z = Math.asin(-clamp(m12, -1, 1));
  4002. if (Math.abs(m12) < 0.9999999) {
  4003. this._x = Math.atan2(m32, m22);
  4004. this._y = Math.atan2(m13, m11);
  4005. } else {
  4006. this._x = Math.atan2(-m23, m33);
  4007. this._y = 0;
  4008. }
  4009. break;
  4010. default:
  4011. console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
  4012. }
  4013. this._order = order;
  4014. if (update === true) this._onChangeCallback();
  4015. return this;
  4016. }
  4017. setFromQuaternion(q, order, update) {
  4018. _matrix$1.makeRotationFromQuaternion(q);
  4019. return this.setFromRotationMatrix(_matrix$1, order, update);
  4020. }
  4021. setFromVector3(v, order = this._order) {
  4022. return this.set(v.x, v.y, v.z, order);
  4023. }
  4024. reorder(newOrder) {
  4025. // WARNING: this discards revolution information -bhouston
  4026. _quaternion$3.setFromEuler(this);
  4027. return this.setFromQuaternion(_quaternion$3, newOrder);
  4028. }
  4029. equals(euler) {
  4030. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4031. }
  4032. fromArray(array) {
  4033. this._x = array[0];
  4034. this._y = array[1];
  4035. this._z = array[2];
  4036. if (array[3] !== undefined) this._order = array[3];
  4037. this._onChangeCallback();
  4038. return this;
  4039. }
  4040. toArray(array = [], offset = 0) {
  4041. array[offset] = this._x;
  4042. array[offset + 1] = this._y;
  4043. array[offset + 2] = this._z;
  4044. array[offset + 3] = this._order;
  4045. return array;
  4046. }
  4047. toVector3(optionalResult) {
  4048. if (optionalResult) {
  4049. return optionalResult.set(this._x, this._y, this._z);
  4050. } else {
  4051. return new Vector3(this._x, this._y, this._z);
  4052. }
  4053. }
  4054. _onChange(callback) {
  4055. this._onChangeCallback = callback;
  4056. return this;
  4057. }
  4058. _onChangeCallback() {}
  4059. }
  4060. Euler.prototype.isEuler = true;
  4061. Euler.DefaultOrder = 'XYZ';
  4062. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4063. class Layers {
  4064. constructor() {
  4065. this.mask = 1 | 0;
  4066. }
  4067. set(channel) {
  4068. this.mask = 1 << channel | 0;
  4069. }
  4070. enable(channel) {
  4071. this.mask |= 1 << channel | 0;
  4072. }
  4073. enableAll() {
  4074. this.mask = 0xffffffff | 0;
  4075. }
  4076. toggle(channel) {
  4077. this.mask ^= 1 << channel | 0;
  4078. }
  4079. disable(channel) {
  4080. this.mask &= ~(1 << channel | 0);
  4081. }
  4082. disableAll() {
  4083. this.mask = 0;
  4084. }
  4085. test(layers) {
  4086. return (this.mask & layers.mask) !== 0;
  4087. }
  4088. }
  4089. let _object3DId = 0;
  4090. const _v1$4 = /*@__PURE__*/new Vector3();
  4091. const _q1 = /*@__PURE__*/new Quaternion();
  4092. const _m1$1 = /*@__PURE__*/new Matrix4();
  4093. const _target = /*@__PURE__*/new Vector3();
  4094. const _position$3 = /*@__PURE__*/new Vector3();
  4095. const _scale$2 = /*@__PURE__*/new Vector3();
  4096. const _quaternion$2 = /*@__PURE__*/new Quaternion();
  4097. const _xAxis = /*@__PURE__*/new Vector3(1, 0, 0);
  4098. const _yAxis = /*@__PURE__*/new Vector3(0, 1, 0);
  4099. const _zAxis = /*@__PURE__*/new Vector3(0, 0, 1);
  4100. const _addedEvent = {
  4101. type: 'added'
  4102. };
  4103. const _removedEvent = {
  4104. type: 'removed'
  4105. };
  4106. class Object3D extends EventDispatcher {
  4107. constructor() {
  4108. super();
  4109. Object.defineProperty(this, 'id', {
  4110. value: _object3DId++
  4111. });
  4112. this.uuid = generateUUID();
  4113. this.name = '';
  4114. this.type = 'Object3D';
  4115. this.parent = null;
  4116. this.children = [];
  4117. this.up = Object3D.DefaultUp.clone();
  4118. const position = new Vector3();
  4119. const rotation = new Euler();
  4120. const quaternion = new Quaternion();
  4121. const scale = new Vector3(1, 1, 1);
  4122. function onRotationChange() {
  4123. quaternion.setFromEuler(rotation, false);
  4124. }
  4125. function onQuaternionChange() {
  4126. rotation.setFromQuaternion(quaternion, undefined, false);
  4127. }
  4128. rotation._onChange(onRotationChange);
  4129. quaternion._onChange(onQuaternionChange);
  4130. Object.defineProperties(this, {
  4131. position: {
  4132. configurable: true,
  4133. enumerable: true,
  4134. value: position
  4135. },
  4136. rotation: {
  4137. configurable: true,
  4138. enumerable: true,
  4139. value: rotation
  4140. },
  4141. quaternion: {
  4142. configurable: true,
  4143. enumerable: true,
  4144. value: quaternion
  4145. },
  4146. scale: {
  4147. configurable: true,
  4148. enumerable: true,
  4149. value: scale
  4150. },
  4151. modelViewMatrix: {
  4152. value: new Matrix4()
  4153. },
  4154. normalMatrix: {
  4155. value: new Matrix3()
  4156. }
  4157. });
  4158. this.matrix = new Matrix4();
  4159. this.matrixWorld = new Matrix4();
  4160. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4161. this.matrixWorldNeedsUpdate = false;
  4162. this.layers = new Layers();
  4163. this.visible = true;
  4164. this.castShadow = false;
  4165. this.receiveShadow = false;
  4166. this.frustumCulled = true;
  4167. this.renderOrder = 0;
  4168. this.animations = [];
  4169. this.userData = {};
  4170. }
  4171. onBeforeRender() {}
  4172. onAfterRender() {}
  4173. applyMatrix4(matrix) {
  4174. if (this.matrixAutoUpdate) this.updateMatrix();
  4175. this.matrix.premultiply(matrix);
  4176. this.matrix.decompose(this.position, this.quaternion, this.scale);
  4177. }
  4178. applyQuaternion(q) {
  4179. this.quaternion.premultiply(q);
  4180. return this;
  4181. }
  4182. setRotationFromAxisAngle(axis, angle) {
  4183. // assumes axis is normalized
  4184. this.quaternion.setFromAxisAngle(axis, angle);
  4185. }
  4186. setRotationFromEuler(euler) {
  4187. this.quaternion.setFromEuler(euler, true);
  4188. }
  4189. setRotationFromMatrix(m) {
  4190. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4191. this.quaternion.setFromRotationMatrix(m);
  4192. }
  4193. setRotationFromQuaternion(q) {
  4194. // assumes q is normalized
  4195. this.quaternion.copy(q);
  4196. }
  4197. rotateOnAxis(axis, angle) {
  4198. // rotate object on axis in object space
  4199. // axis is assumed to be normalized
  4200. _q1.setFromAxisAngle(axis, angle);
  4201. this.quaternion.multiply(_q1);
  4202. return this;
  4203. }
  4204. rotateOnWorldAxis(axis, angle) {
  4205. // rotate object on axis in world space
  4206. // axis is assumed to be normalized
  4207. // method assumes no rotated parent
  4208. _q1.setFromAxisAngle(axis, angle);
  4209. this.quaternion.premultiply(_q1);
  4210. return this;
  4211. }
  4212. rotateX(angle) {
  4213. return this.rotateOnAxis(_xAxis, angle);
  4214. }
  4215. rotateY(angle) {
  4216. return this.rotateOnAxis(_yAxis, angle);
  4217. }
  4218. rotateZ(angle) {
  4219. return this.rotateOnAxis(_zAxis, angle);
  4220. }
  4221. translateOnAxis(axis, distance) {
  4222. // translate object by distance along axis in object space
  4223. // axis is assumed to be normalized
  4224. _v1$4.copy(axis).applyQuaternion(this.quaternion);
  4225. this.position.add(_v1$4.multiplyScalar(distance));
  4226. return this;
  4227. }
  4228. translateX(distance) {
  4229. return this.translateOnAxis(_xAxis, distance);
  4230. }
  4231. translateY(distance) {
  4232. return this.translateOnAxis(_yAxis, distance);
  4233. }
  4234. translateZ(distance) {
  4235. return this.translateOnAxis(_zAxis, distance);
  4236. }
  4237. localToWorld(vector) {
  4238. return vector.applyMatrix4(this.matrixWorld);
  4239. }
  4240. worldToLocal(vector) {
  4241. return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
  4242. }
  4243. lookAt(x, y, z) {
  4244. // This method does not support objects having non-uniformly-scaled parent(s)
  4245. if (x.isVector3) {
  4246. _target.copy(x);
  4247. } else {
  4248. _target.set(x, y, z);
  4249. }
  4250. const parent = this.parent;
  4251. this.updateWorldMatrix(true, false);
  4252. _position$3.setFromMatrixPosition(this.matrixWorld);
  4253. if (this.isCamera || this.isLight) {
  4254. _m1$1.lookAt(_position$3, _target, this.up);
  4255. } else {
  4256. _m1$1.lookAt(_target, _position$3, this.up);
  4257. }
  4258. this.quaternion.setFromRotationMatrix(_m1$1);
  4259. if (parent) {
  4260. _m1$1.extractRotation(parent.matrixWorld);
  4261. _q1.setFromRotationMatrix(_m1$1);
  4262. this.quaternion.premultiply(_q1.invert());
  4263. }
  4264. }
  4265. add(object) {
  4266. if (arguments.length > 1) {
  4267. for (let i = 0; i < arguments.length; i++) {
  4268. this.add(arguments[i]);
  4269. }
  4270. return this;
  4271. }
  4272. if (object === this) {
  4273. console.error('THREE.Object3D.add: object can\'t be added as a child of itself.', object);
  4274. return this;
  4275. }
  4276. if (object && object.isObject3D) {
  4277. if (object.parent !== null) {
  4278. object.parent.remove(object);
  4279. }
  4280. object.parent = this;
  4281. this.children.push(object);
  4282. object.dispatchEvent(_addedEvent);
  4283. } else {
  4284. console.error('THREE.Object3D.add: object not an instance of THREE.Object3D.', object);
  4285. }
  4286. return this;
  4287. }
  4288. remove(object) {
  4289. if (arguments.length > 1) {
  4290. for (let i = 0; i < arguments.length; i++) {
  4291. this.remove(arguments[i]);
  4292. }
  4293. return this;
  4294. }
  4295. const index = this.children.indexOf(object);
  4296. if (index !== -1) {
  4297. object.parent = null;
  4298. this.children.splice(index, 1);
  4299. object.dispatchEvent(_removedEvent);
  4300. }
  4301. return this;
  4302. }
  4303. removeFromParent() {
  4304. const parent = this.parent;
  4305. if (parent !== null) {
  4306. parent.remove(this);
  4307. }
  4308. return this;
  4309. }
  4310. clear() {
  4311. for (let i = 0; i < this.children.length; i++) {
  4312. const object = this.children[i];
  4313. object.parent = null;
  4314. object.dispatchEvent(_removedEvent);
  4315. }
  4316. this.children.length = 0;
  4317. return this;
  4318. }
  4319. attach(object) {
  4320. // adds object as a child of this, while maintaining the object's world transform
  4321. this.updateWorldMatrix(true, false);
  4322. _m1$1.copy(this.matrixWorld).invert();
  4323. if (object.parent !== null) {
  4324. object.parent.updateWorldMatrix(true, false);
  4325. _m1$1.multiply(object.parent.matrixWorld);
  4326. }
  4327. object.applyMatrix4(_m1$1);
  4328. this.add(object);
  4329. object.updateWorldMatrix(false, true);
  4330. return this;
  4331. }
  4332. getObjectById(id) {
  4333. return this.getObjectByProperty('id', id);
  4334. }
  4335. getObjectByName(name) {
  4336. return this.getObjectByProperty('name', name);
  4337. }
  4338. getObjectByProperty(name, value) {
  4339. if (this[name] === value) return this;
  4340. for (let i = 0, l = this.children.length; i < l; i++) {
  4341. const child = this.children[i];
  4342. const object = child.getObjectByProperty(name, value);
  4343. if (object !== undefined) {
  4344. return object;
  4345. }
  4346. }
  4347. return undefined;
  4348. }
  4349. getWorldPosition(target) {
  4350. this.updateWorldMatrix(true, false);
  4351. return target.setFromMatrixPosition(this.matrixWorld);
  4352. }
  4353. getWorldQuaternion(target) {
  4354. this.updateWorldMatrix(true, false);
  4355. this.matrixWorld.decompose(_position$3, target, _scale$2);
  4356. return target;
  4357. }
  4358. getWorldScale(target) {
  4359. this.updateWorldMatrix(true, false);
  4360. this.matrixWorld.decompose(_position$3, _quaternion$2, target);
  4361. return target;
  4362. }
  4363. getWorldDirection(target) {
  4364. this.updateWorldMatrix(true, false);
  4365. const e = this.matrixWorld.elements;
  4366. return target.set(e[8], e[9], e[10]).normalize();
  4367. }
  4368. raycast() {}
  4369. traverse(callback) {
  4370. callback(this);
  4371. const children = this.children;
  4372. for (let i = 0, l = children.length; i < l; i++) {
  4373. children[i].traverse(callback);
  4374. }
  4375. }
  4376. traverseVisible(callback) {
  4377. if (this.visible === false) return;
  4378. callback(this);
  4379. const children = this.children;
  4380. for (let i = 0, l = children.length; i < l; i++) {
  4381. children[i].traverseVisible(callback);
  4382. }
  4383. }
  4384. traverseAncestors(callback) {
  4385. const parent = this.parent;
  4386. if (parent !== null) {
  4387. callback(parent);
  4388. parent.traverseAncestors(callback);
  4389. }
  4390. }
  4391. updateMatrix() {
  4392. this.matrix.compose(this.position, this.quaternion, this.scale);
  4393. this.matrixWorldNeedsUpdate = true;
  4394. }
  4395. updateMatrixWorld(force) {
  4396. if (this.matrixAutoUpdate) this.updateMatrix();
  4397. if (this.matrixWorldNeedsUpdate || force) {
  4398. if (this.parent === null) {
  4399. this.matrixWorld.copy(this.matrix);
  4400. } else {
  4401. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4402. }
  4403. this.matrixWorldNeedsUpdate = false;
  4404. force = true;
  4405. } // update children
  4406. const children = this.children;
  4407. for (let i = 0, l = children.length; i < l; i++) {
  4408. children[i].updateMatrixWorld(force);
  4409. }
  4410. }
  4411. updateWorldMatrix(updateParents, updateChildren) {
  4412. const parent = this.parent;
  4413. if (updateParents === true && parent !== null) {
  4414. parent.updateWorldMatrix(true, false);
  4415. }
  4416. if (this.matrixAutoUpdate) this.updateMatrix();
  4417. if (this.parent === null) {
  4418. this.matrixWorld.copy(this.matrix);
  4419. } else {
  4420. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4421. } // update children
  4422. if (updateChildren === true) {
  4423. const children = this.children;
  4424. for (let i = 0, l = children.length; i < l; i++) {
  4425. children[i].updateWorldMatrix(false, true);
  4426. }
  4427. }
  4428. }
  4429. toJSON(meta) {
  4430. // meta is a string when called from JSON.stringify
  4431. const isRootObject = meta === undefined || typeof meta === 'string';
  4432. const output = {}; // meta is a hash used to collect geometries, materials.
  4433. // not providing it implies that this is the root object
  4434. // being serialized.
  4435. if (isRootObject) {
  4436. // initialize meta obj
  4437. meta = {
  4438. geometries: {},
  4439. materials: {},
  4440. textures: {},
  4441. images: {},
  4442. shapes: {},
  4443. skeletons: {},
  4444. animations: {}
  4445. };
  4446. output.metadata = {
  4447. version: 4.5,
  4448. type: 'Object',
  4449. generator: 'Object3D.toJSON'
  4450. };
  4451. } // standard Object3D serialization
  4452. const object = {};
  4453. object.uuid = this.uuid;
  4454. object.type = this.type;
  4455. if (this.name !== '') object.name = this.name;
  4456. if (this.castShadow === true) object.castShadow = true;
  4457. if (this.receiveShadow === true) object.receiveShadow = true;
  4458. if (this.visible === false) object.visible = false;
  4459. if (this.frustumCulled === false) object.frustumCulled = false;
  4460. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  4461. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  4462. object.layers = this.layers.mask;
  4463. object.matrix = this.matrix.toArray();
  4464. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  4465. if (this.isInstancedMesh) {
  4466. object.type = 'InstancedMesh';
  4467. object.count = this.count;
  4468. object.instanceMatrix = this.instanceMatrix.toJSON();
  4469. if (this.instanceColor !== null) object.instanceColor = this.instanceColor.toJSON();
  4470. } //
  4471. function serialize(library, element) {
  4472. if (library[element.uuid] === undefined) {
  4473. library[element.uuid] = element.toJSON(meta);
  4474. }
  4475. return element.uuid;
  4476. }
  4477. if (this.isScene) {
  4478. if (this.background) {
  4479. if (this.background.isColor) {
  4480. object.background = this.background.toJSON();
  4481. } else if (this.background.isTexture) {
  4482. object.background = this.background.toJSON(meta).uuid;
  4483. }
  4484. }
  4485. if (this.environment && this.environment.isTexture) {
  4486. object.environment = this.environment.toJSON(meta).uuid;
  4487. }
  4488. } else if (this.isMesh || this.isLine || this.isPoints) {
  4489. object.geometry = serialize(meta.geometries, this.geometry);
  4490. const parameters = this.geometry.parameters;
  4491. if (parameters !== undefined && parameters.shapes !== undefined) {
  4492. const shapes = parameters.shapes;
  4493. if (Array.isArray(shapes)) {
  4494. for (let i = 0, l = shapes.length; i < l; i++) {
  4495. const shape = shapes[i];
  4496. serialize(meta.shapes, shape);
  4497. }
  4498. } else {
  4499. serialize(meta.shapes, shapes);
  4500. }
  4501. }
  4502. }
  4503. if (this.isSkinnedMesh) {
  4504. object.bindMode = this.bindMode;
  4505. object.bindMatrix = this.bindMatrix.toArray();
  4506. if (this.skeleton !== undefined) {
  4507. serialize(meta.skeletons, this.skeleton);
  4508. object.skeleton = this.skeleton.uuid;
  4509. }
  4510. }
  4511. if (this.material !== undefined) {
  4512. if (Array.isArray(this.material)) {
  4513. const uuids = [];
  4514. for (let i = 0, l = this.material.length; i < l; i++) {
  4515. uuids.push(serialize(meta.materials, this.material[i]));
  4516. }
  4517. object.material = uuids;
  4518. } else {
  4519. object.material = serialize(meta.materials, this.material);
  4520. }
  4521. } //
  4522. if (this.children.length > 0) {
  4523. object.children = [];
  4524. for (let i = 0; i < this.children.length; i++) {
  4525. object.children.push(this.children[i].toJSON(meta).object);
  4526. }
  4527. } //
  4528. if (this.animations.length > 0) {
  4529. object.animations = [];
  4530. for (let i = 0; i < this.animations.length; i++) {
  4531. const animation = this.animations[i];
  4532. object.animations.push(serialize(meta.animations, animation));
  4533. }
  4534. }
  4535. if (isRootObject) {
  4536. const geometries = extractFromCache(meta.geometries);
  4537. const materials = extractFromCache(meta.materials);
  4538. const textures = extractFromCache(meta.textures);
  4539. const images = extractFromCache(meta.images);
  4540. const shapes = extractFromCache(meta.shapes);
  4541. const skeletons = extractFromCache(meta.skeletons);
  4542. const animations = extractFromCache(meta.animations);
  4543. if (geometries.length > 0) output.geometries = geometries;
  4544. if (materials.length > 0) output.materials = materials;
  4545. if (textures.length > 0) output.textures = textures;
  4546. if (images.length > 0) output.images = images;
  4547. if (shapes.length > 0) output.shapes = shapes;
  4548. if (skeletons.length > 0) output.skeletons = skeletons;
  4549. if (animations.length > 0) output.animations = animations;
  4550. }
  4551. output.object = object;
  4552. return output; // extract data from the cache hash
  4553. // remove metadata on each item
  4554. // and return as array
  4555. function extractFromCache(cache) {
  4556. const values = [];
  4557. for (const key in cache) {
  4558. const data = cache[key];
  4559. delete data.metadata;
  4560. values.push(data);
  4561. }
  4562. return values;
  4563. }
  4564. }
  4565. clone(recursive) {
  4566. return new this.constructor().copy(this, recursive);
  4567. }
  4568. copy(source, recursive = true) {
  4569. this.name = source.name;
  4570. this.up.copy(source.up);
  4571. this.position.copy(source.position);
  4572. this.rotation.order = source.rotation.order;
  4573. this.quaternion.copy(source.quaternion);
  4574. this.scale.copy(source.scale);
  4575. this.matrix.copy(source.matrix);
  4576. this.matrixWorld.copy(source.matrixWorld);
  4577. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4578. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4579. this.layers.mask = source.layers.mask;
  4580. this.visible = source.visible;
  4581. this.castShadow = source.castShadow;
  4582. this.receiveShadow = source.receiveShadow;
  4583. this.frustumCulled = source.frustumCulled;
  4584. this.renderOrder = source.renderOrder;
  4585. this.userData = JSON.parse(JSON.stringify(source.userData));
  4586. if (recursive === true) {
  4587. for (let i = 0; i < source.children.length; i++) {
  4588. const child = source.children[i];
  4589. this.add(child.clone());
  4590. }
  4591. }
  4592. return this;
  4593. }
  4594. }
  4595. Object3D.DefaultUp = new Vector3(0, 1, 0);
  4596. Object3D.DefaultMatrixAutoUpdate = true;
  4597. Object3D.prototype.isObject3D = true;
  4598. const _v0$1 = /*@__PURE__*/new Vector3();
  4599. const _v1$3 = /*@__PURE__*/new Vector3();
  4600. const _v2$2 = /*@__PURE__*/new Vector3();
  4601. const _v3$1 = /*@__PURE__*/new Vector3();
  4602. const _vab = /*@__PURE__*/new Vector3();
  4603. const _vac = /*@__PURE__*/new Vector3();
  4604. const _vbc = /*@__PURE__*/new Vector3();
  4605. const _vap = /*@__PURE__*/new Vector3();
  4606. const _vbp = /*@__PURE__*/new Vector3();
  4607. const _vcp = /*@__PURE__*/new Vector3();
  4608. class Triangle {
  4609. constructor(a = new Vector3(), b = new Vector3(), c = new Vector3()) {
  4610. this.a = a;
  4611. this.b = b;
  4612. this.c = c;
  4613. }
  4614. static getNormal(a, b, c, target) {
  4615. target.subVectors(c, b);
  4616. _v0$1.subVectors(a, b);
  4617. target.cross(_v0$1);
  4618. const targetLengthSq = target.lengthSq();
  4619. if (targetLengthSq > 0) {
  4620. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  4621. }
  4622. return target.set(0, 0, 0);
  4623. } // static/instance method to calculate barycentric coordinates
  4624. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4625. static getBarycoord(point, a, b, c, target) {
  4626. _v0$1.subVectors(c, a);
  4627. _v1$3.subVectors(b, a);
  4628. _v2$2.subVectors(point, a);
  4629. const dot00 = _v0$1.dot(_v0$1);
  4630. const dot01 = _v0$1.dot(_v1$3);
  4631. const dot02 = _v0$1.dot(_v2$2);
  4632. const dot11 = _v1$3.dot(_v1$3);
  4633. const dot12 = _v1$3.dot(_v2$2);
  4634. const denom = dot00 * dot11 - dot01 * dot01; // collinear or singular triangle
  4635. if (denom === 0) {
  4636. // arbitrary location outside of triangle?
  4637. // not sure if this is the best idea, maybe should be returning undefined
  4638. return target.set(-2, -1, -1);
  4639. }
  4640. const invDenom = 1 / denom;
  4641. const u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  4642. const v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  4643. return target.set(1 - u - v, v, u);
  4644. }
  4645. static containsPoint(point, a, b, c) {
  4646. this.getBarycoord(point, a, b, c, _v3$1);
  4647. return _v3$1.x >= 0 && _v3$1.y >= 0 && _v3$1.x + _v3$1.y <= 1;
  4648. }
  4649. static getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
  4650. this.getBarycoord(point, p1, p2, p3, _v3$1);
  4651. target.set(0, 0);
  4652. target.addScaledVector(uv1, _v3$1.x);
  4653. target.addScaledVector(uv2, _v3$1.y);
  4654. target.addScaledVector(uv3, _v3$1.z);
  4655. return target;
  4656. }
  4657. static isFrontFacing(a, b, c, direction) {
  4658. _v0$1.subVectors(c, b);
  4659. _v1$3.subVectors(a, b); // strictly front facing
  4660. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  4661. }
  4662. set(a, b, c) {
  4663. this.a.copy(a);
  4664. this.b.copy(b);
  4665. this.c.copy(c);
  4666. return this;
  4667. }
  4668. setFromPointsAndIndices(points, i0, i1, i2) {
  4669. this.a.copy(points[i0]);
  4670. this.b.copy(points[i1]);
  4671. this.c.copy(points[i2]);
  4672. return this;
  4673. }
  4674. clone() {
  4675. return new this.constructor().copy(this);
  4676. }
  4677. copy(triangle) {
  4678. this.a.copy(triangle.a);
  4679. this.b.copy(triangle.b);
  4680. this.c.copy(triangle.c);
  4681. return this;
  4682. }
  4683. getArea() {
  4684. _v0$1.subVectors(this.c, this.b);
  4685. _v1$3.subVectors(this.a, this.b);
  4686. return _v0$1.cross(_v1$3).length() * 0.5;
  4687. }
  4688. getMidpoint(target) {
  4689. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  4690. }
  4691. getNormal(target) {
  4692. return Triangle.getNormal(this.a, this.b, this.c, target);
  4693. }
  4694. getPlane(target) {
  4695. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  4696. }
  4697. getBarycoord(point, target) {
  4698. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  4699. }
  4700. getUV(point, uv1, uv2, uv3, target) {
  4701. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  4702. }
  4703. containsPoint(point) {
  4704. return Triangle.containsPoint(point, this.a, this.b, this.c);
  4705. }
  4706. isFrontFacing(direction) {
  4707. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  4708. }
  4709. intersectsBox(box) {
  4710. return box.intersectsTriangle(this);
  4711. }
  4712. closestPointToPoint(p, target) {
  4713. const a = this.a,
  4714. b = this.b,
  4715. c = this.c;
  4716. let v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4717. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4718. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4719. // basically, we're distinguishing which of the voronoi regions of the triangle
  4720. // the point lies in with the minimum amount of redundant computation.
  4721. _vab.subVectors(b, a);
  4722. _vac.subVectors(c, a);
  4723. _vap.subVectors(p, a);
  4724. const d1 = _vab.dot(_vap);
  4725. const d2 = _vac.dot(_vap);
  4726. if (d1 <= 0 && d2 <= 0) {
  4727. // vertex region of A; barycentric coords (1, 0, 0)
  4728. return target.copy(a);
  4729. }
  4730. _vbp.subVectors(p, b);
  4731. const d3 = _vab.dot(_vbp);
  4732. const d4 = _vac.dot(_vbp);
  4733. if (d3 >= 0 && d4 <= d3) {
  4734. // vertex region of B; barycentric coords (0, 1, 0)
  4735. return target.copy(b);
  4736. }
  4737. const vc = d1 * d4 - d3 * d2;
  4738. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  4739. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  4740. return target.copy(a).addScaledVector(_vab, v);
  4741. }
  4742. _vcp.subVectors(p, c);
  4743. const d5 = _vab.dot(_vcp);
  4744. const d6 = _vac.dot(_vcp);
  4745. if (d6 >= 0 && d5 <= d6) {
  4746. // vertex region of C; barycentric coords (0, 0, 1)
  4747. return target.copy(c);
  4748. }
  4749. const vb = d5 * d2 - d1 * d6;
  4750. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  4751. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  4752. return target.copy(a).addScaledVector(_vac, w);
  4753. }
  4754. const va = d3 * d6 - d5 * d4;
  4755. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  4756. _vbc.subVectors(c, b);
  4757. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  4758. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  4759. } // face region
  4760. const denom = 1 / (va + vb + vc); // u = va * denom
  4761. v = vb * denom;
  4762. w = vc * denom;
  4763. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  4764. }
  4765. equals(triangle) {
  4766. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  4767. }
  4768. }
  4769. let materialId = 0;
  4770. class Material extends EventDispatcher {
  4771. constructor() {
  4772. super();
  4773. Object.defineProperty(this, 'id', {
  4774. value: materialId++
  4775. });
  4776. this.uuid = generateUUID();
  4777. this.name = '';
  4778. this.type = 'Material';
  4779. this.fog = true;
  4780. this.blending = NormalBlending;
  4781. this.side = FrontSide;
  4782. this.vertexColors = false;
  4783. this.opacity = 1;
  4784. this.transparent = false;
  4785. this.blendSrc = SrcAlphaFactor;
  4786. this.blendDst = OneMinusSrcAlphaFactor;
  4787. this.blendEquation = AddEquation;
  4788. this.blendSrcAlpha = null;
  4789. this.blendDstAlpha = null;
  4790. this.blendEquationAlpha = null;
  4791. this.depthFunc = LessEqualDepth;
  4792. this.depthTest = true;
  4793. this.depthWrite = true;
  4794. this.stencilWriteMask = 0xff;
  4795. this.stencilFunc = AlwaysStencilFunc;
  4796. this.stencilRef = 0;
  4797. this.stencilFuncMask = 0xff;
  4798. this.stencilFail = KeepStencilOp;
  4799. this.stencilZFail = KeepStencilOp;
  4800. this.stencilZPass = KeepStencilOp;
  4801. this.stencilWrite = false;
  4802. this.clippingPlanes = null;
  4803. this.clipIntersection = false;
  4804. this.clipShadows = false;
  4805. this.shadowSide = null;
  4806. this.colorWrite = true;
  4807. this.precision = null; // override the renderer's default precision for this material
  4808. this.polygonOffset = false;
  4809. this.polygonOffsetFactor = 0;
  4810. this.polygonOffsetUnits = 0;
  4811. this.dithering = false;
  4812. this.alphaTest = 0;
  4813. this.alphaToCoverage = false;
  4814. this.premultipliedAlpha = false;
  4815. this.visible = true;
  4816. this.toneMapped = true;
  4817. this.userData = {};
  4818. this.version = 0;
  4819. }
  4820. onBuild()
  4821. /* shaderobject, renderer */
  4822. {}
  4823. onBeforeCompile()
  4824. /* shaderobject, renderer */
  4825. {}
  4826. customProgramCacheKey() {
  4827. return this.onBeforeCompile.toString();
  4828. }
  4829. setValues(values) {
  4830. if (values === undefined) return;
  4831. for (const key in values) {
  4832. const newValue = values[key];
  4833. if (newValue === undefined) {
  4834. console.warn('THREE.Material: \'' + key + '\' parameter is undefined.');
  4835. continue;
  4836. } // for backward compatability if shading is set in the constructor
  4837. if (key === 'shading') {
  4838. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  4839. this.flatShading = newValue === FlatShading ? true : false;
  4840. continue;
  4841. }
  4842. const currentValue = this[key];
  4843. if (currentValue === undefined) {
  4844. console.warn('THREE.' + this.type + ': \'' + key + '\' is not a property of this material.');
  4845. continue;
  4846. }
  4847. if (currentValue && currentValue.isColor) {
  4848. currentValue.set(newValue);
  4849. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  4850. currentValue.copy(newValue);
  4851. } else {
  4852. this[key] = newValue;
  4853. }
  4854. }
  4855. }
  4856. toJSON(meta) {
  4857. const isRoot = meta === undefined || typeof meta === 'string';
  4858. if (isRoot) {
  4859. meta = {
  4860. textures: {},
  4861. images: {}
  4862. };
  4863. }
  4864. const data = {
  4865. metadata: {
  4866. version: 4.5,
  4867. type: 'Material',
  4868. generator: 'Material.toJSON'
  4869. }
  4870. }; // standard Material serialization
  4871. data.uuid = this.uuid;
  4872. data.type = this.type;
  4873. if (this.name !== '') data.name = this.name;
  4874. if (this.color && this.color.isColor) data.color = this.color.getHex();
  4875. if (this.roughness !== undefined) data.roughness = this.roughness;
  4876. if (this.metalness !== undefined) data.metalness = this.metalness;
  4877. if (this.sheen && this.sheen.isColor) data.sheen = this.sheen.getHex();
  4878. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  4879. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  4880. if (this.specular && this.specular.isColor) data.specular = this.specular.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.envMap && this.envMap.isTexture) {
  4924. data.envMap = this.envMap.toJSON(meta).uuid;
  4925. if (this.combine !== undefined) data.combine = this.combine;
  4926. }
  4927. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  4928. if (this.reflectivity !== undefined) data.reflectivity = this.reflectivity;
  4929. if (this.refractionRatio !== undefined) data.refractionRatio = this.refractionRatio;
  4930. if (this.gradientMap && this.gradientMap.isTexture) {
  4931. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  4932. }
  4933. if (this.transmission !== undefined) data.transmission = this.transmission;
  4934. if (this.transmissionMap && this.transmissionMap.isTexture) data.transmissionMap = this.transmissionMap.toJSON(meta).uuid;
  4935. if (this.thickness !== undefined) data.thickness = this.thickness;
  4936. if (this.thicknessMap && this.thicknessMap.isTexture) data.thicknessMap = this.thicknessMap.toJSON(meta).uuid;
  4937. if (this.attenuationDistance !== undefined) data.attenuationDistance = this.attenuationDistance;
  4938. if (this.attenuationColor !== undefined) data.attenuationColor = this.attenuationColor.getHex();
  4939. if (this.size !== undefined) data.size = this.size;
  4940. if (this.shadowSide !== null) data.shadowSide = this.shadowSide;
  4941. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  4942. if (this.blending !== NormalBlending) data.blending = this.blending;
  4943. if (this.side !== FrontSide) data.side = this.side;
  4944. if (this.vertexColors) data.vertexColors = true;
  4945. if (this.opacity < 1) data.opacity = this.opacity;
  4946. if (this.transparent === true) data.transparent = this.transparent;
  4947. data.depthFunc = this.depthFunc;
  4948. data.depthTest = this.depthTest;
  4949. data.depthWrite = this.depthWrite;
  4950. data.colorWrite = this.colorWrite;
  4951. data.stencilWrite = this.stencilWrite;
  4952. data.stencilWriteMask = this.stencilWriteMask;
  4953. data.stencilFunc = this.stencilFunc;
  4954. data.stencilRef = this.stencilRef;
  4955. data.stencilFuncMask = this.stencilFuncMask;
  4956. data.stencilFail = this.stencilFail;
  4957. data.stencilZFail = this.stencilZFail;
  4958. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  4959. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  4960. if (this.polygonOffset === true) data.polygonOffset = true;
  4961. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  4962. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  4963. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  4964. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  4965. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  4966. if (this.scale !== undefined) data.scale = this.scale;
  4967. if (this.dithering === true) data.dithering = true;
  4968. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  4969. if (this.alphaToCoverage === true) data.alphaToCoverage = this.alphaToCoverage;
  4970. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  4971. if (this.wireframe === true) data.wireframe = this.wireframe;
  4972. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  4973. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  4974. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  4975. if (this.morphTargets === true) data.morphTargets = true;
  4976. if (this.morphNormals === true) data.morphNormals = true;
  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. * morphTargets: <bool>
  5591. * }
  5592. */
  5593. class MeshBasicMaterial extends Material {
  5594. constructor(parameters) {
  5595. super();
  5596. this.type = 'MeshBasicMaterial';
  5597. this.color = new Color(0xffffff); // emissive
  5598. this.map = null;
  5599. this.lightMap = null;
  5600. this.lightMapIntensity = 1.0;
  5601. this.aoMap = null;
  5602. this.aoMapIntensity = 1.0;
  5603. this.specularMap = null;
  5604. this.alphaMap = null;
  5605. this.envMap = null;
  5606. this.combine = MultiplyOperation;
  5607. this.reflectivity = 1;
  5608. this.refractionRatio = 0.98;
  5609. this.wireframe = false;
  5610. this.wireframeLinewidth = 1;
  5611. this.wireframeLinecap = 'round';
  5612. this.wireframeLinejoin = 'round';
  5613. this.morphTargets = false;
  5614. this.setValues(parameters);
  5615. }
  5616. copy(source) {
  5617. super.copy(source);
  5618. this.color.copy(source.color);
  5619. this.map = source.map;
  5620. this.lightMap = source.lightMap;
  5621. this.lightMapIntensity = source.lightMapIntensity;
  5622. this.aoMap = source.aoMap;
  5623. this.aoMapIntensity = source.aoMapIntensity;
  5624. this.specularMap = source.specularMap;
  5625. this.alphaMap = source.alphaMap;
  5626. this.envMap = source.envMap;
  5627. this.combine = source.combine;
  5628. this.reflectivity = source.reflectivity;
  5629. this.refractionRatio = source.refractionRatio;
  5630. this.wireframe = source.wireframe;
  5631. this.wireframeLinewidth = source.wireframeLinewidth;
  5632. this.wireframeLinecap = source.wireframeLinecap;
  5633. this.wireframeLinejoin = source.wireframeLinejoin;
  5634. this.morphTargets = source.morphTargets;
  5635. return this;
  5636. }
  5637. }
  5638. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  5639. const _vector$9 = /*@__PURE__*/new Vector3();
  5640. const _vector2$1 = /*@__PURE__*/new Vector2();
  5641. class BufferAttribute {
  5642. constructor(array, itemSize, normalized) {
  5643. if (Array.isArray(array)) {
  5644. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  5645. }
  5646. this.name = '';
  5647. this.array = array;
  5648. this.itemSize = itemSize;
  5649. this.count = array !== undefined ? array.length / itemSize : 0;
  5650. this.normalized = normalized === true;
  5651. this.usage = StaticDrawUsage;
  5652. this.updateRange = {
  5653. offset: 0,
  5654. count: -1
  5655. };
  5656. this.version = 0;
  5657. }
  5658. onUploadCallback() {}
  5659. set needsUpdate(value) {
  5660. if (value === true) this.version++;
  5661. }
  5662. setUsage(value) {
  5663. this.usage = value;
  5664. return this;
  5665. }
  5666. copy(source) {
  5667. this.name = source.name;
  5668. this.array = new source.array.constructor(source.array);
  5669. this.itemSize = source.itemSize;
  5670. this.count = source.count;
  5671. this.normalized = source.normalized;
  5672. this.usage = source.usage;
  5673. return this;
  5674. }
  5675. copyAt(index1, attribute, index2) {
  5676. index1 *= this.itemSize;
  5677. index2 *= attribute.itemSize;
  5678. for (let i = 0, l = this.itemSize; i < l; i++) {
  5679. this.array[index1 + i] = attribute.array[index2 + i];
  5680. }
  5681. return this;
  5682. }
  5683. copyArray(array) {
  5684. this.array.set(array);
  5685. return this;
  5686. }
  5687. copyColorsArray(colors) {
  5688. const array = this.array;
  5689. let offset = 0;
  5690. for (let i = 0, l = colors.length; i < l; i++) {
  5691. let color = colors[i];
  5692. if (color === undefined) {
  5693. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  5694. color = new Color();
  5695. }
  5696. array[offset++] = color.r;
  5697. array[offset++] = color.g;
  5698. array[offset++] = color.b;
  5699. }
  5700. return this;
  5701. }
  5702. copyVector2sArray(vectors) {
  5703. const array = this.array;
  5704. let offset = 0;
  5705. for (let i = 0, l = vectors.length; i < l; i++) {
  5706. let vector = vectors[i];
  5707. if (vector === undefined) {
  5708. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  5709. vector = new Vector2();
  5710. }
  5711. array[offset++] = vector.x;
  5712. array[offset++] = vector.y;
  5713. }
  5714. return this;
  5715. }
  5716. copyVector3sArray(vectors) {
  5717. const array = this.array;
  5718. let offset = 0;
  5719. for (let i = 0, l = vectors.length; i < l; i++) {
  5720. let vector = vectors[i];
  5721. if (vector === undefined) {
  5722. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  5723. vector = new Vector3();
  5724. }
  5725. array[offset++] = vector.x;
  5726. array[offset++] = vector.y;
  5727. array[offset++] = vector.z;
  5728. }
  5729. return this;
  5730. }
  5731. copyVector4sArray(vectors) {
  5732. const array = this.array;
  5733. let offset = 0;
  5734. for (let i = 0, l = vectors.length; i < l; i++) {
  5735. let vector = vectors[i];
  5736. if (vector === undefined) {
  5737. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  5738. vector = new Vector4();
  5739. }
  5740. array[offset++] = vector.x;
  5741. array[offset++] = vector.y;
  5742. array[offset++] = vector.z;
  5743. array[offset++] = vector.w;
  5744. }
  5745. return this;
  5746. }
  5747. applyMatrix3(m) {
  5748. if (this.itemSize === 2) {
  5749. for (let i = 0, l = this.count; i < l; i++) {
  5750. _vector2$1.fromBufferAttribute(this, i);
  5751. _vector2$1.applyMatrix3(m);
  5752. this.setXY(i, _vector2$1.x, _vector2$1.y);
  5753. }
  5754. } else if (this.itemSize === 3) {
  5755. for (let i = 0, l = this.count; i < l; i++) {
  5756. _vector$9.fromBufferAttribute(this, i);
  5757. _vector$9.applyMatrix3(m);
  5758. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5759. }
  5760. }
  5761. return this;
  5762. }
  5763. applyMatrix4(m) {
  5764. for (let i = 0, l = this.count; i < l; i++) {
  5765. _vector$9.x = this.getX(i);
  5766. _vector$9.y = this.getY(i);
  5767. _vector$9.z = this.getZ(i);
  5768. _vector$9.applyMatrix4(m);
  5769. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5770. }
  5771. return this;
  5772. }
  5773. applyNormalMatrix(m) {
  5774. for (let i = 0, l = this.count; i < l; i++) {
  5775. _vector$9.x = this.getX(i);
  5776. _vector$9.y = this.getY(i);
  5777. _vector$9.z = this.getZ(i);
  5778. _vector$9.applyNormalMatrix(m);
  5779. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5780. }
  5781. return this;
  5782. }
  5783. transformDirection(m) {
  5784. for (let i = 0, l = this.count; i < l; i++) {
  5785. _vector$9.x = this.getX(i);
  5786. _vector$9.y = this.getY(i);
  5787. _vector$9.z = this.getZ(i);
  5788. _vector$9.transformDirection(m);
  5789. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5790. }
  5791. return this;
  5792. }
  5793. set(value, offset = 0) {
  5794. this.array.set(value, offset);
  5795. return this;
  5796. }
  5797. getX(index) {
  5798. return this.array[index * this.itemSize];
  5799. }
  5800. setX(index, x) {
  5801. this.array[index * this.itemSize] = x;
  5802. return this;
  5803. }
  5804. getY(index) {
  5805. return this.array[index * this.itemSize + 1];
  5806. }
  5807. setY(index, y) {
  5808. this.array[index * this.itemSize + 1] = y;
  5809. return this;
  5810. }
  5811. getZ(index) {
  5812. return this.array[index * this.itemSize + 2];
  5813. }
  5814. setZ(index, z) {
  5815. this.array[index * this.itemSize + 2] = z;
  5816. return this;
  5817. }
  5818. getW(index) {
  5819. return this.array[index * this.itemSize + 3];
  5820. }
  5821. setW(index, w) {
  5822. this.array[index * this.itemSize + 3] = w;
  5823. return this;
  5824. }
  5825. setXY(index, x, y) {
  5826. index *= this.itemSize;
  5827. this.array[index + 0] = x;
  5828. this.array[index + 1] = y;
  5829. return this;
  5830. }
  5831. setXYZ(index, x, y, z) {
  5832. index *= this.itemSize;
  5833. this.array[index + 0] = x;
  5834. this.array[index + 1] = y;
  5835. this.array[index + 2] = z;
  5836. return this;
  5837. }
  5838. setXYZW(index, x, y, z, w) {
  5839. index *= this.itemSize;
  5840. this.array[index + 0] = x;
  5841. this.array[index + 1] = y;
  5842. this.array[index + 2] = z;
  5843. this.array[index + 3] = w;
  5844. return this;
  5845. }
  5846. onUpload(callback) {
  5847. this.onUploadCallback = callback;
  5848. return this;
  5849. }
  5850. clone() {
  5851. return new this.constructor(this.array, this.itemSize).copy(this);
  5852. }
  5853. toJSON() {
  5854. const data = {
  5855. itemSize: this.itemSize,
  5856. type: this.array.constructor.name,
  5857. array: Array.prototype.slice.call(this.array),
  5858. normalized: this.normalized
  5859. };
  5860. if (this.name !== '') data.name = this.name;
  5861. if (this.usage !== StaticDrawUsage) data.usage = this.usage;
  5862. if (this.updateRange.offset !== 0 || this.updateRange.count !== -1) data.updateRange = this.updateRange;
  5863. return data;
  5864. }
  5865. }
  5866. BufferAttribute.prototype.isBufferAttribute = true; //
  5867. class Int8BufferAttribute extends BufferAttribute {
  5868. constructor(array, itemSize, normalized) {
  5869. super(new Int8Array(array), itemSize, normalized);
  5870. }
  5871. }
  5872. class Uint8BufferAttribute extends BufferAttribute {
  5873. constructor(array, itemSize, normalized) {
  5874. super(new Uint8Array(array), itemSize, normalized);
  5875. }
  5876. }
  5877. class Uint8ClampedBufferAttribute extends BufferAttribute {
  5878. constructor(array, itemSize, normalized) {
  5879. super(new Uint8ClampedArray(array), itemSize, normalized);
  5880. }
  5881. }
  5882. class Int16BufferAttribute extends BufferAttribute {
  5883. constructor(array, itemSize, normalized) {
  5884. super(new Int16Array(array), itemSize, normalized);
  5885. }
  5886. }
  5887. class Uint16BufferAttribute extends BufferAttribute {
  5888. constructor(array, itemSize, normalized) {
  5889. super(new Uint16Array(array), itemSize, normalized);
  5890. }
  5891. }
  5892. class Int32BufferAttribute extends BufferAttribute {
  5893. constructor(array, itemSize, normalized) {
  5894. super(new Int32Array(array), itemSize, normalized);
  5895. }
  5896. }
  5897. class Uint32BufferAttribute extends BufferAttribute {
  5898. constructor(array, itemSize, normalized) {
  5899. super(new Uint32Array(array), itemSize, normalized);
  5900. }
  5901. }
  5902. class Float16BufferAttribute extends BufferAttribute {
  5903. constructor(array, itemSize, normalized) {
  5904. super(new Uint16Array(array), itemSize, normalized);
  5905. }
  5906. }
  5907. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  5908. class Float32BufferAttribute extends BufferAttribute {
  5909. constructor(array, itemSize, normalized) {
  5910. super(new Float32Array(array), itemSize, normalized);
  5911. }
  5912. }
  5913. class Float64BufferAttribute extends BufferAttribute {
  5914. constructor(array, itemSize, normalized) {
  5915. super(new Float64Array(array), itemSize, normalized);
  5916. }
  5917. } //
  5918. function arrayMax(array) {
  5919. if (array.length === 0) return -Infinity;
  5920. let max = array[0];
  5921. for (let i = 1, l = array.length; i < l; ++i) {
  5922. if (array[i] > max) max = array[i];
  5923. }
  5924. return max;
  5925. }
  5926. const TYPED_ARRAYS = {
  5927. Int8Array: Int8Array,
  5928. Uint8Array: Uint8Array,
  5929. Uint8ClampedArray: Uint8ClampedArray,
  5930. Int16Array: Int16Array,
  5931. Uint16Array: Uint16Array,
  5932. Int32Array: Int32Array,
  5933. Uint32Array: Uint32Array,
  5934. Float32Array: Float32Array,
  5935. Float64Array: Float64Array
  5936. };
  5937. function getTypedArray(type, buffer) {
  5938. return new TYPED_ARRAYS[type](buffer);
  5939. }
  5940. let _id = 0;
  5941. const _m1 = /*@__PURE__*/new Matrix4();
  5942. const _obj = /*@__PURE__*/new Object3D();
  5943. const _offset = /*@__PURE__*/new Vector3();
  5944. const _box$1 = /*@__PURE__*/new Box3();
  5945. const _boxMorphTargets = /*@__PURE__*/new Box3();
  5946. const _vector$8 = /*@__PURE__*/new Vector3();
  5947. class BufferGeometry extends EventDispatcher {
  5948. constructor() {
  5949. super();
  5950. Object.defineProperty(this, 'id', {
  5951. value: _id++
  5952. });
  5953. this.uuid = generateUUID();
  5954. this.name = '';
  5955. this.type = 'BufferGeometry';
  5956. this.index = null;
  5957. this.attributes = {};
  5958. this.morphAttributes = {};
  5959. this.morphTargetsRelative = false;
  5960. this.groups = [];
  5961. this.boundingBox = null;
  5962. this.boundingSphere = null;
  5963. this.drawRange = {
  5964. start: 0,
  5965. count: Infinity
  5966. };
  5967. this.userData = {};
  5968. }
  5969. getIndex() {
  5970. return this.index;
  5971. }
  5972. setIndex(index) {
  5973. if (Array.isArray(index)) {
  5974. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  5975. } else {
  5976. this.index = index;
  5977. }
  5978. return this;
  5979. }
  5980. getAttribute(name) {
  5981. return this.attributes[name];
  5982. }
  5983. setAttribute(name, attribute) {
  5984. this.attributes[name] = attribute;
  5985. return this;
  5986. }
  5987. deleteAttribute(name) {
  5988. delete this.attributes[name];
  5989. return this;
  5990. }
  5991. hasAttribute(name) {
  5992. return this.attributes[name] !== undefined;
  5993. }
  5994. addGroup(start, count, materialIndex = 0) {
  5995. this.groups.push({
  5996. start: start,
  5997. count: count,
  5998. materialIndex: materialIndex
  5999. });
  6000. }
  6001. clearGroups() {
  6002. this.groups = [];
  6003. }
  6004. setDrawRange(start, count) {
  6005. this.drawRange.start = start;
  6006. this.drawRange.count = count;
  6007. }
  6008. applyMatrix4(matrix) {
  6009. const position = this.attributes.position;
  6010. if (position !== undefined) {
  6011. position.applyMatrix4(matrix);
  6012. position.needsUpdate = true;
  6013. }
  6014. const normal = this.attributes.normal;
  6015. if (normal !== undefined) {
  6016. const normalMatrix = new Matrix3().getNormalMatrix(matrix);
  6017. normal.applyNormalMatrix(normalMatrix);
  6018. normal.needsUpdate = true;
  6019. }
  6020. const tangent = this.attributes.tangent;
  6021. if (tangent !== undefined) {
  6022. tangent.transformDirection(matrix);
  6023. tangent.needsUpdate = true;
  6024. }
  6025. if (this.boundingBox !== null) {
  6026. this.computeBoundingBox();
  6027. }
  6028. if (this.boundingSphere !== null) {
  6029. this.computeBoundingSphere();
  6030. }
  6031. return this;
  6032. }
  6033. applyQuaternion(q) {
  6034. _m1.makeRotationFromQuaternion(q);
  6035. this.applyMatrix4(_m1);
  6036. return this;
  6037. }
  6038. rotateX(angle) {
  6039. // rotate geometry around world x-axis
  6040. _m1.makeRotationX(angle);
  6041. this.applyMatrix4(_m1);
  6042. return this;
  6043. }
  6044. rotateY(angle) {
  6045. // rotate geometry around world y-axis
  6046. _m1.makeRotationY(angle);
  6047. this.applyMatrix4(_m1);
  6048. return this;
  6049. }
  6050. rotateZ(angle) {
  6051. // rotate geometry around world z-axis
  6052. _m1.makeRotationZ(angle);
  6053. this.applyMatrix4(_m1);
  6054. return this;
  6055. }
  6056. translate(x, y, z) {
  6057. // translate geometry
  6058. _m1.makeTranslation(x, y, z);
  6059. this.applyMatrix4(_m1);
  6060. return this;
  6061. }
  6062. scale(x, y, z) {
  6063. // scale geometry
  6064. _m1.makeScale(x, y, z);
  6065. this.applyMatrix4(_m1);
  6066. return this;
  6067. }
  6068. lookAt(vector) {
  6069. _obj.lookAt(vector);
  6070. _obj.updateMatrix();
  6071. this.applyMatrix4(_obj.matrix);
  6072. return this;
  6073. }
  6074. center() {
  6075. this.computeBoundingBox();
  6076. this.boundingBox.getCenter(_offset).negate();
  6077. this.translate(_offset.x, _offset.y, _offset.z);
  6078. return this;
  6079. }
  6080. setFromPoints(points) {
  6081. const position = [];
  6082. for (let i = 0, l = points.length; i < l; i++) {
  6083. const point = points[i];
  6084. position.push(point.x, point.y, point.z || 0);
  6085. }
  6086. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  6087. return this;
  6088. }
  6089. computeBoundingBox() {
  6090. if (this.boundingBox === null) {
  6091. this.boundingBox = new Box3();
  6092. }
  6093. const position = this.attributes.position;
  6094. const morphAttributesPosition = this.morphAttributes.position;
  6095. if (position && position.isGLBufferAttribute) {
  6096. console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
  6097. this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
  6098. return;
  6099. }
  6100. if (position !== undefined) {
  6101. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  6102. if (morphAttributesPosition) {
  6103. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6104. const morphAttribute = morphAttributesPosition[i];
  6105. _box$1.setFromBufferAttribute(morphAttribute);
  6106. if (this.morphTargetsRelative) {
  6107. _vector$8.addVectors(this.boundingBox.min, _box$1.min);
  6108. this.boundingBox.expandByPoint(_vector$8);
  6109. _vector$8.addVectors(this.boundingBox.max, _box$1.max);
  6110. this.boundingBox.expandByPoint(_vector$8);
  6111. } else {
  6112. this.boundingBox.expandByPoint(_box$1.min);
  6113. this.boundingBox.expandByPoint(_box$1.max);
  6114. }
  6115. }
  6116. }
  6117. } else {
  6118. this.boundingBox.makeEmpty();
  6119. }
  6120. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  6121. console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  6122. }
  6123. }
  6124. computeBoundingSphere() {
  6125. if (this.boundingSphere === null) {
  6126. this.boundingSphere = new Sphere();
  6127. }
  6128. const position = this.attributes.position;
  6129. const morphAttributesPosition = this.morphAttributes.position;
  6130. if (position && position.isGLBufferAttribute) {
  6131. console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
  6132. this.boundingSphere.set(new Vector3(), Infinity);
  6133. return;
  6134. }
  6135. if (position) {
  6136. // first, find the center of the bounding sphere
  6137. const center = this.boundingSphere.center;
  6138. _box$1.setFromBufferAttribute(position); // process morph attributes if present
  6139. if (morphAttributesPosition) {
  6140. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6141. const morphAttribute = morphAttributesPosition[i];
  6142. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  6143. if (this.morphTargetsRelative) {
  6144. _vector$8.addVectors(_box$1.min, _boxMorphTargets.min);
  6145. _box$1.expandByPoint(_vector$8);
  6146. _vector$8.addVectors(_box$1.max, _boxMorphTargets.max);
  6147. _box$1.expandByPoint(_vector$8);
  6148. } else {
  6149. _box$1.expandByPoint(_boxMorphTargets.min);
  6150. _box$1.expandByPoint(_boxMorphTargets.max);
  6151. }
  6152. }
  6153. }
  6154. _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  6155. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6156. let maxRadiusSq = 0;
  6157. for (let i = 0, il = position.count; i < il; i++) {
  6158. _vector$8.fromBufferAttribute(position, i);
  6159. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6160. } // process morph attributes if present
  6161. if (morphAttributesPosition) {
  6162. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6163. const morphAttribute = morphAttributesPosition[i];
  6164. const morphTargetsRelative = this.morphTargetsRelative;
  6165. for (let j = 0, jl = morphAttribute.count; j < jl; j++) {
  6166. _vector$8.fromBufferAttribute(morphAttribute, j);
  6167. if (morphTargetsRelative) {
  6168. _offset.fromBufferAttribute(position, j);
  6169. _vector$8.add(_offset);
  6170. }
  6171. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6172. }
  6173. }
  6174. }
  6175. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  6176. if (isNaN(this.boundingSphere.radius)) {
  6177. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  6178. }
  6179. }
  6180. }
  6181. computeFaceNormals() {// backwards compatibility
  6182. }
  6183. computeTangents() {
  6184. const index = this.index;
  6185. const attributes = this.attributes; // based on http://www.terathon.com/code/tangent.html
  6186. // (per vertex tangents)
  6187. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  6188. console.error('THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)');
  6189. return;
  6190. }
  6191. const indices = index.array;
  6192. const positions = attributes.position.array;
  6193. const normals = attributes.normal.array;
  6194. const uvs = attributes.uv.array;
  6195. const nVertices = positions.length / 3;
  6196. if (attributes.tangent === undefined) {
  6197. this.setAttribute('tangent', new BufferAttribute(new Float32Array(4 * nVertices), 4));
  6198. }
  6199. const tangents = attributes.tangent.array;
  6200. const tan1 = [],
  6201. tan2 = [];
  6202. for (let i = 0; i < nVertices; i++) {
  6203. tan1[i] = new Vector3();
  6204. tan2[i] = new Vector3();
  6205. }
  6206. const vA = new Vector3(),
  6207. vB = new Vector3(),
  6208. vC = new Vector3(),
  6209. uvA = new Vector2(),
  6210. uvB = new Vector2(),
  6211. uvC = new Vector2(),
  6212. sdir = new Vector3(),
  6213. tdir = new Vector3();
  6214. function handleTriangle(a, b, c) {
  6215. vA.fromArray(positions, a * 3);
  6216. vB.fromArray(positions, b * 3);
  6217. vC.fromArray(positions, c * 3);
  6218. uvA.fromArray(uvs, a * 2);
  6219. uvB.fromArray(uvs, b * 2);
  6220. uvC.fromArray(uvs, c * 2);
  6221. vB.sub(vA);
  6222. vC.sub(vA);
  6223. uvB.sub(uvA);
  6224. uvC.sub(uvA);
  6225. const r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y); // silently ignore degenerate uv triangles having coincident or colinear vertices
  6226. if (!isFinite(r)) return;
  6227. sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
  6228. tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
  6229. tan1[a].add(sdir);
  6230. tan1[b].add(sdir);
  6231. tan1[c].add(sdir);
  6232. tan2[a].add(tdir);
  6233. tan2[b].add(tdir);
  6234. tan2[c].add(tdir);
  6235. }
  6236. let groups = this.groups;
  6237. if (groups.length === 0) {
  6238. groups = [{
  6239. start: 0,
  6240. count: indices.length
  6241. }];
  6242. }
  6243. for (let i = 0, il = groups.length; i < il; ++i) {
  6244. const group = groups[i];
  6245. const start = group.start;
  6246. const count = group.count;
  6247. for (let j = start, jl = start + count; j < jl; j += 3) {
  6248. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  6249. }
  6250. }
  6251. const tmp = new Vector3(),
  6252. tmp2 = new Vector3();
  6253. const n = new Vector3(),
  6254. n2 = new Vector3();
  6255. function handleVertex(v) {
  6256. n.fromArray(normals, v * 3);
  6257. n2.copy(n);
  6258. const t = tan1[v]; // Gram-Schmidt orthogonalize
  6259. tmp.copy(t);
  6260. tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
  6261. tmp2.crossVectors(n2, t);
  6262. const test = tmp2.dot(tan2[v]);
  6263. const w = test < 0.0 ? -1.0 : 1.0;
  6264. tangents[v * 4] = tmp.x;
  6265. tangents[v * 4 + 1] = tmp.y;
  6266. tangents[v * 4 + 2] = tmp.z;
  6267. tangents[v * 4 + 3] = w;
  6268. }
  6269. for (let i = 0, il = groups.length; i < il; ++i) {
  6270. const group = groups[i];
  6271. const start = group.start;
  6272. const count = group.count;
  6273. for (let j = start, jl = start + count; j < jl; j += 3) {
  6274. handleVertex(indices[j + 0]);
  6275. handleVertex(indices[j + 1]);
  6276. handleVertex(indices[j + 2]);
  6277. }
  6278. }
  6279. }
  6280. computeVertexNormals() {
  6281. const index = this.index;
  6282. const positionAttribute = this.getAttribute('position');
  6283. if (positionAttribute !== undefined) {
  6284. let normalAttribute = this.getAttribute('normal');
  6285. if (normalAttribute === undefined) {
  6286. normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
  6287. this.setAttribute('normal', normalAttribute);
  6288. } else {
  6289. // reset existing normals to zero
  6290. for (let i = 0, il = normalAttribute.count; i < il; i++) {
  6291. normalAttribute.setXYZ(i, 0, 0, 0);
  6292. }
  6293. }
  6294. const pA = new Vector3(),
  6295. pB = new Vector3(),
  6296. pC = new Vector3();
  6297. const nA = new Vector3(),
  6298. nB = new Vector3(),
  6299. nC = new Vector3();
  6300. const cb = new Vector3(),
  6301. ab = new Vector3(); // indexed elements
  6302. if (index) {
  6303. for (let i = 0, il = index.count; i < il; i += 3) {
  6304. const vA = index.getX(i + 0);
  6305. const vB = index.getX(i + 1);
  6306. const vC = index.getX(i + 2);
  6307. pA.fromBufferAttribute(positionAttribute, vA);
  6308. pB.fromBufferAttribute(positionAttribute, vB);
  6309. pC.fromBufferAttribute(positionAttribute, vC);
  6310. cb.subVectors(pC, pB);
  6311. ab.subVectors(pA, pB);
  6312. cb.cross(ab);
  6313. nA.fromBufferAttribute(normalAttribute, vA);
  6314. nB.fromBufferAttribute(normalAttribute, vB);
  6315. nC.fromBufferAttribute(normalAttribute, vC);
  6316. nA.add(cb);
  6317. nB.add(cb);
  6318. nC.add(cb);
  6319. normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
  6320. normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
  6321. normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
  6322. }
  6323. } else {
  6324. // non-indexed elements (unconnected triangle soup)
  6325. for (let i = 0, il = positionAttribute.count; i < il; i += 3) {
  6326. pA.fromBufferAttribute(positionAttribute, i + 0);
  6327. pB.fromBufferAttribute(positionAttribute, i + 1);
  6328. pC.fromBufferAttribute(positionAttribute, i + 2);
  6329. cb.subVectors(pC, pB);
  6330. ab.subVectors(pA, pB);
  6331. cb.cross(ab);
  6332. normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z);
  6333. normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z);
  6334. normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z);
  6335. }
  6336. }
  6337. this.normalizeNormals();
  6338. normalAttribute.needsUpdate = true;
  6339. }
  6340. }
  6341. merge(geometry, offset) {
  6342. if (!(geometry && geometry.isBufferGeometry)) {
  6343. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  6344. return;
  6345. }
  6346. if (offset === undefined) {
  6347. offset = 0;
  6348. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  6349. }
  6350. const attributes = this.attributes;
  6351. for (const key in attributes) {
  6352. if (geometry.attributes[key] === undefined) continue;
  6353. const attribute1 = attributes[key];
  6354. const attributeArray1 = attribute1.array;
  6355. const attribute2 = geometry.attributes[key];
  6356. const attributeArray2 = attribute2.array;
  6357. const attributeOffset = attribute2.itemSize * offset;
  6358. const length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  6359. for (let i = 0, j = attributeOffset; i < length; i++, j++) {
  6360. attributeArray1[j] = attributeArray2[i];
  6361. }
  6362. }
  6363. return this;
  6364. }
  6365. normalizeNormals() {
  6366. const normals = this.attributes.normal;
  6367. for (let i = 0, il = normals.count; i < il; i++) {
  6368. _vector$8.fromBufferAttribute(normals, i);
  6369. _vector$8.normalize();
  6370. normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z);
  6371. }
  6372. }
  6373. toNonIndexed() {
  6374. function convertBufferAttribute(attribute, indices) {
  6375. const array = attribute.array;
  6376. const itemSize = attribute.itemSize;
  6377. const normalized = attribute.normalized;
  6378. const array2 = new array.constructor(indices.length * itemSize);
  6379. let index = 0,
  6380. index2 = 0;
  6381. for (let i = 0, l = indices.length; i < l; i++) {
  6382. if (attribute.isInterleavedBufferAttribute) {
  6383. index = indices[i] * attribute.data.stride + attribute.offset;
  6384. } else {
  6385. index = indices[i] * itemSize;
  6386. }
  6387. for (let j = 0; j < itemSize; j++) {
  6388. array2[index2++] = array[index++];
  6389. }
  6390. }
  6391. return new BufferAttribute(array2, itemSize, normalized);
  6392. } //
  6393. if (this.index === null) {
  6394. console.warn('THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.');
  6395. return this;
  6396. }
  6397. const geometry2 = new BufferGeometry();
  6398. const indices = this.index.array;
  6399. const attributes = this.attributes; // attributes
  6400. for (const name in attributes) {
  6401. const attribute = attributes[name];
  6402. const newAttribute = convertBufferAttribute(attribute, indices);
  6403. geometry2.setAttribute(name, newAttribute);
  6404. } // morph attributes
  6405. const morphAttributes = this.morphAttributes;
  6406. for (const name in morphAttributes) {
  6407. const morphArray = [];
  6408. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6409. for (let i = 0, il = morphAttribute.length; i < il; i++) {
  6410. const attribute = morphAttribute[i];
  6411. const newAttribute = convertBufferAttribute(attribute, indices);
  6412. morphArray.push(newAttribute);
  6413. }
  6414. geometry2.morphAttributes[name] = morphArray;
  6415. }
  6416. geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
  6417. const groups = this.groups;
  6418. for (let i = 0, l = groups.length; i < l; i++) {
  6419. const group = groups[i];
  6420. geometry2.addGroup(group.start, group.count, group.materialIndex);
  6421. }
  6422. return geometry2;
  6423. }
  6424. toJSON() {
  6425. const data = {
  6426. metadata: {
  6427. version: 4.5,
  6428. type: 'BufferGeometry',
  6429. generator: 'BufferGeometry.toJSON'
  6430. }
  6431. }; // standard BufferGeometry serialization
  6432. data.uuid = this.uuid;
  6433. data.type = this.type;
  6434. if (this.name !== '') data.name = this.name;
  6435. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  6436. if (this.parameters !== undefined) {
  6437. const parameters = this.parameters;
  6438. for (const key in parameters) {
  6439. if (parameters[key] !== undefined) data[key] = parameters[key];
  6440. }
  6441. return data;
  6442. } // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6443. data.data = {
  6444. attributes: {}
  6445. };
  6446. const index = this.index;
  6447. if (index !== null) {
  6448. data.data.index = {
  6449. type: index.array.constructor.name,
  6450. array: Array.prototype.slice.call(index.array)
  6451. };
  6452. }
  6453. const attributes = this.attributes;
  6454. for (const key in attributes) {
  6455. const attribute = attributes[key];
  6456. data.data.attributes[key] = attribute.toJSON(data.data);
  6457. }
  6458. const morphAttributes = {};
  6459. let hasMorphAttributes = false;
  6460. for (const key in this.morphAttributes) {
  6461. const attributeArray = this.morphAttributes[key];
  6462. const array = [];
  6463. for (let i = 0, il = attributeArray.length; i < il; i++) {
  6464. const attribute = attributeArray[i];
  6465. array.push(attribute.toJSON(data.data));
  6466. }
  6467. if (array.length > 0) {
  6468. morphAttributes[key] = array;
  6469. hasMorphAttributes = true;
  6470. }
  6471. }
  6472. if (hasMorphAttributes) {
  6473. data.data.morphAttributes = morphAttributes;
  6474. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6475. }
  6476. const groups = this.groups;
  6477. if (groups.length > 0) {
  6478. data.data.groups = JSON.parse(JSON.stringify(groups));
  6479. }
  6480. const boundingSphere = this.boundingSphere;
  6481. if (boundingSphere !== null) {
  6482. data.data.boundingSphere = {
  6483. center: boundingSphere.center.toArray(),
  6484. radius: boundingSphere.radius
  6485. };
  6486. }
  6487. return data;
  6488. }
  6489. clone() {
  6490. /*
  6491. // Handle primitives
  6492. const parameters = this.parameters;
  6493. if ( parameters !== undefined ) {
  6494. const values = [];
  6495. for ( const key in parameters ) {
  6496. values.push( parameters[ key ] );
  6497. }
  6498. const geometry = Object.create( this.constructor.prototype );
  6499. this.constructor.apply( geometry, values );
  6500. return geometry;
  6501. }
  6502. return new this.constructor().copy( this );
  6503. */
  6504. return new BufferGeometry().copy(this);
  6505. }
  6506. copy(source) {
  6507. // reset
  6508. this.index = null;
  6509. this.attributes = {};
  6510. this.morphAttributes = {};
  6511. this.groups = [];
  6512. this.boundingBox = null;
  6513. this.boundingSphere = null; // used for storing cloned, shared data
  6514. const data = {}; // name
  6515. this.name = source.name; // index
  6516. const index = source.index;
  6517. if (index !== null) {
  6518. this.setIndex(index.clone(data));
  6519. } // attributes
  6520. const attributes = source.attributes;
  6521. for (const name in attributes) {
  6522. const attribute = attributes[name];
  6523. this.setAttribute(name, attribute.clone(data));
  6524. } // morph attributes
  6525. const morphAttributes = source.morphAttributes;
  6526. for (const name in morphAttributes) {
  6527. const array = [];
  6528. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6529. for (let i = 0, l = morphAttribute.length; i < l; i++) {
  6530. array.push(morphAttribute[i].clone(data));
  6531. }
  6532. this.morphAttributes[name] = array;
  6533. }
  6534. this.morphTargetsRelative = source.morphTargetsRelative; // groups
  6535. const groups = source.groups;
  6536. for (let i = 0, l = groups.length; i < l; i++) {
  6537. const group = groups[i];
  6538. this.addGroup(group.start, group.count, group.materialIndex);
  6539. } // bounding box
  6540. const boundingBox = source.boundingBox;
  6541. if (boundingBox !== null) {
  6542. this.boundingBox = boundingBox.clone();
  6543. } // bounding sphere
  6544. const boundingSphere = source.boundingSphere;
  6545. if (boundingSphere !== null) {
  6546. this.boundingSphere = boundingSphere.clone();
  6547. } // draw range
  6548. this.drawRange.start = source.drawRange.start;
  6549. this.drawRange.count = source.drawRange.count; // user data
  6550. this.userData = source.userData;
  6551. return this;
  6552. }
  6553. dispose() {
  6554. this.dispatchEvent({
  6555. type: 'dispose'
  6556. });
  6557. }
  6558. }
  6559. BufferGeometry.prototype.isBufferGeometry = true;
  6560. const _inverseMatrix$2 = /*@__PURE__*/new Matrix4();
  6561. const _ray$2 = /*@__PURE__*/new Ray();
  6562. const _sphere$3 = /*@__PURE__*/new Sphere();
  6563. const _vA$1 = /*@__PURE__*/new Vector3();
  6564. const _vB$1 = /*@__PURE__*/new Vector3();
  6565. const _vC$1 = /*@__PURE__*/new Vector3();
  6566. const _tempA = /*@__PURE__*/new Vector3();
  6567. const _tempB = /*@__PURE__*/new Vector3();
  6568. const _tempC = /*@__PURE__*/new Vector3();
  6569. const _morphA = /*@__PURE__*/new Vector3();
  6570. const _morphB = /*@__PURE__*/new Vector3();
  6571. const _morphC = /*@__PURE__*/new Vector3();
  6572. const _uvA$1 = /*@__PURE__*/new Vector2();
  6573. const _uvB$1 = /*@__PURE__*/new Vector2();
  6574. const _uvC$1 = /*@__PURE__*/new Vector2();
  6575. const _intersectionPoint = /*@__PURE__*/new Vector3();
  6576. const _intersectionPointWorld = /*@__PURE__*/new Vector3();
  6577. class Mesh extends Object3D {
  6578. constructor(geometry = new BufferGeometry(), material = new MeshBasicMaterial()) {
  6579. super();
  6580. this.type = 'Mesh';
  6581. this.geometry = geometry;
  6582. this.material = material;
  6583. this.updateMorphTargets();
  6584. }
  6585. copy(source) {
  6586. super.copy(source);
  6587. if (source.morphTargetInfluences !== undefined) {
  6588. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6589. }
  6590. if (source.morphTargetDictionary !== undefined) {
  6591. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  6592. }
  6593. this.material = source.material;
  6594. this.geometry = source.geometry;
  6595. return this;
  6596. }
  6597. updateMorphTargets() {
  6598. const geometry = this.geometry;
  6599. if (geometry.isBufferGeometry) {
  6600. const morphAttributes = geometry.morphAttributes;
  6601. const keys = Object.keys(morphAttributes);
  6602. if (keys.length > 0) {
  6603. const morphAttribute = morphAttributes[keys[0]];
  6604. if (morphAttribute !== undefined) {
  6605. this.morphTargetInfluences = [];
  6606. this.morphTargetDictionary = {};
  6607. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  6608. const name = morphAttribute[m].name || String(m);
  6609. this.morphTargetInfluences.push(0);
  6610. this.morphTargetDictionary[name] = m;
  6611. }
  6612. }
  6613. }
  6614. } else {
  6615. const morphTargets = geometry.morphTargets;
  6616. if (morphTargets !== undefined && morphTargets.length > 0) {
  6617. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6618. }
  6619. }
  6620. }
  6621. raycast(raycaster, intersects) {
  6622. const geometry = this.geometry;
  6623. const material = this.material;
  6624. const matrixWorld = this.matrixWorld;
  6625. if (material === undefined) return; // Checking boundingSphere distance to ray
  6626. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  6627. _sphere$3.copy(geometry.boundingSphere);
  6628. _sphere$3.applyMatrix4(matrixWorld);
  6629. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  6630. _inverseMatrix$2.copy(matrixWorld).invert();
  6631. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2); // Check boundingBox before continuing
  6632. if (geometry.boundingBox !== null) {
  6633. if (_ray$2.intersectsBox(geometry.boundingBox) === false) return;
  6634. }
  6635. let intersection;
  6636. if (geometry.isBufferGeometry) {
  6637. const index = geometry.index;
  6638. const position = geometry.attributes.position;
  6639. const morphPosition = geometry.morphAttributes.position;
  6640. const morphTargetsRelative = geometry.morphTargetsRelative;
  6641. const uv = geometry.attributes.uv;
  6642. const uv2 = geometry.attributes.uv2;
  6643. const groups = geometry.groups;
  6644. const drawRange = geometry.drawRange;
  6645. if (index !== null) {
  6646. // indexed buffer geometry
  6647. if (Array.isArray(material)) {
  6648. for (let i = 0, il = groups.length; i < il; i++) {
  6649. const group = groups[i];
  6650. const groupMaterial = material[group.materialIndex];
  6651. const start = Math.max(group.start, drawRange.start);
  6652. const end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  6653. for (let j = start, jl = end; j < jl; j += 3) {
  6654. const a = index.getX(j);
  6655. const b = index.getX(j + 1);
  6656. const c = index.getX(j + 2);
  6657. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6658. if (intersection) {
  6659. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  6660. intersection.face.materialIndex = group.materialIndex;
  6661. intersects.push(intersection);
  6662. }
  6663. }
  6664. }
  6665. } else {
  6666. const start = Math.max(0, drawRange.start);
  6667. const end = Math.min(index.count, drawRange.start + drawRange.count);
  6668. for (let i = start, il = end; i < il; i += 3) {
  6669. const a = index.getX(i);
  6670. const b = index.getX(i + 1);
  6671. const c = index.getX(i + 2);
  6672. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6673. if (intersection) {
  6674. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  6675. intersects.push(intersection);
  6676. }
  6677. }
  6678. }
  6679. } else if (position !== undefined) {
  6680. // non-indexed buffer geometry
  6681. if (Array.isArray(material)) {
  6682. for (let i = 0, il = groups.length; i < il; i++) {
  6683. const group = groups[i];
  6684. const groupMaterial = material[group.materialIndex];
  6685. const start = Math.max(group.start, drawRange.start);
  6686. const end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  6687. for (let j = start, jl = end; j < jl; j += 3) {
  6688. const a = j;
  6689. const b = j + 1;
  6690. const c = j + 2;
  6691. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6692. if (intersection) {
  6693. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  6694. intersection.face.materialIndex = group.materialIndex;
  6695. intersects.push(intersection);
  6696. }
  6697. }
  6698. }
  6699. } else {
  6700. const start = Math.max(0, drawRange.start);
  6701. const end = Math.min(position.count, drawRange.start + drawRange.count);
  6702. for (let i = start, il = end; i < il; i += 3) {
  6703. const a = i;
  6704. const b = i + 1;
  6705. const c = i + 2;
  6706. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6707. if (intersection) {
  6708. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  6709. intersects.push(intersection);
  6710. }
  6711. }
  6712. }
  6713. }
  6714. } else if (geometry.isGeometry) {
  6715. console.error('THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6716. }
  6717. }
  6718. }
  6719. Mesh.prototype.isMesh = true;
  6720. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  6721. let intersect;
  6722. if (material.side === BackSide) {
  6723. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  6724. } else {
  6725. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  6726. }
  6727. if (intersect === null) return null;
  6728. _intersectionPointWorld.copy(point);
  6729. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  6730. const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  6731. if (distance < raycaster.near || distance > raycaster.far) return null;
  6732. return {
  6733. distance: distance,
  6734. point: _intersectionPointWorld.clone(),
  6735. object: object
  6736. };
  6737. }
  6738. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  6739. _vA$1.fromBufferAttribute(position, a);
  6740. _vB$1.fromBufferAttribute(position, b);
  6741. _vC$1.fromBufferAttribute(position, c);
  6742. const morphInfluences = object.morphTargetInfluences;
  6743. if (material.morphTargets && morphPosition && morphInfluences) {
  6744. _morphA.set(0, 0, 0);
  6745. _morphB.set(0, 0, 0);
  6746. _morphC.set(0, 0, 0);
  6747. for (let i = 0, il = morphPosition.length; i < il; i++) {
  6748. const influence = morphInfluences[i];
  6749. const morphAttribute = morphPosition[i];
  6750. if (influence === 0) continue;
  6751. _tempA.fromBufferAttribute(morphAttribute, a);
  6752. _tempB.fromBufferAttribute(morphAttribute, b);
  6753. _tempC.fromBufferAttribute(morphAttribute, c);
  6754. if (morphTargetsRelative) {
  6755. _morphA.addScaledVector(_tempA, influence);
  6756. _morphB.addScaledVector(_tempB, influence);
  6757. _morphC.addScaledVector(_tempC, influence);
  6758. } else {
  6759. _morphA.addScaledVector(_tempA.sub(_vA$1), influence);
  6760. _morphB.addScaledVector(_tempB.sub(_vB$1), influence);
  6761. _morphC.addScaledVector(_tempC.sub(_vC$1), influence);
  6762. }
  6763. }
  6764. _vA$1.add(_morphA);
  6765. _vB$1.add(_morphB);
  6766. _vC$1.add(_morphC);
  6767. }
  6768. if (object.isSkinnedMesh) {
  6769. object.boneTransform(a, _vA$1);
  6770. object.boneTransform(b, _vB$1);
  6771. object.boneTransform(c, _vC$1);
  6772. }
  6773. const intersection = checkIntersection(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint);
  6774. if (intersection) {
  6775. if (uv) {
  6776. _uvA$1.fromBufferAttribute(uv, a);
  6777. _uvB$1.fromBufferAttribute(uv, b);
  6778. _uvC$1.fromBufferAttribute(uv, c);
  6779. intersection.uv = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6780. }
  6781. if (uv2) {
  6782. _uvA$1.fromBufferAttribute(uv2, a);
  6783. _uvB$1.fromBufferAttribute(uv2, b);
  6784. _uvC$1.fromBufferAttribute(uv2, c);
  6785. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6786. }
  6787. const face = {
  6788. a: a,
  6789. b: b,
  6790. c: c,
  6791. normal: new Vector3(),
  6792. materialIndex: 0
  6793. };
  6794. Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal);
  6795. intersection.face = face;
  6796. }
  6797. return intersection;
  6798. }
  6799. class BoxGeometry extends BufferGeometry {
  6800. constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
  6801. super();
  6802. this.type = 'BoxGeometry';
  6803. this.parameters = {
  6804. width: width,
  6805. height: height,
  6806. depth: depth,
  6807. widthSegments: widthSegments,
  6808. heightSegments: heightSegments,
  6809. depthSegments: depthSegments
  6810. };
  6811. const scope = this; // segments
  6812. widthSegments = Math.floor(widthSegments);
  6813. heightSegments = Math.floor(heightSegments);
  6814. depthSegments = Math.floor(depthSegments); // buffers
  6815. const indices = [];
  6816. const vertices = [];
  6817. const normals = [];
  6818. const uvs = []; // helper variables
  6819. let numberOfVertices = 0;
  6820. let groupStart = 0; // build each side of the box geometry
  6821. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  6822. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  6823. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  6824. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  6825. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  6826. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  6827. // build geometry
  6828. this.setIndex(indices);
  6829. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  6830. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  6831. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  6832. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  6833. const segmentWidth = width / gridX;
  6834. const segmentHeight = height / gridY;
  6835. const widthHalf = width / 2;
  6836. const heightHalf = height / 2;
  6837. const depthHalf = depth / 2;
  6838. const gridX1 = gridX + 1;
  6839. const gridY1 = gridY + 1;
  6840. let vertexCounter = 0;
  6841. let groupCount = 0;
  6842. const vector = new Vector3(); // generate vertices, normals and uvs
  6843. for (let iy = 0; iy < gridY1; iy++) {
  6844. const y = iy * segmentHeight - heightHalf;
  6845. for (let ix = 0; ix < gridX1; ix++) {
  6846. const x = ix * segmentWidth - widthHalf; // set values to correct vector component
  6847. vector[u] = x * udir;
  6848. vector[v] = y * vdir;
  6849. vector[w] = depthHalf; // now apply vector to vertex buffer
  6850. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  6851. vector[u] = 0;
  6852. vector[v] = 0;
  6853. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  6854. normals.push(vector.x, vector.y, vector.z); // uvs
  6855. uvs.push(ix / gridX);
  6856. uvs.push(1 - iy / gridY); // counters
  6857. vertexCounter += 1;
  6858. }
  6859. } // indices
  6860. // 1. you need three indices to draw a single face
  6861. // 2. a single segment consists of two faces
  6862. // 3. so we need to generate six (2*3) indices per segment
  6863. for (let iy = 0; iy < gridY; iy++) {
  6864. for (let ix = 0; ix < gridX; ix++) {
  6865. const a = numberOfVertices + ix + gridX1 * iy;
  6866. const b = numberOfVertices + ix + gridX1 * (iy + 1);
  6867. const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  6868. const d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  6869. indices.push(a, b, d);
  6870. indices.push(b, c, d); // increase counter
  6871. groupCount += 6;
  6872. }
  6873. } // add a group to the geometry. this will ensure multi material support
  6874. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  6875. groupStart += groupCount; // update total number of vertices
  6876. numberOfVertices += vertexCounter;
  6877. }
  6878. }
  6879. static fromJSON(data) {
  6880. return new BoxGeometry(data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  6881. }
  6882. }
  6883. /**
  6884. * Uniform Utilities
  6885. */
  6886. function cloneUniforms(src) {
  6887. const dst = {};
  6888. for (const u in src) {
  6889. dst[u] = {};
  6890. for (const p in src[u]) {
  6891. const property = src[u][p];
  6892. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion)) {
  6893. dst[u][p] = property.clone();
  6894. } else if (Array.isArray(property)) {
  6895. dst[u][p] = property.slice();
  6896. } else {
  6897. dst[u][p] = property;
  6898. }
  6899. }
  6900. }
  6901. return dst;
  6902. }
  6903. function mergeUniforms(uniforms) {
  6904. const merged = {};
  6905. for (let u = 0; u < uniforms.length; u++) {
  6906. const tmp = cloneUniforms(uniforms[u]);
  6907. for (const p in tmp) {
  6908. merged[p] = tmp[p];
  6909. }
  6910. }
  6911. return merged;
  6912. } // Legacy
  6913. const UniformsUtils = {
  6914. clone: cloneUniforms,
  6915. merge: mergeUniforms
  6916. };
  6917. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  6918. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  6919. /**
  6920. * parameters = {
  6921. * defines: { "label" : "value" },
  6922. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  6923. *
  6924. * fragmentShader: <string>,
  6925. * vertexShader: <string>,
  6926. *
  6927. * wireframe: <boolean>,
  6928. * wireframeLinewidth: <float>,
  6929. *
  6930. * lights: <bool>,
  6931. *
  6932. * morphTargets: <bool>,
  6933. * morphNormals: <bool>
  6934. * }
  6935. */
  6936. class ShaderMaterial extends Material {
  6937. constructor(parameters) {
  6938. super();
  6939. this.type = 'ShaderMaterial';
  6940. this.defines = {};
  6941. this.uniforms = {};
  6942. this.vertexShader = default_vertex;
  6943. this.fragmentShader = default_fragment;
  6944. this.linewidth = 1;
  6945. this.wireframe = false;
  6946. this.wireframeLinewidth = 1;
  6947. this.fog = false; // set to use scene fog
  6948. this.lights = false; // set to use scene lights
  6949. this.clipping = false; // set to use user-defined clipping planes
  6950. this.morphTargets = false; // set to use morph targets
  6951. this.morphNormals = false; // set to use morph normals
  6952. this.extensions = {
  6953. derivatives: false,
  6954. // set to use derivatives
  6955. fragDepth: false,
  6956. // set to use fragment depth values
  6957. drawBuffers: false,
  6958. // set to use draw buffers
  6959. shaderTextureLOD: false // set to use shader texture LOD
  6960. }; // When rendered geometry doesn't include these attributes but the material does,
  6961. // use these default values in WebGL. This avoids errors when buffer data is missing.
  6962. this.defaultAttributeValues = {
  6963. 'color': [1, 1, 1],
  6964. 'uv': [0, 0],
  6965. 'uv2': [0, 0]
  6966. };
  6967. this.index0AttributeName = undefined;
  6968. this.uniformsNeedUpdate = false;
  6969. this.glslVersion = null;
  6970. if (parameters !== undefined) {
  6971. if (parameters.attributes !== undefined) {
  6972. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  6973. }
  6974. this.setValues(parameters);
  6975. }
  6976. }
  6977. copy(source) {
  6978. super.copy(source);
  6979. this.fragmentShader = source.fragmentShader;
  6980. this.vertexShader = source.vertexShader;
  6981. this.uniforms = cloneUniforms(source.uniforms);
  6982. this.defines = Object.assign({}, source.defines);
  6983. this.wireframe = source.wireframe;
  6984. this.wireframeLinewidth = source.wireframeLinewidth;
  6985. this.lights = source.lights;
  6986. this.clipping = source.clipping;
  6987. this.morphTargets = source.morphTargets;
  6988. this.morphNormals = source.morphNormals;
  6989. this.extensions = Object.assign({}, source.extensions);
  6990. this.glslVersion = source.glslVersion;
  6991. return this;
  6992. }
  6993. toJSON(meta) {
  6994. const data = super.toJSON(meta);
  6995. data.glslVersion = this.glslVersion;
  6996. data.uniforms = {};
  6997. for (const name in this.uniforms) {
  6998. const uniform = this.uniforms[name];
  6999. const value = uniform.value;
  7000. if (value && value.isTexture) {
  7001. data.uniforms[name] = {
  7002. type: 't',
  7003. value: value.toJSON(meta).uuid
  7004. };
  7005. } else if (value && value.isColor) {
  7006. data.uniforms[name] = {
  7007. type: 'c',
  7008. value: value.getHex()
  7009. };
  7010. } else if (value && value.isVector2) {
  7011. data.uniforms[name] = {
  7012. type: 'v2',
  7013. value: value.toArray()
  7014. };
  7015. } else if (value && value.isVector3) {
  7016. data.uniforms[name] = {
  7017. type: 'v3',
  7018. value: value.toArray()
  7019. };
  7020. } else if (value && value.isVector4) {
  7021. data.uniforms[name] = {
  7022. type: 'v4',
  7023. value: value.toArray()
  7024. };
  7025. } else if (value && value.isMatrix3) {
  7026. data.uniforms[name] = {
  7027. type: 'm3',
  7028. value: value.toArray()
  7029. };
  7030. } else if (value && value.isMatrix4) {
  7031. data.uniforms[name] = {
  7032. type: 'm4',
  7033. value: value.toArray()
  7034. };
  7035. } else {
  7036. data.uniforms[name] = {
  7037. value: value
  7038. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7039. }
  7040. }
  7041. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  7042. data.vertexShader = this.vertexShader;
  7043. data.fragmentShader = this.fragmentShader;
  7044. const extensions = {};
  7045. for (const key in this.extensions) {
  7046. if (this.extensions[key] === true) extensions[key] = true;
  7047. }
  7048. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  7049. return data;
  7050. }
  7051. }
  7052. ShaderMaterial.prototype.isShaderMaterial = true;
  7053. class Camera extends Object3D {
  7054. constructor() {
  7055. super();
  7056. this.type = 'Camera';
  7057. this.matrixWorldInverse = new Matrix4();
  7058. this.projectionMatrix = new Matrix4();
  7059. this.projectionMatrixInverse = new Matrix4();
  7060. }
  7061. copy(source, recursive) {
  7062. super.copy(source, recursive);
  7063. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  7064. this.projectionMatrix.copy(source.projectionMatrix);
  7065. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  7066. return this;
  7067. }
  7068. getWorldDirection(target) {
  7069. this.updateWorldMatrix(true, false);
  7070. const e = this.matrixWorld.elements;
  7071. return target.set(-e[8], -e[9], -e[10]).normalize();
  7072. }
  7073. updateMatrixWorld(force) {
  7074. super.updateMatrixWorld(force);
  7075. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7076. }
  7077. updateWorldMatrix(updateParents, updateChildren) {
  7078. super.updateWorldMatrix(updateParents, updateChildren);
  7079. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7080. }
  7081. clone() {
  7082. return new this.constructor().copy(this);
  7083. }
  7084. }
  7085. Camera.prototype.isCamera = true;
  7086. class PerspectiveCamera extends Camera {
  7087. constructor(fov = 50, aspect = 1, near = 0.1, far = 2000) {
  7088. super();
  7089. this.type = 'PerspectiveCamera';
  7090. this.fov = fov;
  7091. this.zoom = 1;
  7092. this.near = near;
  7093. this.far = far;
  7094. this.focus = 10;
  7095. this.aspect = aspect;
  7096. this.view = null;
  7097. this.filmGauge = 35; // width of the film (default in millimeters)
  7098. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7099. this.updateProjectionMatrix();
  7100. }
  7101. copy(source, recursive) {
  7102. super.copy(source, recursive);
  7103. this.fov = source.fov;
  7104. this.zoom = source.zoom;
  7105. this.near = source.near;
  7106. this.far = source.far;
  7107. this.focus = source.focus;
  7108. this.aspect = source.aspect;
  7109. this.view = source.view === null ? null : Object.assign({}, source.view);
  7110. this.filmGauge = source.filmGauge;
  7111. this.filmOffset = source.filmOffset;
  7112. return this;
  7113. }
  7114. /**
  7115. * Sets the FOV by focal length in respect to the current .filmGauge.
  7116. *
  7117. * The default film gauge is 35, so that the focal length can be specified for
  7118. * a 35mm (full frame) camera.
  7119. *
  7120. * Values for focal length and film gauge must have the same unit.
  7121. */
  7122. setFocalLength(focalLength) {
  7123. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7124. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7125. this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope);
  7126. this.updateProjectionMatrix();
  7127. }
  7128. /**
  7129. * Calculates the focal length from the current .fov and .filmGauge.
  7130. */
  7131. getFocalLength() {
  7132. const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov);
  7133. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7134. }
  7135. getEffectiveFOV() {
  7136. return RAD2DEG * 2 * Math.atan(Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom);
  7137. }
  7138. getFilmWidth() {
  7139. // film not completely covered in portrait format (aspect < 1)
  7140. return this.filmGauge * Math.min(this.aspect, 1);
  7141. }
  7142. getFilmHeight() {
  7143. // film not completely covered in landscape format (aspect > 1)
  7144. return this.filmGauge / Math.max(this.aspect, 1);
  7145. }
  7146. /**
  7147. * Sets an offset in a larger frustum. This is useful for multi-window or
  7148. * multi-monitor/multi-machine setups.
  7149. *
  7150. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7151. * the monitors are in grid like this
  7152. *
  7153. * +---+---+---+
  7154. * | A | B | C |
  7155. * +---+---+---+
  7156. * | D | E | F |
  7157. * +---+---+---+
  7158. *
  7159. * then for each monitor you would call it like this
  7160. *
  7161. * const w = 1920;
  7162. * const h = 1080;
  7163. * const fullWidth = w * 3;
  7164. * const fullHeight = h * 2;
  7165. *
  7166. * --A--
  7167. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7168. * --B--
  7169. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7170. * --C--
  7171. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7172. * --D--
  7173. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7174. * --E--
  7175. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7176. * --F--
  7177. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7178. *
  7179. * Note there is no reason monitors have to be the same size or in a grid.
  7180. */
  7181. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  7182. this.aspect = fullWidth / fullHeight;
  7183. if (this.view === null) {
  7184. this.view = {
  7185. enabled: true,
  7186. fullWidth: 1,
  7187. fullHeight: 1,
  7188. offsetX: 0,
  7189. offsetY: 0,
  7190. width: 1,
  7191. height: 1
  7192. };
  7193. }
  7194. this.view.enabled = true;
  7195. this.view.fullWidth = fullWidth;
  7196. this.view.fullHeight = fullHeight;
  7197. this.view.offsetX = x;
  7198. this.view.offsetY = y;
  7199. this.view.width = width;
  7200. this.view.height = height;
  7201. this.updateProjectionMatrix();
  7202. }
  7203. clearViewOffset() {
  7204. if (this.view !== null) {
  7205. this.view.enabled = false;
  7206. }
  7207. this.updateProjectionMatrix();
  7208. }
  7209. updateProjectionMatrix() {
  7210. const near = this.near;
  7211. let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom;
  7212. let height = 2 * top;
  7213. let width = this.aspect * height;
  7214. let left = -0.5 * width;
  7215. const view = this.view;
  7216. if (this.view !== null && this.view.enabled) {
  7217. const fullWidth = view.fullWidth,
  7218. fullHeight = view.fullHeight;
  7219. left += view.offsetX * width / fullWidth;
  7220. top -= view.offsetY * height / fullHeight;
  7221. width *= view.width / fullWidth;
  7222. height *= view.height / fullHeight;
  7223. }
  7224. const skew = this.filmOffset;
  7225. if (skew !== 0) left += near * skew / this.getFilmWidth();
  7226. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  7227. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  7228. }
  7229. toJSON(meta) {
  7230. const data = super.toJSON(meta);
  7231. data.object.fov = this.fov;
  7232. data.object.zoom = this.zoom;
  7233. data.object.near = this.near;
  7234. data.object.far = this.far;
  7235. data.object.focus = this.focus;
  7236. data.object.aspect = this.aspect;
  7237. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  7238. data.object.filmGauge = this.filmGauge;
  7239. data.object.filmOffset = this.filmOffset;
  7240. return data;
  7241. }
  7242. }
  7243. PerspectiveCamera.prototype.isPerspectiveCamera = true;
  7244. const fov = 90,
  7245. aspect = 1;
  7246. class CubeCamera extends Object3D {
  7247. constructor(near, far, renderTarget) {
  7248. super();
  7249. this.type = 'CubeCamera';
  7250. if (renderTarget.isWebGLCubeRenderTarget !== true) {
  7251. console.error('THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.');
  7252. return;
  7253. }
  7254. this.renderTarget = renderTarget;
  7255. const cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  7256. cameraPX.layers = this.layers;
  7257. cameraPX.up.set(0, -1, 0);
  7258. cameraPX.lookAt(new Vector3(1, 0, 0));
  7259. this.add(cameraPX);
  7260. const cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  7261. cameraNX.layers = this.layers;
  7262. cameraNX.up.set(0, -1, 0);
  7263. cameraNX.lookAt(new Vector3(-1, 0, 0));
  7264. this.add(cameraNX);
  7265. const cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  7266. cameraPY.layers = this.layers;
  7267. cameraPY.up.set(0, 0, 1);
  7268. cameraPY.lookAt(new Vector3(0, 1, 0));
  7269. this.add(cameraPY);
  7270. const cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  7271. cameraNY.layers = this.layers;
  7272. cameraNY.up.set(0, 0, -1);
  7273. cameraNY.lookAt(new Vector3(0, -1, 0));
  7274. this.add(cameraNY);
  7275. const cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  7276. cameraPZ.layers = this.layers;
  7277. cameraPZ.up.set(0, -1, 0);
  7278. cameraPZ.lookAt(new Vector3(0, 0, 1));
  7279. this.add(cameraPZ);
  7280. const cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  7281. cameraNZ.layers = this.layers;
  7282. cameraNZ.up.set(0, -1, 0);
  7283. cameraNZ.lookAt(new Vector3(0, 0, -1));
  7284. this.add(cameraNZ);
  7285. }
  7286. update(renderer, scene) {
  7287. if (this.parent === null) this.updateMatrixWorld();
  7288. const renderTarget = this.renderTarget;
  7289. const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children;
  7290. const currentXrEnabled = renderer.xr.enabled;
  7291. const currentRenderTarget = renderer.getRenderTarget();
  7292. renderer.xr.enabled = false;
  7293. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7294. renderTarget.texture.generateMipmaps = false;
  7295. renderer.setRenderTarget(renderTarget, 0);
  7296. renderer.render(scene, cameraPX);
  7297. renderer.setRenderTarget(renderTarget, 1);
  7298. renderer.render(scene, cameraNX);
  7299. renderer.setRenderTarget(renderTarget, 2);
  7300. renderer.render(scene, cameraPY);
  7301. renderer.setRenderTarget(renderTarget, 3);
  7302. renderer.render(scene, cameraNY);
  7303. renderer.setRenderTarget(renderTarget, 4);
  7304. renderer.render(scene, cameraPZ);
  7305. renderTarget.texture.generateMipmaps = generateMipmaps;
  7306. renderer.setRenderTarget(renderTarget, 5);
  7307. renderer.render(scene, cameraNZ);
  7308. renderer.setRenderTarget(currentRenderTarget);
  7309. renderer.xr.enabled = currentXrEnabled;
  7310. }
  7311. }
  7312. class CubeTexture extends Texture {
  7313. constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  7314. images = images !== undefined ? images : [];
  7315. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7316. format = format !== undefined ? format : RGBFormat;
  7317. super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding); // Why CubeTexture._needsFlipEnvMap is necessary:
  7318. //
  7319. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7320. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7321. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7322. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7323. // and the flag _needsFlipEnvMap controls this conversion. The flip is not required (and thus _needsFlipEnvMap is set to false)
  7324. // when using WebGLCubeRenderTarget.texture as a cube texture.
  7325. this._needsFlipEnvMap = true;
  7326. this.flipY = false;
  7327. }
  7328. get images() {
  7329. return this.image;
  7330. }
  7331. set images(value) {
  7332. this.image = value;
  7333. }
  7334. }
  7335. CubeTexture.prototype.isCubeTexture = true;
  7336. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7337. constructor(size, options, dummy) {
  7338. if (Number.isInteger(options)) {
  7339. console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');
  7340. options = dummy;
  7341. }
  7342. super(size, size, options);
  7343. options = options || {};
  7344. this.texture = new CubeTexture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  7345. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7346. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7347. this.texture._needsFlipEnvMap = false;
  7348. }
  7349. fromEquirectangularTexture(renderer, texture) {
  7350. this.texture.type = texture.type;
  7351. this.texture.format = RGBAFormat; // see #18859
  7352. this.texture.encoding = texture.encoding;
  7353. this.texture.generateMipmaps = texture.generateMipmaps;
  7354. this.texture.minFilter = texture.minFilter;
  7355. this.texture.magFilter = texture.magFilter;
  7356. const shader = {
  7357. uniforms: {
  7358. tEquirect: {
  7359. value: null
  7360. }
  7361. },
  7362. vertexShader:
  7363. /* glsl */
  7364. `
  7365. varying vec3 vWorldDirection;
  7366. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7367. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7368. }
  7369. void main() {
  7370. vWorldDirection = transformDirection( position, modelMatrix );
  7371. #include <begin_vertex>
  7372. #include <project_vertex>
  7373. }
  7374. `,
  7375. fragmentShader:
  7376. /* glsl */
  7377. `
  7378. uniform sampler2D tEquirect;
  7379. varying vec3 vWorldDirection;
  7380. #include <common>
  7381. void main() {
  7382. vec3 direction = normalize( vWorldDirection );
  7383. vec2 sampleUV = equirectUv( direction );
  7384. gl_FragColor = texture2D( tEquirect, sampleUV );
  7385. }
  7386. `
  7387. };
  7388. const geometry = new BoxGeometry(5, 5, 5);
  7389. const material = new ShaderMaterial({
  7390. name: 'CubemapFromEquirect',
  7391. uniforms: cloneUniforms(shader.uniforms),
  7392. vertexShader: shader.vertexShader,
  7393. fragmentShader: shader.fragmentShader,
  7394. side: BackSide,
  7395. blending: NoBlending
  7396. });
  7397. material.uniforms.tEquirect.value = texture;
  7398. const mesh = new Mesh(geometry, material);
  7399. const currentMinFilter = texture.minFilter; // Avoid blurred poles
  7400. if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
  7401. const camera = new CubeCamera(1, 10, this);
  7402. camera.update(renderer, mesh);
  7403. texture.minFilter = currentMinFilter;
  7404. mesh.geometry.dispose();
  7405. mesh.material.dispose();
  7406. return this;
  7407. }
  7408. clear(renderer, color, depth, stencil) {
  7409. const currentRenderTarget = renderer.getRenderTarget();
  7410. for (let i = 0; i < 6; i++) {
  7411. renderer.setRenderTarget(this, i);
  7412. renderer.clear(color, depth, stencil);
  7413. }
  7414. renderer.setRenderTarget(currentRenderTarget);
  7415. }
  7416. }
  7417. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  7418. const _vector1 = /*@__PURE__*/new Vector3();
  7419. const _vector2 = /*@__PURE__*/new Vector3();
  7420. const _normalMatrix = /*@__PURE__*/new Matrix3();
  7421. class Plane {
  7422. constructor(normal = new Vector3(1, 0, 0), constant = 0) {
  7423. // normal is assumed to be normalized
  7424. this.normal = normal;
  7425. this.constant = constant;
  7426. }
  7427. set(normal, constant) {
  7428. this.normal.copy(normal);
  7429. this.constant = constant;
  7430. return this;
  7431. }
  7432. setComponents(x, y, z, w) {
  7433. this.normal.set(x, y, z);
  7434. this.constant = w;
  7435. return this;
  7436. }
  7437. setFromNormalAndCoplanarPoint(normal, point) {
  7438. this.normal.copy(normal);
  7439. this.constant = -point.dot(this.normal);
  7440. return this;
  7441. }
  7442. setFromCoplanarPoints(a, b, c) {
  7443. 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)?
  7444. this.setFromNormalAndCoplanarPoint(normal, a);
  7445. return this;
  7446. }
  7447. copy(plane) {
  7448. this.normal.copy(plane.normal);
  7449. this.constant = plane.constant;
  7450. return this;
  7451. }
  7452. normalize() {
  7453. // Note: will lead to a divide by zero if the plane is invalid.
  7454. const inverseNormalLength = 1.0 / this.normal.length();
  7455. this.normal.multiplyScalar(inverseNormalLength);
  7456. this.constant *= inverseNormalLength;
  7457. return this;
  7458. }
  7459. negate() {
  7460. this.constant *= -1;
  7461. this.normal.negate();
  7462. return this;
  7463. }
  7464. distanceToPoint(point) {
  7465. return this.normal.dot(point) + this.constant;
  7466. }
  7467. distanceToSphere(sphere) {
  7468. return this.distanceToPoint(sphere.center) - sphere.radius;
  7469. }
  7470. projectPoint(point, target) {
  7471. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  7472. }
  7473. intersectLine(line, target) {
  7474. const direction = line.delta(_vector1);
  7475. const denominator = this.normal.dot(direction);
  7476. if (denominator === 0) {
  7477. // line is coplanar, return origin
  7478. if (this.distanceToPoint(line.start) === 0) {
  7479. return target.copy(line.start);
  7480. } // Unsure if this is the correct method to handle this case.
  7481. return null;
  7482. }
  7483. const t = -(line.start.dot(this.normal) + this.constant) / denominator;
  7484. if (t < 0 || t > 1) {
  7485. return null;
  7486. }
  7487. return target.copy(direction).multiplyScalar(t).add(line.start);
  7488. }
  7489. intersectsLine(line) {
  7490. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7491. const startSign = this.distanceToPoint(line.start);
  7492. const endSign = this.distanceToPoint(line.end);
  7493. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  7494. }
  7495. intersectsBox(box) {
  7496. return box.intersectsPlane(this);
  7497. }
  7498. intersectsSphere(sphere) {
  7499. return sphere.intersectsPlane(this);
  7500. }
  7501. coplanarPoint(target) {
  7502. return target.copy(this.normal).multiplyScalar(-this.constant);
  7503. }
  7504. applyMatrix4(matrix, optionalNormalMatrix) {
  7505. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  7506. const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  7507. const normal = this.normal.applyMatrix3(normalMatrix).normalize();
  7508. this.constant = -referencePoint.dot(normal);
  7509. return this;
  7510. }
  7511. translate(offset) {
  7512. this.constant -= offset.dot(this.normal);
  7513. return this;
  7514. }
  7515. equals(plane) {
  7516. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  7517. }
  7518. clone() {
  7519. return new this.constructor().copy(this);
  7520. }
  7521. }
  7522. Plane.prototype.isPlane = true;
  7523. const _sphere$2 = /*@__PURE__*/new Sphere();
  7524. const _vector$7 = /*@__PURE__*/new Vector3();
  7525. class Frustum {
  7526. constructor(p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane()) {
  7527. this.planes = [p0, p1, p2, p3, p4, p5];
  7528. }
  7529. set(p0, p1, p2, p3, p4, p5) {
  7530. const planes = this.planes;
  7531. planes[0].copy(p0);
  7532. planes[1].copy(p1);
  7533. planes[2].copy(p2);
  7534. planes[3].copy(p3);
  7535. planes[4].copy(p4);
  7536. planes[5].copy(p5);
  7537. return this;
  7538. }
  7539. copy(frustum) {
  7540. const planes = this.planes;
  7541. for (let i = 0; i < 6; i++) {
  7542. planes[i].copy(frustum.planes[i]);
  7543. }
  7544. return this;
  7545. }
  7546. setFromProjectionMatrix(m) {
  7547. const planes = this.planes;
  7548. const me = m.elements;
  7549. const me0 = me[0],
  7550. me1 = me[1],
  7551. me2 = me[2],
  7552. me3 = me[3];
  7553. const me4 = me[4],
  7554. me5 = me[5],
  7555. me6 = me[6],
  7556. me7 = me[7];
  7557. const me8 = me[8],
  7558. me9 = me[9],
  7559. me10 = me[10],
  7560. me11 = me[11];
  7561. const me12 = me[12],
  7562. me13 = me[13],
  7563. me14 = me[14],
  7564. me15 = me[15];
  7565. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  7566. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  7567. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  7568. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  7569. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  7570. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  7571. return this;
  7572. }
  7573. intersectsObject(object) {
  7574. const geometry = object.geometry;
  7575. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  7576. _sphere$2.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  7577. return this.intersectsSphere(_sphere$2);
  7578. }
  7579. intersectsSprite(sprite) {
  7580. _sphere$2.center.set(0, 0, 0);
  7581. _sphere$2.radius = 0.7071067811865476;
  7582. _sphere$2.applyMatrix4(sprite.matrixWorld);
  7583. return this.intersectsSphere(_sphere$2);
  7584. }
  7585. intersectsSphere(sphere) {
  7586. const planes = this.planes;
  7587. const center = sphere.center;
  7588. const negRadius = -sphere.radius;
  7589. for (let i = 0; i < 6; i++) {
  7590. const distance = planes[i].distanceToPoint(center);
  7591. if (distance < negRadius) {
  7592. return false;
  7593. }
  7594. }
  7595. return true;
  7596. }
  7597. intersectsBox(box) {
  7598. const planes = this.planes;
  7599. for (let i = 0; i < 6; i++) {
  7600. const plane = planes[i]; // corner at max distance
  7601. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7602. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7603. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7604. if (plane.distanceToPoint(_vector$7) < 0) {
  7605. return false;
  7606. }
  7607. }
  7608. return true;
  7609. }
  7610. containsPoint(point) {
  7611. const planes = this.planes;
  7612. for (let i = 0; i < 6; i++) {
  7613. if (planes[i].distanceToPoint(point) < 0) {
  7614. return false;
  7615. }
  7616. }
  7617. return true;
  7618. }
  7619. clone() {
  7620. return new this.constructor().copy(this);
  7621. }
  7622. }
  7623. function WebGLAnimation() {
  7624. let context = null;
  7625. let isAnimating = false;
  7626. let animationLoop = null;
  7627. let requestId = null;
  7628. function onAnimationFrame(time, frame) {
  7629. animationLoop(time, frame);
  7630. requestId = context.requestAnimationFrame(onAnimationFrame);
  7631. }
  7632. return {
  7633. start: function () {
  7634. if (isAnimating === true) return;
  7635. if (animationLoop === null) return;
  7636. requestId = context.requestAnimationFrame(onAnimationFrame);
  7637. isAnimating = true;
  7638. },
  7639. stop: function () {
  7640. context.cancelAnimationFrame(requestId);
  7641. isAnimating = false;
  7642. },
  7643. setAnimationLoop: function (callback) {
  7644. animationLoop = callback;
  7645. },
  7646. setContext: function (value) {
  7647. context = value;
  7648. }
  7649. };
  7650. }
  7651. function WebGLAttributes(gl, capabilities) {
  7652. const isWebGL2 = capabilities.isWebGL2;
  7653. const buffers = new WeakMap();
  7654. function createBuffer(attribute, bufferType) {
  7655. const array = attribute.array;
  7656. const usage = attribute.usage;
  7657. const buffer = gl.createBuffer();
  7658. gl.bindBuffer(bufferType, buffer);
  7659. gl.bufferData(bufferType, array, usage);
  7660. attribute.onUploadCallback();
  7661. let type = gl.FLOAT;
  7662. if (array instanceof Float32Array) {
  7663. type = gl.FLOAT;
  7664. } else if (array instanceof Float64Array) {
  7665. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  7666. } else if (array instanceof Uint16Array) {
  7667. if (attribute.isFloat16BufferAttribute) {
  7668. if (isWebGL2) {
  7669. type = gl.HALF_FLOAT;
  7670. } else {
  7671. console.warn('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
  7672. }
  7673. } else {
  7674. type = gl.UNSIGNED_SHORT;
  7675. }
  7676. } else if (array instanceof Int16Array) {
  7677. type = gl.SHORT;
  7678. } else if (array instanceof Uint32Array) {
  7679. type = gl.UNSIGNED_INT;
  7680. } else if (array instanceof Int32Array) {
  7681. type = gl.INT;
  7682. } else if (array instanceof Int8Array) {
  7683. type = gl.BYTE;
  7684. } else if (array instanceof Uint8Array) {
  7685. type = gl.UNSIGNED_BYTE;
  7686. } else if (array instanceof Uint8ClampedArray) {
  7687. type = gl.UNSIGNED_BYTE;
  7688. }
  7689. return {
  7690. buffer: buffer,
  7691. type: type,
  7692. bytesPerElement: array.BYTES_PER_ELEMENT,
  7693. version: attribute.version
  7694. };
  7695. }
  7696. function updateBuffer(buffer, attribute, bufferType) {
  7697. const array = attribute.array;
  7698. const updateRange = attribute.updateRange;
  7699. gl.bindBuffer(bufferType, buffer);
  7700. if (updateRange.count === -1) {
  7701. // Not using update ranges
  7702. gl.bufferSubData(bufferType, 0, array);
  7703. } else {
  7704. if (isWebGL2) {
  7705. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  7706. } else {
  7707. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  7708. }
  7709. updateRange.count = -1; // reset range
  7710. }
  7711. } //
  7712. function get(attribute) {
  7713. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7714. return buffers.get(attribute);
  7715. }
  7716. function remove(attribute) {
  7717. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7718. const data = buffers.get(attribute);
  7719. if (data) {
  7720. gl.deleteBuffer(data.buffer);
  7721. buffers.delete(attribute);
  7722. }
  7723. }
  7724. function update(attribute, bufferType) {
  7725. if (attribute.isGLBufferAttribute) {
  7726. const cached = buffers.get(attribute);
  7727. if (!cached || cached.version < attribute.version) {
  7728. buffers.set(attribute, {
  7729. buffer: attribute.buffer,
  7730. type: attribute.type,
  7731. bytesPerElement: attribute.elementSize,
  7732. version: attribute.version
  7733. });
  7734. }
  7735. return;
  7736. }
  7737. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7738. const data = buffers.get(attribute);
  7739. if (data === undefined) {
  7740. buffers.set(attribute, createBuffer(attribute, bufferType));
  7741. } else if (data.version < attribute.version) {
  7742. updateBuffer(data.buffer, attribute, bufferType);
  7743. data.version = attribute.version;
  7744. }
  7745. }
  7746. return {
  7747. get: get,
  7748. remove: remove,
  7749. update: update
  7750. };
  7751. }
  7752. class PlaneGeometry extends BufferGeometry {
  7753. constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) {
  7754. super();
  7755. this.type = 'PlaneGeometry';
  7756. this.parameters = {
  7757. width: width,
  7758. height: height,
  7759. widthSegments: widthSegments,
  7760. heightSegments: heightSegments
  7761. };
  7762. const width_half = width / 2;
  7763. const height_half = height / 2;
  7764. const gridX = Math.floor(widthSegments);
  7765. const gridY = Math.floor(heightSegments);
  7766. const gridX1 = gridX + 1;
  7767. const gridY1 = gridY + 1;
  7768. const segment_width = width / gridX;
  7769. const segment_height = height / gridY; //
  7770. const indices = [];
  7771. const vertices = [];
  7772. const normals = [];
  7773. const uvs = [];
  7774. for (let iy = 0; iy < gridY1; iy++) {
  7775. const y = iy * segment_height - height_half;
  7776. for (let ix = 0; ix < gridX1; ix++) {
  7777. const x = ix * segment_width - width_half;
  7778. vertices.push(x, -y, 0);
  7779. normals.push(0, 0, 1);
  7780. uvs.push(ix / gridX);
  7781. uvs.push(1 - iy / gridY);
  7782. }
  7783. }
  7784. for (let iy = 0; iy < gridY; iy++) {
  7785. for (let ix = 0; ix < gridX; ix++) {
  7786. const a = ix + gridX1 * iy;
  7787. const b = ix + gridX1 * (iy + 1);
  7788. const c = ix + 1 + gridX1 * (iy + 1);
  7789. const d = ix + 1 + gridX1 * iy;
  7790. indices.push(a, b, d);
  7791. indices.push(b, c, d);
  7792. }
  7793. }
  7794. this.setIndex(indices);
  7795. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  7796. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  7797. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  7798. }
  7799. static fromJSON(data) {
  7800. return new PlaneGeometry(data.width, data.height, data.widthSegments, data.heightSegments);
  7801. }
  7802. }
  7803. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7804. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7805. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  7806. 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";
  7807. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7808. var begin_vertex = "vec3 transformed = vec3( position );";
  7809. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7810. var bsdfs = "vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotVH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif";
  7811. 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";
  7812. 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";
  7813. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7814. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7815. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7816. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7817. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7818. 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";
  7819. 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";
  7820. var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat max3( vec3 v ) { return max( max( v.x, v.y ), v.z ); }\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}";
  7821. 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";
  7822. 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";
  7823. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7824. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7825. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7826. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7827. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7828. 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}";
  7829. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifndef ENVMAP_TYPE_CUBE_UV\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  7830. 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";
  7831. 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";
  7832. 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";
  7833. 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";
  7834. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = - mvPosition.z;\n#endif";
  7835. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  7836. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * fogDepth * fogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
  7837. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
  7838. 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}";
  7839. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";
  7840. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7841. 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";
  7842. 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";
  7843. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif";
  7844. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7845. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)";
  7846. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7847. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";
  7848. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.specularRoughness = max( roughnessFactor, 0.0525 );material.specularRoughness += geometryRoughness;\nmaterial.specularRoughness = min( material.specularRoughness, 1.0 );\n#ifdef REFLECTIVITY\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheen;\n#endif";
  7849. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat specularRoughness;\n\tvec3 specularColor;\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\n#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearcoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tccIrradiance *= PI;\n\t\t#endif\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(\n\t\t\tmaterial.specularRoughness,\n\t\t\tdirectLight.direction,\n\t\t\tgeometry,\n\t\t\tmaterial.sheenColor\n\t\t);\n\t#else\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularRoughness);\n\t#endif\n\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += clearcoatInv * radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  7850. 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";
  7851. 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";
  7852. 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";
  7853. 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";
  7854. 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";
  7855. 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";
  7856. 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";
  7857. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  7858. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7859. 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";
  7860. 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";
  7861. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7862. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7863. 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";
  7864. 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";
  7865. 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";
  7866. 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;";
  7867. 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";
  7868. 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";
  7869. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7870. 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";
  7871. 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";
  7872. 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}";
  7873. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7874. 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;";
  7875. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7876. 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";
  7877. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7878. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7879. 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";
  7880. 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";
  7881. 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";
  7882. 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}";
  7883. 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";
  7884. 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";
  7885. 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";
  7886. 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";
  7887. 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";
  7888. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7889. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7890. 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; }";
  7891. 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_THICKNESSNMAP\n\t\tthicknessFactor *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition.xyz / vWorldPosition.w;\n\tvec3 v = normalize( cameraPosition - pos );\n\tfloat ior = ( 1.0 + 0.4 * reflectivity ) / ( 1.0 - 0.4 * reflectivity );\n\tvec3 transmission = transmissionFactor * getIBLVolumeRefraction(\n\t\tnormal, v, roughnessFactor, material.diffuseColor, totalSpecular,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, ior, thicknessFactor,\n\t\tattenuationColor, attenuationDistance );\n\ttotalDiffuse = mix( totalDiffuse, transmission, transmissionFactor );\n#endif";
  7892. var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec4 vWorldPosition;\n\tvec3 getVolumeTransmissionRay(vec3 n, vec3 v, float thickness, float ior, mat4 modelMatrix) {\n\t\tvec3 refractionVector = refract(-v, normalize(n), 1.0 / ior);\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length(vec3(modelMatrix[0].xyz));\n\t\tmodelScale.y = length(vec3(modelMatrix[1].xyz));\n\t\tmodelScale.z = length(vec3(modelMatrix[2].xyz));\n\t\treturn normalize(refractionVector) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness(float roughness, float ior) {\n\t\treturn roughness * clamp(ior * 2.0 - 2.0, 0.0, 1.0);\n\t}\n\tvec3 getTransmissionSample(vec2 fragCoord, float roughness, float ior) {\n\t\tfloat framebufferLod = log2(transmissionSamplerSize.x) * applyIorToRoughness(roughness, ior);\n\t\treturn texture2DLodEXT(transmissionSamplerMap, fragCoord.xy, framebufferLod).rgb;\n\t}\n\tvec3 applyVolumeAttenuation(vec3 radiance, float transmissionDistance, vec3 attenuationColor, float attenuationDistance) {\n\t\tif (attenuationDistance == 0.0) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log(attenuationColor) / attenuationDistance;\n\t\t\tvec3 transmittance = exp(-attenuationCoefficient * transmissionDistance);\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec3 getIBLVolumeRefraction(vec3 n, vec3 v, float perceptualRoughness, vec3 baseColor, vec3 specularColor,\n\t\tvec3 position, mat4 modelMatrix, mat4 viewMatrix, mat4 projMatrix, float ior, float thickness,\n\t\tvec3 attenuationColor, float attenuationDistance) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay(n, v, thickness, ior, modelMatrix);\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4(refractedRayExit, 1.0);\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec3 transmittedLight = getTransmissionSample(refractionCoords, perceptualRoughness, ior);\n\t\tvec3 attenuatedColor = applyVolumeAttenuation(transmittedLight, length(transmissionRay), attenuationColor, attenuationDistance);\n\t\treturn (1.0 - specularColor) * attenuatedColor * baseColor;\n\t}\n#endif";
  7893. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7894. 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";
  7895. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7896. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7897. 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";
  7898. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7899. 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";
  7900. 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}";
  7901. 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}";
  7902. 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}";
  7903. 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}";
  7904. 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}";
  7905. 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}";
  7906. 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}";
  7907. 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}";
  7908. 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}";
  7909. 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}";
  7910. 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}";
  7911. 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}";
  7912. 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}";
  7913. var meshbasic_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  7914. 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}";
  7915. 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}";
  7916. var meshmatcap_frag = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7917. var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  7918. var meshtoon_frag = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7919. var meshtoon_vert = "#define TOON\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7920. var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  7921. var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7922. var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform vec3 attenuationColor;\n\tuniform float attenuationDistance;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <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 <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}";
  7923. var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#ifdef USE_TRANSMISSION\n\tvarying vec4 vWorldPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition;\n#endif\n}";
  7924. var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}";
  7925. var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  7926. 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}";
  7927. 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}";
  7928. 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}";
  7929. 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}";
  7930. 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}";
  7931. 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}";
  7932. const ShaderChunk = {
  7933. alphamap_fragment: alphamap_fragment,
  7934. alphamap_pars_fragment: alphamap_pars_fragment,
  7935. alphatest_fragment: alphatest_fragment,
  7936. aomap_fragment: aomap_fragment,
  7937. aomap_pars_fragment: aomap_pars_fragment,
  7938. begin_vertex: begin_vertex,
  7939. beginnormal_vertex: beginnormal_vertex,
  7940. bsdfs: bsdfs,
  7941. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7942. clipping_planes_fragment: clipping_planes_fragment,
  7943. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7944. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7945. clipping_planes_vertex: clipping_planes_vertex,
  7946. color_fragment: color_fragment,
  7947. color_pars_fragment: color_pars_fragment,
  7948. color_pars_vertex: color_pars_vertex,
  7949. color_vertex: color_vertex,
  7950. common: common,
  7951. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7952. defaultnormal_vertex: defaultnormal_vertex,
  7953. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7954. displacementmap_vertex: displacementmap_vertex,
  7955. emissivemap_fragment: emissivemap_fragment,
  7956. emissivemap_pars_fragment: emissivemap_pars_fragment,
  7957. encodings_fragment: encodings_fragment,
  7958. encodings_pars_fragment: encodings_pars_fragment,
  7959. envmap_fragment: envmap_fragment,
  7960. envmap_common_pars_fragment: envmap_common_pars_fragment,
  7961. envmap_pars_fragment: envmap_pars_fragment,
  7962. envmap_pars_vertex: envmap_pars_vertex,
  7963. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  7964. envmap_vertex: envmap_vertex,
  7965. fog_vertex: fog_vertex,
  7966. fog_pars_vertex: fog_pars_vertex,
  7967. fog_fragment: fog_fragment,
  7968. fog_pars_fragment: fog_pars_fragment,
  7969. gradientmap_pars_fragment: gradientmap_pars_fragment,
  7970. lightmap_fragment: lightmap_fragment,
  7971. lightmap_pars_fragment: lightmap_pars_fragment,
  7972. lights_lambert_vertex: lights_lambert_vertex,
  7973. lights_pars_begin: lights_pars_begin,
  7974. lights_toon_fragment: lights_toon_fragment,
  7975. lights_toon_pars_fragment: lights_toon_pars_fragment,
  7976. lights_phong_fragment: lights_phong_fragment,
  7977. lights_phong_pars_fragment: lights_phong_pars_fragment,
  7978. lights_physical_fragment: lights_physical_fragment,
  7979. lights_physical_pars_fragment: lights_physical_pars_fragment,
  7980. lights_fragment_begin: lights_fragment_begin,
  7981. lights_fragment_maps: lights_fragment_maps,
  7982. lights_fragment_end: lights_fragment_end,
  7983. logdepthbuf_fragment: logdepthbuf_fragment,
  7984. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  7985. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  7986. logdepthbuf_vertex: logdepthbuf_vertex,
  7987. map_fragment: map_fragment,
  7988. map_pars_fragment: map_pars_fragment,
  7989. map_particle_fragment: map_particle_fragment,
  7990. map_particle_pars_fragment: map_particle_pars_fragment,
  7991. metalnessmap_fragment: metalnessmap_fragment,
  7992. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  7993. morphnormal_vertex: morphnormal_vertex,
  7994. morphtarget_pars_vertex: morphtarget_pars_vertex,
  7995. morphtarget_vertex: morphtarget_vertex,
  7996. normal_fragment_begin: normal_fragment_begin,
  7997. normal_fragment_maps: normal_fragment_maps,
  7998. normalmap_pars_fragment: normalmap_pars_fragment,
  7999. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8000. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8001. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8002. packing: packing,
  8003. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8004. project_vertex: project_vertex,
  8005. dithering_fragment: dithering_fragment,
  8006. dithering_pars_fragment: dithering_pars_fragment,
  8007. roughnessmap_fragment: roughnessmap_fragment,
  8008. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8009. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8010. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8011. shadowmap_vertex: shadowmap_vertex,
  8012. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8013. skinbase_vertex: skinbase_vertex,
  8014. skinning_pars_vertex: skinning_pars_vertex,
  8015. skinning_vertex: skinning_vertex,
  8016. skinnormal_vertex: skinnormal_vertex,
  8017. specularmap_fragment: specularmap_fragment,
  8018. specularmap_pars_fragment: specularmap_pars_fragment,
  8019. tonemapping_fragment: tonemapping_fragment,
  8020. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8021. transmission_fragment: transmission_fragment,
  8022. transmission_pars_fragment: transmission_pars_fragment,
  8023. uv_pars_fragment: uv_pars_fragment,
  8024. uv_pars_vertex: uv_pars_vertex,
  8025. uv_vertex: uv_vertex,
  8026. uv2_pars_fragment: uv2_pars_fragment,
  8027. uv2_pars_vertex: uv2_pars_vertex,
  8028. uv2_vertex: uv2_vertex,
  8029. worldpos_vertex: worldpos_vertex,
  8030. background_frag: background_frag,
  8031. background_vert: background_vert,
  8032. cube_frag: cube_frag,
  8033. cube_vert: cube_vert,
  8034. depth_frag: depth_frag,
  8035. depth_vert: depth_vert,
  8036. distanceRGBA_frag: distanceRGBA_frag,
  8037. distanceRGBA_vert: distanceRGBA_vert,
  8038. equirect_frag: equirect_frag,
  8039. equirect_vert: equirect_vert,
  8040. linedashed_frag: linedashed_frag,
  8041. linedashed_vert: linedashed_vert,
  8042. meshbasic_frag: meshbasic_frag,
  8043. meshbasic_vert: meshbasic_vert,
  8044. meshlambert_frag: meshlambert_frag,
  8045. meshlambert_vert: meshlambert_vert,
  8046. meshmatcap_frag: meshmatcap_frag,
  8047. meshmatcap_vert: meshmatcap_vert,
  8048. meshtoon_frag: meshtoon_frag,
  8049. meshtoon_vert: meshtoon_vert,
  8050. meshphong_frag: meshphong_frag,
  8051. meshphong_vert: meshphong_vert,
  8052. meshphysical_frag: meshphysical_frag,
  8053. meshphysical_vert: meshphysical_vert,
  8054. normal_frag: normal_frag,
  8055. normal_vert: normal_vert,
  8056. points_frag: points_frag,
  8057. points_vert: points_vert,
  8058. shadow_frag: shadow_frag,
  8059. shadow_vert: shadow_vert,
  8060. sprite_frag: sprite_frag,
  8061. sprite_vert: sprite_vert
  8062. };
  8063. /**
  8064. * Uniforms library for shared webgl shaders
  8065. */
  8066. const UniformsLib = {
  8067. common: {
  8068. diffuse: {
  8069. value: new Color(0xffffff)
  8070. },
  8071. opacity: {
  8072. value: 1.0
  8073. },
  8074. map: {
  8075. value: null
  8076. },
  8077. uvTransform: {
  8078. value: new Matrix3()
  8079. },
  8080. uv2Transform: {
  8081. value: new Matrix3()
  8082. },
  8083. alphaMap: {
  8084. value: null
  8085. }
  8086. },
  8087. specularmap: {
  8088. specularMap: {
  8089. value: null
  8090. }
  8091. },
  8092. envmap: {
  8093. envMap: {
  8094. value: null
  8095. },
  8096. flipEnvMap: {
  8097. value: -1
  8098. },
  8099. reflectivity: {
  8100. value: 1.0
  8101. },
  8102. refractionRatio: {
  8103. value: 0.98
  8104. },
  8105. maxMipLevel: {
  8106. value: 0
  8107. }
  8108. },
  8109. aomap: {
  8110. aoMap: {
  8111. value: null
  8112. },
  8113. aoMapIntensity: {
  8114. value: 1
  8115. }
  8116. },
  8117. lightmap: {
  8118. lightMap: {
  8119. value: null
  8120. },
  8121. lightMapIntensity: {
  8122. value: 1
  8123. }
  8124. },
  8125. emissivemap: {
  8126. emissiveMap: {
  8127. value: null
  8128. }
  8129. },
  8130. bumpmap: {
  8131. bumpMap: {
  8132. value: null
  8133. },
  8134. bumpScale: {
  8135. value: 1
  8136. }
  8137. },
  8138. normalmap: {
  8139. normalMap: {
  8140. value: null
  8141. },
  8142. normalScale: {
  8143. value: new Vector2(1, 1)
  8144. }
  8145. },
  8146. displacementmap: {
  8147. displacementMap: {
  8148. value: null
  8149. },
  8150. displacementScale: {
  8151. value: 1
  8152. },
  8153. displacementBias: {
  8154. value: 0
  8155. }
  8156. },
  8157. roughnessmap: {
  8158. roughnessMap: {
  8159. value: null
  8160. }
  8161. },
  8162. metalnessmap: {
  8163. metalnessMap: {
  8164. value: null
  8165. }
  8166. },
  8167. gradientmap: {
  8168. gradientMap: {
  8169. value: null
  8170. }
  8171. },
  8172. fog: {
  8173. fogDensity: {
  8174. value: 0.00025
  8175. },
  8176. fogNear: {
  8177. value: 1
  8178. },
  8179. fogFar: {
  8180. value: 2000
  8181. },
  8182. fogColor: {
  8183. value: new Color(0xffffff)
  8184. }
  8185. },
  8186. lights: {
  8187. ambientLightColor: {
  8188. value: []
  8189. },
  8190. lightProbe: {
  8191. value: []
  8192. },
  8193. directionalLights: {
  8194. value: [],
  8195. properties: {
  8196. direction: {},
  8197. color: {}
  8198. }
  8199. },
  8200. directionalLightShadows: {
  8201. value: [],
  8202. properties: {
  8203. shadowBias: {},
  8204. shadowNormalBias: {},
  8205. shadowRadius: {},
  8206. shadowMapSize: {}
  8207. }
  8208. },
  8209. directionalShadowMap: {
  8210. value: []
  8211. },
  8212. directionalShadowMatrix: {
  8213. value: []
  8214. },
  8215. spotLights: {
  8216. value: [],
  8217. properties: {
  8218. color: {},
  8219. position: {},
  8220. direction: {},
  8221. distance: {},
  8222. coneCos: {},
  8223. penumbraCos: {},
  8224. decay: {}
  8225. }
  8226. },
  8227. spotLightShadows: {
  8228. value: [],
  8229. properties: {
  8230. shadowBias: {},
  8231. shadowNormalBias: {},
  8232. shadowRadius: {},
  8233. shadowMapSize: {}
  8234. }
  8235. },
  8236. spotShadowMap: {
  8237. value: []
  8238. },
  8239. spotShadowMatrix: {
  8240. value: []
  8241. },
  8242. pointLights: {
  8243. value: [],
  8244. properties: {
  8245. color: {},
  8246. position: {},
  8247. decay: {},
  8248. distance: {}
  8249. }
  8250. },
  8251. pointLightShadows: {
  8252. value: [],
  8253. properties: {
  8254. shadowBias: {},
  8255. shadowNormalBias: {},
  8256. shadowRadius: {},
  8257. shadowMapSize: {},
  8258. shadowCameraNear: {},
  8259. shadowCameraFar: {}
  8260. }
  8261. },
  8262. pointShadowMap: {
  8263. value: []
  8264. },
  8265. pointShadowMatrix: {
  8266. value: []
  8267. },
  8268. hemisphereLights: {
  8269. value: [],
  8270. properties: {
  8271. direction: {},
  8272. skyColor: {},
  8273. groundColor: {}
  8274. }
  8275. },
  8276. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8277. rectAreaLights: {
  8278. value: [],
  8279. properties: {
  8280. color: {},
  8281. position: {},
  8282. width: {},
  8283. height: {}
  8284. }
  8285. },
  8286. ltc_1: {
  8287. value: null
  8288. },
  8289. ltc_2: {
  8290. value: null
  8291. }
  8292. },
  8293. points: {
  8294. diffuse: {
  8295. value: new Color(0xffffff)
  8296. },
  8297. opacity: {
  8298. value: 1.0
  8299. },
  8300. size: {
  8301. value: 1.0
  8302. },
  8303. scale: {
  8304. value: 1.0
  8305. },
  8306. map: {
  8307. value: null
  8308. },
  8309. alphaMap: {
  8310. value: null
  8311. },
  8312. uvTransform: {
  8313. value: new Matrix3()
  8314. }
  8315. },
  8316. sprite: {
  8317. diffuse: {
  8318. value: new Color(0xffffff)
  8319. },
  8320. opacity: {
  8321. value: 1.0
  8322. },
  8323. center: {
  8324. value: new Vector2(0.5, 0.5)
  8325. },
  8326. rotation: {
  8327. value: 0.0
  8328. },
  8329. map: {
  8330. value: null
  8331. },
  8332. alphaMap: {
  8333. value: null
  8334. },
  8335. uvTransform: {
  8336. value: new Matrix3()
  8337. }
  8338. }
  8339. };
  8340. const ShaderLib = {
  8341. basic: {
  8342. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  8343. vertexShader: ShaderChunk.meshbasic_vert,
  8344. fragmentShader: ShaderChunk.meshbasic_frag
  8345. },
  8346. lambert: {
  8347. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  8348. emissive: {
  8349. value: new Color(0x000000)
  8350. }
  8351. }]),
  8352. vertexShader: ShaderChunk.meshlambert_vert,
  8353. fragmentShader: ShaderChunk.meshlambert_frag
  8354. },
  8355. phong: {
  8356. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  8357. emissive: {
  8358. value: new Color(0x000000)
  8359. },
  8360. specular: {
  8361. value: new Color(0x111111)
  8362. },
  8363. shininess: {
  8364. value: 30
  8365. }
  8366. }]),
  8367. vertexShader: ShaderChunk.meshphong_vert,
  8368. fragmentShader: ShaderChunk.meshphong_frag
  8369. },
  8370. standard: {
  8371. 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, {
  8372. emissive: {
  8373. value: new Color(0x000000)
  8374. },
  8375. roughness: {
  8376. value: 1.0
  8377. },
  8378. metalness: {
  8379. value: 0.0
  8380. },
  8381. envMapIntensity: {
  8382. value: 1
  8383. } // temporary
  8384. }]),
  8385. vertexShader: ShaderChunk.meshphysical_vert,
  8386. fragmentShader: ShaderChunk.meshphysical_frag
  8387. },
  8388. toon: {
  8389. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  8390. emissive: {
  8391. value: new Color(0x000000)
  8392. }
  8393. }]),
  8394. vertexShader: ShaderChunk.meshtoon_vert,
  8395. fragmentShader: ShaderChunk.meshtoon_frag
  8396. },
  8397. matcap: {
  8398. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  8399. matcap: {
  8400. value: null
  8401. }
  8402. }]),
  8403. vertexShader: ShaderChunk.meshmatcap_vert,
  8404. fragmentShader: ShaderChunk.meshmatcap_frag
  8405. },
  8406. points: {
  8407. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  8408. vertexShader: ShaderChunk.points_vert,
  8409. fragmentShader: ShaderChunk.points_frag
  8410. },
  8411. dashed: {
  8412. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  8413. scale: {
  8414. value: 1
  8415. },
  8416. dashSize: {
  8417. value: 1
  8418. },
  8419. totalSize: {
  8420. value: 2
  8421. }
  8422. }]),
  8423. vertexShader: ShaderChunk.linedashed_vert,
  8424. fragmentShader: ShaderChunk.linedashed_frag
  8425. },
  8426. depth: {
  8427. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  8428. vertexShader: ShaderChunk.depth_vert,
  8429. fragmentShader: ShaderChunk.depth_frag
  8430. },
  8431. normal: {
  8432. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  8433. opacity: {
  8434. value: 1.0
  8435. }
  8436. }]),
  8437. vertexShader: ShaderChunk.normal_vert,
  8438. fragmentShader: ShaderChunk.normal_frag
  8439. },
  8440. sprite: {
  8441. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  8442. vertexShader: ShaderChunk.sprite_vert,
  8443. fragmentShader: ShaderChunk.sprite_frag
  8444. },
  8445. background: {
  8446. uniforms: {
  8447. uvTransform: {
  8448. value: new Matrix3()
  8449. },
  8450. t2D: {
  8451. value: null
  8452. }
  8453. },
  8454. vertexShader: ShaderChunk.background_vert,
  8455. fragmentShader: ShaderChunk.background_frag
  8456. },
  8457. /* -------------------------------------------------------------------------
  8458. // Cube map shader
  8459. ------------------------------------------------------------------------- */
  8460. cube: {
  8461. uniforms: mergeUniforms([UniformsLib.envmap, {
  8462. opacity: {
  8463. value: 1.0
  8464. }
  8465. }]),
  8466. vertexShader: ShaderChunk.cube_vert,
  8467. fragmentShader: ShaderChunk.cube_frag
  8468. },
  8469. equirect: {
  8470. uniforms: {
  8471. tEquirect: {
  8472. value: null
  8473. }
  8474. },
  8475. vertexShader: ShaderChunk.equirect_vert,
  8476. fragmentShader: ShaderChunk.equirect_frag
  8477. },
  8478. distanceRGBA: {
  8479. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  8480. referencePosition: {
  8481. value: new Vector3()
  8482. },
  8483. nearDistance: {
  8484. value: 1
  8485. },
  8486. farDistance: {
  8487. value: 1000
  8488. }
  8489. }]),
  8490. vertexShader: ShaderChunk.distanceRGBA_vert,
  8491. fragmentShader: ShaderChunk.distanceRGBA_frag
  8492. },
  8493. shadow: {
  8494. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  8495. color: {
  8496. value: new Color(0x00000)
  8497. },
  8498. opacity: {
  8499. value: 1.0
  8500. }
  8501. }]),
  8502. vertexShader: ShaderChunk.shadow_vert,
  8503. fragmentShader: ShaderChunk.shadow_frag
  8504. }
  8505. };
  8506. ShaderLib.physical = {
  8507. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  8508. clearcoat: {
  8509. value: 0
  8510. },
  8511. clearcoatMap: {
  8512. value: null
  8513. },
  8514. clearcoatRoughness: {
  8515. value: 0
  8516. },
  8517. clearcoatRoughnessMap: {
  8518. value: null
  8519. },
  8520. clearcoatNormalScale: {
  8521. value: new Vector2(1, 1)
  8522. },
  8523. clearcoatNormalMap: {
  8524. value: null
  8525. },
  8526. sheen: {
  8527. value: new Color(0x000000)
  8528. },
  8529. transmission: {
  8530. value: 0
  8531. },
  8532. transmissionMap: {
  8533. value: null
  8534. },
  8535. transmissionSamplerSize: {
  8536. value: new Vector2()
  8537. },
  8538. transmissionSamplerMap: {
  8539. value: null
  8540. },
  8541. thickness: {
  8542. value: 0
  8543. },
  8544. thicknessMap: {
  8545. value: null
  8546. },
  8547. attenuationDistance: {
  8548. value: 0
  8549. },
  8550. attenuationColor: {
  8551. value: new Color(0x000000)
  8552. }
  8553. }]),
  8554. vertexShader: ShaderChunk.meshphysical_vert,
  8555. fragmentShader: ShaderChunk.meshphysical_frag
  8556. };
  8557. function WebGLBackground(renderer, cubemaps, state, objects, premultipliedAlpha) {
  8558. const clearColor = new Color(0x000000);
  8559. let clearAlpha = 0;
  8560. let planeMesh;
  8561. let boxMesh;
  8562. let currentBackground = null;
  8563. let currentBackgroundVersion = 0;
  8564. let currentTonemapping = null;
  8565. function render(renderList, scene) {
  8566. let forceClear = false;
  8567. let background = scene.isScene === true ? scene.background : null;
  8568. if (background && background.isTexture) {
  8569. background = cubemaps.get(background);
  8570. } // Ignore background in AR
  8571. // TODO: Reconsider this.
  8572. const xr = renderer.xr;
  8573. const session = xr.getSession && xr.getSession();
  8574. if (session && session.environmentBlendMode === 'additive') {
  8575. background = null;
  8576. }
  8577. if (background === null) {
  8578. setClear(clearColor, clearAlpha);
  8579. } else if (background && background.isColor) {
  8580. setClear(background, 1);
  8581. forceClear = true;
  8582. }
  8583. if (renderer.autoClear || forceClear) {
  8584. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  8585. }
  8586. if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) {
  8587. if (boxMesh === undefined) {
  8588. boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({
  8589. name: 'BackgroundCubeMaterial',
  8590. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  8591. vertexShader: ShaderLib.cube.vertexShader,
  8592. fragmentShader: ShaderLib.cube.fragmentShader,
  8593. side: BackSide,
  8594. depthTest: false,
  8595. depthWrite: false,
  8596. fog: false
  8597. }));
  8598. boxMesh.geometry.deleteAttribute('normal');
  8599. boxMesh.geometry.deleteAttribute('uv');
  8600. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  8601. this.matrixWorld.copyPosition(camera.matrixWorld);
  8602. }; // enable code injection for non-built-in material
  8603. Object.defineProperty(boxMesh.material, 'envMap', {
  8604. get: function () {
  8605. return this.uniforms.envMap.value;
  8606. }
  8607. });
  8608. objects.update(boxMesh);
  8609. }
  8610. boxMesh.material.uniforms.envMap.value = background;
  8611. boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background._needsFlipEnvMap ? -1 : 1;
  8612. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8613. boxMesh.material.needsUpdate = true;
  8614. currentBackground = background;
  8615. currentBackgroundVersion = background.version;
  8616. currentTonemapping = renderer.toneMapping;
  8617. } // push to the pre-sorted opaque render list
  8618. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  8619. } else if (background && background.isTexture) {
  8620. if (planeMesh === undefined) {
  8621. planeMesh = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({
  8622. name: 'BackgroundMaterial',
  8623. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  8624. vertexShader: ShaderLib.background.vertexShader,
  8625. fragmentShader: ShaderLib.background.fragmentShader,
  8626. side: FrontSide,
  8627. depthTest: false,
  8628. depthWrite: false,
  8629. fog: false
  8630. }));
  8631. planeMesh.geometry.deleteAttribute('normal'); // enable code injection for non-built-in material
  8632. Object.defineProperty(planeMesh.material, 'map', {
  8633. get: function () {
  8634. return this.uniforms.t2D.value;
  8635. }
  8636. });
  8637. objects.update(planeMesh);
  8638. }
  8639. planeMesh.material.uniforms.t2D.value = background;
  8640. if (background.matrixAutoUpdate === true) {
  8641. background.updateMatrix();
  8642. }
  8643. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  8644. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8645. planeMesh.material.needsUpdate = true;
  8646. currentBackground = background;
  8647. currentBackgroundVersion = background.version;
  8648. currentTonemapping = renderer.toneMapping;
  8649. } // push to the pre-sorted opaque render list
  8650. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  8651. }
  8652. }
  8653. function setClear(color, alpha) {
  8654. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  8655. }
  8656. return {
  8657. getClearColor: function () {
  8658. return clearColor;
  8659. },
  8660. setClearColor: function (color, alpha = 1) {
  8661. clearColor.set(color);
  8662. clearAlpha = alpha;
  8663. setClear(clearColor, clearAlpha);
  8664. },
  8665. getClearAlpha: function () {
  8666. return clearAlpha;
  8667. },
  8668. setClearAlpha: function (alpha) {
  8669. clearAlpha = alpha;
  8670. setClear(clearColor, clearAlpha);
  8671. },
  8672. render: render
  8673. };
  8674. }
  8675. function WebGLBindingStates(gl, extensions, attributes, capabilities) {
  8676. const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  8677. const extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
  8678. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8679. const bindingStates = {};
  8680. const defaultState = createBindingState(null);
  8681. let currentState = defaultState;
  8682. function setup(object, material, program, geometry, index) {
  8683. let updateBuffers = false;
  8684. if (vaoAvailable) {
  8685. const state = getBindingState(geometry, program, material);
  8686. if (currentState !== state) {
  8687. currentState = state;
  8688. bindVertexArrayObject(currentState.object);
  8689. }
  8690. updateBuffers = needsUpdate(geometry, index);
  8691. if (updateBuffers) saveCache(geometry, index);
  8692. } else {
  8693. const wireframe = material.wireframe === true;
  8694. if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
  8695. currentState.geometry = geometry.id;
  8696. currentState.program = program.id;
  8697. currentState.wireframe = wireframe;
  8698. updateBuffers = true;
  8699. }
  8700. }
  8701. if (object.isInstancedMesh === true) {
  8702. updateBuffers = true;
  8703. }
  8704. if (index !== null) {
  8705. attributes.update(index, gl.ELEMENT_ARRAY_BUFFER);
  8706. }
  8707. if (updateBuffers) {
  8708. setupVertexAttributes(object, material, program, geometry);
  8709. if (index !== null) {
  8710. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index).buffer);
  8711. }
  8712. }
  8713. }
  8714. function createVertexArrayObject() {
  8715. if (capabilities.isWebGL2) return gl.createVertexArray();
  8716. return extension.createVertexArrayOES();
  8717. }
  8718. function bindVertexArrayObject(vao) {
  8719. if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
  8720. return extension.bindVertexArrayOES(vao);
  8721. }
  8722. function deleteVertexArrayObject(vao) {
  8723. if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
  8724. return extension.deleteVertexArrayOES(vao);
  8725. }
  8726. function getBindingState(geometry, program, material) {
  8727. const wireframe = material.wireframe === true;
  8728. let programMap = bindingStates[geometry.id];
  8729. if (programMap === undefined) {
  8730. programMap = {};
  8731. bindingStates[geometry.id] = programMap;
  8732. }
  8733. let stateMap = programMap[program.id];
  8734. if (stateMap === undefined) {
  8735. stateMap = {};
  8736. programMap[program.id] = stateMap;
  8737. }
  8738. let state = stateMap[wireframe];
  8739. if (state === undefined) {
  8740. state = createBindingState(createVertexArrayObject());
  8741. stateMap[wireframe] = state;
  8742. }
  8743. return state;
  8744. }
  8745. function createBindingState(vao) {
  8746. const newAttributes = [];
  8747. const enabledAttributes = [];
  8748. const attributeDivisors = [];
  8749. for (let i = 0; i < maxVertexAttributes; i++) {
  8750. newAttributes[i] = 0;
  8751. enabledAttributes[i] = 0;
  8752. attributeDivisors[i] = 0;
  8753. }
  8754. return {
  8755. // for backward compatibility on non-VAO support browser
  8756. geometry: null,
  8757. program: null,
  8758. wireframe: false,
  8759. newAttributes: newAttributes,
  8760. enabledAttributes: enabledAttributes,
  8761. attributeDivisors: attributeDivisors,
  8762. object: vao,
  8763. attributes: {},
  8764. index: null
  8765. };
  8766. }
  8767. function needsUpdate(geometry, index) {
  8768. const cachedAttributes = currentState.attributes;
  8769. const geometryAttributes = geometry.attributes;
  8770. let attributesNum = 0;
  8771. for (const key in geometryAttributes) {
  8772. const cachedAttribute = cachedAttributes[key];
  8773. const geometryAttribute = geometryAttributes[key];
  8774. if (cachedAttribute === undefined) return true;
  8775. if (cachedAttribute.attribute !== geometryAttribute) return true;
  8776. if (cachedAttribute.data !== geometryAttribute.data) return true;
  8777. attributesNum++;
  8778. }
  8779. if (currentState.attributesNum !== attributesNum) return true;
  8780. if (currentState.index !== index) return true;
  8781. return false;
  8782. }
  8783. function saveCache(geometry, index) {
  8784. const cache = {};
  8785. const attributes = geometry.attributes;
  8786. let attributesNum = 0;
  8787. for (const key in attributes) {
  8788. const attribute = attributes[key];
  8789. const data = {};
  8790. data.attribute = attribute;
  8791. if (attribute.data) {
  8792. data.data = attribute.data;
  8793. }
  8794. cache[key] = data;
  8795. attributesNum++;
  8796. }
  8797. currentState.attributes = cache;
  8798. currentState.attributesNum = attributesNum;
  8799. currentState.index = index;
  8800. }
  8801. function initAttributes() {
  8802. const newAttributes = currentState.newAttributes;
  8803. for (let i = 0, il = newAttributes.length; i < il; i++) {
  8804. newAttributes[i] = 0;
  8805. }
  8806. }
  8807. function enableAttribute(attribute) {
  8808. enableAttributeAndDivisor(attribute, 0);
  8809. }
  8810. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  8811. const newAttributes = currentState.newAttributes;
  8812. const enabledAttributes = currentState.enabledAttributes;
  8813. const attributeDivisors = currentState.attributeDivisors;
  8814. newAttributes[attribute] = 1;
  8815. if (enabledAttributes[attribute] === 0) {
  8816. gl.enableVertexAttribArray(attribute);
  8817. enabledAttributes[attribute] = 1;
  8818. }
  8819. if (attributeDivisors[attribute] !== meshPerAttribute) {
  8820. const extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  8821. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  8822. attributeDivisors[attribute] = meshPerAttribute;
  8823. }
  8824. }
  8825. function disableUnusedAttributes() {
  8826. const newAttributes = currentState.newAttributes;
  8827. const enabledAttributes = currentState.enabledAttributes;
  8828. for (let i = 0, il = enabledAttributes.length; i < il; i++) {
  8829. if (enabledAttributes[i] !== newAttributes[i]) {
  8830. gl.disableVertexAttribArray(i);
  8831. enabledAttributes[i] = 0;
  8832. }
  8833. }
  8834. }
  8835. function vertexAttribPointer(index, size, type, normalized, stride, offset) {
  8836. if (capabilities.isWebGL2 === true && (type === gl.INT || type === gl.UNSIGNED_INT)) {
  8837. gl.vertexAttribIPointer(index, size, type, stride, offset);
  8838. } else {
  8839. gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
  8840. }
  8841. }
  8842. function setupVertexAttributes(object, material, program, geometry) {
  8843. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  8844. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  8845. }
  8846. initAttributes();
  8847. const geometryAttributes = geometry.attributes;
  8848. const programAttributes = program.getAttributes();
  8849. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8850. for (const name in programAttributes) {
  8851. const programAttribute = programAttributes[name];
  8852. if (programAttribute >= 0) {
  8853. const geometryAttribute = geometryAttributes[name];
  8854. if (geometryAttribute !== undefined) {
  8855. const normalized = geometryAttribute.normalized;
  8856. const size = geometryAttribute.itemSize;
  8857. const attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  8858. if (attribute === undefined) continue;
  8859. const buffer = attribute.buffer;
  8860. const type = attribute.type;
  8861. const bytesPerElement = attribute.bytesPerElement;
  8862. if (geometryAttribute.isInterleavedBufferAttribute) {
  8863. const data = geometryAttribute.data;
  8864. const stride = data.stride;
  8865. const offset = geometryAttribute.offset;
  8866. if (data && data.isInstancedInterleavedBuffer) {
  8867. enableAttributeAndDivisor(programAttribute, data.meshPerAttribute);
  8868. if (geometry._maxInstanceCount === undefined) {
  8869. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8870. }
  8871. } else {
  8872. enableAttribute(programAttribute);
  8873. }
  8874. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8875. vertexAttribPointer(programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement);
  8876. } else {
  8877. if (geometryAttribute.isInstancedBufferAttribute) {
  8878. enableAttributeAndDivisor(programAttribute, geometryAttribute.meshPerAttribute);
  8879. if (geometry._maxInstanceCount === undefined) {
  8880. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8881. }
  8882. } else {
  8883. enableAttribute(programAttribute);
  8884. }
  8885. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8886. vertexAttribPointer(programAttribute, size, type, normalized, 0, 0);
  8887. }
  8888. } else if (name === 'instanceMatrix') {
  8889. const attribute = attributes.get(object.instanceMatrix); // TODO Attribute may not be available on context restore
  8890. if (attribute === undefined) continue;
  8891. const buffer = attribute.buffer;
  8892. const type = attribute.type;
  8893. enableAttributeAndDivisor(programAttribute + 0, 1);
  8894. enableAttributeAndDivisor(programAttribute + 1, 1);
  8895. enableAttributeAndDivisor(programAttribute + 2, 1);
  8896. enableAttributeAndDivisor(programAttribute + 3, 1);
  8897. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8898. gl.vertexAttribPointer(programAttribute + 0, 4, type, false, 64, 0);
  8899. gl.vertexAttribPointer(programAttribute + 1, 4, type, false, 64, 16);
  8900. gl.vertexAttribPointer(programAttribute + 2, 4, type, false, 64, 32);
  8901. gl.vertexAttribPointer(programAttribute + 3, 4, type, false, 64, 48);
  8902. } else if (name === 'instanceColor') {
  8903. const attribute = attributes.get(object.instanceColor); // TODO Attribute may not be available on context restore
  8904. if (attribute === undefined) continue;
  8905. const buffer = attribute.buffer;
  8906. const type = attribute.type;
  8907. enableAttributeAndDivisor(programAttribute, 1);
  8908. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8909. gl.vertexAttribPointer(programAttribute, 3, type, false, 12, 0);
  8910. } else if (materialDefaultAttributeValues !== undefined) {
  8911. const value = materialDefaultAttributeValues[name];
  8912. if (value !== undefined) {
  8913. switch (value.length) {
  8914. case 2:
  8915. gl.vertexAttrib2fv(programAttribute, value);
  8916. break;
  8917. case 3:
  8918. gl.vertexAttrib3fv(programAttribute, value);
  8919. break;
  8920. case 4:
  8921. gl.vertexAttrib4fv(programAttribute, value);
  8922. break;
  8923. default:
  8924. gl.vertexAttrib1fv(programAttribute, value);
  8925. }
  8926. }
  8927. }
  8928. }
  8929. }
  8930. disableUnusedAttributes();
  8931. }
  8932. function dispose() {
  8933. reset();
  8934. for (const geometryId in bindingStates) {
  8935. const programMap = bindingStates[geometryId];
  8936. for (const programId in programMap) {
  8937. const stateMap = programMap[programId];
  8938. for (const wireframe in stateMap) {
  8939. deleteVertexArrayObject(stateMap[wireframe].object);
  8940. delete stateMap[wireframe];
  8941. }
  8942. delete programMap[programId];
  8943. }
  8944. delete bindingStates[geometryId];
  8945. }
  8946. }
  8947. function releaseStatesOfGeometry(geometry) {
  8948. if (bindingStates[geometry.id] === undefined) return;
  8949. const programMap = bindingStates[geometry.id];
  8950. for (const programId in programMap) {
  8951. const stateMap = programMap[programId];
  8952. for (const wireframe in stateMap) {
  8953. deleteVertexArrayObject(stateMap[wireframe].object);
  8954. delete stateMap[wireframe];
  8955. }
  8956. delete programMap[programId];
  8957. }
  8958. delete bindingStates[geometry.id];
  8959. }
  8960. function releaseStatesOfProgram(program) {
  8961. for (const geometryId in bindingStates) {
  8962. const programMap = bindingStates[geometryId];
  8963. if (programMap[program.id] === undefined) continue;
  8964. const stateMap = programMap[program.id];
  8965. for (const wireframe in stateMap) {
  8966. deleteVertexArrayObject(stateMap[wireframe].object);
  8967. delete stateMap[wireframe];
  8968. }
  8969. delete programMap[program.id];
  8970. }
  8971. }
  8972. function reset() {
  8973. resetDefaultState();
  8974. if (currentState === defaultState) return;
  8975. currentState = defaultState;
  8976. bindVertexArrayObject(currentState.object);
  8977. } // for backward-compatilibity
  8978. function resetDefaultState() {
  8979. defaultState.geometry = null;
  8980. defaultState.program = null;
  8981. defaultState.wireframe = false;
  8982. }
  8983. return {
  8984. setup: setup,
  8985. reset: reset,
  8986. resetDefaultState: resetDefaultState,
  8987. dispose: dispose,
  8988. releaseStatesOfGeometry: releaseStatesOfGeometry,
  8989. releaseStatesOfProgram: releaseStatesOfProgram,
  8990. initAttributes: initAttributes,
  8991. enableAttribute: enableAttribute,
  8992. disableUnusedAttributes: disableUnusedAttributes
  8993. };
  8994. }
  8995. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  8996. const isWebGL2 = capabilities.isWebGL2;
  8997. let mode;
  8998. function setMode(value) {
  8999. mode = value;
  9000. }
  9001. function render(start, count) {
  9002. gl.drawArrays(mode, start, count);
  9003. info.update(count, mode, 1);
  9004. }
  9005. function renderInstances(start, count, primcount) {
  9006. if (primcount === 0) return;
  9007. let extension, methodName;
  9008. if (isWebGL2) {
  9009. extension = gl;
  9010. methodName = 'drawArraysInstanced';
  9011. } else {
  9012. extension = extensions.get('ANGLE_instanced_arrays');
  9013. methodName = 'drawArraysInstancedANGLE';
  9014. if (extension === null) {
  9015. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9016. return;
  9017. }
  9018. }
  9019. extension[methodName](mode, start, count, primcount);
  9020. info.update(count, mode, primcount);
  9021. } //
  9022. this.setMode = setMode;
  9023. this.render = render;
  9024. this.renderInstances = renderInstances;
  9025. }
  9026. function WebGLCapabilities(gl, extensions, parameters) {
  9027. let maxAnisotropy;
  9028. function getMaxAnisotropy() {
  9029. if (maxAnisotropy !== undefined) return maxAnisotropy;
  9030. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  9031. const extension = extensions.get('EXT_texture_filter_anisotropic');
  9032. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  9033. } else {
  9034. maxAnisotropy = 0;
  9035. }
  9036. return maxAnisotropy;
  9037. }
  9038. function getMaxPrecision(precision) {
  9039. if (precision === 'highp') {
  9040. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) {
  9041. return 'highp';
  9042. }
  9043. precision = 'mediump';
  9044. }
  9045. if (precision === 'mediump') {
  9046. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) {
  9047. return 'mediump';
  9048. }
  9049. }
  9050. return 'lowp';
  9051. }
  9052. /* eslint-disable no-undef */
  9053. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  9054. /* eslint-enable no-undef */
  9055. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9056. const maxPrecision = getMaxPrecision(precision);
  9057. if (maxPrecision !== precision) {
  9058. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  9059. precision = maxPrecision;
  9060. }
  9061. const drawBuffers = isWebGL2 || extensions.has('WEBGL_draw_buffers');
  9062. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9063. const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
  9064. const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9065. const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
  9066. const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9067. const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  9068. const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
  9069. const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS);
  9070. const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9071. const vertexTextures = maxVertexTextures > 0;
  9072. const floatFragmentTextures = isWebGL2 || extensions.has('OES_texture_float');
  9073. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9074. const maxSamples = isWebGL2 ? gl.getParameter(gl.MAX_SAMPLES) : 0;
  9075. return {
  9076. isWebGL2: isWebGL2,
  9077. drawBuffers: drawBuffers,
  9078. getMaxAnisotropy: getMaxAnisotropy,
  9079. getMaxPrecision: getMaxPrecision,
  9080. precision: precision,
  9081. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9082. maxTextures: maxTextures,
  9083. maxVertexTextures: maxVertexTextures,
  9084. maxTextureSize: maxTextureSize,
  9085. maxCubemapSize: maxCubemapSize,
  9086. maxAttributes: maxAttributes,
  9087. maxVertexUniforms: maxVertexUniforms,
  9088. maxVaryings: maxVaryings,
  9089. maxFragmentUniforms: maxFragmentUniforms,
  9090. vertexTextures: vertexTextures,
  9091. floatFragmentTextures: floatFragmentTextures,
  9092. floatVertexTextures: floatVertexTextures,
  9093. maxSamples: maxSamples
  9094. };
  9095. }
  9096. function WebGLClipping(properties) {
  9097. const scope = this;
  9098. let globalState = null,
  9099. numGlobalPlanes = 0,
  9100. localClippingEnabled = false,
  9101. renderingShadows = false;
  9102. const plane = new Plane(),
  9103. viewNormalMatrix = new Matrix3(),
  9104. uniform = {
  9105. value: null,
  9106. needsUpdate: false
  9107. };
  9108. this.uniform = uniform;
  9109. this.numPlanes = 0;
  9110. this.numIntersection = 0;
  9111. this.init = function (planes, enableLocalClipping, camera) {
  9112. const enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  9113. // run another frame in order to reset the state:
  9114. numGlobalPlanes !== 0 || localClippingEnabled;
  9115. localClippingEnabled = enableLocalClipping;
  9116. globalState = projectPlanes(planes, camera, 0);
  9117. numGlobalPlanes = planes.length;
  9118. return enabled;
  9119. };
  9120. this.beginShadows = function () {
  9121. renderingShadows = true;
  9122. projectPlanes(null);
  9123. };
  9124. this.endShadows = function () {
  9125. renderingShadows = false;
  9126. resetGlobalState();
  9127. };
  9128. this.setState = function (material, camera, useCache) {
  9129. const planes = material.clippingPlanes,
  9130. clipIntersection = material.clipIntersection,
  9131. clipShadows = material.clipShadows;
  9132. const materialProperties = properties.get(material);
  9133. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  9134. // there's no local clipping
  9135. if (renderingShadows) {
  9136. // there's no global clipping
  9137. projectPlanes(null);
  9138. } else {
  9139. resetGlobalState();
  9140. }
  9141. } else {
  9142. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9143. lGlobal = nGlobal * 4;
  9144. let dstArray = materialProperties.clippingState || null;
  9145. uniform.value = dstArray; // ensure unique state
  9146. dstArray = projectPlanes(planes, camera, lGlobal, useCache);
  9147. for (let i = 0; i !== lGlobal; ++i) {
  9148. dstArray[i] = globalState[i];
  9149. }
  9150. materialProperties.clippingState = dstArray;
  9151. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9152. this.numPlanes += nGlobal;
  9153. }
  9154. };
  9155. function resetGlobalState() {
  9156. if (uniform.value !== globalState) {
  9157. uniform.value = globalState;
  9158. uniform.needsUpdate = numGlobalPlanes > 0;
  9159. }
  9160. scope.numPlanes = numGlobalPlanes;
  9161. scope.numIntersection = 0;
  9162. }
  9163. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  9164. const nPlanes = planes !== null ? planes.length : 0;
  9165. let dstArray = null;
  9166. if (nPlanes !== 0) {
  9167. dstArray = uniform.value;
  9168. if (skipTransform !== true || dstArray === null) {
  9169. const flatSize = dstOffset + nPlanes * 4,
  9170. viewMatrix = camera.matrixWorldInverse;
  9171. viewNormalMatrix.getNormalMatrix(viewMatrix);
  9172. if (dstArray === null || dstArray.length < flatSize) {
  9173. dstArray = new Float32Array(flatSize);
  9174. }
  9175. for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  9176. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  9177. plane.normal.toArray(dstArray, i4);
  9178. dstArray[i4 + 3] = plane.constant;
  9179. }
  9180. }
  9181. uniform.value = dstArray;
  9182. uniform.needsUpdate = true;
  9183. }
  9184. scope.numPlanes = nPlanes;
  9185. scope.numIntersection = 0;
  9186. return dstArray;
  9187. }
  9188. }
  9189. function WebGLCubeMaps(renderer) {
  9190. let cubemaps = new WeakMap();
  9191. function mapTextureMapping(texture, mapping) {
  9192. if (mapping === EquirectangularReflectionMapping) {
  9193. texture.mapping = CubeReflectionMapping;
  9194. } else if (mapping === EquirectangularRefractionMapping) {
  9195. texture.mapping = CubeRefractionMapping;
  9196. }
  9197. return texture;
  9198. }
  9199. function get(texture) {
  9200. if (texture && texture.isTexture) {
  9201. const mapping = texture.mapping;
  9202. if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
  9203. if (cubemaps.has(texture)) {
  9204. const cubemap = cubemaps.get(texture).texture;
  9205. return mapTextureMapping(cubemap, texture.mapping);
  9206. } else {
  9207. const image = texture.image;
  9208. if (image && image.height > 0) {
  9209. const currentRenderTarget = renderer.getRenderTarget();
  9210. const renderTarget = new WebGLCubeRenderTarget(image.height / 2);
  9211. renderTarget.fromEquirectangularTexture(renderer, texture);
  9212. cubemaps.set(texture, renderTarget);
  9213. renderer.setRenderTarget(currentRenderTarget);
  9214. texture.addEventListener('dispose', onTextureDispose);
  9215. return mapTextureMapping(renderTarget.texture, texture.mapping);
  9216. } else {
  9217. // image not yet ready. try the conversion next frame
  9218. return null;
  9219. }
  9220. }
  9221. }
  9222. }
  9223. return texture;
  9224. }
  9225. function onTextureDispose(event) {
  9226. const texture = event.target;
  9227. texture.removeEventListener('dispose', onTextureDispose);
  9228. const cubemap = cubemaps.get(texture);
  9229. if (cubemap !== undefined) {
  9230. cubemaps.delete(texture);
  9231. cubemap.dispose();
  9232. }
  9233. }
  9234. function dispose() {
  9235. cubemaps = new WeakMap();
  9236. }
  9237. return {
  9238. get: get,
  9239. dispose: dispose
  9240. };
  9241. }
  9242. function WebGLExtensions(gl) {
  9243. const extensions = {};
  9244. function getExtension(name) {
  9245. if (extensions[name] !== undefined) {
  9246. return extensions[name];
  9247. }
  9248. let extension;
  9249. switch (name) {
  9250. case 'WEBGL_depth_texture':
  9251. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  9252. break;
  9253. case 'EXT_texture_filter_anisotropic':
  9254. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  9255. break;
  9256. case 'WEBGL_compressed_texture_s3tc':
  9257. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  9258. break;
  9259. case 'WEBGL_compressed_texture_pvrtc':
  9260. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  9261. break;
  9262. default:
  9263. extension = gl.getExtension(name);
  9264. }
  9265. extensions[name] = extension;
  9266. return extension;
  9267. }
  9268. return {
  9269. has: function (name) {
  9270. return getExtension(name) !== null;
  9271. },
  9272. init: function (capabilities) {
  9273. if (capabilities.isWebGL2) {
  9274. getExtension('EXT_color_buffer_float');
  9275. } else {
  9276. getExtension('WEBGL_depth_texture');
  9277. getExtension('OES_texture_float');
  9278. getExtension('OES_texture_half_float');
  9279. getExtension('OES_texture_half_float_linear');
  9280. getExtension('OES_standard_derivatives');
  9281. getExtension('OES_element_index_uint');
  9282. getExtension('OES_vertex_array_object');
  9283. getExtension('ANGLE_instanced_arrays');
  9284. }
  9285. getExtension('OES_texture_float_linear');
  9286. getExtension('EXT_color_buffer_half_float');
  9287. },
  9288. get: function (name) {
  9289. const extension = getExtension(name);
  9290. if (extension === null) {
  9291. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  9292. }
  9293. return extension;
  9294. }
  9295. };
  9296. }
  9297. function WebGLGeometries(gl, attributes, info, bindingStates) {
  9298. const geometries = {};
  9299. const wireframeAttributes = new WeakMap();
  9300. function onGeometryDispose(event) {
  9301. const geometry = event.target;
  9302. if (geometry.index !== null) {
  9303. attributes.remove(geometry.index);
  9304. }
  9305. for (const name in geometry.attributes) {
  9306. attributes.remove(geometry.attributes[name]);
  9307. }
  9308. geometry.removeEventListener('dispose', onGeometryDispose);
  9309. delete geometries[geometry.id];
  9310. const attribute = wireframeAttributes.get(geometry);
  9311. if (attribute) {
  9312. attributes.remove(attribute);
  9313. wireframeAttributes.delete(geometry);
  9314. }
  9315. bindingStates.releaseStatesOfGeometry(geometry);
  9316. if (geometry.isInstancedBufferGeometry === true) {
  9317. delete geometry._maxInstanceCount;
  9318. } //
  9319. info.memory.geometries--;
  9320. }
  9321. function get(object, geometry) {
  9322. if (geometries[geometry.id] === true) return geometry;
  9323. geometry.addEventListener('dispose', onGeometryDispose);
  9324. geometries[geometry.id] = true;
  9325. info.memory.geometries++;
  9326. return geometry;
  9327. }
  9328. function update(geometry) {
  9329. const geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates.
  9330. for (const name in geometryAttributes) {
  9331. attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER);
  9332. } // morph targets
  9333. const morphAttributes = geometry.morphAttributes;
  9334. for (const name in morphAttributes) {
  9335. const array = morphAttributes[name];
  9336. for (let i = 0, l = array.length; i < l; i++) {
  9337. attributes.update(array[i], gl.ARRAY_BUFFER);
  9338. }
  9339. }
  9340. }
  9341. function updateWireframeAttribute(geometry) {
  9342. const indices = [];
  9343. const geometryIndex = geometry.index;
  9344. const geometryPosition = geometry.attributes.position;
  9345. let version = 0;
  9346. if (geometryIndex !== null) {
  9347. const array = geometryIndex.array;
  9348. version = geometryIndex.version;
  9349. for (let i = 0, l = array.length; i < l; i += 3) {
  9350. const a = array[i + 0];
  9351. const b = array[i + 1];
  9352. const c = array[i + 2];
  9353. indices.push(a, b, b, c, c, a);
  9354. }
  9355. } else {
  9356. const array = geometryPosition.array;
  9357. version = geometryPosition.version;
  9358. for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  9359. const a = i + 0;
  9360. const b = i + 1;
  9361. const c = i + 2;
  9362. indices.push(a, b, b, c, c, a);
  9363. }
  9364. }
  9365. const attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  9366. attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
  9367. //
  9368. const previousAttribute = wireframeAttributes.get(geometry);
  9369. if (previousAttribute) attributes.remove(previousAttribute); //
  9370. wireframeAttributes.set(geometry, attribute);
  9371. }
  9372. function getWireframeAttribute(geometry) {
  9373. const currentAttribute = wireframeAttributes.get(geometry);
  9374. if (currentAttribute) {
  9375. const geometryIndex = geometry.index;
  9376. if (geometryIndex !== null) {
  9377. // if the attribute is obsolete, create a new one
  9378. if (currentAttribute.version < geometryIndex.version) {
  9379. updateWireframeAttribute(geometry);
  9380. }
  9381. }
  9382. } else {
  9383. updateWireframeAttribute(geometry);
  9384. }
  9385. return wireframeAttributes.get(geometry);
  9386. }
  9387. return {
  9388. get: get,
  9389. update: update,
  9390. getWireframeAttribute: getWireframeAttribute
  9391. };
  9392. }
  9393. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  9394. const isWebGL2 = capabilities.isWebGL2;
  9395. let mode;
  9396. function setMode(value) {
  9397. mode = value;
  9398. }
  9399. let type, bytesPerElement;
  9400. function setIndex(value) {
  9401. type = value.type;
  9402. bytesPerElement = value.bytesPerElement;
  9403. }
  9404. function render(start, count) {
  9405. gl.drawElements(mode, count, type, start * bytesPerElement);
  9406. info.update(count, mode, 1);
  9407. }
  9408. function renderInstances(start, count, primcount) {
  9409. if (primcount === 0) return;
  9410. let extension, methodName;
  9411. if (isWebGL2) {
  9412. extension = gl;
  9413. methodName = 'drawElementsInstanced';
  9414. } else {
  9415. extension = extensions.get('ANGLE_instanced_arrays');
  9416. methodName = 'drawElementsInstancedANGLE';
  9417. if (extension === null) {
  9418. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9419. return;
  9420. }
  9421. }
  9422. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  9423. info.update(count, mode, primcount);
  9424. } //
  9425. this.setMode = setMode;
  9426. this.setIndex = setIndex;
  9427. this.render = render;
  9428. this.renderInstances = renderInstances;
  9429. }
  9430. function WebGLInfo(gl) {
  9431. const memory = {
  9432. geometries: 0,
  9433. textures: 0
  9434. };
  9435. const render = {
  9436. frame: 0,
  9437. calls: 0,
  9438. triangles: 0,
  9439. points: 0,
  9440. lines: 0
  9441. };
  9442. function update(count, mode, instanceCount) {
  9443. render.calls++;
  9444. switch (mode) {
  9445. case gl.TRIANGLES:
  9446. render.triangles += instanceCount * (count / 3);
  9447. break;
  9448. case gl.LINES:
  9449. render.lines += instanceCount * (count / 2);
  9450. break;
  9451. case gl.LINE_STRIP:
  9452. render.lines += instanceCount * (count - 1);
  9453. break;
  9454. case gl.LINE_LOOP:
  9455. render.lines += instanceCount * count;
  9456. break;
  9457. case gl.POINTS:
  9458. render.points += instanceCount * count;
  9459. break;
  9460. default:
  9461. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  9462. break;
  9463. }
  9464. }
  9465. function reset() {
  9466. render.frame++;
  9467. render.calls = 0;
  9468. render.triangles = 0;
  9469. render.points = 0;
  9470. render.lines = 0;
  9471. }
  9472. return {
  9473. memory: memory,
  9474. render: render,
  9475. programs: null,
  9476. autoReset: true,
  9477. reset: reset,
  9478. update: update
  9479. };
  9480. }
  9481. function numericalSort(a, b) {
  9482. return a[0] - b[0];
  9483. }
  9484. function absNumericalSort(a, b) {
  9485. return Math.abs(b[1]) - Math.abs(a[1]);
  9486. }
  9487. function WebGLMorphtargets(gl) {
  9488. const influencesList = {};
  9489. const morphInfluences = new Float32Array(8);
  9490. const workInfluences = [];
  9491. for (let i = 0; i < 8; i++) {
  9492. workInfluences[i] = [i, 0];
  9493. }
  9494. function update(object, geometry, material, program) {
  9495. const objectInfluences = object.morphTargetInfluences; // When object doesn't have morph target influences defined, we treat it as a 0-length array
  9496. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  9497. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  9498. let influences = influencesList[geometry.id];
  9499. if (influences === undefined || influences.length !== length) {
  9500. // initialise list
  9501. influences = [];
  9502. for (let i = 0; i < length; i++) {
  9503. influences[i] = [i, 0];
  9504. }
  9505. influencesList[geometry.id] = influences;
  9506. } // Collect influences
  9507. for (let i = 0; i < length; i++) {
  9508. const influence = influences[i];
  9509. influence[0] = i;
  9510. influence[1] = objectInfluences[i];
  9511. }
  9512. influences.sort(absNumericalSort);
  9513. for (let i = 0; i < 8; i++) {
  9514. if (i < length && influences[i][1]) {
  9515. workInfluences[i][0] = influences[i][0];
  9516. workInfluences[i][1] = influences[i][1];
  9517. } else {
  9518. workInfluences[i][0] = Number.MAX_SAFE_INTEGER;
  9519. workInfluences[i][1] = 0;
  9520. }
  9521. }
  9522. workInfluences.sort(numericalSort);
  9523. const morphTargets = material.morphTargets && geometry.morphAttributes.position;
  9524. const morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  9525. let morphInfluencesSum = 0;
  9526. for (let i = 0; i < 8; i++) {
  9527. const influence = workInfluences[i];
  9528. const index = influence[0];
  9529. const value = influence[1];
  9530. if (index !== Number.MAX_SAFE_INTEGER && value) {
  9531. if (morphTargets && geometry.getAttribute('morphTarget' + i) !== morphTargets[index]) {
  9532. geometry.setAttribute('morphTarget' + i, morphTargets[index]);
  9533. }
  9534. if (morphNormals && geometry.getAttribute('morphNormal' + i) !== morphNormals[index]) {
  9535. geometry.setAttribute('morphNormal' + i, morphNormals[index]);
  9536. }
  9537. morphInfluences[i] = value;
  9538. morphInfluencesSum += value;
  9539. } else {
  9540. if (morphTargets && geometry.hasAttribute('morphTarget' + i) === true) {
  9541. geometry.deleteAttribute('morphTarget' + i);
  9542. }
  9543. if (morphNormals && geometry.hasAttribute('morphNormal' + i) === true) {
  9544. geometry.deleteAttribute('morphNormal' + i);
  9545. }
  9546. morphInfluences[i] = 0;
  9547. }
  9548. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  9549. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  9550. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  9551. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  9552. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  9553. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  9554. }
  9555. return {
  9556. update: update
  9557. };
  9558. }
  9559. function WebGLObjects(gl, geometries, attributes, info) {
  9560. let updateMap = new WeakMap();
  9561. function update(object) {
  9562. const frame = info.render.frame;
  9563. const geometry = object.geometry;
  9564. const buffergeometry = geometries.get(object, geometry); // Update once per frame
  9565. if (updateMap.get(buffergeometry) !== frame) {
  9566. geometries.update(buffergeometry);
  9567. updateMap.set(buffergeometry, frame);
  9568. }
  9569. if (object.isInstancedMesh) {
  9570. if (object.hasEventListener('dispose', onInstancedMeshDispose) === false) {
  9571. object.addEventListener('dispose', onInstancedMeshDispose);
  9572. }
  9573. attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER);
  9574. if (object.instanceColor !== null) {
  9575. attributes.update(object.instanceColor, gl.ARRAY_BUFFER);
  9576. }
  9577. }
  9578. return buffergeometry;
  9579. }
  9580. function dispose() {
  9581. updateMap = new WeakMap();
  9582. }
  9583. function onInstancedMeshDispose(event) {
  9584. const instancedMesh = event.target;
  9585. instancedMesh.removeEventListener('dispose', onInstancedMeshDispose);
  9586. attributes.remove(instancedMesh.instanceMatrix);
  9587. if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor);
  9588. }
  9589. return {
  9590. update: update,
  9591. dispose: dispose
  9592. };
  9593. }
  9594. class DataTexture2DArray extends Texture {
  9595. constructor(data = null, width = 1, height = 1, depth = 1) {
  9596. super(null);
  9597. this.image = {
  9598. data,
  9599. width,
  9600. height,
  9601. depth
  9602. };
  9603. this.magFilter = NearestFilter;
  9604. this.minFilter = NearestFilter;
  9605. this.wrapR = ClampToEdgeWrapping;
  9606. this.generateMipmaps = false;
  9607. this.flipY = false;
  9608. this.unpackAlignment = 1;
  9609. this.needsUpdate = true;
  9610. }
  9611. }
  9612. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  9613. class DataTexture3D extends Texture {
  9614. constructor(data = null, width = 1, height = 1, depth = 1) {
  9615. // We're going to add .setXXX() methods for setting properties later.
  9616. // Users can still set in DataTexture3D directly.
  9617. //
  9618. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  9619. // texture.anisotropy = 16;
  9620. //
  9621. // See #14839
  9622. super(null);
  9623. this.image = {
  9624. data,
  9625. width,
  9626. height,
  9627. depth
  9628. };
  9629. this.magFilter = NearestFilter;
  9630. this.minFilter = NearestFilter;
  9631. this.wrapR = ClampToEdgeWrapping;
  9632. this.generateMipmaps = false;
  9633. this.flipY = false;
  9634. this.unpackAlignment = 1;
  9635. this.needsUpdate = true;
  9636. }
  9637. }
  9638. DataTexture3D.prototype.isDataTexture3D = true;
  9639. /**
  9640. * Uniforms of a program.
  9641. * Those form a tree structure with a special top-level container for the root,
  9642. * which you get by calling 'new WebGLUniforms( gl, program )'.
  9643. *
  9644. *
  9645. * Properties of inner nodes including the top-level container:
  9646. *
  9647. * .seq - array of nested uniforms
  9648. * .map - nested uniforms by name
  9649. *
  9650. *
  9651. * Methods of all nodes except the top-level container:
  9652. *
  9653. * .setValue( gl, value, [textures] )
  9654. *
  9655. * uploads a uniform value(s)
  9656. * the 'textures' parameter is needed for sampler uniforms
  9657. *
  9658. *
  9659. * Static methods of the top-level container (textures factorizations):
  9660. *
  9661. * .upload( gl, seq, values, textures )
  9662. *
  9663. * sets uniforms in 'seq' to 'values[id].value'
  9664. *
  9665. * .seqWithValue( seq, values ) : filteredSeq
  9666. *
  9667. * filters 'seq' entries with corresponding entry in values
  9668. *
  9669. *
  9670. * Methods of the top-level container (textures factorizations):
  9671. *
  9672. * .setValue( gl, name, value, textures )
  9673. *
  9674. * sets uniform with name 'name' to 'value'
  9675. *
  9676. * .setOptional( gl, obj, prop )
  9677. *
  9678. * like .set for an optional property of the object
  9679. *
  9680. */
  9681. const emptyTexture = new Texture();
  9682. const emptyTexture2dArray = new DataTexture2DArray();
  9683. const emptyTexture3d = new DataTexture3D();
  9684. const emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  9685. // Array Caches (provide typed arrays for temporary by size)
  9686. const arrayCacheF32 = [];
  9687. const arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  9688. const mat4array = new Float32Array(16);
  9689. const mat3array = new Float32Array(9);
  9690. const mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  9691. function flatten(array, nBlocks, blockSize) {
  9692. const firstElem = array[0];
  9693. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  9694. // see http://jacksondunstan.com/articles/983
  9695. const n = nBlocks * blockSize;
  9696. let r = arrayCacheF32[n];
  9697. if (r === undefined) {
  9698. r = new Float32Array(n);
  9699. arrayCacheF32[n] = r;
  9700. }
  9701. if (nBlocks !== 0) {
  9702. firstElem.toArray(r, 0);
  9703. for (let i = 1, offset = 0; i !== nBlocks; ++i) {
  9704. offset += blockSize;
  9705. array[i].toArray(r, offset);
  9706. }
  9707. }
  9708. return r;
  9709. }
  9710. function arraysEqual(a, b) {
  9711. if (a.length !== b.length) return false;
  9712. for (let i = 0, l = a.length; i < l; i++) {
  9713. if (a[i] !== b[i]) return false;
  9714. }
  9715. return true;
  9716. }
  9717. function copyArray(a, b) {
  9718. for (let i = 0, l = b.length; i < l; i++) {
  9719. a[i] = b[i];
  9720. }
  9721. } // Texture unit allocation
  9722. function allocTexUnits(textures, n) {
  9723. let r = arrayCacheI32[n];
  9724. if (r === undefined) {
  9725. r = new Int32Array(n);
  9726. arrayCacheI32[n] = r;
  9727. }
  9728. for (let i = 0; i !== n; ++i) {
  9729. r[i] = textures.allocateTextureUnit();
  9730. }
  9731. return r;
  9732. } // --- Setters ---
  9733. // Note: Defining these methods externally, because they come in a bunch
  9734. // and this way their names minify.
  9735. // Single scalar
  9736. function setValueV1f(gl, v) {
  9737. const cache = this.cache;
  9738. if (cache[0] === v) return;
  9739. gl.uniform1f(this.addr, v);
  9740. cache[0] = v;
  9741. } // Single float vector (from flat array or THREE.VectorN)
  9742. function setValueV2f(gl, v) {
  9743. const cache = this.cache;
  9744. if (v.x !== undefined) {
  9745. if (cache[0] !== v.x || cache[1] !== v.y) {
  9746. gl.uniform2f(this.addr, v.x, v.y);
  9747. cache[0] = v.x;
  9748. cache[1] = v.y;
  9749. }
  9750. } else {
  9751. if (arraysEqual(cache, v)) return;
  9752. gl.uniform2fv(this.addr, v);
  9753. copyArray(cache, v);
  9754. }
  9755. }
  9756. function setValueV3f(gl, v) {
  9757. const cache = this.cache;
  9758. if (v.x !== undefined) {
  9759. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  9760. gl.uniform3f(this.addr, v.x, v.y, v.z);
  9761. cache[0] = v.x;
  9762. cache[1] = v.y;
  9763. cache[2] = v.z;
  9764. }
  9765. } else if (v.r !== undefined) {
  9766. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  9767. gl.uniform3f(this.addr, v.r, v.g, v.b);
  9768. cache[0] = v.r;
  9769. cache[1] = v.g;
  9770. cache[2] = v.b;
  9771. }
  9772. } else {
  9773. if (arraysEqual(cache, v)) return;
  9774. gl.uniform3fv(this.addr, v);
  9775. copyArray(cache, v);
  9776. }
  9777. }
  9778. function setValueV4f(gl, v) {
  9779. const cache = this.cache;
  9780. if (v.x !== undefined) {
  9781. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  9782. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  9783. cache[0] = v.x;
  9784. cache[1] = v.y;
  9785. cache[2] = v.z;
  9786. cache[3] = v.w;
  9787. }
  9788. } else {
  9789. if (arraysEqual(cache, v)) return;
  9790. gl.uniform4fv(this.addr, v);
  9791. copyArray(cache, v);
  9792. }
  9793. } // Single matrix (from flat array or THREE.MatrixN)
  9794. function setValueM2(gl, v) {
  9795. const cache = this.cache;
  9796. const elements = v.elements;
  9797. if (elements === undefined) {
  9798. if (arraysEqual(cache, v)) return;
  9799. gl.uniformMatrix2fv(this.addr, false, v);
  9800. copyArray(cache, v);
  9801. } else {
  9802. if (arraysEqual(cache, elements)) return;
  9803. mat2array.set(elements);
  9804. gl.uniformMatrix2fv(this.addr, false, mat2array);
  9805. copyArray(cache, elements);
  9806. }
  9807. }
  9808. function setValueM3(gl, v) {
  9809. const cache = this.cache;
  9810. const elements = v.elements;
  9811. if (elements === undefined) {
  9812. if (arraysEqual(cache, v)) return;
  9813. gl.uniformMatrix3fv(this.addr, false, v);
  9814. copyArray(cache, v);
  9815. } else {
  9816. if (arraysEqual(cache, elements)) return;
  9817. mat3array.set(elements);
  9818. gl.uniformMatrix3fv(this.addr, false, mat3array);
  9819. copyArray(cache, elements);
  9820. }
  9821. }
  9822. function setValueM4(gl, v) {
  9823. const cache = this.cache;
  9824. const elements = v.elements;
  9825. if (elements === undefined) {
  9826. if (arraysEqual(cache, v)) return;
  9827. gl.uniformMatrix4fv(this.addr, false, v);
  9828. copyArray(cache, v);
  9829. } else {
  9830. if (arraysEqual(cache, elements)) return;
  9831. mat4array.set(elements);
  9832. gl.uniformMatrix4fv(this.addr, false, mat4array);
  9833. copyArray(cache, elements);
  9834. }
  9835. } // Single integer / boolean
  9836. function setValueV1i(gl, v) {
  9837. const cache = this.cache;
  9838. if (cache[0] === v) return;
  9839. gl.uniform1i(this.addr, v);
  9840. cache[0] = v;
  9841. } // Single integer / boolean vector (from flat array)
  9842. function setValueV2i(gl, v) {
  9843. const cache = this.cache;
  9844. if (arraysEqual(cache, v)) return;
  9845. gl.uniform2iv(this.addr, v);
  9846. copyArray(cache, v);
  9847. }
  9848. function setValueV3i(gl, v) {
  9849. const cache = this.cache;
  9850. if (arraysEqual(cache, v)) return;
  9851. gl.uniform3iv(this.addr, v);
  9852. copyArray(cache, v);
  9853. }
  9854. function setValueV4i(gl, v) {
  9855. const cache = this.cache;
  9856. if (arraysEqual(cache, v)) return;
  9857. gl.uniform4iv(this.addr, v);
  9858. copyArray(cache, v);
  9859. } // Single unsigned integer
  9860. function setValueV1ui(gl, v) {
  9861. const cache = this.cache;
  9862. if (cache[0] === v) return;
  9863. gl.uniform1ui(this.addr, v);
  9864. cache[0] = v;
  9865. } // Single unsigned integer vector (from flat array)
  9866. function setValueV2ui(gl, v) {
  9867. const cache = this.cache;
  9868. if (arraysEqual(cache, v)) return;
  9869. gl.uniform2uiv(this.addr, v);
  9870. copyArray(cache, v);
  9871. }
  9872. function setValueV3ui(gl, v) {
  9873. const cache = this.cache;
  9874. if (arraysEqual(cache, v)) return;
  9875. gl.uniform3uiv(this.addr, v);
  9876. copyArray(cache, v);
  9877. }
  9878. function setValueV4ui(gl, v) {
  9879. const cache = this.cache;
  9880. if (arraysEqual(cache, v)) return;
  9881. gl.uniform4uiv(this.addr, v);
  9882. copyArray(cache, v);
  9883. } // Single texture (2D / Cube)
  9884. function setValueT1(gl, v, textures) {
  9885. const cache = this.cache;
  9886. const unit = textures.allocateTextureUnit();
  9887. if (cache[0] !== unit) {
  9888. gl.uniform1i(this.addr, unit);
  9889. cache[0] = unit;
  9890. }
  9891. textures.safeSetTexture2D(v || emptyTexture, unit);
  9892. }
  9893. function setValueT3D1(gl, v, textures) {
  9894. const cache = this.cache;
  9895. const unit = textures.allocateTextureUnit();
  9896. if (cache[0] !== unit) {
  9897. gl.uniform1i(this.addr, unit);
  9898. cache[0] = unit;
  9899. }
  9900. textures.setTexture3D(v || emptyTexture3d, unit);
  9901. }
  9902. function setValueT6(gl, v, textures) {
  9903. const cache = this.cache;
  9904. const unit = textures.allocateTextureUnit();
  9905. if (cache[0] !== unit) {
  9906. gl.uniform1i(this.addr, unit);
  9907. cache[0] = unit;
  9908. }
  9909. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  9910. }
  9911. function setValueT2DArray1(gl, v, textures) {
  9912. const cache = this.cache;
  9913. const unit = textures.allocateTextureUnit();
  9914. if (cache[0] !== unit) {
  9915. gl.uniform1i(this.addr, unit);
  9916. cache[0] = unit;
  9917. }
  9918. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  9919. } // Helper to pick the right setter for the singular case
  9920. function getSingularSetter(type) {
  9921. switch (type) {
  9922. case 0x1406:
  9923. return setValueV1f;
  9924. // FLOAT
  9925. case 0x8b50:
  9926. return setValueV2f;
  9927. // _VEC2
  9928. case 0x8b51:
  9929. return setValueV3f;
  9930. // _VEC3
  9931. case 0x8b52:
  9932. return setValueV4f;
  9933. // _VEC4
  9934. case 0x8b5a:
  9935. return setValueM2;
  9936. // _MAT2
  9937. case 0x8b5b:
  9938. return setValueM3;
  9939. // _MAT3
  9940. case 0x8b5c:
  9941. return setValueM4;
  9942. // _MAT4
  9943. case 0x1404:
  9944. case 0x8b56:
  9945. return setValueV1i;
  9946. // INT, BOOL
  9947. case 0x8b53:
  9948. case 0x8b57:
  9949. return setValueV2i;
  9950. // _VEC2
  9951. case 0x8b54:
  9952. case 0x8b58:
  9953. return setValueV3i;
  9954. // _VEC3
  9955. case 0x8b55:
  9956. case 0x8b59:
  9957. return setValueV4i;
  9958. // _VEC4
  9959. case 0x1405:
  9960. return setValueV1ui;
  9961. // UINT
  9962. case 0x8dc6:
  9963. return setValueV2ui;
  9964. // _VEC2
  9965. case 0x8dc7:
  9966. return setValueV3ui;
  9967. // _VEC3
  9968. case 0x8dc8:
  9969. return setValueV4ui;
  9970. // _VEC4
  9971. case 0x8b5e: // SAMPLER_2D
  9972. case 0x8d66: // SAMPLER_EXTERNAL_OES
  9973. case 0x8dca: // INT_SAMPLER_2D
  9974. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  9975. case 0x8b62:
  9976. // SAMPLER_2D_SHADOW
  9977. return setValueT1;
  9978. case 0x8b5f: // SAMPLER_3D
  9979. case 0x8dcb: // INT_SAMPLER_3D
  9980. case 0x8dd3:
  9981. // UNSIGNED_INT_SAMPLER_3D
  9982. return setValueT3D1;
  9983. case 0x8b60: // SAMPLER_CUBE
  9984. case 0x8dcc: // INT_SAMPLER_CUBE
  9985. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  9986. case 0x8dc5:
  9987. // SAMPLER_CUBE_SHADOW
  9988. return setValueT6;
  9989. case 0x8dc1: // SAMPLER_2D_ARRAY
  9990. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  9991. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  9992. case 0x8dc4:
  9993. // SAMPLER_2D_ARRAY_SHADOW
  9994. return setValueT2DArray1;
  9995. }
  9996. } // Array of scalars
  9997. function setValueV1fArray(gl, v) {
  9998. gl.uniform1fv(this.addr, v);
  9999. } // Array of vectors (from flat array or array of THREE.VectorN)
  10000. function setValueV2fArray(gl, v) {
  10001. const data = flatten(v, this.size, 2);
  10002. gl.uniform2fv(this.addr, data);
  10003. }
  10004. function setValueV3fArray(gl, v) {
  10005. const data = flatten(v, this.size, 3);
  10006. gl.uniform3fv(this.addr, data);
  10007. }
  10008. function setValueV4fArray(gl, v) {
  10009. const data = flatten(v, this.size, 4);
  10010. gl.uniform4fv(this.addr, data);
  10011. } // Array of matrices (from flat array or array of THREE.MatrixN)
  10012. function setValueM2Array(gl, v) {
  10013. const data = flatten(v, this.size, 4);
  10014. gl.uniformMatrix2fv(this.addr, false, data);
  10015. }
  10016. function setValueM3Array(gl, v) {
  10017. const data = flatten(v, this.size, 9);
  10018. gl.uniformMatrix3fv(this.addr, false, data);
  10019. }
  10020. function setValueM4Array(gl, v) {
  10021. const data = flatten(v, this.size, 16);
  10022. gl.uniformMatrix4fv(this.addr, false, data);
  10023. } // Array of integer / boolean
  10024. function setValueV1iArray(gl, v) {
  10025. gl.uniform1iv(this.addr, v);
  10026. } // Array of integer / boolean vectors (from flat array)
  10027. function setValueV2iArray(gl, v) {
  10028. gl.uniform2iv(this.addr, v);
  10029. }
  10030. function setValueV3iArray(gl, v) {
  10031. gl.uniform3iv(this.addr, v);
  10032. }
  10033. function setValueV4iArray(gl, v) {
  10034. gl.uniform4iv(this.addr, v);
  10035. } // Array of unsigned integer
  10036. function setValueV1uiArray(gl, v) {
  10037. gl.uniform1uiv(this.addr, v);
  10038. } // Array of unsigned integer vectors (from flat array)
  10039. function setValueV2uiArray(gl, v) {
  10040. gl.uniform2uiv(this.addr, v);
  10041. }
  10042. function setValueV3uiArray(gl, v) {
  10043. gl.uniform3uiv(this.addr, v);
  10044. }
  10045. function setValueV4uiArray(gl, v) {
  10046. gl.uniform4uiv(this.addr, v);
  10047. } // Array of textures (2D / Cube)
  10048. function setValueT1Array(gl, v, textures) {
  10049. const n = v.length;
  10050. const units = allocTexUnits(textures, n);
  10051. gl.uniform1iv(this.addr, units);
  10052. for (let i = 0; i !== n; ++i) {
  10053. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  10054. }
  10055. }
  10056. function setValueT6Array(gl, v, textures) {
  10057. const n = v.length;
  10058. const units = allocTexUnits(textures, n);
  10059. gl.uniform1iv(this.addr, units);
  10060. for (let i = 0; i !== n; ++i) {
  10061. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  10062. }
  10063. } // Helper to pick the right setter for a pure (bottom-level) array
  10064. function getPureArraySetter(type) {
  10065. switch (type) {
  10066. case 0x1406:
  10067. return setValueV1fArray;
  10068. // FLOAT
  10069. case 0x8b50:
  10070. return setValueV2fArray;
  10071. // _VEC2
  10072. case 0x8b51:
  10073. return setValueV3fArray;
  10074. // _VEC3
  10075. case 0x8b52:
  10076. return setValueV4fArray;
  10077. // _VEC4
  10078. case 0x8b5a:
  10079. return setValueM2Array;
  10080. // _MAT2
  10081. case 0x8b5b:
  10082. return setValueM3Array;
  10083. // _MAT3
  10084. case 0x8b5c:
  10085. return setValueM4Array;
  10086. // _MAT4
  10087. case 0x1404:
  10088. case 0x8b56:
  10089. return setValueV1iArray;
  10090. // INT, BOOL
  10091. case 0x8b53:
  10092. case 0x8b57:
  10093. return setValueV2iArray;
  10094. // _VEC2
  10095. case 0x8b54:
  10096. case 0x8b58:
  10097. return setValueV3iArray;
  10098. // _VEC3
  10099. case 0x8b55:
  10100. case 0x8b59:
  10101. return setValueV4iArray;
  10102. // _VEC4
  10103. case 0x1405:
  10104. return setValueV1uiArray;
  10105. // UINT
  10106. case 0x8dc6:
  10107. return setValueV2uiArray;
  10108. // _VEC2
  10109. case 0x8dc7:
  10110. return setValueV3uiArray;
  10111. // _VEC3
  10112. case 0x8dc8:
  10113. return setValueV4uiArray;
  10114. // _VEC4
  10115. case 0x8b5e: // SAMPLER_2D
  10116. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10117. case 0x8dca: // INT_SAMPLER_2D
  10118. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10119. case 0x8b62:
  10120. // SAMPLER_2D_SHADOW
  10121. return setValueT1Array;
  10122. case 0x8b60: // SAMPLER_CUBE
  10123. case 0x8dcc: // INT_SAMPLER_CUBE
  10124. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10125. case 0x8dc5:
  10126. // SAMPLER_CUBE_SHADOW
  10127. return setValueT6Array;
  10128. }
  10129. } // --- Uniform Classes ---
  10130. function SingleUniform(id, activeInfo, addr) {
  10131. this.id = id;
  10132. this.addr = addr;
  10133. this.cache = [];
  10134. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  10135. }
  10136. function PureArrayUniform(id, activeInfo, addr) {
  10137. this.id = id;
  10138. this.addr = addr;
  10139. this.cache = [];
  10140. this.size = activeInfo.size;
  10141. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  10142. }
  10143. PureArrayUniform.prototype.updateCache = function (data) {
  10144. const cache = this.cache;
  10145. if (data instanceof Float32Array && cache.length !== data.length) {
  10146. this.cache = new Float32Array(data.length);
  10147. }
  10148. copyArray(cache, data);
  10149. };
  10150. function StructuredUniform(id) {
  10151. this.id = id;
  10152. this.seq = [];
  10153. this.map = {};
  10154. }
  10155. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  10156. const seq = this.seq;
  10157. for (let i = 0, n = seq.length; i !== n; ++i) {
  10158. const u = seq[i];
  10159. u.setValue(gl, value[u.id], textures);
  10160. }
  10161. }; // --- Top-level ---
  10162. // Parser - builds up the property tree from the path strings
  10163. const RePathPart = /(\w+)(\])?(\[|\.)?/g; // extracts
  10164. // - the identifier (member name or array index)
  10165. // - followed by an optional right bracket (found when array index)
  10166. // - followed by an optional left bracket or dot (type of subscript)
  10167. //
  10168. // Note: These portions can be read in a non-overlapping fashion and
  10169. // allow straightforward parsing of the hierarchy that WebGL encodes
  10170. // in the uniform names.
  10171. function addUniform(container, uniformObject) {
  10172. container.seq.push(uniformObject);
  10173. container.map[uniformObject.id] = uniformObject;
  10174. }
  10175. function parseUniform(activeInfo, addr, container) {
  10176. const path = activeInfo.name,
  10177. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  10178. RePathPart.lastIndex = 0;
  10179. while (true) {
  10180. const match = RePathPart.exec(path),
  10181. matchEnd = RePathPart.lastIndex;
  10182. let id = match[1];
  10183. const idIsIndex = match[2] === ']',
  10184. subscript = match[3];
  10185. if (idIsIndex) id = id | 0; // convert to integer
  10186. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  10187. // bare name or "pure" bottom-level array "[0]" suffix
  10188. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  10189. break;
  10190. } else {
  10191. // step into inner node / create it in case it doesn't exist
  10192. const map = container.map;
  10193. let next = map[id];
  10194. if (next === undefined) {
  10195. next = new StructuredUniform(id);
  10196. addUniform(container, next);
  10197. }
  10198. container = next;
  10199. }
  10200. }
  10201. } // Root Container
  10202. function WebGLUniforms(gl, program) {
  10203. this.seq = [];
  10204. this.map = {};
  10205. const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  10206. for (let i = 0; i < n; ++i) {
  10207. const info = gl.getActiveUniform(program, i),
  10208. addr = gl.getUniformLocation(program, info.name);
  10209. parseUniform(info, addr, this);
  10210. }
  10211. }
  10212. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  10213. const u = this.map[name];
  10214. if (u !== undefined) u.setValue(gl, value, textures);
  10215. };
  10216. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  10217. const v = object[name];
  10218. if (v !== undefined) this.setValue(gl, name, v);
  10219. }; // Static interface
  10220. WebGLUniforms.upload = function (gl, seq, values, textures) {
  10221. for (let i = 0, n = seq.length; i !== n; ++i) {
  10222. const u = seq[i],
  10223. v = values[u.id];
  10224. if (v.needsUpdate !== false) {
  10225. // note: always updating when .needsUpdate is undefined
  10226. u.setValue(gl, v.value, textures);
  10227. }
  10228. }
  10229. };
  10230. WebGLUniforms.seqWithValue = function (seq, values) {
  10231. const r = [];
  10232. for (let i = 0, n = seq.length; i !== n; ++i) {
  10233. const u = seq[i];
  10234. if (u.id in values) r.push(u);
  10235. }
  10236. return r;
  10237. };
  10238. function WebGLShader(gl, type, string) {
  10239. const shader = gl.createShader(type);
  10240. gl.shaderSource(shader, string);
  10241. gl.compileShader(shader);
  10242. return shader;
  10243. }
  10244. let programIdCount = 0;
  10245. function addLineNumbers(string) {
  10246. const lines = string.split('\n');
  10247. for (let i = 0; i < lines.length; i++) {
  10248. lines[i] = i + 1 + ': ' + lines[i];
  10249. }
  10250. return lines.join('\n');
  10251. }
  10252. function getEncodingComponents(encoding) {
  10253. switch (encoding) {
  10254. case LinearEncoding:
  10255. return ['Linear', '( value )'];
  10256. case sRGBEncoding:
  10257. return ['sRGB', '( value )'];
  10258. case RGBEEncoding:
  10259. return ['RGBE', '( value )'];
  10260. case RGBM7Encoding:
  10261. return ['RGBM', '( value, 7.0 )'];
  10262. case RGBM16Encoding:
  10263. return ['RGBM', '( value, 16.0 )'];
  10264. case RGBDEncoding:
  10265. return ['RGBD', '( value, 256.0 )'];
  10266. case GammaEncoding:
  10267. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  10268. case LogLuvEncoding:
  10269. return ['LogLuv', '( value )'];
  10270. default:
  10271. console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
  10272. return ['Linear', '( value )'];
  10273. }
  10274. }
  10275. function getShaderErrors(gl, shader, type) {
  10276. const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  10277. const log = gl.getShaderInfoLog(shader).trim();
  10278. if (status && log === '') return ''; // --enable-privileged-webgl-extension
  10279. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10280. const source = gl.getShaderSource(shader);
  10281. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers(source);
  10282. }
  10283. function getTexelDecodingFunction(functionName, encoding) {
  10284. const components = getEncodingComponents(encoding);
  10285. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  10286. }
  10287. function getTexelEncodingFunction(functionName, encoding) {
  10288. const components = getEncodingComponents(encoding);
  10289. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  10290. }
  10291. function getToneMappingFunction(functionName, toneMapping) {
  10292. let toneMappingName;
  10293. switch (toneMapping) {
  10294. case LinearToneMapping:
  10295. toneMappingName = 'Linear';
  10296. break;
  10297. case ReinhardToneMapping:
  10298. toneMappingName = 'Reinhard';
  10299. break;
  10300. case CineonToneMapping:
  10301. toneMappingName = 'OptimizedCineon';
  10302. break;
  10303. case ACESFilmicToneMapping:
  10304. toneMappingName = 'ACESFilmic';
  10305. break;
  10306. case CustomToneMapping:
  10307. toneMappingName = 'Custom';
  10308. break;
  10309. default:
  10310. console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
  10311. toneMappingName = 'Linear';
  10312. }
  10313. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  10314. }
  10315. function generateExtensions(parameters) {
  10316. 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' : ''];
  10317. return chunks.filter(filterEmptyLine).join('\n');
  10318. }
  10319. function generateDefines(defines) {
  10320. const chunks = [];
  10321. for (const name in defines) {
  10322. const value = defines[name];
  10323. if (value === false) continue;
  10324. chunks.push('#define ' + name + ' ' + value);
  10325. }
  10326. return chunks.join('\n');
  10327. }
  10328. function fetchAttributeLocations(gl, program) {
  10329. const attributes = {};
  10330. const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  10331. for (let i = 0; i < n; i++) {
  10332. const info = gl.getActiveAttrib(program, i);
  10333. const name = info.name; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  10334. attributes[name] = gl.getAttribLocation(program, name);
  10335. }
  10336. return attributes;
  10337. }
  10338. function filterEmptyLine(string) {
  10339. return string !== '';
  10340. }
  10341. function replaceLightNums(string, parameters) {
  10342. 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);
  10343. }
  10344. function replaceClippingPlaneNums(string, parameters) {
  10345. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  10346. } // Resolve Includes
  10347. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  10348. function resolveIncludes(string) {
  10349. return string.replace(includePattern, includeReplacer);
  10350. }
  10351. function includeReplacer(match, include) {
  10352. const string = ShaderChunk[include];
  10353. if (string === undefined) {
  10354. throw new Error('Can not resolve #include <' + include + '>');
  10355. }
  10356. return resolveIncludes(string);
  10357. } // Unroll Loops
  10358. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  10359. 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;
  10360. function unrollLoops(string) {
  10361. return string.replace(unrollLoopPattern, loopReplacer).replace(deprecatedUnrollLoopPattern, deprecatedLoopReplacer);
  10362. }
  10363. function deprecatedLoopReplacer(match, start, end, snippet) {
  10364. console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');
  10365. return loopReplacer(match, start, end, snippet);
  10366. }
  10367. function loopReplacer(match, start, end, snippet) {
  10368. let string = '';
  10369. for (let i = parseInt(start); i < parseInt(end); i++) {
  10370. string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  10371. }
  10372. return string;
  10373. } //
  10374. function generatePrecision(parameters) {
  10375. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  10376. if (parameters.precision === 'highp') {
  10377. precisionstring += '\n#define HIGH_PRECISION';
  10378. } else if (parameters.precision === 'mediump') {
  10379. precisionstring += '\n#define MEDIUM_PRECISION';
  10380. } else if (parameters.precision === 'lowp') {
  10381. precisionstring += '\n#define LOW_PRECISION';
  10382. }
  10383. return precisionstring;
  10384. }
  10385. function generateShadowMapTypeDefine(parameters) {
  10386. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  10387. if (parameters.shadowMapType === PCFShadowMap) {
  10388. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  10389. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  10390. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  10391. } else if (parameters.shadowMapType === VSMShadowMap) {
  10392. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  10393. }
  10394. return shadowMapTypeDefine;
  10395. }
  10396. function generateEnvMapTypeDefine(parameters) {
  10397. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10398. if (parameters.envMap) {
  10399. switch (parameters.envMapMode) {
  10400. case CubeReflectionMapping:
  10401. case CubeRefractionMapping:
  10402. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10403. break;
  10404. case CubeUVReflectionMapping:
  10405. case CubeUVRefractionMapping:
  10406. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  10407. break;
  10408. }
  10409. }
  10410. return envMapTypeDefine;
  10411. }
  10412. function generateEnvMapModeDefine(parameters) {
  10413. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  10414. if (parameters.envMap) {
  10415. switch (parameters.envMapMode) {
  10416. case CubeRefractionMapping:
  10417. case CubeUVRefractionMapping:
  10418. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  10419. break;
  10420. }
  10421. }
  10422. return envMapModeDefine;
  10423. }
  10424. function generateEnvMapBlendingDefine(parameters) {
  10425. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  10426. if (parameters.envMap) {
  10427. switch (parameters.combine) {
  10428. case MultiplyOperation:
  10429. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10430. break;
  10431. case MixOperation:
  10432. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  10433. break;
  10434. case AddOperation:
  10435. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  10436. break;
  10437. }
  10438. }
  10439. return envMapBlendingDefine;
  10440. }
  10441. function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
  10442. const gl = renderer.getContext();
  10443. const defines = parameters.defines;
  10444. let vertexShader = parameters.vertexShader;
  10445. let fragmentShader = parameters.fragmentShader;
  10446. const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  10447. const envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  10448. const envMapModeDefine = generateEnvMapModeDefine(parameters);
  10449. const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  10450. const gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  10451. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  10452. const customDefines = generateDefines(defines);
  10453. const program = gl.createProgram();
  10454. let prefixVertex, prefixFragment;
  10455. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  10456. if (parameters.isRawShaderMaterial) {
  10457. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  10458. if (prefixVertex.length > 0) {
  10459. prefixVertex += '\n';
  10460. }
  10461. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  10462. if (prefixFragment.length > 0) {
  10463. prefixFragment += '\n';
  10464. }
  10465. } else {
  10466. prefixVertex = [generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.instancing ? '#define USE_INSTANCING' : '', parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', '#define GAMMA_FACTOR ' + gammaFactorDefine, '#define MAX_BONES ' + parameters.maxBones, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.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');
  10467. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + (parameters.alphaTest % 1 ? '' : '.0') : '', // add '.0' if integer
  10468. '#define GAMMA_FACTOR ' + gammaFactorDefine, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.matcap ? '#define USE_MATCAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapTypeDefine : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.envMap ? '#define ' + envMapBlendingDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.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
  10469. 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
  10470. parameters.map ? getTexelDecodingFunction('mapTexelToLinear', parameters.mapEncoding) : '', parameters.matcap ? getTexelDecodingFunction('matcapTexelToLinear', parameters.matcapEncoding) : '', parameters.envMap ? getTexelDecodingFunction('envMapTexelToLinear', parameters.envMapEncoding) : '', parameters.emissiveMap ? getTexelDecodingFunction('emissiveMapTexelToLinear', parameters.emissiveMapEncoding) : '', parameters.lightMap ? getTexelDecodingFunction('lightMapTexelToLinear', parameters.lightMapEncoding) : '', getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  10471. }
  10472. vertexShader = resolveIncludes(vertexShader);
  10473. vertexShader = replaceLightNums(vertexShader, parameters);
  10474. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  10475. fragmentShader = resolveIncludes(fragmentShader);
  10476. fragmentShader = replaceLightNums(fragmentShader, parameters);
  10477. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  10478. vertexShader = unrollLoops(vertexShader);
  10479. fragmentShader = unrollLoops(fragmentShader);
  10480. if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
  10481. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  10482. versionString = '#version 300 es\n';
  10483. prefixVertex = ['#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  10484. 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;
  10485. }
  10486. const vertexGlsl = versionString + prefixVertex + vertexShader;
  10487. const fragmentGlsl = versionString + prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  10488. // console.log( '*FRAGMENT*', fragmentGlsl );
  10489. const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl);
  10490. const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl);
  10491. gl.attachShader(program, glVertexShader);
  10492. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  10493. if (parameters.index0AttributeName !== undefined) {
  10494. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  10495. } else if (parameters.morphTargets === true) {
  10496. // programs with morphTargets displace position out of attribute 0
  10497. gl.bindAttribLocation(program, 0, 'position');
  10498. }
  10499. gl.linkProgram(program); // check for link errors
  10500. if (renderer.debug.checkShaderErrors) {
  10501. const programLog = gl.getProgramInfoLog(program).trim();
  10502. const vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  10503. const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  10504. let runnable = true;
  10505. let haveDiagnostics = true;
  10506. if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {
  10507. runnable = false;
  10508. const vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  10509. const fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  10510. console.error('THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors);
  10511. } else if (programLog !== '') {
  10512. console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()', programLog);
  10513. } else if (vertexLog === '' || fragmentLog === '') {
  10514. haveDiagnostics = false;
  10515. }
  10516. if (haveDiagnostics) {
  10517. this.diagnostics = {
  10518. runnable: runnable,
  10519. programLog: programLog,
  10520. vertexShader: {
  10521. log: vertexLog,
  10522. prefix: prefixVertex
  10523. },
  10524. fragmentShader: {
  10525. log: fragmentLog,
  10526. prefix: prefixFragment
  10527. }
  10528. };
  10529. }
  10530. } // Clean up
  10531. // Crashes in iOS9 and iOS10. #18402
  10532. // gl.detachShader( program, glVertexShader );
  10533. // gl.detachShader( program, glFragmentShader );
  10534. gl.deleteShader(glVertexShader);
  10535. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  10536. let cachedUniforms;
  10537. this.getUniforms = function () {
  10538. if (cachedUniforms === undefined) {
  10539. cachedUniforms = new WebGLUniforms(gl, program);
  10540. }
  10541. return cachedUniforms;
  10542. }; // set up caching for attribute locations
  10543. let cachedAttributes;
  10544. this.getAttributes = function () {
  10545. if (cachedAttributes === undefined) {
  10546. cachedAttributes = fetchAttributeLocations(gl, program);
  10547. }
  10548. return cachedAttributes;
  10549. }; // free resource
  10550. this.destroy = function () {
  10551. bindingStates.releaseStatesOfProgram(this);
  10552. gl.deleteProgram(program);
  10553. this.program = undefined;
  10554. }; //
  10555. this.name = parameters.shaderName;
  10556. this.id = programIdCount++;
  10557. this.cacheKey = cacheKey;
  10558. this.usedTimes = 1;
  10559. this.program = program;
  10560. this.vertexShader = glVertexShader;
  10561. this.fragmentShader = glFragmentShader;
  10562. return this;
  10563. }
  10564. function WebGLPrograms(renderer, cubemaps, extensions, capabilities, bindingStates, clipping) {
  10565. const programs = [];
  10566. const isWebGL2 = capabilities.isWebGL2;
  10567. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  10568. const floatVertexTextures = capabilities.floatVertexTextures;
  10569. const maxVertexUniforms = capabilities.maxVertexUniforms;
  10570. const vertexTextures = capabilities.vertexTextures;
  10571. let precision = capabilities.precision;
  10572. const shaderIDs = {
  10573. MeshDepthMaterial: 'depth',
  10574. MeshDistanceMaterial: 'distanceRGBA',
  10575. MeshNormalMaterial: 'normal',
  10576. MeshBasicMaterial: 'basic',
  10577. MeshLambertMaterial: 'lambert',
  10578. MeshPhongMaterial: 'phong',
  10579. MeshToonMaterial: 'toon',
  10580. MeshStandardMaterial: 'physical',
  10581. MeshPhysicalMaterial: 'physical',
  10582. MeshMatcapMaterial: 'matcap',
  10583. LineBasicMaterial: 'basic',
  10584. LineDashedMaterial: 'dashed',
  10585. PointsMaterial: 'points',
  10586. ShadowMaterial: 'shadow',
  10587. SpriteMaterial: 'sprite'
  10588. };
  10589. const parameterNames = ['precision', 'isWebGL2', 'supportsVertexTextures', 'outputEncoding', 'instancing', 'instancingColor', 'map', 'mapEncoding', 'matcap', 'matcapEncoding', 'envMap', 'envMapMode', 'envMapEncoding', 'envMapCubeUV', 'lightMap', 'lightMapEncoding', 'aoMap', 'emissiveMap', 'emissiveMapEncoding', 'bumpMap', 'normalMap', 'objectSpaceNormalMap', 'tangentSpaceNormalMap', 'clearcoatMap', 'clearcoatRoughnessMap', 'clearcoatNormalMap', 'displacementMap', 'specularMap', 'roughnessMap', 'metalnessMap', 'gradientMap', 'alphaMap', 'combine', 'vertexColors', 'vertexAlphas', 'vertexTangents', 'vertexUvs', 'uvsVertexOnly', 'fog', 'useFog', 'fogExp2', 'flatShading', 'sizeAttenuation', 'logarithmicDepthBuffer', 'skinning', 'maxBones', 'useVertexTexture', 'morphTargets', 'morphNormals', 'premultipliedAlpha', 'numDirLights', 'numPointLights', 'numSpotLights', 'numHemiLights', 'numRectAreaLights', 'numDirLightShadows', 'numPointLightShadows', 'numSpotLightShadows', 'shadowMapEnabled', 'shadowMapType', 'toneMapping', 'physicallyCorrectLights', 'alphaTest', 'doubleSided', 'flipSided', 'numClippingPlanes', 'numClipIntersection', 'depthPacking', 'dithering', 'sheen', 'transmission', 'transmissionMap', 'thicknessMap'];
  10590. function getMaxBones(object) {
  10591. const skeleton = object.skeleton;
  10592. const bones = skeleton.bones;
  10593. if (floatVertexTextures) {
  10594. return 1024;
  10595. } else {
  10596. // default for when object is not specified
  10597. // ( for example when prebuilding shader to be used with multiple objects )
  10598. //
  10599. // - leave some extra space for other uniforms
  10600. // - limit here is ANGLE's 254 max uniform vectors
  10601. // (up to 54 should be safe)
  10602. const nVertexUniforms = maxVertexUniforms;
  10603. const nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  10604. const maxBones = Math.min(nVertexMatrices, bones.length);
  10605. if (maxBones < bones.length) {
  10606. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  10607. return 0;
  10608. }
  10609. return maxBones;
  10610. }
  10611. }
  10612. function getTextureEncodingFromMap(map) {
  10613. let encoding;
  10614. if (map && map.isTexture) {
  10615. encoding = map.encoding;
  10616. } else if (map && map.isWebGLRenderTarget) {
  10617. console.warn('THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.');
  10618. encoding = map.texture.encoding;
  10619. } else {
  10620. encoding = LinearEncoding;
  10621. }
  10622. return encoding;
  10623. }
  10624. function getParameters(material, lights, shadows, scene, object) {
  10625. const fog = scene.fog;
  10626. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  10627. const envMap = cubemaps.get(material.envMap || environment);
  10628. const shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  10629. // (not to blow over maxLights budget)
  10630. const maxBones = object.isSkinnedMesh ? getMaxBones(object) : 0;
  10631. if (material.precision !== null) {
  10632. precision = capabilities.getMaxPrecision(material.precision);
  10633. if (precision !== material.precision) {
  10634. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  10635. }
  10636. }
  10637. let vertexShader, fragmentShader;
  10638. if (shaderID) {
  10639. const shader = ShaderLib[shaderID];
  10640. vertexShader = shader.vertexShader;
  10641. fragmentShader = shader.fragmentShader;
  10642. } else {
  10643. vertexShader = material.vertexShader;
  10644. fragmentShader = material.fragmentShader;
  10645. }
  10646. const currentRenderTarget = renderer.getRenderTarget();
  10647. const parameters = {
  10648. isWebGL2: isWebGL2,
  10649. shaderID: shaderID,
  10650. shaderName: material.type,
  10651. vertexShader: vertexShader,
  10652. fragmentShader: fragmentShader,
  10653. defines: material.defines,
  10654. isRawShaderMaterial: material.isRawShaderMaterial === true,
  10655. glslVersion: material.glslVersion,
  10656. precision: precision,
  10657. instancing: object.isInstancedMesh === true,
  10658. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  10659. supportsVertexTextures: vertexTextures,
  10660. outputEncoding: currentRenderTarget !== null ? getTextureEncodingFromMap(currentRenderTarget.texture) : renderer.outputEncoding,
  10661. map: !!material.map,
  10662. mapEncoding: getTextureEncodingFromMap(material.map),
  10663. matcap: !!material.matcap,
  10664. matcapEncoding: getTextureEncodingFromMap(material.matcap),
  10665. envMap: !!envMap,
  10666. envMapMode: envMap && envMap.mapping,
  10667. envMapEncoding: getTextureEncodingFromMap(envMap),
  10668. envMapCubeUV: !!envMap && (envMap.mapping === CubeUVReflectionMapping || envMap.mapping === CubeUVRefractionMapping),
  10669. lightMap: !!material.lightMap,
  10670. lightMapEncoding: getTextureEncodingFromMap(material.lightMap),
  10671. aoMap: !!material.aoMap,
  10672. emissiveMap: !!material.emissiveMap,
  10673. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap),
  10674. bumpMap: !!material.bumpMap,
  10675. normalMap: !!material.normalMap,
  10676. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  10677. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  10678. clearcoatMap: !!material.clearcoatMap,
  10679. clearcoatRoughnessMap: !!material.clearcoatRoughnessMap,
  10680. clearcoatNormalMap: !!material.clearcoatNormalMap,
  10681. displacementMap: !!material.displacementMap,
  10682. roughnessMap: !!material.roughnessMap,
  10683. metalnessMap: !!material.metalnessMap,
  10684. specularMap: !!material.specularMap,
  10685. alphaMap: !!material.alphaMap,
  10686. gradientMap: !!material.gradientMap,
  10687. sheen: !!material.sheen,
  10688. transmission: !!material.transmission,
  10689. transmissionMap: !!material.transmissionMap,
  10690. thicknessMap: !!material.thicknessMap,
  10691. combine: material.combine,
  10692. vertexTangents: material.normalMap && material.vertexTangents,
  10693. vertexColors: material.vertexColors,
  10694. vertexAlphas: material.vertexColors === true && object.geometry && object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4,
  10695. 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,
  10696. 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.displacementMap,
  10697. fog: !!fog,
  10698. useFog: material.fog,
  10699. fogExp2: fog && fog.isFogExp2,
  10700. flatShading: !!material.flatShading,
  10701. sizeAttenuation: material.sizeAttenuation,
  10702. logarithmicDepthBuffer: logarithmicDepthBuffer,
  10703. skinning: object.isSkinnedMesh === true && maxBones > 0,
  10704. maxBones: maxBones,
  10705. useVertexTexture: floatVertexTextures,
  10706. morphTargets: material.morphTargets,
  10707. morphNormals: material.morphNormals,
  10708. numDirLights: lights.directional.length,
  10709. numPointLights: lights.point.length,
  10710. numSpotLights: lights.spot.length,
  10711. numRectAreaLights: lights.rectArea.length,
  10712. numHemiLights: lights.hemi.length,
  10713. numDirLightShadows: lights.directionalShadowMap.length,
  10714. numPointLightShadows: lights.pointShadowMap.length,
  10715. numSpotLightShadows: lights.spotShadowMap.length,
  10716. numClippingPlanes: clipping.numPlanes,
  10717. numClipIntersection: clipping.numIntersection,
  10718. dithering: material.dithering,
  10719. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  10720. shadowMapType: renderer.shadowMap.type,
  10721. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  10722. physicallyCorrectLights: renderer.physicallyCorrectLights,
  10723. premultipliedAlpha: material.premultipliedAlpha,
  10724. alphaTest: material.alphaTest,
  10725. doubleSided: material.side === DoubleSide,
  10726. flipSided: material.side === BackSide,
  10727. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false,
  10728. index0AttributeName: material.index0AttributeName,
  10729. extensionDerivatives: material.extensions && material.extensions.derivatives,
  10730. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  10731. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  10732. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  10733. rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
  10734. rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
  10735. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
  10736. customProgramCacheKey: material.customProgramCacheKey()
  10737. };
  10738. return parameters;
  10739. }
  10740. function getProgramCacheKey(parameters) {
  10741. const array = [];
  10742. if (parameters.shaderID) {
  10743. array.push(parameters.shaderID);
  10744. } else {
  10745. array.push(parameters.fragmentShader);
  10746. array.push(parameters.vertexShader);
  10747. }
  10748. if (parameters.defines !== undefined) {
  10749. for (const name in parameters.defines) {
  10750. array.push(name);
  10751. array.push(parameters.defines[name]);
  10752. }
  10753. }
  10754. if (parameters.isRawShaderMaterial === false) {
  10755. for (let i = 0; i < parameterNames.length; i++) {
  10756. array.push(parameters[parameterNames[i]]);
  10757. }
  10758. array.push(renderer.outputEncoding);
  10759. array.push(renderer.gammaFactor);
  10760. }
  10761. array.push(parameters.customProgramCacheKey);
  10762. return array.join();
  10763. }
  10764. function getUniforms(material) {
  10765. const shaderID = shaderIDs[material.type];
  10766. let uniforms;
  10767. if (shaderID) {
  10768. const shader = ShaderLib[shaderID];
  10769. uniforms = UniformsUtils.clone(shader.uniforms);
  10770. } else {
  10771. uniforms = material.uniforms;
  10772. }
  10773. return uniforms;
  10774. }
  10775. function acquireProgram(parameters, cacheKey) {
  10776. let program; // Check if code has been already compiled
  10777. for (let p = 0, pl = programs.length; p < pl; p++) {
  10778. const preexistingProgram = programs[p];
  10779. if (preexistingProgram.cacheKey === cacheKey) {
  10780. program = preexistingProgram;
  10781. ++program.usedTimes;
  10782. break;
  10783. }
  10784. }
  10785. if (program === undefined) {
  10786. program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
  10787. programs.push(program);
  10788. }
  10789. return program;
  10790. }
  10791. function releaseProgram(program) {
  10792. if (--program.usedTimes === 0) {
  10793. // Remove from unordered set
  10794. const i = programs.indexOf(program);
  10795. programs[i] = programs[programs.length - 1];
  10796. programs.pop(); // Free WebGL resources
  10797. program.destroy();
  10798. }
  10799. }
  10800. return {
  10801. getParameters: getParameters,
  10802. getProgramCacheKey: getProgramCacheKey,
  10803. getUniforms: getUniforms,
  10804. acquireProgram: acquireProgram,
  10805. releaseProgram: releaseProgram,
  10806. // Exposed for resource monitoring & error feedback via renderer.info:
  10807. programs: programs
  10808. };
  10809. }
  10810. function WebGLProperties() {
  10811. let properties = new WeakMap();
  10812. function get(object) {
  10813. let map = properties.get(object);
  10814. if (map === undefined) {
  10815. map = {};
  10816. properties.set(object, map);
  10817. }
  10818. return map;
  10819. }
  10820. function remove(object) {
  10821. properties.delete(object);
  10822. }
  10823. function update(object, key, value) {
  10824. properties.get(object)[key] = value;
  10825. }
  10826. function dispose() {
  10827. properties = new WeakMap();
  10828. }
  10829. return {
  10830. get: get,
  10831. remove: remove,
  10832. update: update,
  10833. dispose: dispose
  10834. };
  10835. }
  10836. function painterSortStable(a, b) {
  10837. if (a.groupOrder !== b.groupOrder) {
  10838. return a.groupOrder - b.groupOrder;
  10839. } else if (a.renderOrder !== b.renderOrder) {
  10840. return a.renderOrder - b.renderOrder;
  10841. } else if (a.program !== b.program) {
  10842. return a.program.id - b.program.id;
  10843. } else if (a.material.id !== b.material.id) {
  10844. return a.material.id - b.material.id;
  10845. } else if (a.z !== b.z) {
  10846. return a.z - b.z;
  10847. } else {
  10848. return a.id - b.id;
  10849. }
  10850. }
  10851. function reversePainterSortStable(a, b) {
  10852. if (a.groupOrder !== b.groupOrder) {
  10853. return a.groupOrder - b.groupOrder;
  10854. } else if (a.renderOrder !== b.renderOrder) {
  10855. return a.renderOrder - b.renderOrder;
  10856. } else if (a.z !== b.z) {
  10857. return b.z - a.z;
  10858. } else {
  10859. return a.id - b.id;
  10860. }
  10861. }
  10862. function WebGLRenderList(properties) {
  10863. const renderItems = [];
  10864. let renderItemsIndex = 0;
  10865. const opaque = [];
  10866. const transmissive = [];
  10867. const transparent = [];
  10868. const defaultProgram = {
  10869. id: -1
  10870. };
  10871. function init() {
  10872. renderItemsIndex = 0;
  10873. opaque.length = 0;
  10874. transmissive.length = 0;
  10875. transparent.length = 0;
  10876. }
  10877. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  10878. let renderItem = renderItems[renderItemsIndex];
  10879. const materialProperties = properties.get(material);
  10880. if (renderItem === undefined) {
  10881. renderItem = {
  10882. id: object.id,
  10883. object: object,
  10884. geometry: geometry,
  10885. material: material,
  10886. program: materialProperties.program || defaultProgram,
  10887. groupOrder: groupOrder,
  10888. renderOrder: object.renderOrder,
  10889. z: z,
  10890. group: group
  10891. };
  10892. renderItems[renderItemsIndex] = renderItem;
  10893. } else {
  10894. renderItem.id = object.id;
  10895. renderItem.object = object;
  10896. renderItem.geometry = geometry;
  10897. renderItem.material = material;
  10898. renderItem.program = materialProperties.program || defaultProgram;
  10899. renderItem.groupOrder = groupOrder;
  10900. renderItem.renderOrder = object.renderOrder;
  10901. renderItem.z = z;
  10902. renderItem.group = group;
  10903. }
  10904. renderItemsIndex++;
  10905. return renderItem;
  10906. }
  10907. function push(object, geometry, material, groupOrder, z, group) {
  10908. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  10909. if (material.transmission > 0.0) {
  10910. transmissive.push(renderItem);
  10911. } else if (material.transparent === true) {
  10912. transparent.push(renderItem);
  10913. } else {
  10914. opaque.push(renderItem);
  10915. }
  10916. }
  10917. function unshift(object, geometry, material, groupOrder, z, group) {
  10918. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  10919. if (material.transmission > 0.0) {
  10920. transmissive.unshift(renderItem);
  10921. } else if (material.transparent === true) {
  10922. transparent.unshift(renderItem);
  10923. } else {
  10924. opaque.unshift(renderItem);
  10925. }
  10926. }
  10927. function sort(customOpaqueSort, customTransparentSort) {
  10928. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  10929. if (transmissive.length > 1) transmissive.sort(customTransparentSort || reversePainterSortStable);
  10930. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  10931. }
  10932. function finish() {
  10933. // Clear references from inactive renderItems in the list
  10934. for (let i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  10935. const renderItem = renderItems[i];
  10936. if (renderItem.id === null) break;
  10937. renderItem.id = null;
  10938. renderItem.object = null;
  10939. renderItem.geometry = null;
  10940. renderItem.material = null;
  10941. renderItem.program = null;
  10942. renderItem.group = null;
  10943. }
  10944. }
  10945. return {
  10946. opaque: opaque,
  10947. transmissive: transmissive,
  10948. transparent: transparent,
  10949. init: init,
  10950. push: push,
  10951. unshift: unshift,
  10952. finish: finish,
  10953. sort: sort
  10954. };
  10955. }
  10956. function WebGLRenderLists(properties) {
  10957. let lists = new WeakMap();
  10958. function get(scene, renderCallDepth) {
  10959. let list;
  10960. if (lists.has(scene) === false) {
  10961. list = new WebGLRenderList(properties);
  10962. lists.set(scene, [list]);
  10963. } else {
  10964. if (renderCallDepth >= lists.get(scene).length) {
  10965. list = new WebGLRenderList(properties);
  10966. lists.get(scene).push(list);
  10967. } else {
  10968. list = lists.get(scene)[renderCallDepth];
  10969. }
  10970. }
  10971. return list;
  10972. }
  10973. function dispose() {
  10974. lists = new WeakMap();
  10975. }
  10976. return {
  10977. get: get,
  10978. dispose: dispose
  10979. };
  10980. }
  10981. function UniformsCache() {
  10982. const lights = {};
  10983. return {
  10984. get: function (light) {
  10985. if (lights[light.id] !== undefined) {
  10986. return lights[light.id];
  10987. }
  10988. let uniforms;
  10989. switch (light.type) {
  10990. case 'DirectionalLight':
  10991. uniforms = {
  10992. direction: new Vector3(),
  10993. color: new Color()
  10994. };
  10995. break;
  10996. case 'SpotLight':
  10997. uniforms = {
  10998. position: new Vector3(),
  10999. direction: new Vector3(),
  11000. color: new Color(),
  11001. distance: 0,
  11002. coneCos: 0,
  11003. penumbraCos: 0,
  11004. decay: 0
  11005. };
  11006. break;
  11007. case 'PointLight':
  11008. uniforms = {
  11009. position: new Vector3(),
  11010. color: new Color(),
  11011. distance: 0,
  11012. decay: 0
  11013. };
  11014. break;
  11015. case 'HemisphereLight':
  11016. uniforms = {
  11017. direction: new Vector3(),
  11018. skyColor: new Color(),
  11019. groundColor: new Color()
  11020. };
  11021. break;
  11022. case 'RectAreaLight':
  11023. uniforms = {
  11024. color: new Color(),
  11025. position: new Vector3(),
  11026. halfWidth: new Vector3(),
  11027. halfHeight: new Vector3()
  11028. };
  11029. break;
  11030. }
  11031. lights[light.id] = uniforms;
  11032. return uniforms;
  11033. }
  11034. };
  11035. }
  11036. function ShadowUniformsCache() {
  11037. const lights = {};
  11038. return {
  11039. get: function (light) {
  11040. if (lights[light.id] !== undefined) {
  11041. return lights[light.id];
  11042. }
  11043. let uniforms;
  11044. switch (light.type) {
  11045. case 'DirectionalLight':
  11046. uniforms = {
  11047. shadowBias: 0,
  11048. shadowNormalBias: 0,
  11049. shadowRadius: 1,
  11050. shadowMapSize: new Vector2()
  11051. };
  11052. break;
  11053. case 'SpotLight':
  11054. uniforms = {
  11055. shadowBias: 0,
  11056. shadowNormalBias: 0,
  11057. shadowRadius: 1,
  11058. shadowMapSize: new Vector2()
  11059. };
  11060. break;
  11061. case 'PointLight':
  11062. uniforms = {
  11063. shadowBias: 0,
  11064. shadowNormalBias: 0,
  11065. shadowRadius: 1,
  11066. shadowMapSize: new Vector2(),
  11067. shadowCameraNear: 1,
  11068. shadowCameraFar: 1000
  11069. };
  11070. break;
  11071. // TODO (abelnation): set RectAreaLight shadow uniforms
  11072. }
  11073. lights[light.id] = uniforms;
  11074. return uniforms;
  11075. }
  11076. };
  11077. }
  11078. let nextVersion = 0;
  11079. function shadowCastingLightsFirst(lightA, lightB) {
  11080. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  11081. }
  11082. function WebGLLights(extensions, capabilities) {
  11083. const cache = new UniformsCache();
  11084. const shadowCache = ShadowUniformsCache();
  11085. const state = {
  11086. version: 0,
  11087. hash: {
  11088. directionalLength: -1,
  11089. pointLength: -1,
  11090. spotLength: -1,
  11091. rectAreaLength: -1,
  11092. hemiLength: -1,
  11093. numDirectionalShadows: -1,
  11094. numPointShadows: -1,
  11095. numSpotShadows: -1
  11096. },
  11097. ambient: [0, 0, 0],
  11098. probe: [],
  11099. directional: [],
  11100. directionalShadow: [],
  11101. directionalShadowMap: [],
  11102. directionalShadowMatrix: [],
  11103. spot: [],
  11104. spotShadow: [],
  11105. spotShadowMap: [],
  11106. spotShadowMatrix: [],
  11107. rectArea: [],
  11108. rectAreaLTC1: null,
  11109. rectAreaLTC2: null,
  11110. point: [],
  11111. pointShadow: [],
  11112. pointShadowMap: [],
  11113. pointShadowMatrix: [],
  11114. hemi: []
  11115. };
  11116. for (let i = 0; i < 9; i++) state.probe.push(new Vector3());
  11117. const vector3 = new Vector3();
  11118. const matrix4 = new Matrix4();
  11119. const matrix42 = new Matrix4();
  11120. function setup(lights) {
  11121. let r = 0,
  11122. g = 0,
  11123. b = 0;
  11124. for (let i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  11125. let directionalLength = 0;
  11126. let pointLength = 0;
  11127. let spotLength = 0;
  11128. let rectAreaLength = 0;
  11129. let hemiLength = 0;
  11130. let numDirectionalShadows = 0;
  11131. let numPointShadows = 0;
  11132. let numSpotShadows = 0;
  11133. lights.sort(shadowCastingLightsFirst);
  11134. for (let i = 0, l = lights.length; i < l; i++) {
  11135. const light = lights[i];
  11136. const color = light.color;
  11137. const intensity = light.intensity;
  11138. const distance = light.distance;
  11139. const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  11140. if (light.isAmbientLight) {
  11141. r += color.r * intensity;
  11142. g += color.g * intensity;
  11143. b += color.b * intensity;
  11144. } else if (light.isLightProbe) {
  11145. for (let j = 0; j < 9; j++) {
  11146. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  11147. }
  11148. } else if (light.isDirectionalLight) {
  11149. const uniforms = cache.get(light);
  11150. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  11151. if (light.castShadow) {
  11152. const shadow = light.shadow;
  11153. const shadowUniforms = shadowCache.get(light);
  11154. shadowUniforms.shadowBias = shadow.bias;
  11155. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11156. shadowUniforms.shadowRadius = shadow.radius;
  11157. shadowUniforms.shadowMapSize = shadow.mapSize;
  11158. state.directionalShadow[directionalLength] = shadowUniforms;
  11159. state.directionalShadowMap[directionalLength] = shadowMap;
  11160. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  11161. numDirectionalShadows++;
  11162. }
  11163. state.directional[directionalLength] = uniforms;
  11164. directionalLength++;
  11165. } else if (light.isSpotLight) {
  11166. const uniforms = cache.get(light);
  11167. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11168. uniforms.color.copy(color).multiplyScalar(intensity);
  11169. uniforms.distance = distance;
  11170. uniforms.coneCos = Math.cos(light.angle);
  11171. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  11172. uniforms.decay = light.decay;
  11173. if (light.castShadow) {
  11174. const shadow = light.shadow;
  11175. const shadowUniforms = shadowCache.get(light);
  11176. shadowUniforms.shadowBias = shadow.bias;
  11177. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11178. shadowUniforms.shadowRadius = shadow.radius;
  11179. shadowUniforms.shadowMapSize = shadow.mapSize;
  11180. state.spotShadow[spotLength] = shadowUniforms;
  11181. state.spotShadowMap[spotLength] = shadowMap;
  11182. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  11183. numSpotShadows++;
  11184. }
  11185. state.spot[spotLength] = uniforms;
  11186. spotLength++;
  11187. } else if (light.isRectAreaLight) {
  11188. const uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  11189. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  11190. // (b) intensity is the brightness of the light
  11191. uniforms.color.copy(color).multiplyScalar(intensity);
  11192. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  11193. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  11194. state.rectArea[rectAreaLength] = uniforms;
  11195. rectAreaLength++;
  11196. } else if (light.isPointLight) {
  11197. const uniforms = cache.get(light);
  11198. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  11199. uniforms.distance = light.distance;
  11200. uniforms.decay = light.decay;
  11201. if (light.castShadow) {
  11202. const shadow = light.shadow;
  11203. const shadowUniforms = shadowCache.get(light);
  11204. shadowUniforms.shadowBias = shadow.bias;
  11205. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11206. shadowUniforms.shadowRadius = shadow.radius;
  11207. shadowUniforms.shadowMapSize = shadow.mapSize;
  11208. shadowUniforms.shadowCameraNear = shadow.camera.near;
  11209. shadowUniforms.shadowCameraFar = shadow.camera.far;
  11210. state.pointShadow[pointLength] = shadowUniforms;
  11211. state.pointShadowMap[pointLength] = shadowMap;
  11212. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  11213. numPointShadows++;
  11214. }
  11215. state.point[pointLength] = uniforms;
  11216. pointLength++;
  11217. } else if (light.isHemisphereLight) {
  11218. const uniforms = cache.get(light);
  11219. uniforms.skyColor.copy(light.color).multiplyScalar(intensity);
  11220. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity);
  11221. state.hemi[hemiLength] = uniforms;
  11222. hemiLength++;
  11223. }
  11224. }
  11225. if (rectAreaLength > 0) {
  11226. if (capabilities.isWebGL2) {
  11227. // WebGL 2
  11228. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11229. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11230. } else {
  11231. // WebGL 1
  11232. if (extensions.has('OES_texture_float_linear') === true) {
  11233. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11234. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11235. } else if (extensions.has('OES_texture_half_float_linear') === true) {
  11236. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  11237. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  11238. } else {
  11239. console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
  11240. }
  11241. }
  11242. }
  11243. state.ambient[0] = r;
  11244. state.ambient[1] = g;
  11245. state.ambient[2] = b;
  11246. const hash = state.hash;
  11247. 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) {
  11248. state.directional.length = directionalLength;
  11249. state.spot.length = spotLength;
  11250. state.rectArea.length = rectAreaLength;
  11251. state.point.length = pointLength;
  11252. state.hemi.length = hemiLength;
  11253. state.directionalShadow.length = numDirectionalShadows;
  11254. state.directionalShadowMap.length = numDirectionalShadows;
  11255. state.pointShadow.length = numPointShadows;
  11256. state.pointShadowMap.length = numPointShadows;
  11257. state.spotShadow.length = numSpotShadows;
  11258. state.spotShadowMap.length = numSpotShadows;
  11259. state.directionalShadowMatrix.length = numDirectionalShadows;
  11260. state.pointShadowMatrix.length = numPointShadows;
  11261. state.spotShadowMatrix.length = numSpotShadows;
  11262. hash.directionalLength = directionalLength;
  11263. hash.pointLength = pointLength;
  11264. hash.spotLength = spotLength;
  11265. hash.rectAreaLength = rectAreaLength;
  11266. hash.hemiLength = hemiLength;
  11267. hash.numDirectionalShadows = numDirectionalShadows;
  11268. hash.numPointShadows = numPointShadows;
  11269. hash.numSpotShadows = numSpotShadows;
  11270. state.version = nextVersion++;
  11271. }
  11272. }
  11273. function setupView(lights, camera) {
  11274. let directionalLength = 0;
  11275. let pointLength = 0;
  11276. let spotLength = 0;
  11277. let rectAreaLength = 0;
  11278. let hemiLength = 0;
  11279. const viewMatrix = camera.matrixWorldInverse;
  11280. for (let i = 0, l = lights.length; i < l; i++) {
  11281. const light = lights[i];
  11282. if (light.isDirectionalLight) {
  11283. const uniforms = state.directional[directionalLength];
  11284. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11285. vector3.setFromMatrixPosition(light.target.matrixWorld);
  11286. uniforms.direction.sub(vector3);
  11287. uniforms.direction.transformDirection(viewMatrix);
  11288. directionalLength++;
  11289. } else if (light.isSpotLight) {
  11290. const uniforms = state.spot[spotLength];
  11291. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11292. uniforms.position.applyMatrix4(viewMatrix);
  11293. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11294. vector3.setFromMatrixPosition(light.target.matrixWorld);
  11295. uniforms.direction.sub(vector3);
  11296. uniforms.direction.transformDirection(viewMatrix);
  11297. spotLength++;
  11298. } else if (light.isRectAreaLight) {
  11299. const uniforms = state.rectArea[rectAreaLength];
  11300. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11301. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  11302. matrix42.identity();
  11303. matrix4.copy(light.matrixWorld);
  11304. matrix4.premultiply(viewMatrix);
  11305. matrix42.extractRotation(matrix4);
  11306. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  11307. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  11308. uniforms.halfWidth.applyMatrix4(matrix42);
  11309. uniforms.halfHeight.applyMatrix4(matrix42);
  11310. rectAreaLength++;
  11311. } else if (light.isPointLight) {
  11312. const uniforms = state.point[pointLength];
  11313. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11314. uniforms.position.applyMatrix4(viewMatrix);
  11315. pointLength++;
  11316. } else if (light.isHemisphereLight) {
  11317. const uniforms = state.hemi[hemiLength];
  11318. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11319. uniforms.direction.transformDirection(viewMatrix);
  11320. uniforms.direction.normalize();
  11321. hemiLength++;
  11322. }
  11323. }
  11324. }
  11325. return {
  11326. setup: setup,
  11327. setupView: setupView,
  11328. state: state
  11329. };
  11330. }
  11331. function WebGLRenderState(extensions, capabilities) {
  11332. const lights = new WebGLLights(extensions, capabilities);
  11333. const lightsArray = [];
  11334. const shadowsArray = [];
  11335. function init() {
  11336. lightsArray.length = 0;
  11337. shadowsArray.length = 0;
  11338. }
  11339. function pushLight(light) {
  11340. lightsArray.push(light);
  11341. }
  11342. function pushShadow(shadowLight) {
  11343. shadowsArray.push(shadowLight);
  11344. }
  11345. function setupLights() {
  11346. lights.setup(lightsArray);
  11347. }
  11348. function setupLightsView(camera) {
  11349. lights.setupView(lightsArray, camera);
  11350. }
  11351. const state = {
  11352. lightsArray: lightsArray,
  11353. shadowsArray: shadowsArray,
  11354. lights: lights
  11355. };
  11356. return {
  11357. init: init,
  11358. state: state,
  11359. setupLights: setupLights,
  11360. setupLightsView: setupLightsView,
  11361. pushLight: pushLight,
  11362. pushShadow: pushShadow
  11363. };
  11364. }
  11365. function WebGLRenderStates(extensions, capabilities) {
  11366. let renderStates = new WeakMap();
  11367. function get(scene, renderCallDepth = 0) {
  11368. let renderState;
  11369. if (renderStates.has(scene) === false) {
  11370. renderState = new WebGLRenderState(extensions, capabilities);
  11371. renderStates.set(scene, [renderState]);
  11372. } else {
  11373. if (renderCallDepth >= renderStates.get(scene).length) {
  11374. renderState = new WebGLRenderState(extensions, capabilities);
  11375. renderStates.get(scene).push(renderState);
  11376. } else {
  11377. renderState = renderStates.get(scene)[renderCallDepth];
  11378. }
  11379. }
  11380. return renderState;
  11381. }
  11382. function dispose() {
  11383. renderStates = new WeakMap();
  11384. }
  11385. return {
  11386. get: get,
  11387. dispose: dispose
  11388. };
  11389. }
  11390. /**
  11391. * parameters = {
  11392. *
  11393. * opacity: <float>,
  11394. *
  11395. * map: new THREE.Texture( <Image> ),
  11396. *
  11397. * alphaMap: new THREE.Texture( <Image> ),
  11398. *
  11399. * displacementMap: new THREE.Texture( <Image> ),
  11400. * displacementScale: <float>,
  11401. * displacementBias: <float>,
  11402. *
  11403. * wireframe: <boolean>,
  11404. * wireframeLinewidth: <float>
  11405. * }
  11406. */
  11407. class MeshDepthMaterial extends Material {
  11408. constructor(parameters) {
  11409. super();
  11410. this.type = 'MeshDepthMaterial';
  11411. this.depthPacking = BasicDepthPacking;
  11412. this.morphTargets = false;
  11413. this.map = null;
  11414. this.alphaMap = null;
  11415. this.displacementMap = null;
  11416. this.displacementScale = 1;
  11417. this.displacementBias = 0;
  11418. this.wireframe = false;
  11419. this.wireframeLinewidth = 1;
  11420. this.fog = false;
  11421. this.setValues(parameters);
  11422. }
  11423. copy(source) {
  11424. super.copy(source);
  11425. this.depthPacking = source.depthPacking;
  11426. this.morphTargets = source.morphTargets;
  11427. this.map = source.map;
  11428. this.alphaMap = source.alphaMap;
  11429. this.displacementMap = source.displacementMap;
  11430. this.displacementScale = source.displacementScale;
  11431. this.displacementBias = source.displacementBias;
  11432. this.wireframe = source.wireframe;
  11433. this.wireframeLinewidth = source.wireframeLinewidth;
  11434. return this;
  11435. }
  11436. }
  11437. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  11438. /**
  11439. * parameters = {
  11440. *
  11441. * referencePosition: <float>,
  11442. * nearDistance: <float>,
  11443. * farDistance: <float>,
  11444. *
  11445. * morphTargets: <bool>,
  11446. *
  11447. * map: new THREE.Texture( <Image> ),
  11448. *
  11449. * alphaMap: new THREE.Texture( <Image> ),
  11450. *
  11451. * displacementMap: new THREE.Texture( <Image> ),
  11452. * displacementScale: <float>,
  11453. * displacementBias: <float>
  11454. *
  11455. * }
  11456. */
  11457. class MeshDistanceMaterial extends Material {
  11458. constructor(parameters) {
  11459. super();
  11460. this.type = 'MeshDistanceMaterial';
  11461. this.referencePosition = new Vector3();
  11462. this.nearDistance = 1;
  11463. this.farDistance = 1000;
  11464. this.morphTargets = false;
  11465. this.map = null;
  11466. this.alphaMap = null;
  11467. this.displacementMap = null;
  11468. this.displacementScale = 1;
  11469. this.displacementBias = 0;
  11470. this.fog = false;
  11471. this.setValues(parameters);
  11472. }
  11473. copy(source) {
  11474. super.copy(source);
  11475. this.referencePosition.copy(source.referencePosition);
  11476. this.nearDistance = source.nearDistance;
  11477. this.farDistance = source.farDistance;
  11478. this.morphTargets = source.morphTargets;
  11479. this.map = source.map;
  11480. this.alphaMap = source.alphaMap;
  11481. this.displacementMap = source.displacementMap;
  11482. this.displacementScale = source.displacementScale;
  11483. this.displacementBias = source.displacementBias;
  11484. return this;
  11485. }
  11486. }
  11487. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  11488. var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n\tfor ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, i ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean * HALF_SAMPLE_RATE;\n\tsquared_mean = squared_mean * HALF_SAMPLE_RATE;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  11489. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  11490. function WebGLShadowMap(_renderer, _objects, _capabilities) {
  11491. let _frustum = new Frustum();
  11492. const _shadowMapSize = new Vector2(),
  11493. _viewportSize = new Vector2(),
  11494. _viewport = new Vector4(),
  11495. _depthMaterials = [],
  11496. _distanceMaterials = [],
  11497. _materialCache = {},
  11498. _maxTextureSize = _capabilities.maxTextureSize;
  11499. const shadowSide = {
  11500. 0: BackSide,
  11501. 1: FrontSide,
  11502. 2: DoubleSide
  11503. };
  11504. const shadowMaterialVertical = new ShaderMaterial({
  11505. defines: {
  11506. SAMPLE_RATE: 2.0 / 8.0,
  11507. HALF_SAMPLE_RATE: 1.0 / 8.0
  11508. },
  11509. uniforms: {
  11510. shadow_pass: {
  11511. value: null
  11512. },
  11513. resolution: {
  11514. value: new Vector2()
  11515. },
  11516. radius: {
  11517. value: 4.0
  11518. }
  11519. },
  11520. vertexShader: vsm_vert,
  11521. fragmentShader: vsm_frag
  11522. });
  11523. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  11524. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  11525. const fullScreenTri = new BufferGeometry();
  11526. fullScreenTri.setAttribute('position', new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  11527. const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  11528. const scope = this;
  11529. this.enabled = false;
  11530. this.autoUpdate = true;
  11531. this.needsUpdate = false;
  11532. this.type = PCFShadowMap;
  11533. this.render = function (lights, scene, camera) {
  11534. if (scope.enabled === false) return;
  11535. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  11536. if (lights.length === 0) return;
  11537. const currentRenderTarget = _renderer.getRenderTarget();
  11538. const activeCubeFace = _renderer.getActiveCubeFace();
  11539. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  11540. const _state = _renderer.state; // Set GL state for depth map.
  11541. _state.setBlending(NoBlending);
  11542. _state.buffers.color.setClear(1, 1, 1, 1);
  11543. _state.buffers.depth.setTest(true);
  11544. _state.setScissorTest(false); // render depth map
  11545. for (let i = 0, il = lights.length; i < il; i++) {
  11546. const light = lights[i];
  11547. const shadow = light.shadow;
  11548. if (shadow === undefined) {
  11549. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  11550. continue;
  11551. }
  11552. if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
  11553. _shadowMapSize.copy(shadow.mapSize);
  11554. const shadowFrameExtents = shadow.getFrameExtents();
  11555. _shadowMapSize.multiply(shadowFrameExtents);
  11556. _viewportSize.copy(shadow.mapSize);
  11557. if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) {
  11558. if (_shadowMapSize.x > _maxTextureSize) {
  11559. _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x);
  11560. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  11561. shadow.mapSize.x = _viewportSize.x;
  11562. }
  11563. if (_shadowMapSize.y > _maxTextureSize) {
  11564. _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y);
  11565. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  11566. shadow.mapSize.y = _viewportSize.y;
  11567. }
  11568. }
  11569. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  11570. const pars = {
  11571. minFilter: LinearFilter,
  11572. magFilter: LinearFilter,
  11573. format: RGBAFormat
  11574. };
  11575. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  11576. shadow.map.texture.name = light.name + '.shadowMap';
  11577. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  11578. shadow.camera.updateProjectionMatrix();
  11579. }
  11580. if (shadow.map === null) {
  11581. const pars = {
  11582. minFilter: NearestFilter,
  11583. magFilter: NearestFilter,
  11584. format: RGBAFormat
  11585. };
  11586. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  11587. shadow.map.texture.name = light.name + '.shadowMap';
  11588. shadow.camera.updateProjectionMatrix();
  11589. }
  11590. _renderer.setRenderTarget(shadow.map);
  11591. _renderer.clear();
  11592. const viewportCount = shadow.getViewportCount();
  11593. for (let vp = 0; vp < viewportCount; vp++) {
  11594. const viewport = shadow.getViewport(vp);
  11595. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  11596. _state.viewport(_viewport);
  11597. shadow.updateMatrices(light, vp);
  11598. _frustum = shadow.getFrustum();
  11599. renderObject(scene, camera, shadow.camera, light, this.type);
  11600. } // do blur pass for VSM
  11601. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  11602. VSMPass(shadow, camera);
  11603. }
  11604. shadow.needsUpdate = false;
  11605. }
  11606. scope.needsUpdate = false;
  11607. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  11608. };
  11609. function VSMPass(shadow, camera) {
  11610. const geometry = _objects.update(fullScreenMesh); // vertical pass
  11611. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  11612. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  11613. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  11614. _renderer.setRenderTarget(shadow.mapPass);
  11615. _renderer.clear();
  11616. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizontal pass
  11617. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  11618. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  11619. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  11620. _renderer.setRenderTarget(shadow.map);
  11621. _renderer.clear();
  11622. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null);
  11623. }
  11624. function getDepthMaterialVariant(useMorphing) {
  11625. const index = useMorphing << 0;
  11626. let material = _depthMaterials[index];
  11627. if (material === undefined) {
  11628. material = new MeshDepthMaterial({
  11629. depthPacking: RGBADepthPacking,
  11630. morphTargets: useMorphing
  11631. });
  11632. _depthMaterials[index] = material;
  11633. }
  11634. return material;
  11635. }
  11636. function getDistanceMaterialVariant(useMorphing) {
  11637. const index = useMorphing << 0;
  11638. let material = _distanceMaterials[index];
  11639. if (material === undefined) {
  11640. material = new MeshDistanceMaterial({
  11641. morphTargets: useMorphing
  11642. });
  11643. _distanceMaterials[index] = material;
  11644. }
  11645. return material;
  11646. }
  11647. function getDepthMaterial(object, geometry, material, light, shadowCameraNear, shadowCameraFar, type) {
  11648. let result = null;
  11649. let getMaterialVariant = getDepthMaterialVariant;
  11650. let customMaterial = object.customDepthMaterial;
  11651. if (light.isPointLight === true) {
  11652. getMaterialVariant = getDistanceMaterialVariant;
  11653. customMaterial = object.customDistanceMaterial;
  11654. }
  11655. if (customMaterial === undefined) {
  11656. let useMorphing = false;
  11657. if (material.morphTargets === true) {
  11658. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  11659. }
  11660. result = getMaterialVariant(useMorphing);
  11661. } else {
  11662. result = customMaterial;
  11663. }
  11664. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0) {
  11665. // in this case we need a unique material instance reflecting the
  11666. // appropriate state
  11667. const keyA = result.uuid,
  11668. keyB = material.uuid;
  11669. let materialsForVariant = _materialCache[keyA];
  11670. if (materialsForVariant === undefined) {
  11671. materialsForVariant = {};
  11672. _materialCache[keyA] = materialsForVariant;
  11673. }
  11674. let cachedMaterial = materialsForVariant[keyB];
  11675. if (cachedMaterial === undefined) {
  11676. cachedMaterial = result.clone();
  11677. materialsForVariant[keyB] = cachedMaterial;
  11678. }
  11679. result = cachedMaterial;
  11680. }
  11681. result.visible = material.visible;
  11682. result.wireframe = material.wireframe;
  11683. if (type === VSMShadowMap) {
  11684. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  11685. } else {
  11686. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  11687. }
  11688. result.clipShadows = material.clipShadows;
  11689. result.clippingPlanes = material.clippingPlanes;
  11690. result.clipIntersection = material.clipIntersection;
  11691. result.wireframeLinewidth = material.wireframeLinewidth;
  11692. result.linewidth = material.linewidth;
  11693. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  11694. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  11695. result.nearDistance = shadowCameraNear;
  11696. result.farDistance = shadowCameraFar;
  11697. }
  11698. return result;
  11699. }
  11700. function renderObject(object, camera, shadowCamera, light, type) {
  11701. if (object.visible === false) return;
  11702. const visible = object.layers.test(camera.layers);
  11703. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  11704. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  11705. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  11706. const geometry = _objects.update(object);
  11707. const material = object.material;
  11708. if (Array.isArray(material)) {
  11709. const groups = geometry.groups;
  11710. for (let k = 0, kl = groups.length; k < kl; k++) {
  11711. const group = groups[k];
  11712. const groupMaterial = material[group.materialIndex];
  11713. if (groupMaterial && groupMaterial.visible) {
  11714. const depthMaterial = getDepthMaterial(object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  11715. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  11716. }
  11717. }
  11718. } else if (material.visible) {
  11719. const depthMaterial = getDepthMaterial(object, geometry, material, light, shadowCamera.near, shadowCamera.far, type);
  11720. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  11721. }
  11722. }
  11723. }
  11724. const children = object.children;
  11725. for (let i = 0, l = children.length; i < l; i++) {
  11726. renderObject(children[i], camera, shadowCamera, light, type);
  11727. }
  11728. }
  11729. }
  11730. function WebGLState(gl, extensions, capabilities) {
  11731. const isWebGL2 = capabilities.isWebGL2;
  11732. function ColorBuffer() {
  11733. let locked = false;
  11734. const color = new Vector4();
  11735. let currentColorMask = null;
  11736. const currentColorClear = new Vector4(0, 0, 0, 0);
  11737. return {
  11738. setMask: function (colorMask) {
  11739. if (currentColorMask !== colorMask && !locked) {
  11740. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  11741. currentColorMask = colorMask;
  11742. }
  11743. },
  11744. setLocked: function (lock) {
  11745. locked = lock;
  11746. },
  11747. setClear: function (r, g, b, a, premultipliedAlpha) {
  11748. if (premultipliedAlpha === true) {
  11749. r *= a;
  11750. g *= a;
  11751. b *= a;
  11752. }
  11753. color.set(r, g, b, a);
  11754. if (currentColorClear.equals(color) === false) {
  11755. gl.clearColor(r, g, b, a);
  11756. currentColorClear.copy(color);
  11757. }
  11758. },
  11759. reset: function () {
  11760. locked = false;
  11761. currentColorMask = null;
  11762. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  11763. }
  11764. };
  11765. }
  11766. function DepthBuffer() {
  11767. let locked = false;
  11768. let currentDepthMask = null;
  11769. let currentDepthFunc = null;
  11770. let currentDepthClear = null;
  11771. return {
  11772. setTest: function (depthTest) {
  11773. if (depthTest) {
  11774. enable(gl.DEPTH_TEST);
  11775. } else {
  11776. disable(gl.DEPTH_TEST);
  11777. }
  11778. },
  11779. setMask: function (depthMask) {
  11780. if (currentDepthMask !== depthMask && !locked) {
  11781. gl.depthMask(depthMask);
  11782. currentDepthMask = depthMask;
  11783. }
  11784. },
  11785. setFunc: function (depthFunc) {
  11786. if (currentDepthFunc !== depthFunc) {
  11787. if (depthFunc) {
  11788. switch (depthFunc) {
  11789. case NeverDepth:
  11790. gl.depthFunc(gl.NEVER);
  11791. break;
  11792. case AlwaysDepth:
  11793. gl.depthFunc(gl.ALWAYS);
  11794. break;
  11795. case LessDepth:
  11796. gl.depthFunc(gl.LESS);
  11797. break;
  11798. case LessEqualDepth:
  11799. gl.depthFunc(gl.LEQUAL);
  11800. break;
  11801. case EqualDepth:
  11802. gl.depthFunc(gl.EQUAL);
  11803. break;
  11804. case GreaterEqualDepth:
  11805. gl.depthFunc(gl.GEQUAL);
  11806. break;
  11807. case GreaterDepth:
  11808. gl.depthFunc(gl.GREATER);
  11809. break;
  11810. case NotEqualDepth:
  11811. gl.depthFunc(gl.NOTEQUAL);
  11812. break;
  11813. default:
  11814. gl.depthFunc(gl.LEQUAL);
  11815. }
  11816. } else {
  11817. gl.depthFunc(gl.LEQUAL);
  11818. }
  11819. currentDepthFunc = depthFunc;
  11820. }
  11821. },
  11822. setLocked: function (lock) {
  11823. locked = lock;
  11824. },
  11825. setClear: function (depth) {
  11826. if (currentDepthClear !== depth) {
  11827. gl.clearDepth(depth);
  11828. currentDepthClear = depth;
  11829. }
  11830. },
  11831. reset: function () {
  11832. locked = false;
  11833. currentDepthMask = null;
  11834. currentDepthFunc = null;
  11835. currentDepthClear = null;
  11836. }
  11837. };
  11838. }
  11839. function StencilBuffer() {
  11840. let locked = false;
  11841. let currentStencilMask = null;
  11842. let currentStencilFunc = null;
  11843. let currentStencilRef = null;
  11844. let currentStencilFuncMask = null;
  11845. let currentStencilFail = null;
  11846. let currentStencilZFail = null;
  11847. let currentStencilZPass = null;
  11848. let currentStencilClear = null;
  11849. return {
  11850. setTest: function (stencilTest) {
  11851. if (!locked) {
  11852. if (stencilTest) {
  11853. enable(gl.STENCIL_TEST);
  11854. } else {
  11855. disable(gl.STENCIL_TEST);
  11856. }
  11857. }
  11858. },
  11859. setMask: function (stencilMask) {
  11860. if (currentStencilMask !== stencilMask && !locked) {
  11861. gl.stencilMask(stencilMask);
  11862. currentStencilMask = stencilMask;
  11863. }
  11864. },
  11865. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  11866. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  11867. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  11868. currentStencilFunc = stencilFunc;
  11869. currentStencilRef = stencilRef;
  11870. currentStencilFuncMask = stencilMask;
  11871. }
  11872. },
  11873. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  11874. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  11875. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  11876. currentStencilFail = stencilFail;
  11877. currentStencilZFail = stencilZFail;
  11878. currentStencilZPass = stencilZPass;
  11879. }
  11880. },
  11881. setLocked: function (lock) {
  11882. locked = lock;
  11883. },
  11884. setClear: function (stencil) {
  11885. if (currentStencilClear !== stencil) {
  11886. gl.clearStencil(stencil);
  11887. currentStencilClear = stencil;
  11888. }
  11889. },
  11890. reset: function () {
  11891. locked = false;
  11892. currentStencilMask = null;
  11893. currentStencilFunc = null;
  11894. currentStencilRef = null;
  11895. currentStencilFuncMask = null;
  11896. currentStencilFail = null;
  11897. currentStencilZFail = null;
  11898. currentStencilZPass = null;
  11899. currentStencilClear = null;
  11900. }
  11901. };
  11902. } //
  11903. const colorBuffer = new ColorBuffer();
  11904. const depthBuffer = new DepthBuffer();
  11905. const stencilBuffer = new StencilBuffer();
  11906. let enabledCapabilities = {};
  11907. let xrFramebuffer = null;
  11908. let currentBoundFramebuffers = {};
  11909. let currentProgram = null;
  11910. let currentBlendingEnabled = false;
  11911. let currentBlending = null;
  11912. let currentBlendEquation = null;
  11913. let currentBlendSrc = null;
  11914. let currentBlendDst = null;
  11915. let currentBlendEquationAlpha = null;
  11916. let currentBlendSrcAlpha = null;
  11917. let currentBlendDstAlpha = null;
  11918. let currentPremultipledAlpha = false;
  11919. let currentFlipSided = null;
  11920. let currentCullFace = null;
  11921. let currentLineWidth = null;
  11922. let currentPolygonOffsetFactor = null;
  11923. let currentPolygonOffsetUnits = null;
  11924. const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11925. let lineWidthAvailable = false;
  11926. let version = 0;
  11927. const glVersion = gl.getParameter(gl.VERSION);
  11928. if (glVersion.indexOf('WebGL') !== -1) {
  11929. version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]);
  11930. lineWidthAvailable = version >= 1.0;
  11931. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  11932. version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);
  11933. lineWidthAvailable = version >= 2.0;
  11934. }
  11935. let currentTextureSlot = null;
  11936. let currentBoundTextures = {};
  11937. const scissorParam = gl.getParameter(gl.SCISSOR_BOX);
  11938. const viewportParam = gl.getParameter(gl.VIEWPORT);
  11939. const currentScissor = new Vector4().fromArray(scissorParam);
  11940. const currentViewport = new Vector4().fromArray(viewportParam);
  11941. function createTexture(type, target, count) {
  11942. const data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  11943. const texture = gl.createTexture();
  11944. gl.bindTexture(type, texture);
  11945. gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11946. gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11947. for (let i = 0; i < count; i++) {
  11948. gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
  11949. }
  11950. return texture;
  11951. }
  11952. const emptyTextures = {};
  11953. emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1);
  11954. emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); // init
  11955. colorBuffer.setClear(0, 0, 0, 1);
  11956. depthBuffer.setClear(1);
  11957. stencilBuffer.setClear(0);
  11958. enable(gl.DEPTH_TEST);
  11959. depthBuffer.setFunc(LessEqualDepth);
  11960. setFlipSided(false);
  11961. setCullFace(CullFaceBack);
  11962. enable(gl.CULL_FACE);
  11963. setBlending(NoBlending); //
  11964. function enable(id) {
  11965. if (enabledCapabilities[id] !== true) {
  11966. gl.enable(id);
  11967. enabledCapabilities[id] = true;
  11968. }
  11969. }
  11970. function disable(id) {
  11971. if (enabledCapabilities[id] !== false) {
  11972. gl.disable(id);
  11973. enabledCapabilities[id] = false;
  11974. }
  11975. }
  11976. function bindXRFramebuffer(framebuffer) {
  11977. if (framebuffer !== xrFramebuffer) {
  11978. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  11979. xrFramebuffer = framebuffer;
  11980. }
  11981. }
  11982. function bindFramebuffer(target, framebuffer) {
  11983. if (framebuffer === null && xrFramebuffer !== null) framebuffer = xrFramebuffer; // use active XR framebuffer if available
  11984. if (currentBoundFramebuffers[target] !== framebuffer) {
  11985. gl.bindFramebuffer(target, framebuffer);
  11986. currentBoundFramebuffers[target] = framebuffer;
  11987. if (isWebGL2) {
  11988. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  11989. if (target === gl.DRAW_FRAMEBUFFER) {
  11990. currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer;
  11991. }
  11992. if (target === gl.FRAMEBUFFER) {
  11993. currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer;
  11994. }
  11995. }
  11996. return true;
  11997. }
  11998. return false;
  11999. }
  12000. function useProgram(program) {
  12001. if (currentProgram !== program) {
  12002. gl.useProgram(program);
  12003. currentProgram = program;
  12004. return true;
  12005. }
  12006. return false;
  12007. }
  12008. const equationToGL = {
  12009. [AddEquation]: gl.FUNC_ADD,
  12010. [SubtractEquation]: gl.FUNC_SUBTRACT,
  12011. [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT
  12012. };
  12013. if (isWebGL2) {
  12014. equationToGL[MinEquation] = gl.MIN;
  12015. equationToGL[MaxEquation] = gl.MAX;
  12016. } else {
  12017. const extension = extensions.get('EXT_blend_minmax');
  12018. if (extension !== null) {
  12019. equationToGL[MinEquation] = extension.MIN_EXT;
  12020. equationToGL[MaxEquation] = extension.MAX_EXT;
  12021. }
  12022. }
  12023. const factorToGL = {
  12024. [ZeroFactor]: gl.ZERO,
  12025. [OneFactor]: gl.ONE,
  12026. [SrcColorFactor]: gl.SRC_COLOR,
  12027. [SrcAlphaFactor]: gl.SRC_ALPHA,
  12028. [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE,
  12029. [DstColorFactor]: gl.DST_COLOR,
  12030. [DstAlphaFactor]: gl.DST_ALPHA,
  12031. [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR,
  12032. [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA,
  12033. [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR,
  12034. [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA
  12035. };
  12036. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  12037. if (blending === NoBlending) {
  12038. if (currentBlendingEnabled === true) {
  12039. disable(gl.BLEND);
  12040. currentBlendingEnabled = false;
  12041. }
  12042. return;
  12043. }
  12044. if (currentBlendingEnabled === false) {
  12045. enable(gl.BLEND);
  12046. currentBlendingEnabled = true;
  12047. }
  12048. if (blending !== CustomBlending) {
  12049. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  12050. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  12051. gl.blendEquation(gl.FUNC_ADD);
  12052. currentBlendEquation = AddEquation;
  12053. currentBlendEquationAlpha = AddEquation;
  12054. }
  12055. if (premultipliedAlpha) {
  12056. switch (blending) {
  12057. case NormalBlending:
  12058. gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  12059. break;
  12060. case AdditiveBlending:
  12061. gl.blendFunc(gl.ONE, gl.ONE);
  12062. break;
  12063. case SubtractiveBlending:
  12064. gl.blendFuncSeparate(gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA);
  12065. break;
  12066. case MultiplyBlending:
  12067. gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA);
  12068. break;
  12069. default:
  12070. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12071. break;
  12072. }
  12073. } else {
  12074. switch (blending) {
  12075. case NormalBlending:
  12076. gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  12077. break;
  12078. case AdditiveBlending:
  12079. gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  12080. break;
  12081. case SubtractiveBlending:
  12082. gl.blendFunc(gl.ZERO, gl.ONE_MINUS_SRC_COLOR);
  12083. break;
  12084. case MultiplyBlending:
  12085. gl.blendFunc(gl.ZERO, gl.SRC_COLOR);
  12086. break;
  12087. default:
  12088. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12089. break;
  12090. }
  12091. }
  12092. currentBlendSrc = null;
  12093. currentBlendDst = null;
  12094. currentBlendSrcAlpha = null;
  12095. currentBlendDstAlpha = null;
  12096. currentBlending = blending;
  12097. currentPremultipledAlpha = premultipliedAlpha;
  12098. }
  12099. return;
  12100. } // custom blending
  12101. blendEquationAlpha = blendEquationAlpha || blendEquation;
  12102. blendSrcAlpha = blendSrcAlpha || blendSrc;
  12103. blendDstAlpha = blendDstAlpha || blendDst;
  12104. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  12105. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  12106. currentBlendEquation = blendEquation;
  12107. currentBlendEquationAlpha = blendEquationAlpha;
  12108. }
  12109. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  12110. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  12111. currentBlendSrc = blendSrc;
  12112. currentBlendDst = blendDst;
  12113. currentBlendSrcAlpha = blendSrcAlpha;
  12114. currentBlendDstAlpha = blendDstAlpha;
  12115. }
  12116. currentBlending = blending;
  12117. currentPremultipledAlpha = null;
  12118. }
  12119. function setMaterial(material, frontFaceCW) {
  12120. material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE);
  12121. let flipSided = material.side === BackSide;
  12122. if (frontFaceCW) flipSided = !flipSided;
  12123. setFlipSided(flipSided);
  12124. 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);
  12125. depthBuffer.setFunc(material.depthFunc);
  12126. depthBuffer.setTest(material.depthTest);
  12127. depthBuffer.setMask(material.depthWrite);
  12128. colorBuffer.setMask(material.colorWrite);
  12129. const stencilWrite = material.stencilWrite;
  12130. stencilBuffer.setTest(stencilWrite);
  12131. if (stencilWrite) {
  12132. stencilBuffer.setMask(material.stencilWriteMask);
  12133. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  12134. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  12135. }
  12136. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  12137. material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  12138. } //
  12139. function setFlipSided(flipSided) {
  12140. if (currentFlipSided !== flipSided) {
  12141. if (flipSided) {
  12142. gl.frontFace(gl.CW);
  12143. } else {
  12144. gl.frontFace(gl.CCW);
  12145. }
  12146. currentFlipSided = flipSided;
  12147. }
  12148. }
  12149. function setCullFace(cullFace) {
  12150. if (cullFace !== CullFaceNone) {
  12151. enable(gl.CULL_FACE);
  12152. if (cullFace !== currentCullFace) {
  12153. if (cullFace === CullFaceBack) {
  12154. gl.cullFace(gl.BACK);
  12155. } else if (cullFace === CullFaceFront) {
  12156. gl.cullFace(gl.FRONT);
  12157. } else {
  12158. gl.cullFace(gl.FRONT_AND_BACK);
  12159. }
  12160. }
  12161. } else {
  12162. disable(gl.CULL_FACE);
  12163. }
  12164. currentCullFace = cullFace;
  12165. }
  12166. function setLineWidth(width) {
  12167. if (width !== currentLineWidth) {
  12168. if (lineWidthAvailable) gl.lineWidth(width);
  12169. currentLineWidth = width;
  12170. }
  12171. }
  12172. function setPolygonOffset(polygonOffset, factor, units) {
  12173. if (polygonOffset) {
  12174. enable(gl.POLYGON_OFFSET_FILL);
  12175. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  12176. gl.polygonOffset(factor, units);
  12177. currentPolygonOffsetFactor = factor;
  12178. currentPolygonOffsetUnits = units;
  12179. }
  12180. } else {
  12181. disable(gl.POLYGON_OFFSET_FILL);
  12182. }
  12183. }
  12184. function setScissorTest(scissorTest) {
  12185. if (scissorTest) {
  12186. enable(gl.SCISSOR_TEST);
  12187. } else {
  12188. disable(gl.SCISSOR_TEST);
  12189. }
  12190. } // texture
  12191. function activeTexture(webglSlot) {
  12192. if (webglSlot === undefined) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  12193. if (currentTextureSlot !== webglSlot) {
  12194. gl.activeTexture(webglSlot);
  12195. currentTextureSlot = webglSlot;
  12196. }
  12197. }
  12198. function bindTexture(webglType, webglTexture) {
  12199. if (currentTextureSlot === null) {
  12200. activeTexture();
  12201. }
  12202. let boundTexture = currentBoundTextures[currentTextureSlot];
  12203. if (boundTexture === undefined) {
  12204. boundTexture = {
  12205. type: undefined,
  12206. texture: undefined
  12207. };
  12208. currentBoundTextures[currentTextureSlot] = boundTexture;
  12209. }
  12210. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  12211. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  12212. boundTexture.type = webglType;
  12213. boundTexture.texture = webglTexture;
  12214. }
  12215. }
  12216. function unbindTexture() {
  12217. const boundTexture = currentBoundTextures[currentTextureSlot];
  12218. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  12219. gl.bindTexture(boundTexture.type, null);
  12220. boundTexture.type = undefined;
  12221. boundTexture.texture = undefined;
  12222. }
  12223. }
  12224. function compressedTexImage2D() {
  12225. try {
  12226. gl.compressedTexImage2D.apply(gl, arguments);
  12227. } catch (error) {
  12228. console.error('THREE.WebGLState:', error);
  12229. }
  12230. }
  12231. function texImage2D() {
  12232. try {
  12233. gl.texImage2D.apply(gl, arguments);
  12234. } catch (error) {
  12235. console.error('THREE.WebGLState:', error);
  12236. }
  12237. }
  12238. function texImage3D() {
  12239. try {
  12240. gl.texImage3D.apply(gl, arguments);
  12241. } catch (error) {
  12242. console.error('THREE.WebGLState:', error);
  12243. }
  12244. } //
  12245. function scissor(scissor) {
  12246. if (currentScissor.equals(scissor) === false) {
  12247. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  12248. currentScissor.copy(scissor);
  12249. }
  12250. }
  12251. function viewport(viewport) {
  12252. if (currentViewport.equals(viewport) === false) {
  12253. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  12254. currentViewport.copy(viewport);
  12255. }
  12256. } //
  12257. function reset() {
  12258. // reset state
  12259. gl.disable(gl.BLEND);
  12260. gl.disable(gl.CULL_FACE);
  12261. gl.disable(gl.DEPTH_TEST);
  12262. gl.disable(gl.POLYGON_OFFSET_FILL);
  12263. gl.disable(gl.SCISSOR_TEST);
  12264. gl.disable(gl.STENCIL_TEST);
  12265. gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  12266. gl.blendEquation(gl.FUNC_ADD);
  12267. gl.blendFunc(gl.ONE, gl.ZERO);
  12268. gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO);
  12269. gl.colorMask(true, true, true, true);
  12270. gl.clearColor(0, 0, 0, 0);
  12271. gl.depthMask(true);
  12272. gl.depthFunc(gl.LESS);
  12273. gl.clearDepth(1);
  12274. gl.stencilMask(0xffffffff);
  12275. gl.stencilFunc(gl.ALWAYS, 0, 0xffffffff);
  12276. gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
  12277. gl.clearStencil(0);
  12278. gl.cullFace(gl.BACK);
  12279. gl.frontFace(gl.CCW);
  12280. gl.polygonOffset(0, 0);
  12281. gl.activeTexture(gl.TEXTURE0);
  12282. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12283. if (isWebGL2 === true) {
  12284. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
  12285. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  12286. }
  12287. gl.useProgram(null);
  12288. gl.lineWidth(1);
  12289. gl.scissor(0, 0, gl.canvas.width, gl.canvas.height);
  12290. gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); // reset internals
  12291. enabledCapabilities = {};
  12292. currentTextureSlot = null;
  12293. currentBoundTextures = {};
  12294. xrFramebuffer = null;
  12295. currentBoundFramebuffers = {};
  12296. currentProgram = null;
  12297. currentBlendingEnabled = false;
  12298. currentBlending = null;
  12299. currentBlendEquation = null;
  12300. currentBlendSrc = null;
  12301. currentBlendDst = null;
  12302. currentBlendEquationAlpha = null;
  12303. currentBlendSrcAlpha = null;
  12304. currentBlendDstAlpha = null;
  12305. currentPremultipledAlpha = false;
  12306. currentFlipSided = null;
  12307. currentCullFace = null;
  12308. currentLineWidth = null;
  12309. currentPolygonOffsetFactor = null;
  12310. currentPolygonOffsetUnits = null;
  12311. currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height);
  12312. currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height);
  12313. colorBuffer.reset();
  12314. depthBuffer.reset();
  12315. stencilBuffer.reset();
  12316. }
  12317. return {
  12318. buffers: {
  12319. color: colorBuffer,
  12320. depth: depthBuffer,
  12321. stencil: stencilBuffer
  12322. },
  12323. enable: enable,
  12324. disable: disable,
  12325. bindFramebuffer: bindFramebuffer,
  12326. bindXRFramebuffer: bindXRFramebuffer,
  12327. useProgram: useProgram,
  12328. setBlending: setBlending,
  12329. setMaterial: setMaterial,
  12330. setFlipSided: setFlipSided,
  12331. setCullFace: setCullFace,
  12332. setLineWidth: setLineWidth,
  12333. setPolygonOffset: setPolygonOffset,
  12334. setScissorTest: setScissorTest,
  12335. activeTexture: activeTexture,
  12336. bindTexture: bindTexture,
  12337. unbindTexture: unbindTexture,
  12338. compressedTexImage2D: compressedTexImage2D,
  12339. texImage2D: texImage2D,
  12340. texImage3D: texImage3D,
  12341. scissor: scissor,
  12342. viewport: viewport,
  12343. reset: reset
  12344. };
  12345. }
  12346. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  12347. const isWebGL2 = capabilities.isWebGL2;
  12348. const maxTextures = capabilities.maxTextures;
  12349. const maxCubemapSize = capabilities.maxCubemapSize;
  12350. const maxTextureSize = capabilities.maxTextureSize;
  12351. const maxSamples = capabilities.maxSamples;
  12352. const _videoTextures = new WeakMap();
  12353. let _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  12354. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  12355. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  12356. let useOffscreenCanvas = false;
  12357. try {
  12358. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext('2d') !== null;
  12359. } catch (err) {// Ignore any errors
  12360. }
  12361. function createCanvas(width, height) {
  12362. // Use OffscreenCanvas when available. Specially needed in web workers
  12363. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  12364. }
  12365. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  12366. let scale = 1; // handle case if texture exceeds max size
  12367. if (image.width > maxSize || image.height > maxSize) {
  12368. scale = maxSize / Math.max(image.width, image.height);
  12369. } // only perform resize if necessary
  12370. if (scale < 1 || needsPowerOfTwo === true) {
  12371. // only perform resize for certain image types
  12372. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  12373. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  12374. const width = floor(scale * image.width);
  12375. const height = floor(scale * image.height);
  12376. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  12377. const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  12378. canvas.width = width;
  12379. canvas.height = height;
  12380. const context = canvas.getContext('2d');
  12381. context.drawImage(image, 0, 0, width, height);
  12382. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  12383. return canvas;
  12384. } else {
  12385. if ('data' in image) {
  12386. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  12387. }
  12388. return image;
  12389. }
  12390. }
  12391. return image;
  12392. }
  12393. function isPowerOfTwo$1(image) {
  12394. return isPowerOfTwo(image.width) && isPowerOfTwo(image.height);
  12395. }
  12396. function textureNeedsPowerOfTwo(texture) {
  12397. if (isWebGL2) return false;
  12398. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  12399. }
  12400. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  12401. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  12402. }
  12403. function generateMipmap(target, texture, width, height, depth = 1) {
  12404. _gl.generateMipmap(target);
  12405. const textureProperties = properties.get(texture);
  12406. textureProperties.__maxMipLevel = Math.log2(Math.max(width, height, depth));
  12407. }
  12408. function getInternalFormat(internalFormatName, glFormat, glType) {
  12409. if (isWebGL2 === false) return glFormat;
  12410. if (internalFormatName !== null) {
  12411. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  12412. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  12413. }
  12414. let internalFormat = glFormat;
  12415. if (glFormat === _gl.RED) {
  12416. if (glType === _gl.FLOAT) internalFormat = _gl.R32F;
  12417. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.R16F;
  12418. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8;
  12419. }
  12420. if (glFormat === _gl.RGB) {
  12421. if (glType === _gl.FLOAT) internalFormat = _gl.RGB32F;
  12422. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGB16F;
  12423. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGB8;
  12424. }
  12425. if (glFormat === _gl.RGBA) {
  12426. if (glType === _gl.FLOAT) internalFormat = _gl.RGBA32F;
  12427. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGBA16F;
  12428. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGBA8;
  12429. }
  12430. if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) {
  12431. extensions.get('EXT_color_buffer_float');
  12432. }
  12433. return internalFormat;
  12434. } // Fallback filters for non-power-of-2 textures
  12435. function filterFallback(f) {
  12436. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  12437. return _gl.NEAREST;
  12438. }
  12439. return _gl.LINEAR;
  12440. } //
  12441. function onTextureDispose(event) {
  12442. const texture = event.target;
  12443. texture.removeEventListener('dispose', onTextureDispose);
  12444. deallocateTexture(texture);
  12445. if (texture.isVideoTexture) {
  12446. _videoTextures.delete(texture);
  12447. }
  12448. info.memory.textures--;
  12449. }
  12450. function onRenderTargetDispose(event) {
  12451. const renderTarget = event.target;
  12452. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  12453. deallocateRenderTarget(renderTarget);
  12454. } //
  12455. function deallocateTexture(texture) {
  12456. const textureProperties = properties.get(texture);
  12457. if (textureProperties.__webglInit === undefined) return;
  12458. _gl.deleteTexture(textureProperties.__webglTexture);
  12459. properties.remove(texture);
  12460. }
  12461. function deallocateRenderTarget(renderTarget) {
  12462. const texture = renderTarget.texture;
  12463. const renderTargetProperties = properties.get(renderTarget);
  12464. const textureProperties = properties.get(texture);
  12465. if (!renderTarget) return;
  12466. if (textureProperties.__webglTexture !== undefined) {
  12467. _gl.deleteTexture(textureProperties.__webglTexture);
  12468. info.memory.textures--;
  12469. }
  12470. if (renderTarget.depthTexture) {
  12471. renderTarget.depthTexture.dispose();
  12472. }
  12473. if (renderTarget.isWebGLCubeRenderTarget) {
  12474. for (let i = 0; i < 6; i++) {
  12475. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  12476. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  12477. }
  12478. } else {
  12479. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  12480. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  12481. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  12482. if (renderTargetProperties.__webglColorRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);
  12483. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  12484. }
  12485. if (renderTarget.isWebGLMultipleRenderTargets) {
  12486. for (let i = 0, il = texture.length; i < il; i++) {
  12487. const attachmentProperties = properties.get(texture[i]);
  12488. if (attachmentProperties.__webglTexture) {
  12489. _gl.deleteTexture(attachmentProperties.__webglTexture);
  12490. info.memory.textures--;
  12491. }
  12492. properties.remove(texture[i]);
  12493. }
  12494. }
  12495. properties.remove(texture);
  12496. properties.remove(renderTarget);
  12497. } //
  12498. let textureUnits = 0;
  12499. function resetTextureUnits() {
  12500. textureUnits = 0;
  12501. }
  12502. function allocateTextureUnit() {
  12503. const textureUnit = textureUnits;
  12504. if (textureUnit >= maxTextures) {
  12505. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  12506. }
  12507. textureUnits += 1;
  12508. return textureUnit;
  12509. } //
  12510. function setTexture2D(texture, slot) {
  12511. const textureProperties = properties.get(texture);
  12512. if (texture.isVideoTexture) updateVideoTexture(texture);
  12513. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  12514. const image = texture.image;
  12515. if (image === undefined) {
  12516. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  12517. } else if (image.complete === false) {
  12518. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  12519. } else {
  12520. uploadTexture(textureProperties, texture, slot);
  12521. return;
  12522. }
  12523. }
  12524. state.activeTexture(_gl.TEXTURE0 + slot);
  12525. state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture);
  12526. }
  12527. function setTexture2DArray(texture, slot) {
  12528. const textureProperties = properties.get(texture);
  12529. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  12530. uploadTexture(textureProperties, texture, slot);
  12531. return;
  12532. }
  12533. state.activeTexture(_gl.TEXTURE0 + slot);
  12534. state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture);
  12535. }
  12536. function setTexture3D(texture, slot) {
  12537. const textureProperties = properties.get(texture);
  12538. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  12539. uploadTexture(textureProperties, texture, slot);
  12540. return;
  12541. }
  12542. state.activeTexture(_gl.TEXTURE0 + slot);
  12543. state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture);
  12544. }
  12545. function setTextureCube(texture, slot) {
  12546. const textureProperties = properties.get(texture);
  12547. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  12548. uploadCubeTexture(textureProperties, texture, slot);
  12549. return;
  12550. }
  12551. state.activeTexture(_gl.TEXTURE0 + slot);
  12552. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  12553. }
  12554. const wrappingToGL = {
  12555. [RepeatWrapping]: _gl.REPEAT,
  12556. [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE,
  12557. [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT
  12558. };
  12559. const filterToGL = {
  12560. [NearestFilter]: _gl.NEAREST,
  12561. [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST,
  12562. [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR,
  12563. [LinearFilter]: _gl.LINEAR,
  12564. [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST,
  12565. [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR
  12566. };
  12567. function setTextureParameters(textureType, texture, supportsMips) {
  12568. if (supportsMips) {
  12569. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]);
  12570. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]);
  12571. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  12572. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]);
  12573. }
  12574. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]);
  12575. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]);
  12576. } else {
  12577. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE);
  12578. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE);
  12579. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  12580. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE);
  12581. }
  12582. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  12583. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  12584. }
  12585. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterFallback(texture.magFilter));
  12586. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterFallback(texture.minFilter));
  12587. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  12588. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  12589. }
  12590. }
  12591. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  12592. const extension = extensions.get('EXT_texture_filter_anisotropic');
  12593. if (texture.type === FloatType && extensions.has('OES_texture_float_linear') === false) return; // verify extension for WebGL 1 and WebGL 2
  12594. if (isWebGL2 === false && texture.type === HalfFloatType && extensions.has('OES_texture_half_float_linear') === false) return; // verify extension for WebGL 1 only
  12595. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  12596. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  12597. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  12598. }
  12599. }
  12600. }
  12601. function initTexture(textureProperties, texture) {
  12602. if (textureProperties.__webglInit === undefined) {
  12603. textureProperties.__webglInit = true;
  12604. texture.addEventListener('dispose', onTextureDispose);
  12605. textureProperties.__webglTexture = _gl.createTexture();
  12606. info.memory.textures++;
  12607. }
  12608. }
  12609. function uploadTexture(textureProperties, texture, slot) {
  12610. let textureType = _gl.TEXTURE_2D;
  12611. if (texture.isDataTexture2DArray) textureType = _gl.TEXTURE_2D_ARRAY;
  12612. if (texture.isDataTexture3D) textureType = _gl.TEXTURE_3D;
  12613. initTexture(textureProperties, texture);
  12614. state.activeTexture(_gl.TEXTURE0 + slot);
  12615. state.bindTexture(textureType, textureProperties.__webglTexture);
  12616. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  12617. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  12618. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  12619. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  12620. const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo$1(texture.image) === false;
  12621. const image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  12622. const supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  12623. glFormat = utils.convert(texture.format);
  12624. let glType = utils.convert(texture.type),
  12625. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12626. setTextureParameters(textureType, texture, supportsMips);
  12627. let mipmap;
  12628. const mipmaps = texture.mipmaps;
  12629. if (texture.isDepthTexture) {
  12630. // populate depth texture with dummy data
  12631. glInternalFormat = _gl.DEPTH_COMPONENT;
  12632. if (isWebGL2) {
  12633. if (texture.type === FloatType) {
  12634. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  12635. } else if (texture.type === UnsignedIntType) {
  12636. glInternalFormat = _gl.DEPTH_COMPONENT24;
  12637. } else if (texture.type === UnsignedInt248Type) {
  12638. glInternalFormat = _gl.DEPTH24_STENCIL8;
  12639. } else {
  12640. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  12641. }
  12642. } else {
  12643. if (texture.type === FloatType) {
  12644. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  12645. }
  12646. } // validation checks for WebGL 1
  12647. if (texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  12648. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  12649. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  12650. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12651. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  12652. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  12653. texture.type = UnsignedShortType;
  12654. glType = utils.convert(texture.type);
  12655. }
  12656. }
  12657. if (texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  12658. // Depth stencil textures need the DEPTH_STENCIL internal format
  12659. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12660. glInternalFormat = _gl.DEPTH_STENCIL; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  12661. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  12662. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12663. if (texture.type !== UnsignedInt248Type) {
  12664. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  12665. texture.type = UnsignedInt248Type;
  12666. glType = utils.convert(texture.type);
  12667. }
  12668. } //
  12669. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  12670. } else if (texture.isDataTexture) {
  12671. // use manually created mipmaps if available
  12672. // if there are no manual mipmaps
  12673. // set 0 level mipmap and then use GL to generate other mipmap levels
  12674. if (mipmaps.length > 0 && supportsMips) {
  12675. for (let i = 0, il = mipmaps.length; i < il; i++) {
  12676. mipmap = mipmaps[i];
  12677. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  12678. }
  12679. texture.generateMipmaps = false;
  12680. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12681. } else {
  12682. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  12683. textureProperties.__maxMipLevel = 0;
  12684. }
  12685. } else if (texture.isCompressedTexture) {
  12686. for (let i = 0, il = mipmaps.length; i < il; i++) {
  12687. mipmap = mipmaps[i];
  12688. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  12689. if (glFormat !== null) {
  12690. state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  12691. } else {
  12692. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  12693. }
  12694. } else {
  12695. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  12696. }
  12697. }
  12698. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12699. } else if (texture.isDataTexture2DArray) {
  12700. state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  12701. textureProperties.__maxMipLevel = 0;
  12702. } else if (texture.isDataTexture3D) {
  12703. state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  12704. textureProperties.__maxMipLevel = 0;
  12705. } else {
  12706. // regular Texture (image, video, canvas)
  12707. // use manually created mipmaps if available
  12708. // if there are no manual mipmaps
  12709. // set 0 level mipmap and then use GL to generate other mipmap levels
  12710. if (mipmaps.length > 0 && supportsMips) {
  12711. for (let i = 0, il = mipmaps.length; i < il; i++) {
  12712. mipmap = mipmaps[i];
  12713. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap);
  12714. }
  12715. texture.generateMipmaps = false;
  12716. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12717. } else {
  12718. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image);
  12719. textureProperties.__maxMipLevel = 0;
  12720. }
  12721. }
  12722. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  12723. generateMipmap(textureType, texture, image.width, image.height);
  12724. }
  12725. textureProperties.__version = texture.version;
  12726. if (texture.onUpdate) texture.onUpdate(texture);
  12727. }
  12728. function uploadCubeTexture(textureProperties, texture, slot) {
  12729. if (texture.image.length !== 6) return;
  12730. initTexture(textureProperties, texture);
  12731. state.activeTexture(_gl.TEXTURE0 + slot);
  12732. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  12733. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  12734. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  12735. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  12736. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  12737. const isCompressed = texture && (texture.isCompressedTexture || texture.image[0].isCompressedTexture);
  12738. const isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  12739. const cubeImage = [];
  12740. for (let i = 0; i < 6; i++) {
  12741. if (!isCompressed && !isDataTexture) {
  12742. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  12743. } else {
  12744. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  12745. }
  12746. }
  12747. const image = cubeImage[0],
  12748. supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  12749. glFormat = utils.convert(texture.format),
  12750. glType = utils.convert(texture.type),
  12751. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12752. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  12753. let mipmaps;
  12754. if (isCompressed) {
  12755. for (let i = 0; i < 6; i++) {
  12756. mipmaps = cubeImage[i].mipmaps;
  12757. for (let j = 0; j < mipmaps.length; j++) {
  12758. const mipmap = mipmaps[j];
  12759. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  12760. if (glFormat !== null) {
  12761. state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  12762. } else {
  12763. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  12764. }
  12765. } else {
  12766. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  12767. }
  12768. }
  12769. }
  12770. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12771. } else {
  12772. mipmaps = texture.mipmaps;
  12773. for (let i = 0; i < 6; i++) {
  12774. if (isDataTexture) {
  12775. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  12776. for (let j = 0; j < mipmaps.length; j++) {
  12777. const mipmap = mipmaps[j];
  12778. const mipmapImage = mipmap.image[i].image;
  12779. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  12780. }
  12781. } else {
  12782. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  12783. for (let j = 0; j < mipmaps.length; j++) {
  12784. const mipmap = mipmaps[j];
  12785. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  12786. }
  12787. }
  12788. }
  12789. textureProperties.__maxMipLevel = mipmaps.length;
  12790. }
  12791. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  12792. // We assume images for cube map have the same size.
  12793. generateMipmap(_gl.TEXTURE_CUBE_MAP, texture, image.width, image.height);
  12794. }
  12795. textureProperties.__version = texture.version;
  12796. if (texture.onUpdate) texture.onUpdate(texture);
  12797. } // Render targets
  12798. // Setup storage for target texture and bind it to correct framebuffer
  12799. function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget) {
  12800. const glFormat = utils.convert(texture.format);
  12801. const glType = utils.convert(texture.type);
  12802. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12803. if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) {
  12804. state.texImage3D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null);
  12805. } else {
  12806. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  12807. }
  12808. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  12809. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0);
  12810. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  12811. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  12812. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  12813. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer);
  12814. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  12815. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  12816. if (isMultisample) {
  12817. const depthTexture = renderTarget.depthTexture;
  12818. if (depthTexture && depthTexture.isDepthTexture) {
  12819. if (depthTexture.type === FloatType) {
  12820. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  12821. } else if (depthTexture.type === UnsignedIntType) {
  12822. glInternalFormat = _gl.DEPTH_COMPONENT24;
  12823. }
  12824. }
  12825. const samples = getRenderTargetSamples(renderTarget);
  12826. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  12827. } else {
  12828. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  12829. }
  12830. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  12831. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  12832. if (isMultisample) {
  12833. const samples = getRenderTargetSamples(renderTarget);
  12834. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  12835. } else {
  12836. _gl.renderbufferStorage(_gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height);
  12837. }
  12838. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  12839. } else {
  12840. // Use the first texture for MRT so far
  12841. const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[0] : renderTarget.texture;
  12842. const glFormat = utils.convert(texture.format);
  12843. const glType = utils.convert(texture.type);
  12844. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12845. if (isMultisample) {
  12846. const samples = getRenderTargetSamples(renderTarget);
  12847. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  12848. } else {
  12849. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  12850. }
  12851. }
  12852. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  12853. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  12854. function setupDepthTexture(framebuffer, renderTarget) {
  12855. const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  12856. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  12857. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  12858. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  12859. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  12860. } // upload an empty depth texture with framebuffer size
  12861. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  12862. renderTarget.depthTexture.image.width = renderTarget.width;
  12863. renderTarget.depthTexture.image.height = renderTarget.height;
  12864. renderTarget.depthTexture.needsUpdate = true;
  12865. }
  12866. setTexture2D(renderTarget.depthTexture, 0);
  12867. const webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  12868. if (renderTarget.depthTexture.format === DepthFormat) {
  12869. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  12870. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  12871. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  12872. } else {
  12873. throw new Error('Unknown depthTexture format');
  12874. }
  12875. } // Setup GL resources for a non-texture depth buffer
  12876. function setupDepthRenderbuffer(renderTarget) {
  12877. const renderTargetProperties = properties.get(renderTarget);
  12878. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  12879. if (renderTarget.depthTexture) {
  12880. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  12881. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  12882. } else {
  12883. if (isCube) {
  12884. renderTargetProperties.__webglDepthbuffer = [];
  12885. for (let i = 0; i < 6; i++) {
  12886. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]);
  12887. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  12888. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  12889. }
  12890. } else {
  12891. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  12892. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  12893. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  12894. }
  12895. }
  12896. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  12897. } // Set up GL resources for the render target
  12898. function setupRenderTarget(renderTarget) {
  12899. const texture = renderTarget.texture;
  12900. const renderTargetProperties = properties.get(renderTarget);
  12901. const textureProperties = properties.get(texture);
  12902. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  12903. if (renderTarget.isWebGLMultipleRenderTargets !== true) {
  12904. textureProperties.__webglTexture = _gl.createTexture();
  12905. textureProperties.__version = texture.version;
  12906. info.memory.textures++;
  12907. }
  12908. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  12909. const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true;
  12910. const isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
  12911. const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray;
  12912. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2; // Handles WebGL2 RGBFormat fallback - #18858
  12913. if (isWebGL2 && texture.format === RGBFormat && (texture.type === FloatType || texture.type === HalfFloatType)) {
  12914. texture.format = RGBAFormat;
  12915. console.warn('THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.');
  12916. } // Setup framebuffer
  12917. if (isCube) {
  12918. renderTargetProperties.__webglFramebuffer = [];
  12919. for (let i = 0; i < 6; i++) {
  12920. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  12921. }
  12922. } else {
  12923. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  12924. if (isMultipleRenderTargets) {
  12925. if (capabilities.drawBuffers) {
  12926. const textures = renderTarget.texture;
  12927. for (let i = 0, il = textures.length; i < il; i++) {
  12928. const attachmentProperties = properties.get(textures[i]);
  12929. if (attachmentProperties.__webglTexture === undefined) {
  12930. attachmentProperties.__webglTexture = _gl.createTexture();
  12931. info.memory.textures++;
  12932. }
  12933. }
  12934. } else {
  12935. console.warn('THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.');
  12936. }
  12937. } else if (isMultisample) {
  12938. if (isWebGL2) {
  12939. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  12940. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  12941. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  12942. const glFormat = utils.convert(texture.format);
  12943. const glType = utils.convert(texture.type);
  12944. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12945. const samples = getRenderTargetSamples(renderTarget);
  12946. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  12947. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  12948. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  12949. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  12950. if (renderTarget.depthBuffer) {
  12951. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  12952. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  12953. }
  12954. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  12955. } else {
  12956. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  12957. }
  12958. }
  12959. } // Setup color buffer
  12960. if (isCube) {
  12961. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  12962. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  12963. for (let i = 0; i < 6; i++) {
  12964. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i);
  12965. }
  12966. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  12967. generateMipmap(_gl.TEXTURE_CUBE_MAP, texture, renderTarget.width, renderTarget.height);
  12968. }
  12969. state.bindTexture(_gl.TEXTURE_CUBE_MAP, null);
  12970. } else if (isMultipleRenderTargets) {
  12971. const textures = renderTarget.texture;
  12972. for (let i = 0, il = textures.length; i < il; i++) {
  12973. const attachment = textures[i];
  12974. const attachmentProperties = properties.get(attachment);
  12975. state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture);
  12976. setTextureParameters(_gl.TEXTURE_2D, attachment, supportsMips);
  12977. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D);
  12978. if (textureNeedsGenerateMipmaps(attachment, supportsMips)) {
  12979. generateMipmap(_gl.TEXTURE_2D, attachment, renderTarget.width, renderTarget.height);
  12980. }
  12981. }
  12982. state.bindTexture(_gl.TEXTURE_2D, null);
  12983. } else {
  12984. let glTextureType = _gl.TEXTURE_2D;
  12985. if (isRenderTarget3D) {
  12986. // Render targets containing layers, i.e: Texture 3D and 2d arrays
  12987. if (isWebGL2) {
  12988. const isTexture3D = texture.isDataTexture3D;
  12989. glTextureType = isTexture3D ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  12990. } else {
  12991. console.warn('THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.');
  12992. }
  12993. }
  12994. state.bindTexture(glTextureType, textureProperties.__webglTexture);
  12995. setTextureParameters(glTextureType, texture, supportsMips);
  12996. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType);
  12997. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  12998. generateMipmap(glTextureType, texture, renderTarget.width, renderTarget.height, renderTarget.depth);
  12999. }
  13000. state.bindTexture(glTextureType, null);
  13001. } // Setup depth and stencil buffers
  13002. if (renderTarget.depthBuffer) {
  13003. setupDepthRenderbuffer(renderTarget);
  13004. }
  13005. }
  13006. function updateRenderTargetMipmap(renderTarget) {
  13007. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2;
  13008. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture];
  13009. for (let i = 0, il = textures.length; i < il; i++) {
  13010. const texture = textures[i];
  13011. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13012. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  13013. const webglTexture = properties.get(texture).__webglTexture;
  13014. state.bindTexture(target, webglTexture);
  13015. generateMipmap(target, texture, renderTarget.width, renderTarget.height);
  13016. state.bindTexture(target, null);
  13017. }
  13018. }
  13019. }
  13020. function updateMultisampleRenderTarget(renderTarget) {
  13021. if (renderTarget.isWebGLMultisampleRenderTarget) {
  13022. if (isWebGL2) {
  13023. const width = renderTarget.width;
  13024. const height = renderTarget.height;
  13025. let mask = _gl.COLOR_BUFFER_BIT;
  13026. if (renderTarget.depthBuffer) mask |= _gl.DEPTH_BUFFER_BIT;
  13027. if (renderTarget.stencilBuffer) mask |= _gl.STENCIL_BUFFER_BIT;
  13028. const renderTargetProperties = properties.get(renderTarget);
  13029. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  13030. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  13031. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST);
  13032. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null);
  13033. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  13034. } else {
  13035. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  13036. }
  13037. }
  13038. }
  13039. function getRenderTargetSamples(renderTarget) {
  13040. return isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(maxSamples, renderTarget.samples) : 0;
  13041. }
  13042. function updateVideoTexture(texture) {
  13043. const frame = info.render.frame; // Check the last frame we updated the VideoTexture
  13044. if (_videoTextures.get(texture) !== frame) {
  13045. _videoTextures.set(texture, frame);
  13046. texture.update();
  13047. }
  13048. } // backwards compatibility
  13049. let warnedTexture2D = false;
  13050. let warnedTextureCube = false;
  13051. function safeSetTexture2D(texture, slot) {
  13052. if (texture && texture.isWebGLRenderTarget) {
  13053. if (warnedTexture2D === false) {
  13054. console.warn('THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.');
  13055. warnedTexture2D = true;
  13056. }
  13057. texture = texture.texture;
  13058. }
  13059. setTexture2D(texture, slot);
  13060. }
  13061. function safeSetTextureCube(texture, slot) {
  13062. if (texture && texture.isWebGLCubeRenderTarget) {
  13063. if (warnedTextureCube === false) {
  13064. console.warn('THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.');
  13065. warnedTextureCube = true;
  13066. }
  13067. texture = texture.texture;
  13068. }
  13069. setTextureCube(texture, slot);
  13070. } //
  13071. this.allocateTextureUnit = allocateTextureUnit;
  13072. this.resetTextureUnits = resetTextureUnits;
  13073. this.setTexture2D = setTexture2D;
  13074. this.setTexture2DArray = setTexture2DArray;
  13075. this.setTexture3D = setTexture3D;
  13076. this.setTextureCube = setTextureCube;
  13077. this.setupRenderTarget = setupRenderTarget;
  13078. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  13079. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  13080. this.safeSetTexture2D = safeSetTexture2D;
  13081. this.safeSetTextureCube = safeSetTextureCube;
  13082. }
  13083. function WebGLUtils(gl, extensions, capabilities) {
  13084. const isWebGL2 = capabilities.isWebGL2;
  13085. function convert(p) {
  13086. let extension;
  13087. if (p === UnsignedByteType) return gl.UNSIGNED_BYTE;
  13088. if (p === UnsignedShort4444Type) return gl.UNSIGNED_SHORT_4_4_4_4;
  13089. if (p === UnsignedShort5551Type) return gl.UNSIGNED_SHORT_5_5_5_1;
  13090. if (p === UnsignedShort565Type) return gl.UNSIGNED_SHORT_5_6_5;
  13091. if (p === ByteType) return gl.BYTE;
  13092. if (p === ShortType) return gl.SHORT;
  13093. if (p === UnsignedShortType) return gl.UNSIGNED_SHORT;
  13094. if (p === IntType) return gl.INT;
  13095. if (p === UnsignedIntType) return gl.UNSIGNED_INT;
  13096. if (p === FloatType) return gl.FLOAT;
  13097. if (p === HalfFloatType) {
  13098. if (isWebGL2) return gl.HALF_FLOAT;
  13099. extension = extensions.get('OES_texture_half_float');
  13100. if (extension !== null) {
  13101. return extension.HALF_FLOAT_OES;
  13102. } else {
  13103. return null;
  13104. }
  13105. }
  13106. if (p === AlphaFormat) return gl.ALPHA;
  13107. if (p === RGBFormat) return gl.RGB;
  13108. if (p === RGBAFormat) return gl.RGBA;
  13109. if (p === LuminanceFormat) return gl.LUMINANCE;
  13110. if (p === LuminanceAlphaFormat) return gl.LUMINANCE_ALPHA;
  13111. if (p === DepthFormat) return gl.DEPTH_COMPONENT;
  13112. if (p === DepthStencilFormat) return gl.DEPTH_STENCIL;
  13113. if (p === RedFormat) return gl.RED; // WebGL2 formats.
  13114. if (p === RedIntegerFormat) return gl.RED_INTEGER;
  13115. if (p === RGFormat) return gl.RG;
  13116. if (p === RGIntegerFormat) return gl.RG_INTEGER;
  13117. if (p === RGBIntegerFormat) return gl.RGB_INTEGER;
  13118. if (p === RGBAIntegerFormat) return gl.RGBA_INTEGER;
  13119. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  13120. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  13121. if (extension !== null) {
  13122. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13123. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13124. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13125. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13126. } else {
  13127. return null;
  13128. }
  13129. }
  13130. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  13131. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  13132. if (extension !== null) {
  13133. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13134. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13135. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13136. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13137. } else {
  13138. return null;
  13139. }
  13140. }
  13141. if (p === RGB_ETC1_Format) {
  13142. extension = extensions.get('WEBGL_compressed_texture_etc1');
  13143. if (extension !== null) {
  13144. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13145. } else {
  13146. return null;
  13147. }
  13148. }
  13149. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  13150. extension = extensions.get('WEBGL_compressed_texture_etc');
  13151. if (extension !== null) {
  13152. if (p === RGB_ETC2_Format) return extension.COMPRESSED_RGB8_ETC2;
  13153. if (p === RGBA_ETC2_EAC_Format) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  13154. }
  13155. }
  13156. 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) {
  13157. extension = extensions.get('WEBGL_compressed_texture_astc');
  13158. if (extension !== null) {
  13159. // TODO Complete?
  13160. return p;
  13161. } else {
  13162. return null;
  13163. }
  13164. }
  13165. if (p === RGBA_BPTC_Format) {
  13166. extension = extensions.get('EXT_texture_compression_bptc');
  13167. if (extension !== null) {
  13168. // TODO Complete?
  13169. return p;
  13170. } else {
  13171. return null;
  13172. }
  13173. }
  13174. if (p === UnsignedInt248Type) {
  13175. if (isWebGL2) return gl.UNSIGNED_INT_24_8;
  13176. extension = extensions.get('WEBGL_depth_texture');
  13177. if (extension !== null) {
  13178. return extension.UNSIGNED_INT_24_8_WEBGL;
  13179. } else {
  13180. return null;
  13181. }
  13182. }
  13183. }
  13184. return {
  13185. convert: convert
  13186. };
  13187. }
  13188. class ArrayCamera extends PerspectiveCamera {
  13189. constructor(array = []) {
  13190. super();
  13191. this.cameras = array;
  13192. }
  13193. }
  13194. ArrayCamera.prototype.isArrayCamera = true;
  13195. class Group extends Object3D {
  13196. constructor() {
  13197. super();
  13198. this.type = 'Group';
  13199. }
  13200. }
  13201. Group.prototype.isGroup = true;
  13202. const _moveEvent = {
  13203. type: 'move'
  13204. };
  13205. class WebXRController {
  13206. constructor() {
  13207. this._targetRay = null;
  13208. this._grip = null;
  13209. this._hand = null;
  13210. }
  13211. getHandSpace() {
  13212. if (this._hand === null) {
  13213. this._hand = new Group();
  13214. this._hand.matrixAutoUpdate = false;
  13215. this._hand.visible = false;
  13216. this._hand.joints = {};
  13217. this._hand.inputState = {
  13218. pinching: false
  13219. };
  13220. }
  13221. return this._hand;
  13222. }
  13223. getTargetRaySpace() {
  13224. if (this._targetRay === null) {
  13225. this._targetRay = new Group();
  13226. this._targetRay.matrixAutoUpdate = false;
  13227. this._targetRay.visible = false;
  13228. this._targetRay.hasLinearVelocity = false;
  13229. this._targetRay.linearVelocity = new Vector3();
  13230. this._targetRay.hasAngularVelocity = false;
  13231. this._targetRay.angularVelocity = new Vector3();
  13232. }
  13233. return this._targetRay;
  13234. }
  13235. getGripSpace() {
  13236. if (this._grip === null) {
  13237. this._grip = new Group();
  13238. this._grip.matrixAutoUpdate = false;
  13239. this._grip.visible = false;
  13240. this._grip.hasLinearVelocity = false;
  13241. this._grip.linearVelocity = new Vector3();
  13242. this._grip.hasAngularVelocity = false;
  13243. this._grip.angularVelocity = new Vector3();
  13244. }
  13245. return this._grip;
  13246. }
  13247. dispatchEvent(event) {
  13248. if (this._targetRay !== null) {
  13249. this._targetRay.dispatchEvent(event);
  13250. }
  13251. if (this._grip !== null) {
  13252. this._grip.dispatchEvent(event);
  13253. }
  13254. if (this._hand !== null) {
  13255. this._hand.dispatchEvent(event);
  13256. }
  13257. return this;
  13258. }
  13259. disconnect(inputSource) {
  13260. this.dispatchEvent({
  13261. type: 'disconnected',
  13262. data: inputSource
  13263. });
  13264. if (this._targetRay !== null) {
  13265. this._targetRay.visible = false;
  13266. }
  13267. if (this._grip !== null) {
  13268. this._grip.visible = false;
  13269. }
  13270. if (this._hand !== null) {
  13271. this._hand.visible = false;
  13272. }
  13273. return this;
  13274. }
  13275. update(inputSource, frame, referenceSpace) {
  13276. let inputPose = null;
  13277. let gripPose = null;
  13278. let handPose = null;
  13279. const targetRay = this._targetRay;
  13280. const grip = this._grip;
  13281. const hand = this._hand;
  13282. if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
  13283. if (targetRay !== null) {
  13284. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  13285. if (inputPose !== null) {
  13286. targetRay.matrix.fromArray(inputPose.transform.matrix);
  13287. targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
  13288. if (inputPose.linearVelocity) {
  13289. targetRay.hasLinearVelocity = true;
  13290. targetRay.linearVelocity.copy(inputPose.linearVelocity);
  13291. } else {
  13292. targetRay.hasLinearVelocity = false;
  13293. }
  13294. if (inputPose.angularVelocity) {
  13295. targetRay.hasAngularVelocity = true;
  13296. targetRay.angularVelocity.copy(inputPose.angularVelocity);
  13297. } else {
  13298. targetRay.hasAngularVelocity = false;
  13299. }
  13300. this.dispatchEvent(_moveEvent);
  13301. }
  13302. }
  13303. if (hand && inputSource.hand) {
  13304. handPose = true;
  13305. for (const inputjoint of inputSource.hand.values()) {
  13306. // Update the joints groups with the XRJoint poses
  13307. const jointPose = frame.getJointPose(inputjoint, referenceSpace);
  13308. if (hand.joints[inputjoint.jointName] === undefined) {
  13309. // The transform of this joint will be updated with the joint pose on each frame
  13310. const joint = new Group();
  13311. joint.matrixAutoUpdate = false;
  13312. joint.visible = false;
  13313. hand.joints[inputjoint.jointName] = joint; // ??
  13314. hand.add(joint);
  13315. }
  13316. const joint = hand.joints[inputjoint.jointName];
  13317. if (jointPose !== null) {
  13318. joint.matrix.fromArray(jointPose.transform.matrix);
  13319. joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
  13320. joint.jointRadius = jointPose.radius;
  13321. }
  13322. joint.visible = jointPose !== null;
  13323. } // Custom events
  13324. // Check pinchz
  13325. const indexTip = hand.joints['index-finger-tip'];
  13326. const thumbTip = hand.joints['thumb-tip'];
  13327. const distance = indexTip.position.distanceTo(thumbTip.position);
  13328. const distanceToPinch = 0.02;
  13329. const threshold = 0.005;
  13330. if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
  13331. hand.inputState.pinching = false;
  13332. this.dispatchEvent({
  13333. type: 'pinchend',
  13334. handedness: inputSource.handedness,
  13335. target: this
  13336. });
  13337. } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
  13338. hand.inputState.pinching = true;
  13339. this.dispatchEvent({
  13340. type: 'pinchstart',
  13341. handedness: inputSource.handedness,
  13342. target: this
  13343. });
  13344. }
  13345. } else {
  13346. if (grip !== null && inputSource.gripSpace) {
  13347. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  13348. if (gripPose !== null) {
  13349. grip.matrix.fromArray(gripPose.transform.matrix);
  13350. grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
  13351. if (gripPose.linearVelocity) {
  13352. grip.hasLinearVelocity = true;
  13353. grip.linearVelocity.copy(gripPose.linearVelocity);
  13354. } else {
  13355. grip.hasLinearVelocity = false;
  13356. }
  13357. if (gripPose.angularVelocity) {
  13358. grip.hasAngularVelocity = true;
  13359. grip.angularVelocity.copy(gripPose.angularVelocity);
  13360. } else {
  13361. grip.hasAngularVelocity = false;
  13362. }
  13363. }
  13364. }
  13365. }
  13366. }
  13367. if (targetRay !== null) {
  13368. targetRay.visible = inputPose !== null;
  13369. }
  13370. if (grip !== null) {
  13371. grip.visible = gripPose !== null;
  13372. }
  13373. if (hand !== null) {
  13374. hand.visible = handPose !== null;
  13375. }
  13376. return this;
  13377. }
  13378. }
  13379. class WebXRManager extends EventDispatcher {
  13380. constructor(renderer, gl) {
  13381. super();
  13382. const scope = this;
  13383. const state = renderer.state;
  13384. let session = null;
  13385. let framebufferScaleFactor = 1.0;
  13386. let referenceSpace = null;
  13387. let referenceSpaceType = 'local-floor';
  13388. let pose = null;
  13389. let glBinding = null;
  13390. let glFramebuffer = null;
  13391. let glProjLayer = null;
  13392. const controllers = [];
  13393. const inputSourcesMap = new Map(); //
  13394. const cameraL = new PerspectiveCamera();
  13395. cameraL.layers.enable(1);
  13396. cameraL.viewport = new Vector4();
  13397. const cameraR = new PerspectiveCamera();
  13398. cameraR.layers.enable(2);
  13399. cameraR.viewport = new Vector4();
  13400. const cameras = [cameraL, cameraR];
  13401. const cameraVR = new ArrayCamera();
  13402. cameraVR.layers.enable(1);
  13403. cameraVR.layers.enable(2);
  13404. let _currentDepthNear = null;
  13405. let _currentDepthFar = null; //
  13406. this.cameraAutoUpdate = true;
  13407. this.enabled = false;
  13408. this.isPresenting = false;
  13409. this.getController = function (index) {
  13410. let controller = controllers[index];
  13411. if (controller === undefined) {
  13412. controller = new WebXRController();
  13413. controllers[index] = controller;
  13414. }
  13415. return controller.getTargetRaySpace();
  13416. };
  13417. this.getControllerGrip = function (index) {
  13418. let controller = controllers[index];
  13419. if (controller === undefined) {
  13420. controller = new WebXRController();
  13421. controllers[index] = controller;
  13422. }
  13423. return controller.getGripSpace();
  13424. };
  13425. this.getHand = function (index) {
  13426. let controller = controllers[index];
  13427. if (controller === undefined) {
  13428. controller = new WebXRController();
  13429. controllers[index] = controller;
  13430. }
  13431. return controller.getHandSpace();
  13432. }; //
  13433. function onSessionEvent(event) {
  13434. const controller = inputSourcesMap.get(event.inputSource);
  13435. if (controller) {
  13436. controller.dispatchEvent({
  13437. type: event.type,
  13438. data: event.inputSource
  13439. });
  13440. }
  13441. }
  13442. function onSessionEnd() {
  13443. inputSourcesMap.forEach(function (controller, inputSource) {
  13444. controller.disconnect(inputSource);
  13445. });
  13446. inputSourcesMap.clear();
  13447. _currentDepthNear = null;
  13448. _currentDepthFar = null; // restore framebuffer/rendering state
  13449. state.bindXRFramebuffer(null);
  13450. renderer.setRenderTarget(renderer.getRenderTarget()); //
  13451. animation.stop();
  13452. scope.isPresenting = false;
  13453. scope.dispatchEvent({
  13454. type: 'sessionend'
  13455. });
  13456. }
  13457. this.setFramebufferScaleFactor = function (value) {
  13458. framebufferScaleFactor = value;
  13459. if (scope.isPresenting === true) {
  13460. console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
  13461. }
  13462. };
  13463. this.setReferenceSpaceType = function (value) {
  13464. referenceSpaceType = value;
  13465. if (scope.isPresenting === true) {
  13466. console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
  13467. }
  13468. };
  13469. this.getReferenceSpace = function () {
  13470. return referenceSpace;
  13471. };
  13472. this.getSession = function () {
  13473. return session;
  13474. };
  13475. this.setSession = async function (value) {
  13476. session = value;
  13477. if (session !== null) {
  13478. session.addEventListener('select', onSessionEvent);
  13479. session.addEventListener('selectstart', onSessionEvent);
  13480. session.addEventListener('selectend', onSessionEvent);
  13481. session.addEventListener('squeeze', onSessionEvent);
  13482. session.addEventListener('squeezestart', onSessionEvent);
  13483. session.addEventListener('squeezeend', onSessionEvent);
  13484. session.addEventListener('end', onSessionEnd);
  13485. session.addEventListener('inputsourceschange', onInputSourcesChange);
  13486. const attributes = gl.getContextAttributes();
  13487. if (attributes.xrCompatible !== true) {
  13488. await gl.makeXRCompatible();
  13489. }
  13490. if (session.renderState.layers === undefined) {
  13491. const layerInit = {
  13492. antialias: attributes.antialias,
  13493. alpha: attributes.alpha,
  13494. depth: attributes.depth,
  13495. stencil: attributes.stencil,
  13496. framebufferScaleFactor: framebufferScaleFactor
  13497. }; // eslint-disable-next-line no-undef
  13498. const baseLayer = new XRWebGLLayer(session, gl, layerInit);
  13499. session.updateRenderState({
  13500. baseLayer: baseLayer
  13501. });
  13502. } else {
  13503. let depthFormat = 0;
  13504. if (attributes.depth) {
  13505. depthFormat = attributes.stencil ? gl.DEPTH_STENCIL : gl.DEPTH_COMPONENT;
  13506. }
  13507. const projectionlayerInit = {
  13508. colorFormat: attributes.alpha ? gl.RGBA : gl.RGB,
  13509. depthFormat: depthFormat,
  13510. scaleFactor: framebufferScaleFactor
  13511. }; // eslint-disable-next-line no-undef
  13512. glBinding = new XRWebGLBinding(session, gl);
  13513. glProjLayer = glBinding.createProjectionLayer(projectionlayerInit);
  13514. glFramebuffer = gl.createFramebuffer();
  13515. session.updateRenderState({
  13516. layers: [glProjLayer]
  13517. });
  13518. }
  13519. referenceSpace = await session.requestReferenceSpace(referenceSpaceType);
  13520. animation.setContext(session);
  13521. animation.start();
  13522. scope.isPresenting = true;
  13523. scope.dispatchEvent({
  13524. type: 'sessionstart'
  13525. });
  13526. }
  13527. };
  13528. function onInputSourcesChange(event) {
  13529. const inputSources = session.inputSources; // Assign inputSources to available controllers
  13530. for (let i = 0; i < controllers.length; i++) {
  13531. inputSourcesMap.set(inputSources[i], controllers[i]);
  13532. } // Notify disconnected
  13533. for (let i = 0; i < event.removed.length; i++) {
  13534. const inputSource = event.removed[i];
  13535. const controller = inputSourcesMap.get(inputSource);
  13536. if (controller) {
  13537. controller.dispatchEvent({
  13538. type: 'disconnected',
  13539. data: inputSource
  13540. });
  13541. inputSourcesMap.delete(inputSource);
  13542. }
  13543. } // Notify connected
  13544. for (let i = 0; i < event.added.length; i++) {
  13545. const inputSource = event.added[i];
  13546. const controller = inputSourcesMap.get(inputSource);
  13547. if (controller) {
  13548. controller.dispatchEvent({
  13549. type: 'connected',
  13550. data: inputSource
  13551. });
  13552. }
  13553. }
  13554. } //
  13555. const cameraLPos = new Vector3();
  13556. const cameraRPos = new Vector3();
  13557. /**
  13558. * Assumes 2 cameras that are parallel and share an X-axis, and that
  13559. * the cameras' projection and world matrices have already been set.
  13560. * And that near and far planes are identical for both cameras.
  13561. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  13562. */
  13563. function setProjectionFromUnion(camera, cameraL, cameraR) {
  13564. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  13565. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  13566. const ipd = cameraLPos.distanceTo(cameraRPos);
  13567. const projL = cameraL.projectionMatrix.elements;
  13568. const projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  13569. // most likely identical top and bottom frustum extents.
  13570. // Use the left camera for these values.
  13571. const near = projL[14] / (projL[10] - 1);
  13572. const far = projL[14] / (projL[10] + 1);
  13573. const topFov = (projL[9] + 1) / projL[5];
  13574. const bottomFov = (projL[9] - 1) / projL[5];
  13575. const leftFov = (projL[8] - 1) / projL[0];
  13576. const rightFov = (projR[8] + 1) / projR[0];
  13577. const left = near * leftFov;
  13578. const right = near * rightFov; // Calculate the new camera's position offset from the
  13579. // left camera. xOffset should be roughly half `ipd`.
  13580. const zOffset = ipd / (-leftFov + rightFov);
  13581. const xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  13582. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  13583. camera.translateX(xOffset);
  13584. camera.translateZ(zOffset);
  13585. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  13586. camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); // Find the union of the frustum values of the cameras and scale
  13587. // the values so that the near plane's position does not change in world space,
  13588. // although must now be relative to the new union camera.
  13589. const near2 = near + zOffset;
  13590. const far2 = far + zOffset;
  13591. const left2 = left - xOffset;
  13592. const right2 = right + (ipd - xOffset);
  13593. const top2 = topFov * far / far2 * near2;
  13594. const bottom2 = bottomFov * far / far2 * near2;
  13595. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  13596. }
  13597. function updateCamera(camera, parent) {
  13598. if (parent === null) {
  13599. camera.matrixWorld.copy(camera.matrix);
  13600. } else {
  13601. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  13602. }
  13603. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  13604. }
  13605. this.updateCamera = function (camera) {
  13606. if (session === null) return;
  13607. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  13608. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  13609. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  13610. // Note that the new renderState won't apply until the next frame. See #18320
  13611. session.updateRenderState({
  13612. depthNear: cameraVR.near,
  13613. depthFar: cameraVR.far
  13614. });
  13615. _currentDepthNear = cameraVR.near;
  13616. _currentDepthFar = cameraVR.far;
  13617. }
  13618. const parent = camera.parent;
  13619. const cameras = cameraVR.cameras;
  13620. updateCamera(cameraVR, parent);
  13621. for (let i = 0; i < cameras.length; i++) {
  13622. updateCamera(cameras[i], parent);
  13623. }
  13624. cameraVR.matrixWorld.decompose(cameraVR.position, cameraVR.quaternion, cameraVR.scale); // update user camera and its children
  13625. camera.position.copy(cameraVR.position);
  13626. camera.quaternion.copy(cameraVR.quaternion);
  13627. camera.scale.copy(cameraVR.scale);
  13628. camera.matrix.copy(cameraVR.matrix);
  13629. camera.matrixWorld.copy(cameraVR.matrixWorld);
  13630. const children = camera.children;
  13631. for (let i = 0, l = children.length; i < l; i++) {
  13632. children[i].updateMatrixWorld(true);
  13633. } // update projection matrix for proper view frustum culling
  13634. if (cameras.length === 2) {
  13635. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  13636. } else {
  13637. // assume single camera setup (AR)
  13638. cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
  13639. }
  13640. };
  13641. this.getCamera = function () {
  13642. return cameraVR;
  13643. }; // Animation Loop
  13644. let onAnimationFrameCallback = null;
  13645. function onAnimationFrame(time, frame) {
  13646. pose = frame.getViewerPose(referenceSpace);
  13647. if (pose !== null) {
  13648. const views = pose.views;
  13649. const baseLayer = session.renderState.baseLayer;
  13650. if (session.renderState.layers === undefined) {
  13651. state.bindXRFramebuffer(baseLayer.framebuffer);
  13652. }
  13653. let cameraVRNeedsUpdate = false; // check if it's necessary to rebuild cameraVR's camera list
  13654. if (views.length !== cameraVR.cameras.length) {
  13655. cameraVR.cameras.length = 0;
  13656. cameraVRNeedsUpdate = true;
  13657. }
  13658. for (let i = 0; i < views.length; i++) {
  13659. const view = views[i];
  13660. let viewport = null;
  13661. if (session.renderState.layers === undefined) {
  13662. viewport = baseLayer.getViewport(view);
  13663. } else {
  13664. const glSubImage = glBinding.getViewSubImage(glProjLayer, view);
  13665. state.bindXRFramebuffer(glFramebuffer);
  13666. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, glSubImage.colorTexture, 0);
  13667. if (glSubImage.depthStencilTexture !== undefined) {
  13668. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, glSubImage.depthStencilTexture, 0);
  13669. }
  13670. viewport = glSubImage.viewport;
  13671. }
  13672. const camera = cameras[i];
  13673. camera.matrix.fromArray(view.transform.matrix);
  13674. camera.projectionMatrix.fromArray(view.projectionMatrix);
  13675. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  13676. if (i === 0) {
  13677. cameraVR.matrix.copy(camera.matrix);
  13678. }
  13679. if (cameraVRNeedsUpdate === true) {
  13680. cameraVR.cameras.push(camera);
  13681. }
  13682. }
  13683. } //
  13684. const inputSources = session.inputSources;
  13685. for (let i = 0; i < controllers.length; i++) {
  13686. const controller = controllers[i];
  13687. const inputSource = inputSources[i];
  13688. controller.update(inputSource, frame, referenceSpace);
  13689. }
  13690. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  13691. }
  13692. const animation = new WebGLAnimation();
  13693. animation.setAnimationLoop(onAnimationFrame);
  13694. this.setAnimationLoop = function (callback) {
  13695. onAnimationFrameCallback = callback;
  13696. };
  13697. this.dispose = function () {};
  13698. }
  13699. }
  13700. function WebGLMaterials(properties) {
  13701. function refreshFogUniforms(uniforms, fog) {
  13702. uniforms.fogColor.value.copy(fog.color);
  13703. if (fog.isFog) {
  13704. uniforms.fogNear.value = fog.near;
  13705. uniforms.fogFar.value = fog.far;
  13706. } else if (fog.isFogExp2) {
  13707. uniforms.fogDensity.value = fog.density;
  13708. }
  13709. }
  13710. function refreshMaterialUniforms(uniforms, material, pixelRatio, height, transmissionRenderTarget) {
  13711. if (material.isMeshBasicMaterial) {
  13712. refreshUniformsCommon(uniforms, material);
  13713. } else if (material.isMeshLambertMaterial) {
  13714. refreshUniformsCommon(uniforms, material);
  13715. refreshUniformsLambert(uniforms, material);
  13716. } else if (material.isMeshToonMaterial) {
  13717. refreshUniformsCommon(uniforms, material);
  13718. refreshUniformsToon(uniforms, material);
  13719. } else if (material.isMeshPhongMaterial) {
  13720. refreshUniformsCommon(uniforms, material);
  13721. refreshUniformsPhong(uniforms, material);
  13722. } else if (material.isMeshStandardMaterial) {
  13723. refreshUniformsCommon(uniforms, material);
  13724. if (material.isMeshPhysicalMaterial) {
  13725. refreshUniformsPhysical(uniforms, material, transmissionRenderTarget);
  13726. } else {
  13727. refreshUniformsStandard(uniforms, material);
  13728. }
  13729. } else if (material.isMeshMatcapMaterial) {
  13730. refreshUniformsCommon(uniforms, material);
  13731. refreshUniformsMatcap(uniforms, material);
  13732. } else if (material.isMeshDepthMaterial) {
  13733. refreshUniformsCommon(uniforms, material);
  13734. refreshUniformsDepth(uniforms, material);
  13735. } else if (material.isMeshDistanceMaterial) {
  13736. refreshUniformsCommon(uniforms, material);
  13737. refreshUniformsDistance(uniforms, material);
  13738. } else if (material.isMeshNormalMaterial) {
  13739. refreshUniformsCommon(uniforms, material);
  13740. refreshUniformsNormal(uniforms, material);
  13741. } else if (material.isLineBasicMaterial) {
  13742. refreshUniformsLine(uniforms, material);
  13743. if (material.isLineDashedMaterial) {
  13744. refreshUniformsDash(uniforms, material);
  13745. }
  13746. } else if (material.isPointsMaterial) {
  13747. refreshUniformsPoints(uniforms, material, pixelRatio, height);
  13748. } else if (material.isSpriteMaterial) {
  13749. refreshUniformsSprites(uniforms, material);
  13750. } else if (material.isShadowMaterial) {
  13751. uniforms.color.value.copy(material.color);
  13752. uniforms.opacity.value = material.opacity;
  13753. } else if (material.isShaderMaterial) {
  13754. material.uniformsNeedUpdate = false; // #15581
  13755. }
  13756. }
  13757. function refreshUniformsCommon(uniforms, material) {
  13758. uniforms.opacity.value = material.opacity;
  13759. if (material.color) {
  13760. uniforms.diffuse.value.copy(material.color);
  13761. }
  13762. if (material.emissive) {
  13763. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  13764. }
  13765. if (material.map) {
  13766. uniforms.map.value = material.map;
  13767. }
  13768. if (material.alphaMap) {
  13769. uniforms.alphaMap.value = material.alphaMap;
  13770. }
  13771. if (material.specularMap) {
  13772. uniforms.specularMap.value = material.specularMap;
  13773. }
  13774. const envMap = properties.get(material).envMap;
  13775. if (envMap) {
  13776. uniforms.envMap.value = envMap;
  13777. uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap._needsFlipEnvMap ? -1 : 1;
  13778. uniforms.reflectivity.value = material.reflectivity;
  13779. uniforms.refractionRatio.value = material.refractionRatio;
  13780. const maxMipLevel = properties.get(envMap).__maxMipLevel;
  13781. if (maxMipLevel !== undefined) {
  13782. uniforms.maxMipLevel.value = maxMipLevel;
  13783. }
  13784. }
  13785. if (material.lightMap) {
  13786. uniforms.lightMap.value = material.lightMap;
  13787. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  13788. }
  13789. if (material.aoMap) {
  13790. uniforms.aoMap.value = material.aoMap;
  13791. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  13792. } // uv repeat and offset setting priorities
  13793. // 1. color map
  13794. // 2. specular map
  13795. // 3. displacementMap map
  13796. // 4. normal map
  13797. // 5. bump map
  13798. // 6. roughnessMap map
  13799. // 7. metalnessMap map
  13800. // 8. alphaMap map
  13801. // 9. emissiveMap map
  13802. // 10. clearcoat map
  13803. // 11. clearcoat normal map
  13804. // 12. clearcoat roughnessMap map
  13805. let uvScaleMap;
  13806. if (material.map) {
  13807. uvScaleMap = material.map;
  13808. } else if (material.specularMap) {
  13809. uvScaleMap = material.specularMap;
  13810. } else if (material.displacementMap) {
  13811. uvScaleMap = material.displacementMap;
  13812. } else if (material.normalMap) {
  13813. uvScaleMap = material.normalMap;
  13814. } else if (material.bumpMap) {
  13815. uvScaleMap = material.bumpMap;
  13816. } else if (material.roughnessMap) {
  13817. uvScaleMap = material.roughnessMap;
  13818. } else if (material.metalnessMap) {
  13819. uvScaleMap = material.metalnessMap;
  13820. } else if (material.alphaMap) {
  13821. uvScaleMap = material.alphaMap;
  13822. } else if (material.emissiveMap) {
  13823. uvScaleMap = material.emissiveMap;
  13824. } else if (material.clearcoatMap) {
  13825. uvScaleMap = material.clearcoatMap;
  13826. } else if (material.clearcoatNormalMap) {
  13827. uvScaleMap = material.clearcoatNormalMap;
  13828. } else if (material.clearcoatRoughnessMap) {
  13829. uvScaleMap = material.clearcoatRoughnessMap;
  13830. }
  13831. if (uvScaleMap !== undefined) {
  13832. // backwards compatibility
  13833. if (uvScaleMap.isWebGLRenderTarget) {
  13834. uvScaleMap = uvScaleMap.texture;
  13835. }
  13836. if (uvScaleMap.matrixAutoUpdate === true) {
  13837. uvScaleMap.updateMatrix();
  13838. }
  13839. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  13840. } // uv repeat and offset setting priorities for uv2
  13841. // 1. ao map
  13842. // 2. light map
  13843. let uv2ScaleMap;
  13844. if (material.aoMap) {
  13845. uv2ScaleMap = material.aoMap;
  13846. } else if (material.lightMap) {
  13847. uv2ScaleMap = material.lightMap;
  13848. }
  13849. if (uv2ScaleMap !== undefined) {
  13850. // backwards compatibility
  13851. if (uv2ScaleMap.isWebGLRenderTarget) {
  13852. uv2ScaleMap = uv2ScaleMap.texture;
  13853. }
  13854. if (uv2ScaleMap.matrixAutoUpdate === true) {
  13855. uv2ScaleMap.updateMatrix();
  13856. }
  13857. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  13858. }
  13859. }
  13860. function refreshUniformsLine(uniforms, material) {
  13861. uniforms.diffuse.value.copy(material.color);
  13862. uniforms.opacity.value = material.opacity;
  13863. }
  13864. function refreshUniformsDash(uniforms, material) {
  13865. uniforms.dashSize.value = material.dashSize;
  13866. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13867. uniforms.scale.value = material.scale;
  13868. }
  13869. function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
  13870. uniforms.diffuse.value.copy(material.color);
  13871. uniforms.opacity.value = material.opacity;
  13872. uniforms.size.value = material.size * pixelRatio;
  13873. uniforms.scale.value = height * 0.5;
  13874. if (material.map) {
  13875. uniforms.map.value = material.map;
  13876. }
  13877. if (material.alphaMap) {
  13878. uniforms.alphaMap.value = material.alphaMap;
  13879. } // uv repeat and offset setting priorities
  13880. // 1. color map
  13881. // 2. alpha map
  13882. let uvScaleMap;
  13883. if (material.map) {
  13884. uvScaleMap = material.map;
  13885. } else if (material.alphaMap) {
  13886. uvScaleMap = material.alphaMap;
  13887. }
  13888. if (uvScaleMap !== undefined) {
  13889. if (uvScaleMap.matrixAutoUpdate === true) {
  13890. uvScaleMap.updateMatrix();
  13891. }
  13892. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  13893. }
  13894. }
  13895. function refreshUniformsSprites(uniforms, material) {
  13896. uniforms.diffuse.value.copy(material.color);
  13897. uniforms.opacity.value = material.opacity;
  13898. uniforms.rotation.value = material.rotation;
  13899. if (material.map) {
  13900. uniforms.map.value = material.map;
  13901. }
  13902. if (material.alphaMap) {
  13903. uniforms.alphaMap.value = material.alphaMap;
  13904. } // uv repeat and offset setting priorities
  13905. // 1. color map
  13906. // 2. alpha map
  13907. let uvScaleMap;
  13908. if (material.map) {
  13909. uvScaleMap = material.map;
  13910. } else if (material.alphaMap) {
  13911. uvScaleMap = material.alphaMap;
  13912. }
  13913. if (uvScaleMap !== undefined) {
  13914. if (uvScaleMap.matrixAutoUpdate === true) {
  13915. uvScaleMap.updateMatrix();
  13916. }
  13917. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  13918. }
  13919. }
  13920. function refreshUniformsLambert(uniforms, material) {
  13921. if (material.emissiveMap) {
  13922. uniforms.emissiveMap.value = material.emissiveMap;
  13923. }
  13924. }
  13925. function refreshUniformsPhong(uniforms, material) {
  13926. uniforms.specular.value.copy(material.specular);
  13927. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  13928. if (material.emissiveMap) {
  13929. uniforms.emissiveMap.value = material.emissiveMap;
  13930. }
  13931. if (material.bumpMap) {
  13932. uniforms.bumpMap.value = material.bumpMap;
  13933. uniforms.bumpScale.value = material.bumpScale;
  13934. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  13935. }
  13936. if (material.normalMap) {
  13937. uniforms.normalMap.value = material.normalMap;
  13938. uniforms.normalScale.value.copy(material.normalScale);
  13939. if (material.side === BackSide) uniforms.normalScale.value.negate();
  13940. }
  13941. if (material.displacementMap) {
  13942. uniforms.displacementMap.value = material.displacementMap;
  13943. uniforms.displacementScale.value = material.displacementScale;
  13944. uniforms.displacementBias.value = material.displacementBias;
  13945. }
  13946. }
  13947. function refreshUniformsToon(uniforms, material) {
  13948. if (material.gradientMap) {
  13949. uniforms.gradientMap.value = material.gradientMap;
  13950. }
  13951. if (material.emissiveMap) {
  13952. uniforms.emissiveMap.value = material.emissiveMap;
  13953. }
  13954. if (material.bumpMap) {
  13955. uniforms.bumpMap.value = material.bumpMap;
  13956. uniforms.bumpScale.value = material.bumpScale;
  13957. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  13958. }
  13959. if (material.normalMap) {
  13960. uniforms.normalMap.value = material.normalMap;
  13961. uniforms.normalScale.value.copy(material.normalScale);
  13962. if (material.side === BackSide) uniforms.normalScale.value.negate();
  13963. }
  13964. if (material.displacementMap) {
  13965. uniforms.displacementMap.value = material.displacementMap;
  13966. uniforms.displacementScale.value = material.displacementScale;
  13967. uniforms.displacementBias.value = material.displacementBias;
  13968. }
  13969. }
  13970. function refreshUniformsStandard(uniforms, material) {
  13971. uniforms.roughness.value = material.roughness;
  13972. uniforms.metalness.value = material.metalness;
  13973. if (material.roughnessMap) {
  13974. uniforms.roughnessMap.value = material.roughnessMap;
  13975. }
  13976. if (material.metalnessMap) {
  13977. uniforms.metalnessMap.value = material.metalnessMap;
  13978. }
  13979. if (material.emissiveMap) {
  13980. uniforms.emissiveMap.value = material.emissiveMap;
  13981. }
  13982. if (material.bumpMap) {
  13983. uniforms.bumpMap.value = material.bumpMap;
  13984. uniforms.bumpScale.value = material.bumpScale;
  13985. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  13986. }
  13987. if (material.normalMap) {
  13988. uniforms.normalMap.value = material.normalMap;
  13989. uniforms.normalScale.value.copy(material.normalScale);
  13990. if (material.side === BackSide) uniforms.normalScale.value.negate();
  13991. }
  13992. if (material.displacementMap) {
  13993. uniforms.displacementMap.value = material.displacementMap;
  13994. uniforms.displacementScale.value = material.displacementScale;
  13995. uniforms.displacementBias.value = material.displacementBias;
  13996. }
  13997. const envMap = properties.get(material).envMap;
  13998. if (envMap) {
  13999. //uniforms.envMap.value = material.envMap; // part of uniforms common
  14000. uniforms.envMapIntensity.value = material.envMapIntensity;
  14001. }
  14002. }
  14003. function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) {
  14004. refreshUniformsStandard(uniforms, material);
  14005. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  14006. uniforms.clearcoat.value = material.clearcoat;
  14007. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  14008. if (material.sheen) uniforms.sheen.value.copy(material.sheen);
  14009. if (material.clearcoatMap) {
  14010. uniforms.clearcoatMap.value = material.clearcoatMap;
  14011. }
  14012. if (material.clearcoatRoughnessMap) {
  14013. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  14014. }
  14015. if (material.clearcoatNormalMap) {
  14016. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  14017. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  14018. if (material.side === BackSide) {
  14019. uniforms.clearcoatNormalScale.value.negate();
  14020. }
  14021. }
  14022. uniforms.transmission.value = material.transmission;
  14023. if (material.transmissionMap) {
  14024. uniforms.transmissionMap.value = material.transmissionMap;
  14025. }
  14026. if (material.transmission > 0.0) {
  14027. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  14028. uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height);
  14029. }
  14030. uniforms.thickness.value = material.thickness;
  14031. if (material.thicknessMap) {
  14032. uniforms.thicknessMap.value = material.thicknessMap;
  14033. }
  14034. uniforms.attenuationDistance.value = material.attenuationDistance;
  14035. uniforms.attenuationColor.value.copy(material.attenuationColor);
  14036. }
  14037. function refreshUniformsMatcap(uniforms, material) {
  14038. if (material.matcap) {
  14039. uniforms.matcap.value = material.matcap;
  14040. }
  14041. if (material.bumpMap) {
  14042. uniforms.bumpMap.value = material.bumpMap;
  14043. uniforms.bumpScale.value = material.bumpScale;
  14044. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14045. }
  14046. if (material.normalMap) {
  14047. uniforms.normalMap.value = material.normalMap;
  14048. uniforms.normalScale.value.copy(material.normalScale);
  14049. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14050. }
  14051. if (material.displacementMap) {
  14052. uniforms.displacementMap.value = material.displacementMap;
  14053. uniforms.displacementScale.value = material.displacementScale;
  14054. uniforms.displacementBias.value = material.displacementBias;
  14055. }
  14056. }
  14057. function refreshUniformsDepth(uniforms, material) {
  14058. if (material.displacementMap) {
  14059. uniforms.displacementMap.value = material.displacementMap;
  14060. uniforms.displacementScale.value = material.displacementScale;
  14061. uniforms.displacementBias.value = material.displacementBias;
  14062. }
  14063. }
  14064. function refreshUniformsDistance(uniforms, material) {
  14065. if (material.displacementMap) {
  14066. uniforms.displacementMap.value = material.displacementMap;
  14067. uniforms.displacementScale.value = material.displacementScale;
  14068. uniforms.displacementBias.value = material.displacementBias;
  14069. }
  14070. uniforms.referencePosition.value.copy(material.referencePosition);
  14071. uniforms.nearDistance.value = material.nearDistance;
  14072. uniforms.farDistance.value = material.farDistance;
  14073. }
  14074. function refreshUniformsNormal(uniforms, material) {
  14075. if (material.bumpMap) {
  14076. uniforms.bumpMap.value = material.bumpMap;
  14077. uniforms.bumpScale.value = material.bumpScale;
  14078. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14079. }
  14080. if (material.normalMap) {
  14081. uniforms.normalMap.value = material.normalMap;
  14082. uniforms.normalScale.value.copy(material.normalScale);
  14083. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14084. }
  14085. if (material.displacementMap) {
  14086. uniforms.displacementMap.value = material.displacementMap;
  14087. uniforms.displacementScale.value = material.displacementScale;
  14088. uniforms.displacementBias.value = material.displacementBias;
  14089. }
  14090. }
  14091. return {
  14092. refreshFogUniforms: refreshFogUniforms,
  14093. refreshMaterialUniforms: refreshMaterialUniforms
  14094. };
  14095. }
  14096. function createCanvasElement() {
  14097. const canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  14098. canvas.style.display = 'block';
  14099. return canvas;
  14100. }
  14101. function WebGLRenderer(parameters = {}) {
  14102. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  14103. _context = parameters.context !== undefined ? parameters.context : null,
  14104. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14105. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14106. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  14107. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  14108. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  14109. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  14110. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  14111. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  14112. let currentRenderList = null;
  14113. let currentRenderState = null; // render() can be called from within a callback triggered by another render.
  14114. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  14115. const renderListStack = [];
  14116. const renderStateStack = []; // public properties
  14117. this.domElement = _canvas; // Debug configuration container
  14118. this.debug = {
  14119. /**
  14120. * Enables error checking and reporting when shader programs are being compiled
  14121. * @type {boolean}
  14122. */
  14123. checkShaderErrors: true
  14124. }; // clearing
  14125. this.autoClear = true;
  14126. this.autoClearColor = true;
  14127. this.autoClearDepth = true;
  14128. this.autoClearStencil = true; // scene graph
  14129. this.sortObjects = true; // user-defined clipping
  14130. this.clippingPlanes = [];
  14131. this.localClippingEnabled = false; // physically based shading
  14132. this.gammaFactor = 2.0; // for backwards compatibility
  14133. this.outputEncoding = LinearEncoding; // physical lights
  14134. this.physicallyCorrectLights = false; // tone mapping
  14135. this.toneMapping = NoToneMapping;
  14136. this.toneMappingExposure = 1.0; // internal properties
  14137. const _this = this;
  14138. let _isContextLost = false; // internal state cache
  14139. let _currentActiveCubeFace = 0;
  14140. let _currentActiveMipmapLevel = 0;
  14141. let _currentRenderTarget = null;
  14142. let _currentMaterialId = -1;
  14143. let _currentCamera = null;
  14144. const _currentViewport = new Vector4();
  14145. const _currentScissor = new Vector4();
  14146. let _currentScissorTest = null; //
  14147. let _width = _canvas.width;
  14148. let _height = _canvas.height;
  14149. let _pixelRatio = 1;
  14150. let _opaqueSort = null;
  14151. let _transparentSort = null;
  14152. const _viewport = new Vector4(0, 0, _width, _height);
  14153. const _scissor = new Vector4(0, 0, _width, _height);
  14154. let _scissorTest = false; //
  14155. const _currentDrawBuffers = []; // frustum
  14156. const _frustum = new Frustum(); // clipping
  14157. let _clippingEnabled = false;
  14158. let _localClippingEnabled = false; // transmission
  14159. let _transmissionRenderTarget = null; // camera matrices cache
  14160. const _projScreenMatrix = new Matrix4();
  14161. const _vector3 = new Vector3();
  14162. const _emptyScene = {
  14163. background: null,
  14164. fog: null,
  14165. environment: null,
  14166. overrideMaterial: null,
  14167. isScene: true
  14168. };
  14169. function getTargetPixelRatio() {
  14170. return _currentRenderTarget === null ? _pixelRatio : 1;
  14171. } // initialize
  14172. let _gl = _context;
  14173. function getContext(contextNames, contextAttributes) {
  14174. for (let i = 0; i < contextNames.length; i++) {
  14175. const contextName = contextNames[i];
  14176. const context = _canvas.getContext(contextName, contextAttributes);
  14177. if (context !== null) return context;
  14178. }
  14179. return null;
  14180. }
  14181. try {
  14182. const contextAttributes = {
  14183. alpha: _alpha,
  14184. depth: _depth,
  14185. stencil: _stencil,
  14186. antialias: _antialias,
  14187. premultipliedAlpha: _premultipliedAlpha,
  14188. preserveDrawingBuffer: _preserveDrawingBuffer,
  14189. powerPreference: _powerPreference,
  14190. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  14191. }; // event listeners must be registered before WebGL context is created, see #12753
  14192. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  14193. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  14194. if (_gl === null) {
  14195. const contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
  14196. if (_this.isWebGL1Renderer === true) {
  14197. contextNames.shift();
  14198. }
  14199. _gl = getContext(contextNames, contextAttributes);
  14200. if (_gl === null) {
  14201. if (getContext(contextNames)) {
  14202. throw new Error('Error creating WebGL context with your selected attributes.');
  14203. } else {
  14204. throw new Error('Error creating WebGL context.');
  14205. }
  14206. }
  14207. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  14208. if (_gl.getShaderPrecisionFormat === undefined) {
  14209. _gl.getShaderPrecisionFormat = function () {
  14210. return {
  14211. 'rangeMin': 1,
  14212. 'rangeMax': 1,
  14213. 'precision': 1
  14214. };
  14215. };
  14216. }
  14217. } catch (error) {
  14218. console.error('THREE.WebGLRenderer: ' + error.message);
  14219. throw error;
  14220. }
  14221. let extensions, capabilities, state, info;
  14222. let properties, textures, cubemaps, attributes, geometries, objects;
  14223. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  14224. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  14225. let utils, bindingStates;
  14226. function initGLContext() {
  14227. extensions = new WebGLExtensions(_gl);
  14228. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  14229. extensions.init(capabilities);
  14230. utils = new WebGLUtils(_gl, extensions, capabilities);
  14231. state = new WebGLState(_gl, extensions, capabilities);
  14232. _currentDrawBuffers[0] = _gl.BACK;
  14233. info = new WebGLInfo(_gl);
  14234. properties = new WebGLProperties();
  14235. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  14236. cubemaps = new WebGLCubeMaps(_this);
  14237. attributes = new WebGLAttributes(_gl, capabilities);
  14238. bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
  14239. geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
  14240. objects = new WebGLObjects(_gl, geometries, attributes, info);
  14241. morphtargets = new WebGLMorphtargets(_gl);
  14242. clipping = new WebGLClipping(properties);
  14243. programCache = new WebGLPrograms(_this, cubemaps, extensions, capabilities, bindingStates, clipping);
  14244. materials = new WebGLMaterials(properties);
  14245. renderLists = new WebGLRenderLists(properties);
  14246. renderStates = new WebGLRenderStates(extensions, capabilities);
  14247. background = new WebGLBackground(_this, cubemaps, state, objects, _premultipliedAlpha);
  14248. shadowMap = new WebGLShadowMap(_this, objects, capabilities);
  14249. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  14250. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  14251. info.programs = programCache.programs;
  14252. _this.capabilities = capabilities;
  14253. _this.extensions = extensions;
  14254. _this.properties = properties;
  14255. _this.renderLists = renderLists;
  14256. _this.shadowMap = shadowMap;
  14257. _this.state = state;
  14258. _this.info = info;
  14259. }
  14260. initGLContext(); // xr
  14261. const xr = new WebXRManager(_this, _gl);
  14262. this.xr = xr; // API
  14263. this.getContext = function () {
  14264. return _gl;
  14265. };
  14266. this.getContextAttributes = function () {
  14267. return _gl.getContextAttributes();
  14268. };
  14269. this.forceContextLoss = function () {
  14270. const extension = extensions.get('WEBGL_lose_context');
  14271. if (extension) extension.loseContext();
  14272. };
  14273. this.forceContextRestore = function () {
  14274. const extension = extensions.get('WEBGL_lose_context');
  14275. if (extension) extension.restoreContext();
  14276. };
  14277. this.getPixelRatio = function () {
  14278. return _pixelRatio;
  14279. };
  14280. this.setPixelRatio = function (value) {
  14281. if (value === undefined) return;
  14282. _pixelRatio = value;
  14283. this.setSize(_width, _height, false);
  14284. };
  14285. this.getSize = function (target) {
  14286. return target.set(_width, _height);
  14287. };
  14288. this.setSize = function (width, height, updateStyle) {
  14289. if (xr.isPresenting) {
  14290. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  14291. return;
  14292. }
  14293. _width = width;
  14294. _height = height;
  14295. _canvas.width = Math.floor(width * _pixelRatio);
  14296. _canvas.height = Math.floor(height * _pixelRatio);
  14297. if (updateStyle !== false) {
  14298. _canvas.style.width = width + 'px';
  14299. _canvas.style.height = height + 'px';
  14300. }
  14301. this.setViewport(0, 0, width, height);
  14302. };
  14303. this.getDrawingBufferSize = function (target) {
  14304. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  14305. };
  14306. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  14307. _width = width;
  14308. _height = height;
  14309. _pixelRatio = pixelRatio;
  14310. _canvas.width = Math.floor(width * pixelRatio);
  14311. _canvas.height = Math.floor(height * pixelRatio);
  14312. this.setViewport(0, 0, width, height);
  14313. };
  14314. this.getCurrentViewport = function (target) {
  14315. return target.copy(_currentViewport);
  14316. };
  14317. this.getViewport = function (target) {
  14318. return target.copy(_viewport);
  14319. };
  14320. this.setViewport = function (x, y, width, height) {
  14321. if (x.isVector4) {
  14322. _viewport.set(x.x, x.y, x.z, x.w);
  14323. } else {
  14324. _viewport.set(x, y, width, height);
  14325. }
  14326. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  14327. };
  14328. this.getScissor = function (target) {
  14329. return target.copy(_scissor);
  14330. };
  14331. this.setScissor = function (x, y, width, height) {
  14332. if (x.isVector4) {
  14333. _scissor.set(x.x, x.y, x.z, x.w);
  14334. } else {
  14335. _scissor.set(x, y, width, height);
  14336. }
  14337. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  14338. };
  14339. this.getScissorTest = function () {
  14340. return _scissorTest;
  14341. };
  14342. this.setScissorTest = function (boolean) {
  14343. state.setScissorTest(_scissorTest = boolean);
  14344. };
  14345. this.setOpaqueSort = function (method) {
  14346. _opaqueSort = method;
  14347. };
  14348. this.setTransparentSort = function (method) {
  14349. _transparentSort = method;
  14350. }; // Clearing
  14351. this.getClearColor = function (target) {
  14352. return target.copy(background.getClearColor());
  14353. };
  14354. this.setClearColor = function () {
  14355. background.setClearColor.apply(background, arguments);
  14356. };
  14357. this.getClearAlpha = function () {
  14358. return background.getClearAlpha();
  14359. };
  14360. this.setClearAlpha = function () {
  14361. background.setClearAlpha.apply(background, arguments);
  14362. };
  14363. this.clear = function (color, depth, stencil) {
  14364. let bits = 0;
  14365. if (color === undefined || color) bits |= _gl.COLOR_BUFFER_BIT;
  14366. if (depth === undefined || depth) bits |= _gl.DEPTH_BUFFER_BIT;
  14367. if (stencil === undefined || stencil) bits |= _gl.STENCIL_BUFFER_BIT;
  14368. _gl.clear(bits);
  14369. };
  14370. this.clearColor = function () {
  14371. this.clear(true, false, false);
  14372. };
  14373. this.clearDepth = function () {
  14374. this.clear(false, true, false);
  14375. };
  14376. this.clearStencil = function () {
  14377. this.clear(false, false, true);
  14378. }; //
  14379. this.dispose = function () {
  14380. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  14381. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  14382. renderLists.dispose();
  14383. renderStates.dispose();
  14384. properties.dispose();
  14385. cubemaps.dispose();
  14386. objects.dispose();
  14387. bindingStates.dispose();
  14388. xr.dispose();
  14389. xr.removeEventListener('sessionstart', onXRSessionStart);
  14390. xr.removeEventListener('sessionend', onXRSessionEnd);
  14391. if (_transmissionRenderTarget) {
  14392. _transmissionRenderTarget.dispose();
  14393. _transmissionRenderTarget = null;
  14394. }
  14395. animation.stop();
  14396. }; // Events
  14397. function onContextLost(event) {
  14398. event.preventDefault();
  14399. console.log('THREE.WebGLRenderer: Context Lost.');
  14400. _isContextLost = true;
  14401. }
  14402. function onContextRestore()
  14403. /* event */
  14404. {
  14405. console.log('THREE.WebGLRenderer: Context Restored.');
  14406. _isContextLost = false;
  14407. const infoAutoReset = info.autoReset;
  14408. const shadowMapEnabled = shadowMap.enabled;
  14409. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  14410. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  14411. const shadowMapType = shadowMap.type;
  14412. initGLContext();
  14413. info.autoReset = infoAutoReset;
  14414. shadowMap.enabled = shadowMapEnabled;
  14415. shadowMap.autoUpdate = shadowMapAutoUpdate;
  14416. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  14417. shadowMap.type = shadowMapType;
  14418. }
  14419. function onMaterialDispose(event) {
  14420. const material = event.target;
  14421. material.removeEventListener('dispose', onMaterialDispose);
  14422. deallocateMaterial(material);
  14423. } // Buffer deallocation
  14424. function deallocateMaterial(material) {
  14425. releaseMaterialProgramReferences(material);
  14426. properties.remove(material);
  14427. }
  14428. function releaseMaterialProgramReferences(material) {
  14429. const programs = properties.get(material).programs;
  14430. if (programs !== undefined) {
  14431. programs.forEach(function (program) {
  14432. programCache.releaseProgram(program);
  14433. });
  14434. }
  14435. } // Buffer rendering
  14436. function renderObjectImmediate(object, program) {
  14437. object.render(function (object) {
  14438. _this.renderBufferImmediate(object, program);
  14439. });
  14440. }
  14441. this.renderBufferImmediate = function (object, program) {
  14442. bindingStates.initAttributes();
  14443. const buffers = properties.get(object);
  14444. if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
  14445. if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
  14446. if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
  14447. if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
  14448. const programAttributes = program.getAttributes();
  14449. if (object.hasPositions) {
  14450. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.position);
  14451. _gl.bufferData(_gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW);
  14452. bindingStates.enableAttribute(programAttributes.position);
  14453. _gl.vertexAttribPointer(programAttributes.position, 3, _gl.FLOAT, false, 0, 0);
  14454. }
  14455. if (object.hasNormals) {
  14456. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.normal);
  14457. _gl.bufferData(_gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW);
  14458. bindingStates.enableAttribute(programAttributes.normal);
  14459. _gl.vertexAttribPointer(programAttributes.normal, 3, _gl.FLOAT, false, 0, 0);
  14460. }
  14461. if (object.hasUvs) {
  14462. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.uv);
  14463. _gl.bufferData(_gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW);
  14464. bindingStates.enableAttribute(programAttributes.uv);
  14465. _gl.vertexAttribPointer(programAttributes.uv, 2, _gl.FLOAT, false, 0, 0);
  14466. }
  14467. if (object.hasColors) {
  14468. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.color);
  14469. _gl.bufferData(_gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW);
  14470. bindingStates.enableAttribute(programAttributes.color);
  14471. _gl.vertexAttribPointer(programAttributes.color, 3, _gl.FLOAT, false, 0, 0);
  14472. }
  14473. bindingStates.disableUnusedAttributes();
  14474. _gl.drawArrays(_gl.TRIANGLES, 0, object.count);
  14475. object.count = 0;
  14476. };
  14477. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  14478. if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  14479. const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  14480. const program = setProgram(camera, scene, material, object);
  14481. state.setMaterial(material, frontFaceCW); //
  14482. let index = geometry.index;
  14483. const position = geometry.attributes.position; //
  14484. if (index === null) {
  14485. if (position === undefined || position.count === 0) return;
  14486. } else if (index.count === 0) {
  14487. return;
  14488. } //
  14489. let rangeFactor = 1;
  14490. if (material.wireframe === true) {
  14491. index = geometries.getWireframeAttribute(geometry);
  14492. rangeFactor = 2;
  14493. }
  14494. if (material.morphTargets || material.morphNormals) {
  14495. morphtargets.update(object, geometry, material, program);
  14496. }
  14497. bindingStates.setup(object, material, program, geometry, index);
  14498. let attribute;
  14499. let renderer = bufferRenderer;
  14500. if (index !== null) {
  14501. attribute = attributes.get(index);
  14502. renderer = indexedBufferRenderer;
  14503. renderer.setIndex(attribute);
  14504. } //
  14505. const dataCount = index !== null ? index.count : position.count;
  14506. const rangeStart = geometry.drawRange.start * rangeFactor;
  14507. const rangeCount = geometry.drawRange.count * rangeFactor;
  14508. const groupStart = group !== null ? group.start * rangeFactor : 0;
  14509. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  14510. const drawStart = Math.max(rangeStart, groupStart);
  14511. const drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  14512. const drawCount = Math.max(0, drawEnd - drawStart + 1);
  14513. if (drawCount === 0) return; //
  14514. if (object.isMesh) {
  14515. if (material.wireframe === true) {
  14516. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  14517. renderer.setMode(_gl.LINES);
  14518. } else {
  14519. renderer.setMode(_gl.TRIANGLES);
  14520. }
  14521. } else if (object.isLine) {
  14522. let lineWidth = material.linewidth;
  14523. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  14524. state.setLineWidth(lineWidth * getTargetPixelRatio());
  14525. if (object.isLineSegments) {
  14526. renderer.setMode(_gl.LINES);
  14527. } else if (object.isLineLoop) {
  14528. renderer.setMode(_gl.LINE_LOOP);
  14529. } else {
  14530. renderer.setMode(_gl.LINE_STRIP);
  14531. }
  14532. } else if (object.isPoints) {
  14533. renderer.setMode(_gl.POINTS);
  14534. } else if (object.isSprite) {
  14535. renderer.setMode(_gl.TRIANGLES);
  14536. }
  14537. if (object.isInstancedMesh) {
  14538. renderer.renderInstances(drawStart, drawCount, object.count);
  14539. } else if (geometry.isInstancedBufferGeometry) {
  14540. const instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount);
  14541. renderer.renderInstances(drawStart, drawCount, instanceCount);
  14542. } else {
  14543. renderer.render(drawStart, drawCount);
  14544. }
  14545. }; // Compile
  14546. this.compile = function (scene, camera) {
  14547. currentRenderState = renderStates.get(scene);
  14548. currentRenderState.init();
  14549. scene.traverseVisible(function (object) {
  14550. if (object.isLight && object.layers.test(camera.layers)) {
  14551. currentRenderState.pushLight(object);
  14552. if (object.castShadow) {
  14553. currentRenderState.pushShadow(object);
  14554. }
  14555. }
  14556. });
  14557. currentRenderState.setupLights();
  14558. scene.traverse(function (object) {
  14559. const material = object.material;
  14560. if (material) {
  14561. if (Array.isArray(material)) {
  14562. for (let i = 0; i < material.length; i++) {
  14563. const material2 = material[i];
  14564. getProgram(material2, scene, object);
  14565. }
  14566. } else {
  14567. getProgram(material, scene, object);
  14568. }
  14569. }
  14570. });
  14571. }; // Animation Loop
  14572. let onAnimationFrameCallback = null;
  14573. function onAnimationFrame(time) {
  14574. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  14575. }
  14576. function onXRSessionStart() {
  14577. animation.stop();
  14578. }
  14579. function onXRSessionEnd() {
  14580. animation.start();
  14581. }
  14582. const animation = new WebGLAnimation();
  14583. animation.setAnimationLoop(onAnimationFrame);
  14584. if (typeof window !== 'undefined') animation.setContext(window);
  14585. this.setAnimationLoop = function (callback) {
  14586. onAnimationFrameCallback = callback;
  14587. xr.setAnimationLoop(callback);
  14588. callback === null ? animation.stop() : animation.start();
  14589. };
  14590. xr.addEventListener('sessionstart', onXRSessionStart);
  14591. xr.addEventListener('sessionend', onXRSessionEnd); // Rendering
  14592. this.render = function (scene, camera) {
  14593. if (camera !== undefined && camera.isCamera !== true) {
  14594. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  14595. return;
  14596. }
  14597. if (_isContextLost === true) return; // update scene graph
  14598. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  14599. if (camera.parent === null) camera.updateMatrixWorld();
  14600. if (xr.enabled === true && xr.isPresenting === true) {
  14601. if (xr.cameraAutoUpdate === true) xr.updateCamera(camera);
  14602. camera = xr.getCamera(); // use XR camera for rendering
  14603. } //
  14604. if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, _currentRenderTarget);
  14605. currentRenderState = renderStates.get(scene, renderStateStack.length);
  14606. currentRenderState.init();
  14607. renderStateStack.push(currentRenderState);
  14608. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  14609. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  14610. _localClippingEnabled = this.localClippingEnabled;
  14611. _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  14612. currentRenderList = renderLists.get(scene, renderListStack.length);
  14613. currentRenderList.init();
  14614. renderListStack.push(currentRenderList);
  14615. projectObject(scene, camera, 0, _this.sortObjects);
  14616. currentRenderList.finish();
  14617. if (_this.sortObjects === true) {
  14618. currentRenderList.sort(_opaqueSort, _transparentSort);
  14619. } //
  14620. if (_clippingEnabled === true) clipping.beginShadows();
  14621. const shadowsArray = currentRenderState.state.shadowsArray;
  14622. shadowMap.render(shadowsArray, scene, camera);
  14623. currentRenderState.setupLights();
  14624. currentRenderState.setupLightsView(camera);
  14625. if (_clippingEnabled === true) clipping.endShadows(); //
  14626. if (this.info.autoReset === true) this.info.reset(); //
  14627. background.render(currentRenderList, scene); // render scene
  14628. const opaqueObjects = currentRenderList.opaque;
  14629. const transmissiveObjects = currentRenderList.transmissive;
  14630. const transparentObjects = currentRenderList.transparent;
  14631. if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
  14632. if (transmissiveObjects.length > 0) renderTransmissiveObjects(opaqueObjects, transmissiveObjects, scene, camera);
  14633. if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera); //
  14634. if (_currentRenderTarget !== null) {
  14635. // resolve multisample renderbuffers to a single-sample texture if necessary
  14636. textures.updateMultisampleRenderTarget(_currentRenderTarget); // Generate mipmap if we're using any kind of mipmap filtering
  14637. textures.updateRenderTargetMipmap(_currentRenderTarget);
  14638. } //
  14639. if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); // Ensure depth buffer writing is enabled so it can be cleared on next render
  14640. state.buffers.depth.setTest(true);
  14641. state.buffers.depth.setMask(true);
  14642. state.buffers.color.setMask(true);
  14643. state.setPolygonOffset(false); // _gl.finish();
  14644. bindingStates.resetDefaultState();
  14645. _currentMaterialId = -1;
  14646. _currentCamera = null;
  14647. renderStateStack.pop();
  14648. if (renderStateStack.length > 0) {
  14649. currentRenderState = renderStateStack[renderStateStack.length - 1];
  14650. } else {
  14651. currentRenderState = null;
  14652. }
  14653. renderListStack.pop();
  14654. if (renderListStack.length > 0) {
  14655. currentRenderList = renderListStack[renderListStack.length - 1];
  14656. } else {
  14657. currentRenderList = null;
  14658. }
  14659. };
  14660. function projectObject(object, camera, groupOrder, sortObjects) {
  14661. if (object.visible === false) return;
  14662. const visible = object.layers.test(camera.layers);
  14663. if (visible) {
  14664. if (object.isGroup) {
  14665. groupOrder = object.renderOrder;
  14666. } else if (object.isLOD) {
  14667. if (object.autoUpdate === true) object.update(camera);
  14668. } else if (object.isLight) {
  14669. currentRenderState.pushLight(object);
  14670. if (object.castShadow) {
  14671. currentRenderState.pushShadow(object);
  14672. }
  14673. } else if (object.isSprite) {
  14674. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  14675. if (sortObjects) {
  14676. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  14677. }
  14678. const geometry = objects.update(object);
  14679. const material = object.material;
  14680. if (material.visible) {
  14681. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  14682. }
  14683. }
  14684. } else if (object.isImmediateRenderObject) {
  14685. if (sortObjects) {
  14686. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  14687. }
  14688. currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
  14689. } else if (object.isMesh || object.isLine || object.isPoints) {
  14690. if (object.isSkinnedMesh) {
  14691. // update skeleton only once in a frame
  14692. if (object.skeleton.frame !== info.render.frame) {
  14693. object.skeleton.update();
  14694. object.skeleton.frame = info.render.frame;
  14695. }
  14696. }
  14697. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  14698. if (sortObjects) {
  14699. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  14700. }
  14701. const geometry = objects.update(object);
  14702. const material = object.material;
  14703. if (Array.isArray(material)) {
  14704. const groups = geometry.groups;
  14705. for (let i = 0, l = groups.length; i < l; i++) {
  14706. const group = groups[i];
  14707. const groupMaterial = material[group.materialIndex];
  14708. if (groupMaterial && groupMaterial.visible) {
  14709. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  14710. }
  14711. }
  14712. } else if (material.visible) {
  14713. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  14714. }
  14715. }
  14716. }
  14717. }
  14718. const children = object.children;
  14719. for (let i = 0, l = children.length; i < l; i++) {
  14720. projectObject(children[i], camera, groupOrder, sortObjects);
  14721. }
  14722. }
  14723. function renderTransmissiveObjects(opaqueObjects, transmissiveObjects, scene, camera) {
  14724. if (_transmissionRenderTarget === null) {
  14725. const needsAntialias = _antialias === true && capabilities.isWebGL2 === true;
  14726. const renderTargetType = needsAntialias ? WebGLMultisampleRenderTarget : WebGLRenderTarget;
  14727. _transmissionRenderTarget = new renderTargetType(1024, 1024, {
  14728. generateMipmaps: true,
  14729. type: utils.convert(HalfFloatType) !== null ? HalfFloatType : UnsignedByteType,
  14730. minFilter: LinearMipmapLinearFilter,
  14731. magFilter: NearestFilter,
  14732. wrapS: ClampToEdgeWrapping,
  14733. wrapT: ClampToEdgeWrapping
  14734. });
  14735. }
  14736. const currentRenderTarget = _this.getRenderTarget();
  14737. _this.setRenderTarget(_transmissionRenderTarget);
  14738. _this.clear(); // Turn off the features which can affect the frag color for opaque objects pass.
  14739. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  14740. const currentToneMapping = _this.toneMapping;
  14741. _this.toneMapping = NoToneMapping;
  14742. renderObjects(opaqueObjects, scene, camera);
  14743. _this.toneMapping = currentToneMapping;
  14744. textures.updateMultisampleRenderTarget(_transmissionRenderTarget);
  14745. textures.updateRenderTargetMipmap(_transmissionRenderTarget);
  14746. _this.setRenderTarget(currentRenderTarget);
  14747. renderObjects(transmissiveObjects, scene, camera);
  14748. }
  14749. function renderObjects(renderList, scene, camera) {
  14750. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  14751. for (let i = 0, l = renderList.length; i < l; i++) {
  14752. const renderItem = renderList[i];
  14753. const object = renderItem.object;
  14754. const geometry = renderItem.geometry;
  14755. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  14756. const group = renderItem.group;
  14757. if (camera.isArrayCamera) {
  14758. const cameras = camera.cameras;
  14759. for (let j = 0, jl = cameras.length; j < jl; j++) {
  14760. const camera2 = cameras[j];
  14761. if (object.layers.test(camera2.layers)) {
  14762. state.viewport(_currentViewport.copy(camera2.viewport));
  14763. currentRenderState.setupLightsView(camera2);
  14764. renderObject(object, scene, camera2, geometry, material, group);
  14765. }
  14766. }
  14767. } else {
  14768. renderObject(object, scene, camera, geometry, material, group);
  14769. }
  14770. }
  14771. }
  14772. function renderObject(object, scene, camera, geometry, material, group) {
  14773. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  14774. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  14775. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  14776. if (object.isImmediateRenderObject) {
  14777. const program = setProgram(camera, scene, material, object);
  14778. state.setMaterial(material);
  14779. bindingStates.reset();
  14780. renderObjectImmediate(object, program);
  14781. } else {
  14782. if (material.transparent === true && material.side === DoubleSide) {
  14783. material.side = BackSide;
  14784. material.needsUpdate = true;
  14785. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  14786. material.side = FrontSide;
  14787. material.needsUpdate = true;
  14788. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  14789. material.side = DoubleSide;
  14790. } else {
  14791. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  14792. }
  14793. }
  14794. object.onAfterRender(_this, scene, camera, geometry, material, group);
  14795. }
  14796. function getProgram(material, scene, object) {
  14797. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  14798. const materialProperties = properties.get(material);
  14799. const lights = currentRenderState.state.lights;
  14800. const shadowsArray = currentRenderState.state.shadowsArray;
  14801. const lightsStateVersion = lights.state.version;
  14802. const parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
  14803. const programCacheKey = programCache.getProgramCacheKey(parameters);
  14804. 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
  14805. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  14806. materialProperties.fog = scene.fog;
  14807. materialProperties.envMap = cubemaps.get(material.envMap || materialProperties.environment);
  14808. if (programs === undefined) {
  14809. // new material
  14810. material.addEventListener('dispose', onMaterialDispose);
  14811. programs = new Map();
  14812. materialProperties.programs = programs;
  14813. }
  14814. let program = programs.get(programCacheKey);
  14815. if (program !== undefined) {
  14816. // early out if program and light state is identical
  14817. if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) {
  14818. updateCommonMaterialProperties(material, parameters);
  14819. return program;
  14820. }
  14821. } else {
  14822. parameters.uniforms = programCache.getUniforms(material);
  14823. material.onBuild(parameters, _this);
  14824. material.onBeforeCompile(parameters, _this);
  14825. program = programCache.acquireProgram(parameters, programCacheKey);
  14826. programs.set(programCacheKey, program);
  14827. materialProperties.uniforms = parameters.uniforms;
  14828. }
  14829. const uniforms = materialProperties.uniforms;
  14830. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  14831. uniforms.clippingPlanes = clipping.uniform;
  14832. }
  14833. updateCommonMaterialProperties(material, parameters); // store the light setup it was created for
  14834. materialProperties.needsLights = materialNeedsLights(material);
  14835. materialProperties.lightsStateVersion = lightsStateVersion;
  14836. if (materialProperties.needsLights) {
  14837. // wire up the material to this renderer's lighting state
  14838. uniforms.ambientLightColor.value = lights.state.ambient;
  14839. uniforms.lightProbe.value = lights.state.probe;
  14840. uniforms.directionalLights.value = lights.state.directional;
  14841. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  14842. uniforms.spotLights.value = lights.state.spot;
  14843. uniforms.spotLightShadows.value = lights.state.spotShadow;
  14844. uniforms.rectAreaLights.value = lights.state.rectArea;
  14845. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  14846. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  14847. uniforms.pointLights.value = lights.state.point;
  14848. uniforms.pointLightShadows.value = lights.state.pointShadow;
  14849. uniforms.hemisphereLights.value = lights.state.hemi;
  14850. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  14851. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  14852. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  14853. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  14854. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  14855. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  14856. }
  14857. const progUniforms = program.getUniforms();
  14858. const uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  14859. materialProperties.currentProgram = program;
  14860. materialProperties.uniformsList = uniformsList;
  14861. return program;
  14862. }
  14863. function updateCommonMaterialProperties(material, parameters) {
  14864. const materialProperties = properties.get(material);
  14865. materialProperties.outputEncoding = parameters.outputEncoding;
  14866. materialProperties.instancing = parameters.instancing;
  14867. materialProperties.skinning = parameters.skinning;
  14868. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  14869. materialProperties.numIntersection = parameters.numClipIntersection;
  14870. materialProperties.vertexAlphas = parameters.vertexAlphas;
  14871. }
  14872. function setProgram(camera, scene, material, object) {
  14873. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  14874. textures.resetTextureUnits();
  14875. const fog = scene.fog;
  14876. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  14877. const encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  14878. const envMap = cubemaps.get(material.envMap || environment);
  14879. const vertexAlphas = material.vertexColors === true && object.geometry && object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4;
  14880. const materialProperties = properties.get(material);
  14881. const lights = currentRenderState.state.lights;
  14882. if (_clippingEnabled === true) {
  14883. if (_localClippingEnabled === true || camera !== _currentCamera) {
  14884. const useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  14885. // object instead of the material, once it becomes feasible
  14886. // (#8465, #8379)
  14887. clipping.setState(material, camera, useCache);
  14888. }
  14889. } //
  14890. let needsProgramChange = false;
  14891. if (material.version === materialProperties.__version) {
  14892. if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  14893. needsProgramChange = true;
  14894. } else if (materialProperties.outputEncoding !== encoding) {
  14895. needsProgramChange = true;
  14896. } else if (object.isInstancedMesh && materialProperties.instancing === false) {
  14897. needsProgramChange = true;
  14898. } else if (!object.isInstancedMesh && materialProperties.instancing === true) {
  14899. needsProgramChange = true;
  14900. } else if (object.isSkinnedMesh && materialProperties.skinning === false) {
  14901. needsProgramChange = true;
  14902. } else if (!object.isSkinnedMesh && materialProperties.skinning === true) {
  14903. needsProgramChange = true;
  14904. } else if (materialProperties.envMap !== envMap) {
  14905. needsProgramChange = true;
  14906. } else if (material.fog && materialProperties.fog !== fog) {
  14907. needsProgramChange = true;
  14908. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
  14909. needsProgramChange = true;
  14910. } else if (materialProperties.vertexAlphas !== vertexAlphas) {
  14911. needsProgramChange = true;
  14912. }
  14913. } else {
  14914. needsProgramChange = true;
  14915. materialProperties.__version = material.version;
  14916. } //
  14917. let program = materialProperties.currentProgram;
  14918. if (needsProgramChange === true) {
  14919. program = getProgram(material, scene, object);
  14920. }
  14921. let refreshProgram = false;
  14922. let refreshMaterial = false;
  14923. let refreshLights = false;
  14924. const p_uniforms = program.getUniforms(),
  14925. m_uniforms = materialProperties.uniforms;
  14926. if (state.useProgram(program.program)) {
  14927. refreshProgram = true;
  14928. refreshMaterial = true;
  14929. refreshLights = true;
  14930. }
  14931. if (material.id !== _currentMaterialId) {
  14932. _currentMaterialId = material.id;
  14933. refreshMaterial = true;
  14934. }
  14935. if (refreshProgram || _currentCamera !== camera) {
  14936. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  14937. if (capabilities.logarithmicDepthBuffer) {
  14938. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  14939. }
  14940. if (_currentCamera !== camera) {
  14941. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  14942. // now, in case this material supports lights - or later, when
  14943. // the next material that does gets activated:
  14944. refreshMaterial = true; // set to true on material change
  14945. refreshLights = true; // remains set until update done
  14946. } // load material specific uniforms
  14947. // (shader material also gets them for the sake of genericity)
  14948. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  14949. const uCamPos = p_uniforms.map.cameraPosition;
  14950. if (uCamPos !== undefined) {
  14951. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  14952. }
  14953. }
  14954. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  14955. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  14956. }
  14957. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || object.isSkinnedMesh) {
  14958. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  14959. }
  14960. } // skinning uniforms must be set even if material didn't change
  14961. // auto-setting of texture unit for bone texture must go before other textures
  14962. // otherwise textures used for skinning can take over texture units reserved for other material textures
  14963. if (object.isSkinnedMesh) {
  14964. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  14965. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  14966. const skeleton = object.skeleton;
  14967. if (skeleton) {
  14968. if (capabilities.floatVertexTextures) {
  14969. if (skeleton.boneTexture === null) skeleton.computeBoneTexture();
  14970. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  14971. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  14972. } else {
  14973. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  14974. }
  14975. }
  14976. }
  14977. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  14978. materialProperties.receiveShadow = object.receiveShadow;
  14979. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  14980. }
  14981. if (refreshMaterial) {
  14982. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  14983. if (materialProperties.needsLights) {
  14984. // the current material requires lighting info
  14985. // note: all lighting uniforms are always set correctly
  14986. // they simply reference the renderer's state for their
  14987. // values
  14988. //
  14989. // use the current material's .needsUpdate flags to set
  14990. // the GL state when required
  14991. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  14992. } // refresh uniforms common to several materials
  14993. if (fog && material.fog) {
  14994. materials.refreshFogUniforms(m_uniforms, fog);
  14995. }
  14996. materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget);
  14997. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  14998. }
  14999. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  15000. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  15001. material.uniformsNeedUpdate = false;
  15002. }
  15003. if (material.isSpriteMaterial) {
  15004. p_uniforms.setValue(_gl, 'center', object.center);
  15005. } // common matrices
  15006. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  15007. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  15008. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  15009. return program;
  15010. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  15011. function markUniformsLightsNeedsUpdate(uniforms, value) {
  15012. uniforms.ambientLightColor.needsUpdate = value;
  15013. uniforms.lightProbe.needsUpdate = value;
  15014. uniforms.directionalLights.needsUpdate = value;
  15015. uniforms.directionalLightShadows.needsUpdate = value;
  15016. uniforms.pointLights.needsUpdate = value;
  15017. uniforms.pointLightShadows.needsUpdate = value;
  15018. uniforms.spotLights.needsUpdate = value;
  15019. uniforms.spotLightShadows.needsUpdate = value;
  15020. uniforms.rectAreaLights.needsUpdate = value;
  15021. uniforms.hemisphereLights.needsUpdate = value;
  15022. }
  15023. function materialNeedsLights(material) {
  15024. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  15025. }
  15026. this.getActiveCubeFace = function () {
  15027. return _currentActiveCubeFace;
  15028. };
  15029. this.getActiveMipmapLevel = function () {
  15030. return _currentActiveMipmapLevel;
  15031. };
  15032. this.getRenderTarget = function () {
  15033. return _currentRenderTarget;
  15034. };
  15035. this.setRenderTarget = function (renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) {
  15036. _currentRenderTarget = renderTarget;
  15037. _currentActiveCubeFace = activeCubeFace;
  15038. _currentActiveMipmapLevel = activeMipmapLevel;
  15039. if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
  15040. textures.setupRenderTarget(renderTarget);
  15041. }
  15042. let framebuffer = null;
  15043. let isCube = false;
  15044. let isRenderTarget3D = false;
  15045. if (renderTarget) {
  15046. const texture = renderTarget.texture;
  15047. if (texture.isDataTexture3D || texture.isDataTexture2DArray) {
  15048. isRenderTarget3D = true;
  15049. }
  15050. const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  15051. if (renderTarget.isWebGLCubeRenderTarget) {
  15052. framebuffer = __webglFramebuffer[activeCubeFace];
  15053. isCube = true;
  15054. } else if (renderTarget.isWebGLMultisampleRenderTarget) {
  15055. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  15056. } else {
  15057. framebuffer = __webglFramebuffer;
  15058. }
  15059. _currentViewport.copy(renderTarget.viewport);
  15060. _currentScissor.copy(renderTarget.scissor);
  15061. _currentScissorTest = renderTarget.scissorTest;
  15062. } else {
  15063. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  15064. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  15065. _currentScissorTest = _scissorTest;
  15066. }
  15067. const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  15068. if (framebufferBound && capabilities.drawBuffers) {
  15069. let needsUpdate = false;
  15070. if (renderTarget) {
  15071. if (renderTarget.isWebGLMultipleRenderTargets) {
  15072. const textures = renderTarget.texture;
  15073. if (_currentDrawBuffers.length !== textures.length || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
  15074. for (let i = 0, il = textures.length; i < il; i++) {
  15075. _currentDrawBuffers[i] = _gl.COLOR_ATTACHMENT0 + i;
  15076. }
  15077. _currentDrawBuffers.length = textures.length;
  15078. needsUpdate = true;
  15079. }
  15080. } else {
  15081. if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
  15082. _currentDrawBuffers[0] = _gl.COLOR_ATTACHMENT0;
  15083. _currentDrawBuffers.length = 1;
  15084. needsUpdate = true;
  15085. }
  15086. }
  15087. } else {
  15088. if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.BACK) {
  15089. _currentDrawBuffers[0] = _gl.BACK;
  15090. _currentDrawBuffers.length = 1;
  15091. needsUpdate = true;
  15092. }
  15093. }
  15094. if (needsUpdate) {
  15095. if (capabilities.isWebGL2) {
  15096. _gl.drawBuffers(_currentDrawBuffers);
  15097. } else {
  15098. extensions.get('WEBGL_draw_buffers').drawBuffersWEBGL(_currentDrawBuffers);
  15099. }
  15100. }
  15101. }
  15102. state.viewport(_currentViewport);
  15103. state.scissor(_currentScissor);
  15104. state.setScissorTest(_currentScissorTest);
  15105. if (isCube) {
  15106. const textureProperties = properties.get(renderTarget.texture);
  15107. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
  15108. } else if (isRenderTarget3D) {
  15109. const textureProperties = properties.get(renderTarget.texture);
  15110. const layer = activeCubeFace || 0;
  15111. _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer);
  15112. }
  15113. };
  15114. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  15115. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  15116. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  15117. return;
  15118. }
  15119. let framebuffer = properties.get(renderTarget).__webglFramebuffer;
  15120. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  15121. framebuffer = framebuffer[activeCubeFaceIndex];
  15122. }
  15123. if (framebuffer) {
  15124. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  15125. try {
  15126. const texture = renderTarget.texture;
  15127. const textureFormat = texture.format;
  15128. const textureType = texture.type;
  15129. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_FORMAT)) {
  15130. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  15131. return;
  15132. }
  15133. const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has('EXT_color_buffer_half_float') || capabilities.isWebGL2 && extensions.has('EXT_color_buffer_float'));
  15134. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513)
  15135. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.has('OES_texture_float') || extensions.has('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  15136. !halfFloatSupportedByExt) {
  15137. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  15138. return;
  15139. }
  15140. if (_gl.checkFramebufferStatus(_gl.FRAMEBUFFER) === _gl.FRAMEBUFFER_COMPLETE) {
  15141. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  15142. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  15143. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  15144. }
  15145. } else {
  15146. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  15147. }
  15148. } finally {
  15149. // restore framebuffer of current render target if necessary
  15150. const framebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null;
  15151. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  15152. }
  15153. }
  15154. };
  15155. this.copyFramebufferToTexture = function (position, texture, level = 0) {
  15156. const levelScale = Math.pow(2, -level);
  15157. const width = Math.floor(texture.image.width * levelScale);
  15158. const height = Math.floor(texture.image.height * levelScale);
  15159. let glFormat = utils.convert(texture.format);
  15160. if (capabilities.isWebGL2) {
  15161. // Workaround for https://bugs.chromium.org/p/chromium/issues/detail?id=1120100
  15162. // Not needed in Chrome 93+
  15163. if (glFormat === _gl.RGB) glFormat = _gl.RGB8;
  15164. if (glFormat === _gl.RGBA) glFormat = _gl.RGBA8;
  15165. }
  15166. textures.setTexture2D(texture, 0);
  15167. _gl.copyTexImage2D(_gl.TEXTURE_2D, level, glFormat, position.x, position.y, width, height, 0);
  15168. state.unbindTexture();
  15169. };
  15170. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level = 0) {
  15171. const width = srcTexture.image.width;
  15172. const height = srcTexture.image.height;
  15173. const glFormat = utils.convert(dstTexture.format);
  15174. const glType = utils.convert(dstTexture.type);
  15175. textures.setTexture2D(dstTexture, 0); // As another texture upload may have changed pixelStorei
  15176. // parameters, make sure they are correct for the dstTexture
  15177. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  15178. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  15179. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  15180. if (srcTexture.isDataTexture) {
  15181. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  15182. } else {
  15183. if (srcTexture.isCompressedTexture) {
  15184. _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
  15185. } else {
  15186. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image);
  15187. }
  15188. } // Generate mipmaps only when copying level 0
  15189. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(_gl.TEXTURE_2D);
  15190. state.unbindTexture();
  15191. };
  15192. this.copyTextureToTexture3D = function (sourceBox, position, srcTexture, dstTexture, level = 0) {
  15193. if (_this.isWebGL1Renderer) {
  15194. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.');
  15195. return;
  15196. }
  15197. const width = sourceBox.max.x - sourceBox.min.x + 1;
  15198. const height = sourceBox.max.y - sourceBox.min.y + 1;
  15199. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  15200. const glFormat = utils.convert(dstTexture.format);
  15201. const glType = utils.convert(dstTexture.type);
  15202. let glTarget;
  15203. if (dstTexture.isDataTexture3D) {
  15204. textures.setTexture3D(dstTexture, 0);
  15205. glTarget = _gl.TEXTURE_3D;
  15206. } else if (dstTexture.isDataTexture2DArray) {
  15207. textures.setTexture2DArray(dstTexture, 0);
  15208. glTarget = _gl.TEXTURE_2D_ARRAY;
  15209. } else {
  15210. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.');
  15211. return;
  15212. }
  15213. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  15214. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  15215. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  15216. const unpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH);
  15217. const unpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT);
  15218. const unpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS);
  15219. const unpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS);
  15220. const unpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES);
  15221. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[0] : srcTexture.image;
  15222. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width);
  15223. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, image.height);
  15224. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, sourceBox.min.x);
  15225. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, sourceBox.min.y);
  15226. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, sourceBox.min.z);
  15227. if (srcTexture.isDataTexture || srcTexture.isDataTexture3D) {
  15228. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data);
  15229. } else {
  15230. if (srcTexture.isCompressedTexture) {
  15231. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.');
  15232. _gl.compressedTexSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data);
  15233. } else {
  15234. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image);
  15235. }
  15236. }
  15237. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, unpackRowLen);
  15238. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight);
  15239. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, unpackSkipPixels);
  15240. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, unpackSkipRows);
  15241. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, unpackSkipImages); // Generate mipmaps only when copying level 0
  15242. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(glTarget);
  15243. state.unbindTexture();
  15244. };
  15245. this.initTexture = function (texture) {
  15246. textures.setTexture2D(texture, 0);
  15247. state.unbindTexture();
  15248. };
  15249. this.resetState = function () {
  15250. _currentActiveCubeFace = 0;
  15251. _currentActiveMipmapLevel = 0;
  15252. _currentRenderTarget = null;
  15253. state.reset();
  15254. bindingStates.reset();
  15255. };
  15256. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  15257. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  15258. detail: this
  15259. })); // eslint-disable-line no-undef
  15260. }
  15261. }
  15262. class WebGL1Renderer extends WebGLRenderer {}
  15263. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  15264. class FogExp2 {
  15265. constructor(color, density = 0.00025) {
  15266. this.name = '';
  15267. this.color = new Color(color);
  15268. this.density = density;
  15269. }
  15270. clone() {
  15271. return new FogExp2(this.color, this.density);
  15272. }
  15273. toJSON()
  15274. /* meta */
  15275. {
  15276. return {
  15277. type: 'FogExp2',
  15278. color: this.color.getHex(),
  15279. density: this.density
  15280. };
  15281. }
  15282. }
  15283. FogExp2.prototype.isFogExp2 = true;
  15284. class Fog {
  15285. constructor(color, near = 1, far = 1000) {
  15286. this.name = '';
  15287. this.color = new Color(color);
  15288. this.near = near;
  15289. this.far = far;
  15290. }
  15291. clone() {
  15292. return new Fog(this.color, this.near, this.far);
  15293. }
  15294. toJSON()
  15295. /* meta */
  15296. {
  15297. return {
  15298. type: 'Fog',
  15299. color: this.color.getHex(),
  15300. near: this.near,
  15301. far: this.far
  15302. };
  15303. }
  15304. }
  15305. Fog.prototype.isFog = true;
  15306. class Scene extends Object3D {
  15307. constructor() {
  15308. super();
  15309. this.type = 'Scene';
  15310. this.background = null;
  15311. this.environment = null;
  15312. this.fog = null;
  15313. this.overrideMaterial = null;
  15314. this.autoUpdate = true; // checked by the renderer
  15315. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  15316. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  15317. detail: this
  15318. })); // eslint-disable-line no-undef
  15319. }
  15320. }
  15321. copy(source, recursive) {
  15322. super.copy(source, recursive);
  15323. if (source.background !== null) this.background = source.background.clone();
  15324. if (source.environment !== null) this.environment = source.environment.clone();
  15325. if (source.fog !== null) this.fog = source.fog.clone();
  15326. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  15327. this.autoUpdate = source.autoUpdate;
  15328. this.matrixAutoUpdate = source.matrixAutoUpdate;
  15329. return this;
  15330. }
  15331. toJSON(meta) {
  15332. const data = super.toJSON(meta);
  15333. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  15334. return data;
  15335. }
  15336. }
  15337. Scene.prototype.isScene = true;
  15338. class InterleavedBuffer {
  15339. constructor(array, stride) {
  15340. this.array = array;
  15341. this.stride = stride;
  15342. this.count = array !== undefined ? array.length / stride : 0;
  15343. this.usage = StaticDrawUsage;
  15344. this.updateRange = {
  15345. offset: 0,
  15346. count: -1
  15347. };
  15348. this.version = 0;
  15349. this.uuid = generateUUID();
  15350. }
  15351. onUploadCallback() {}
  15352. set needsUpdate(value) {
  15353. if (value === true) this.version++;
  15354. }
  15355. setUsage(value) {
  15356. this.usage = value;
  15357. return this;
  15358. }
  15359. copy(source) {
  15360. this.array = new source.array.constructor(source.array);
  15361. this.count = source.count;
  15362. this.stride = source.stride;
  15363. this.usage = source.usage;
  15364. return this;
  15365. }
  15366. copyAt(index1, attribute, index2) {
  15367. index1 *= this.stride;
  15368. index2 *= attribute.stride;
  15369. for (let i = 0, l = this.stride; i < l; i++) {
  15370. this.array[index1 + i] = attribute.array[index2 + i];
  15371. }
  15372. return this;
  15373. }
  15374. set(value, offset = 0) {
  15375. this.array.set(value, offset);
  15376. return this;
  15377. }
  15378. clone(data) {
  15379. if (data.arrayBuffers === undefined) {
  15380. data.arrayBuffers = {};
  15381. }
  15382. if (this.array.buffer._uuid === undefined) {
  15383. this.array.buffer._uuid = generateUUID();
  15384. }
  15385. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  15386. data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
  15387. }
  15388. const array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
  15389. const ib = new this.constructor(array, this.stride);
  15390. ib.setUsage(this.usage);
  15391. return ib;
  15392. }
  15393. onUpload(callback) {
  15394. this.onUploadCallback = callback;
  15395. return this;
  15396. }
  15397. toJSON(data) {
  15398. if (data.arrayBuffers === undefined) {
  15399. data.arrayBuffers = {};
  15400. } // generate UUID for array buffer if necessary
  15401. if (this.array.buffer._uuid === undefined) {
  15402. this.array.buffer._uuid = generateUUID();
  15403. }
  15404. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  15405. data.arrayBuffers[this.array.buffer._uuid] = Array.prototype.slice.call(new Uint32Array(this.array.buffer));
  15406. } //
  15407. return {
  15408. uuid: this.uuid,
  15409. buffer: this.array.buffer._uuid,
  15410. type: this.array.constructor.name,
  15411. stride: this.stride
  15412. };
  15413. }
  15414. }
  15415. InterleavedBuffer.prototype.isInterleavedBuffer = true;
  15416. const _vector$6 = /*@__PURE__*/new Vector3();
  15417. class InterleavedBufferAttribute {
  15418. constructor(interleavedBuffer, itemSize, offset, normalized = false) {
  15419. this.name = '';
  15420. this.data = interleavedBuffer;
  15421. this.itemSize = itemSize;
  15422. this.offset = offset;
  15423. this.normalized = normalized === true;
  15424. }
  15425. get count() {
  15426. return this.data.count;
  15427. }
  15428. get array() {
  15429. return this.data.array;
  15430. }
  15431. set needsUpdate(value) {
  15432. this.data.needsUpdate = value;
  15433. }
  15434. applyMatrix4(m) {
  15435. for (let i = 0, l = this.data.count; i < l; i++) {
  15436. _vector$6.x = this.getX(i);
  15437. _vector$6.y = this.getY(i);
  15438. _vector$6.z = this.getZ(i);
  15439. _vector$6.applyMatrix4(m);
  15440. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  15441. }
  15442. return this;
  15443. }
  15444. applyNormalMatrix(m) {
  15445. for (let i = 0, l = this.count; i < l; i++) {
  15446. _vector$6.x = this.getX(i);
  15447. _vector$6.y = this.getY(i);
  15448. _vector$6.z = this.getZ(i);
  15449. _vector$6.applyNormalMatrix(m);
  15450. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  15451. }
  15452. return this;
  15453. }
  15454. transformDirection(m) {
  15455. for (let i = 0, l = this.count; i < l; i++) {
  15456. _vector$6.x = this.getX(i);
  15457. _vector$6.y = this.getY(i);
  15458. _vector$6.z = this.getZ(i);
  15459. _vector$6.transformDirection(m);
  15460. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  15461. }
  15462. return this;
  15463. }
  15464. setX(index, x) {
  15465. this.data.array[index * this.data.stride + this.offset] = x;
  15466. return this;
  15467. }
  15468. setY(index, y) {
  15469. this.data.array[index * this.data.stride + this.offset + 1] = y;
  15470. return this;
  15471. }
  15472. setZ(index, z) {
  15473. this.data.array[index * this.data.stride + this.offset + 2] = z;
  15474. return this;
  15475. }
  15476. setW(index, w) {
  15477. this.data.array[index * this.data.stride + this.offset + 3] = w;
  15478. return this;
  15479. }
  15480. getX(index) {
  15481. return this.data.array[index * this.data.stride + this.offset];
  15482. }
  15483. getY(index) {
  15484. return this.data.array[index * this.data.stride + this.offset + 1];
  15485. }
  15486. getZ(index) {
  15487. return this.data.array[index * this.data.stride + this.offset + 2];
  15488. }
  15489. getW(index) {
  15490. return this.data.array[index * this.data.stride + this.offset + 3];
  15491. }
  15492. setXY(index, x, y) {
  15493. index = index * this.data.stride + this.offset;
  15494. this.data.array[index + 0] = x;
  15495. this.data.array[index + 1] = y;
  15496. return this;
  15497. }
  15498. setXYZ(index, x, y, z) {
  15499. index = index * this.data.stride + this.offset;
  15500. this.data.array[index + 0] = x;
  15501. this.data.array[index + 1] = y;
  15502. this.data.array[index + 2] = z;
  15503. return this;
  15504. }
  15505. setXYZW(index, x, y, z, w) {
  15506. index = index * this.data.stride + this.offset;
  15507. this.data.array[index + 0] = x;
  15508. this.data.array[index + 1] = y;
  15509. this.data.array[index + 2] = z;
  15510. this.data.array[index + 3] = w;
  15511. return this;
  15512. }
  15513. clone(data) {
  15514. if (data === undefined) {
  15515. console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.');
  15516. const array = [];
  15517. for (let i = 0; i < this.count; i++) {
  15518. const index = i * this.data.stride + this.offset;
  15519. for (let j = 0; j < this.itemSize; j++) {
  15520. array.push(this.data.array[index + j]);
  15521. }
  15522. }
  15523. return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
  15524. } else {
  15525. if (data.interleavedBuffers === undefined) {
  15526. data.interleavedBuffers = {};
  15527. }
  15528. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  15529. data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
  15530. }
  15531. return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  15532. }
  15533. }
  15534. toJSON(data) {
  15535. if (data === undefined) {
  15536. console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.');
  15537. const array = [];
  15538. for (let i = 0; i < this.count; i++) {
  15539. const index = i * this.data.stride + this.offset;
  15540. for (let j = 0; j < this.itemSize; j++) {
  15541. array.push(this.data.array[index + j]);
  15542. }
  15543. } // deinterleave data and save it as an ordinary buffer attribute for now
  15544. return {
  15545. itemSize: this.itemSize,
  15546. type: this.array.constructor.name,
  15547. array: array,
  15548. normalized: this.normalized
  15549. };
  15550. } else {
  15551. // save as true interlaved attribtue
  15552. if (data.interleavedBuffers === undefined) {
  15553. data.interleavedBuffers = {};
  15554. }
  15555. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  15556. data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
  15557. }
  15558. return {
  15559. isInterleavedBufferAttribute: true,
  15560. itemSize: this.itemSize,
  15561. data: this.data.uuid,
  15562. offset: this.offset,
  15563. normalized: this.normalized
  15564. };
  15565. }
  15566. }
  15567. }
  15568. InterleavedBufferAttribute.prototype.isInterleavedBufferAttribute = true;
  15569. /**
  15570. * parameters = {
  15571. * color: <hex>,
  15572. * map: new THREE.Texture( <Image> ),
  15573. * alphaMap: new THREE.Texture( <Image> ),
  15574. * rotation: <float>,
  15575. * sizeAttenuation: <bool>
  15576. * }
  15577. */
  15578. class SpriteMaterial extends Material {
  15579. constructor(parameters) {
  15580. super();
  15581. this.type = 'SpriteMaterial';
  15582. this.color = new Color(0xffffff);
  15583. this.map = null;
  15584. this.alphaMap = null;
  15585. this.rotation = 0;
  15586. this.sizeAttenuation = true;
  15587. this.transparent = true;
  15588. this.setValues(parameters);
  15589. }
  15590. copy(source) {
  15591. super.copy(source);
  15592. this.color.copy(source.color);
  15593. this.map = source.map;
  15594. this.alphaMap = source.alphaMap;
  15595. this.rotation = source.rotation;
  15596. this.sizeAttenuation = source.sizeAttenuation;
  15597. return this;
  15598. }
  15599. }
  15600. SpriteMaterial.prototype.isSpriteMaterial = true;
  15601. let _geometry;
  15602. const _intersectPoint = /*@__PURE__*/new Vector3();
  15603. const _worldScale = /*@__PURE__*/new Vector3();
  15604. const _mvPosition = /*@__PURE__*/new Vector3();
  15605. const _alignedPosition = /*@__PURE__*/new Vector2();
  15606. const _rotatedPosition = /*@__PURE__*/new Vector2();
  15607. const _viewWorldMatrix = /*@__PURE__*/new Matrix4();
  15608. const _vA = /*@__PURE__*/new Vector3();
  15609. const _vB = /*@__PURE__*/new Vector3();
  15610. const _vC = /*@__PURE__*/new Vector3();
  15611. const _uvA = /*@__PURE__*/new Vector2();
  15612. const _uvB = /*@__PURE__*/new Vector2();
  15613. const _uvC = /*@__PURE__*/new Vector2();
  15614. class Sprite extends Object3D {
  15615. constructor(material) {
  15616. super();
  15617. this.type = 'Sprite';
  15618. if (_geometry === undefined) {
  15619. _geometry = new BufferGeometry();
  15620. 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]);
  15621. const interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  15622. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  15623. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  15624. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  15625. }
  15626. this.geometry = _geometry;
  15627. this.material = material !== undefined ? material : new SpriteMaterial();
  15628. this.center = new Vector2(0.5, 0.5);
  15629. }
  15630. raycast(raycaster, intersects) {
  15631. if (raycaster.camera === null) {
  15632. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  15633. }
  15634. _worldScale.setFromMatrixScale(this.matrixWorld);
  15635. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  15636. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  15637. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  15638. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  15639. _worldScale.multiplyScalar(-_mvPosition.z);
  15640. }
  15641. const rotation = this.material.rotation;
  15642. let sin, cos;
  15643. if (rotation !== 0) {
  15644. cos = Math.cos(rotation);
  15645. sin = Math.sin(rotation);
  15646. }
  15647. const center = this.center;
  15648. transformVertex(_vA.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15649. transformVertex(_vB.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15650. transformVertex(_vC.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15651. _uvA.set(0, 0);
  15652. _uvB.set(1, 0);
  15653. _uvC.set(1, 1); // check first triangle
  15654. let intersect = raycaster.ray.intersectTriangle(_vA, _vB, _vC, false, _intersectPoint);
  15655. if (intersect === null) {
  15656. // check second triangle
  15657. transformVertex(_vB.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15658. _uvB.set(0, 1);
  15659. intersect = raycaster.ray.intersectTriangle(_vA, _vC, _vB, false, _intersectPoint);
  15660. if (intersect === null) {
  15661. return;
  15662. }
  15663. }
  15664. const distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  15665. if (distance < raycaster.near || distance > raycaster.far) return;
  15666. intersects.push({
  15667. distance: distance,
  15668. point: _intersectPoint.clone(),
  15669. uv: Triangle.getUV(_intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2()),
  15670. face: null,
  15671. object: this
  15672. });
  15673. }
  15674. copy(source) {
  15675. super.copy(source);
  15676. if (source.center !== undefined) this.center.copy(source.center);
  15677. this.material = source.material;
  15678. return this;
  15679. }
  15680. }
  15681. Sprite.prototype.isSprite = true;
  15682. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  15683. // compute position in camera space
  15684. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  15685. if (sin !== undefined) {
  15686. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  15687. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  15688. } else {
  15689. _rotatedPosition.copy(_alignedPosition);
  15690. }
  15691. vertexPosition.copy(mvPosition);
  15692. vertexPosition.x += _rotatedPosition.x;
  15693. vertexPosition.y += _rotatedPosition.y; // transform to world space
  15694. vertexPosition.applyMatrix4(_viewWorldMatrix);
  15695. }
  15696. const _v1$2 = /*@__PURE__*/new Vector3();
  15697. const _v2$1 = /*@__PURE__*/new Vector3();
  15698. class LOD extends Object3D {
  15699. constructor() {
  15700. super();
  15701. this._currentLevel = 0;
  15702. this.type = 'LOD';
  15703. Object.defineProperties(this, {
  15704. levels: {
  15705. enumerable: true,
  15706. value: []
  15707. },
  15708. isLOD: {
  15709. value: true
  15710. }
  15711. });
  15712. this.autoUpdate = true;
  15713. }
  15714. copy(source) {
  15715. super.copy(source, false);
  15716. const levels = source.levels;
  15717. for (let i = 0, l = levels.length; i < l; i++) {
  15718. const level = levels[i];
  15719. this.addLevel(level.object.clone(), level.distance);
  15720. }
  15721. this.autoUpdate = source.autoUpdate;
  15722. return this;
  15723. }
  15724. addLevel(object, distance = 0) {
  15725. distance = Math.abs(distance);
  15726. const levels = this.levels;
  15727. let l;
  15728. for (l = 0; l < levels.length; l++) {
  15729. if (distance < levels[l].distance) {
  15730. break;
  15731. }
  15732. }
  15733. levels.splice(l, 0, {
  15734. distance: distance,
  15735. object: object
  15736. });
  15737. this.add(object);
  15738. return this;
  15739. }
  15740. getCurrentLevel() {
  15741. return this._currentLevel;
  15742. }
  15743. getObjectForDistance(distance) {
  15744. const levels = this.levels;
  15745. if (levels.length > 0) {
  15746. let i, l;
  15747. for (i = 1, l = levels.length; i < l; i++) {
  15748. if (distance < levels[i].distance) {
  15749. break;
  15750. }
  15751. }
  15752. return levels[i - 1].object;
  15753. }
  15754. return null;
  15755. }
  15756. raycast(raycaster, intersects) {
  15757. const levels = this.levels;
  15758. if (levels.length > 0) {
  15759. _v1$2.setFromMatrixPosition(this.matrixWorld);
  15760. const distance = raycaster.ray.origin.distanceTo(_v1$2);
  15761. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  15762. }
  15763. }
  15764. update(camera) {
  15765. const levels = this.levels;
  15766. if (levels.length > 1) {
  15767. _v1$2.setFromMatrixPosition(camera.matrixWorld);
  15768. _v2$1.setFromMatrixPosition(this.matrixWorld);
  15769. const distance = _v1$2.distanceTo(_v2$1) / camera.zoom;
  15770. levels[0].object.visible = true;
  15771. let i, l;
  15772. for (i = 1, l = levels.length; i < l; i++) {
  15773. if (distance >= levels[i].distance) {
  15774. levels[i - 1].object.visible = false;
  15775. levels[i].object.visible = true;
  15776. } else {
  15777. break;
  15778. }
  15779. }
  15780. this._currentLevel = i - 1;
  15781. for (; i < l; i++) {
  15782. levels[i].object.visible = false;
  15783. }
  15784. }
  15785. }
  15786. toJSON(meta) {
  15787. const data = super.toJSON(meta);
  15788. if (this.autoUpdate === false) data.object.autoUpdate = false;
  15789. data.object.levels = [];
  15790. const levels = this.levels;
  15791. for (let i = 0, l = levels.length; i < l; i++) {
  15792. const level = levels[i];
  15793. data.object.levels.push({
  15794. object: level.object.uuid,
  15795. distance: level.distance
  15796. });
  15797. }
  15798. return data;
  15799. }
  15800. }
  15801. const _basePosition = /*@__PURE__*/new Vector3();
  15802. const _skinIndex = /*@__PURE__*/new Vector4();
  15803. const _skinWeight = /*@__PURE__*/new Vector4();
  15804. const _vector$5 = /*@__PURE__*/new Vector3();
  15805. const _matrix = /*@__PURE__*/new Matrix4();
  15806. class SkinnedMesh extends Mesh {
  15807. constructor(geometry, material) {
  15808. super(geometry, material);
  15809. this.type = 'SkinnedMesh';
  15810. this.bindMode = 'attached';
  15811. this.bindMatrix = new Matrix4();
  15812. this.bindMatrixInverse = new Matrix4();
  15813. }
  15814. copy(source) {
  15815. super.copy(source);
  15816. this.bindMode = source.bindMode;
  15817. this.bindMatrix.copy(source.bindMatrix);
  15818. this.bindMatrixInverse.copy(source.bindMatrixInverse);
  15819. this.skeleton = source.skeleton;
  15820. return this;
  15821. }
  15822. bind(skeleton, bindMatrix) {
  15823. this.skeleton = skeleton;
  15824. if (bindMatrix === undefined) {
  15825. this.updateMatrixWorld(true);
  15826. this.skeleton.calculateInverses();
  15827. bindMatrix = this.matrixWorld;
  15828. }
  15829. this.bindMatrix.copy(bindMatrix);
  15830. this.bindMatrixInverse.copy(bindMatrix).invert();
  15831. }
  15832. pose() {
  15833. this.skeleton.pose();
  15834. }
  15835. normalizeSkinWeights() {
  15836. const vector = new Vector4();
  15837. const skinWeight = this.geometry.attributes.skinWeight;
  15838. for (let i = 0, l = skinWeight.count; i < l; i++) {
  15839. vector.x = skinWeight.getX(i);
  15840. vector.y = skinWeight.getY(i);
  15841. vector.z = skinWeight.getZ(i);
  15842. vector.w = skinWeight.getW(i);
  15843. const scale = 1.0 / vector.manhattanLength();
  15844. if (scale !== Infinity) {
  15845. vector.multiplyScalar(scale);
  15846. } else {
  15847. vector.set(1, 0, 0, 0); // do something reasonable
  15848. }
  15849. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  15850. }
  15851. }
  15852. updateMatrixWorld(force) {
  15853. super.updateMatrixWorld(force);
  15854. if (this.bindMode === 'attached') {
  15855. this.bindMatrixInverse.copy(this.matrixWorld).invert();
  15856. } else if (this.bindMode === 'detached') {
  15857. this.bindMatrixInverse.copy(this.bindMatrix).invert();
  15858. } else {
  15859. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  15860. }
  15861. }
  15862. boneTransform(index, target) {
  15863. const skeleton = this.skeleton;
  15864. const geometry = this.geometry;
  15865. _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
  15866. _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
  15867. _basePosition.fromBufferAttribute(geometry.attributes.position, index).applyMatrix4(this.bindMatrix);
  15868. target.set(0, 0, 0);
  15869. for (let i = 0; i < 4; i++) {
  15870. const weight = _skinWeight.getComponent(i);
  15871. if (weight !== 0) {
  15872. const boneIndex = _skinIndex.getComponent(i);
  15873. _matrix.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
  15874. target.addScaledVector(_vector$5.copy(_basePosition).applyMatrix4(_matrix), weight);
  15875. }
  15876. }
  15877. return target.applyMatrix4(this.bindMatrixInverse);
  15878. }
  15879. }
  15880. SkinnedMesh.prototype.isSkinnedMesh = true;
  15881. class Bone extends Object3D {
  15882. constructor() {
  15883. super();
  15884. this.type = 'Bone';
  15885. }
  15886. }
  15887. Bone.prototype.isBone = true;
  15888. class DataTexture extends Texture {
  15889. constructor(data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding) {
  15890. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  15891. this.image = {
  15892. data: data,
  15893. width: width,
  15894. height: height
  15895. };
  15896. this.magFilter = magFilter;
  15897. this.minFilter = minFilter;
  15898. this.generateMipmaps = false;
  15899. this.flipY = false;
  15900. this.unpackAlignment = 1;
  15901. this.needsUpdate = true;
  15902. }
  15903. }
  15904. DataTexture.prototype.isDataTexture = true;
  15905. const _offsetMatrix = /*@__PURE__*/new Matrix4();
  15906. const _identityMatrix = /*@__PURE__*/new Matrix4();
  15907. class Skeleton {
  15908. constructor(bones = [], boneInverses = []) {
  15909. this.uuid = generateUUID();
  15910. this.bones = bones.slice(0);
  15911. this.boneInverses = boneInverses;
  15912. this.boneMatrices = null;
  15913. this.boneTexture = null;
  15914. this.boneTextureSize = 0;
  15915. this.frame = -1;
  15916. this.init();
  15917. }
  15918. init() {
  15919. const bones = this.bones;
  15920. const boneInverses = this.boneInverses;
  15921. this.boneMatrices = new Float32Array(bones.length * 16); // calculate inverse bone matrices if necessary
  15922. if (boneInverses.length === 0) {
  15923. this.calculateInverses();
  15924. } else {
  15925. // handle special case
  15926. if (bones.length !== boneInverses.length) {
  15927. console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
  15928. this.boneInverses = [];
  15929. for (let i = 0, il = this.bones.length; i < il; i++) {
  15930. this.boneInverses.push(new Matrix4());
  15931. }
  15932. }
  15933. }
  15934. }
  15935. calculateInverses() {
  15936. this.boneInverses.length = 0;
  15937. for (let i = 0, il = this.bones.length; i < il; i++) {
  15938. const inverse = new Matrix4();
  15939. if (this.bones[i]) {
  15940. inverse.copy(this.bones[i].matrixWorld).invert();
  15941. }
  15942. this.boneInverses.push(inverse);
  15943. }
  15944. }
  15945. pose() {
  15946. // recover the bind-time world matrices
  15947. for (let i = 0, il = this.bones.length; i < il; i++) {
  15948. const bone = this.bones[i];
  15949. if (bone) {
  15950. bone.matrixWorld.copy(this.boneInverses[i]).invert();
  15951. }
  15952. } // compute the local matrices, positions, rotations and scales
  15953. for (let i = 0, il = this.bones.length; i < il; i++) {
  15954. const bone = this.bones[i];
  15955. if (bone) {
  15956. if (bone.parent && bone.parent.isBone) {
  15957. bone.matrix.copy(bone.parent.matrixWorld).invert();
  15958. bone.matrix.multiply(bone.matrixWorld);
  15959. } else {
  15960. bone.matrix.copy(bone.matrixWorld);
  15961. }
  15962. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  15963. }
  15964. }
  15965. }
  15966. update() {
  15967. const bones = this.bones;
  15968. const boneInverses = this.boneInverses;
  15969. const boneMatrices = this.boneMatrices;
  15970. const boneTexture = this.boneTexture; // flatten bone matrices to array
  15971. for (let i = 0, il = bones.length; i < il; i++) {
  15972. // compute the offset between the current and the original transform
  15973. const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  15974. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  15975. _offsetMatrix.toArray(boneMatrices, i * 16);
  15976. }
  15977. if (boneTexture !== null) {
  15978. boneTexture.needsUpdate = true;
  15979. }
  15980. }
  15981. clone() {
  15982. return new Skeleton(this.bones, this.boneInverses);
  15983. }
  15984. computeBoneTexture() {
  15985. // layout (1 matrix = 4 pixels)
  15986. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  15987. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  15988. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  15989. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  15990. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  15991. let size = Math.sqrt(this.bones.length * 4); // 4 pixels needed for 1 matrix
  15992. size = ceilPowerOfTwo(size);
  15993. size = Math.max(size, 4);
  15994. const boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  15995. boneMatrices.set(this.boneMatrices); // copy current values
  15996. const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  15997. this.boneMatrices = boneMatrices;
  15998. this.boneTexture = boneTexture;
  15999. this.boneTextureSize = size;
  16000. return this;
  16001. }
  16002. getBoneByName(name) {
  16003. for (let i = 0, il = this.bones.length; i < il; i++) {
  16004. const bone = this.bones[i];
  16005. if (bone.name === name) {
  16006. return bone;
  16007. }
  16008. }
  16009. return undefined;
  16010. }
  16011. dispose() {
  16012. if (this.boneTexture !== null) {
  16013. this.boneTexture.dispose();
  16014. this.boneTexture = null;
  16015. }
  16016. }
  16017. fromJSON(json, bones) {
  16018. this.uuid = json.uuid;
  16019. for (let i = 0, l = json.bones.length; i < l; i++) {
  16020. const uuid = json.bones[i];
  16021. let bone = bones[uuid];
  16022. if (bone === undefined) {
  16023. console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
  16024. bone = new Bone();
  16025. }
  16026. this.bones.push(bone);
  16027. this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
  16028. }
  16029. this.init();
  16030. return this;
  16031. }
  16032. toJSON() {
  16033. const data = {
  16034. metadata: {
  16035. version: 4.5,
  16036. type: 'Skeleton',
  16037. generator: 'Skeleton.toJSON'
  16038. },
  16039. bones: [],
  16040. boneInverses: []
  16041. };
  16042. data.uuid = this.uuid;
  16043. const bones = this.bones;
  16044. const boneInverses = this.boneInverses;
  16045. for (let i = 0, l = bones.length; i < l; i++) {
  16046. const bone = bones[i];
  16047. data.bones.push(bone.uuid);
  16048. const boneInverse = boneInverses[i];
  16049. data.boneInverses.push(boneInverse.toArray());
  16050. }
  16051. return data;
  16052. }
  16053. }
  16054. const _instanceLocalMatrix = /*@__PURE__*/new Matrix4();
  16055. const _instanceWorldMatrix = /*@__PURE__*/new Matrix4();
  16056. const _instanceIntersects = [];
  16057. const _mesh = /*@__PURE__*/new Mesh();
  16058. class InstancedMesh extends Mesh {
  16059. constructor(geometry, material, count) {
  16060. super(geometry, material);
  16061. this.instanceMatrix = new BufferAttribute(new Float32Array(count * 16), 16);
  16062. this.instanceColor = null;
  16063. this.count = count;
  16064. this.frustumCulled = false;
  16065. }
  16066. copy(source) {
  16067. super.copy(source);
  16068. this.instanceMatrix.copy(source.instanceMatrix);
  16069. if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone();
  16070. this.count = source.count;
  16071. return this;
  16072. }
  16073. getColorAt(index, color) {
  16074. color.fromArray(this.instanceColor.array, index * 3);
  16075. }
  16076. getMatrixAt(index, matrix) {
  16077. matrix.fromArray(this.instanceMatrix.array, index * 16);
  16078. }
  16079. raycast(raycaster, intersects) {
  16080. const matrixWorld = this.matrixWorld;
  16081. const raycastTimes = this.count;
  16082. _mesh.geometry = this.geometry;
  16083. _mesh.material = this.material;
  16084. if (_mesh.material === undefined) return;
  16085. for (let instanceId = 0; instanceId < raycastTimes; instanceId++) {
  16086. // calculate the world matrix for each instance
  16087. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  16088. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
  16089. _mesh.matrixWorld = _instanceWorldMatrix;
  16090. _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
  16091. for (let i = 0, l = _instanceIntersects.length; i < l; i++) {
  16092. const intersect = _instanceIntersects[i];
  16093. intersect.instanceId = instanceId;
  16094. intersect.object = this;
  16095. intersects.push(intersect);
  16096. }
  16097. _instanceIntersects.length = 0;
  16098. }
  16099. }
  16100. setColorAt(index, color) {
  16101. if (this.instanceColor === null) {
  16102. this.instanceColor = new BufferAttribute(new Float32Array(this.count * 3), 3);
  16103. }
  16104. color.toArray(this.instanceColor.array, index * 3);
  16105. }
  16106. setMatrixAt(index, matrix) {
  16107. matrix.toArray(this.instanceMatrix.array, index * 16);
  16108. }
  16109. updateMorphTargets() {}
  16110. dispose() {
  16111. this.dispatchEvent({
  16112. type: 'dispose'
  16113. });
  16114. }
  16115. }
  16116. InstancedMesh.prototype.isInstancedMesh = true;
  16117. /**
  16118. * parameters = {
  16119. * color: <hex>,
  16120. * opacity: <float>,
  16121. *
  16122. * linewidth: <float>,
  16123. * linecap: "round",
  16124. * linejoin: "round"
  16125. * }
  16126. */
  16127. class LineBasicMaterial extends Material {
  16128. constructor(parameters) {
  16129. super();
  16130. this.type = 'LineBasicMaterial';
  16131. this.color = new Color(0xffffff);
  16132. this.linewidth = 1;
  16133. this.linecap = 'round';
  16134. this.linejoin = 'round';
  16135. this.morphTargets = false;
  16136. this.setValues(parameters);
  16137. }
  16138. copy(source) {
  16139. super.copy(source);
  16140. this.color.copy(source.color);
  16141. this.linewidth = source.linewidth;
  16142. this.linecap = source.linecap;
  16143. this.linejoin = source.linejoin;
  16144. this.morphTargets = source.morphTargets;
  16145. return this;
  16146. }
  16147. }
  16148. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  16149. const _start$1 = /*@__PURE__*/new Vector3();
  16150. const _end$1 = /*@__PURE__*/new Vector3();
  16151. const _inverseMatrix$1 = /*@__PURE__*/new Matrix4();
  16152. const _ray$1 = /*@__PURE__*/new Ray();
  16153. const _sphere$1 = /*@__PURE__*/new Sphere();
  16154. class Line extends Object3D {
  16155. constructor(geometry = new BufferGeometry(), material = new LineBasicMaterial()) {
  16156. super();
  16157. this.type = 'Line';
  16158. this.geometry = geometry;
  16159. this.material = material;
  16160. this.updateMorphTargets();
  16161. }
  16162. copy(source) {
  16163. super.copy(source);
  16164. this.material = source.material;
  16165. this.geometry = source.geometry;
  16166. return this;
  16167. }
  16168. computeLineDistances() {
  16169. const geometry = this.geometry;
  16170. if (geometry.isBufferGeometry) {
  16171. // we assume non-indexed geometry
  16172. if (geometry.index === null) {
  16173. const positionAttribute = geometry.attributes.position;
  16174. const lineDistances = [0];
  16175. for (let i = 1, l = positionAttribute.count; i < l; i++) {
  16176. _start$1.fromBufferAttribute(positionAttribute, i - 1);
  16177. _end$1.fromBufferAttribute(positionAttribute, i);
  16178. lineDistances[i] = lineDistances[i - 1];
  16179. lineDistances[i] += _start$1.distanceTo(_end$1);
  16180. }
  16181. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16182. } else {
  16183. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16184. }
  16185. } else if (geometry.isGeometry) {
  16186. console.error('THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16187. }
  16188. return this;
  16189. }
  16190. raycast(raycaster, intersects) {
  16191. const geometry = this.geometry;
  16192. const matrixWorld = this.matrixWorld;
  16193. const threshold = raycaster.params.Line.threshold;
  16194. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  16195. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16196. _sphere$1.copy(geometry.boundingSphere);
  16197. _sphere$1.applyMatrix4(matrixWorld);
  16198. _sphere$1.radius += threshold;
  16199. if (raycaster.ray.intersectsSphere(_sphere$1) === false) return; //
  16200. _inverseMatrix$1.copy(matrixWorld).invert();
  16201. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  16202. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16203. const localThresholdSq = localThreshold * localThreshold;
  16204. const vStart = new Vector3();
  16205. const vEnd = new Vector3();
  16206. const interSegment = new Vector3();
  16207. const interRay = new Vector3();
  16208. const step = this.isLineSegments ? 2 : 1;
  16209. if (geometry.isBufferGeometry) {
  16210. const index = geometry.index;
  16211. const attributes = geometry.attributes;
  16212. const positionAttribute = attributes.position;
  16213. if (index !== null) {
  16214. const start = Math.max(0, drawRange.start);
  16215. const end = Math.min(index.count, drawRange.start + drawRange.count);
  16216. for (let i = start, l = end - 1; i < l; i += step) {
  16217. const a = index.getX(i);
  16218. const b = index.getX(i + 1);
  16219. vStart.fromBufferAttribute(positionAttribute, a);
  16220. vEnd.fromBufferAttribute(positionAttribute, b);
  16221. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16222. if (distSq > localThresholdSq) continue;
  16223. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16224. const distance = raycaster.ray.origin.distanceTo(interRay);
  16225. if (distance < raycaster.near || distance > raycaster.far) continue;
  16226. intersects.push({
  16227. distance: distance,
  16228. // What do we want? intersection point on the ray or on the segment??
  16229. // point: raycaster.ray.at( distance ),
  16230. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16231. index: i,
  16232. face: null,
  16233. faceIndex: null,
  16234. object: this
  16235. });
  16236. }
  16237. } else {
  16238. const start = Math.max(0, drawRange.start);
  16239. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  16240. for (let i = start, l = end - 1; i < l; i += step) {
  16241. vStart.fromBufferAttribute(positionAttribute, i);
  16242. vEnd.fromBufferAttribute(positionAttribute, i + 1);
  16243. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16244. if (distSq > localThresholdSq) continue;
  16245. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16246. const distance = raycaster.ray.origin.distanceTo(interRay);
  16247. if (distance < raycaster.near || distance > raycaster.far) continue;
  16248. intersects.push({
  16249. distance: distance,
  16250. // What do we want? intersection point on the ray or on the segment??
  16251. // point: raycaster.ray.at( distance ),
  16252. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16253. index: i,
  16254. face: null,
  16255. faceIndex: null,
  16256. object: this
  16257. });
  16258. }
  16259. }
  16260. } else if (geometry.isGeometry) {
  16261. console.error('THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16262. }
  16263. }
  16264. updateMorphTargets() {
  16265. const geometry = this.geometry;
  16266. if (geometry.isBufferGeometry) {
  16267. const morphAttributes = geometry.morphAttributes;
  16268. const keys = Object.keys(morphAttributes);
  16269. if (keys.length > 0) {
  16270. const morphAttribute = morphAttributes[keys[0]];
  16271. if (morphAttribute !== undefined) {
  16272. this.morphTargetInfluences = [];
  16273. this.morphTargetDictionary = {};
  16274. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  16275. const name = morphAttribute[m].name || String(m);
  16276. this.morphTargetInfluences.push(0);
  16277. this.morphTargetDictionary[name] = m;
  16278. }
  16279. }
  16280. }
  16281. } else {
  16282. const morphTargets = geometry.morphTargets;
  16283. if (morphTargets !== undefined && morphTargets.length > 0) {
  16284. console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  16285. }
  16286. }
  16287. }
  16288. }
  16289. Line.prototype.isLine = true;
  16290. const _start = /*@__PURE__*/new Vector3();
  16291. const _end = /*@__PURE__*/new Vector3();
  16292. class LineSegments extends Line {
  16293. constructor(geometry, material) {
  16294. super(geometry, material);
  16295. this.type = 'LineSegments';
  16296. }
  16297. computeLineDistances() {
  16298. const geometry = this.geometry;
  16299. if (geometry.isBufferGeometry) {
  16300. // we assume non-indexed geometry
  16301. if (geometry.index === null) {
  16302. const positionAttribute = geometry.attributes.position;
  16303. const lineDistances = [];
  16304. for (let i = 0, l = positionAttribute.count; i < l; i += 2) {
  16305. _start.fromBufferAttribute(positionAttribute, i);
  16306. _end.fromBufferAttribute(positionAttribute, i + 1);
  16307. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  16308. lineDistances[i + 1] = lineDistances[i] + _start.distanceTo(_end);
  16309. }
  16310. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16311. } else {
  16312. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16313. }
  16314. } else if (geometry.isGeometry) {
  16315. console.error('THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16316. }
  16317. return this;
  16318. }
  16319. }
  16320. LineSegments.prototype.isLineSegments = true;
  16321. class LineLoop extends Line {
  16322. constructor(geometry, material) {
  16323. super(geometry, material);
  16324. this.type = 'LineLoop';
  16325. }
  16326. }
  16327. LineLoop.prototype.isLineLoop = true;
  16328. /**
  16329. * parameters = {
  16330. * color: <hex>,
  16331. * opacity: <float>,
  16332. * map: new THREE.Texture( <Image> ),
  16333. * alphaMap: new THREE.Texture( <Image> ),
  16334. *
  16335. * size: <float>,
  16336. * sizeAttenuation: <bool>
  16337. *
  16338. * morphTargets: <bool>
  16339. * }
  16340. */
  16341. class PointsMaterial extends Material {
  16342. constructor(parameters) {
  16343. super();
  16344. this.type = 'PointsMaterial';
  16345. this.color = new Color(0xffffff);
  16346. this.map = null;
  16347. this.alphaMap = null;
  16348. this.size = 1;
  16349. this.sizeAttenuation = true;
  16350. this.morphTargets = false;
  16351. this.setValues(parameters);
  16352. }
  16353. copy(source) {
  16354. super.copy(source);
  16355. this.color.copy(source.color);
  16356. this.map = source.map;
  16357. this.alphaMap = source.alphaMap;
  16358. this.size = source.size;
  16359. this.sizeAttenuation = source.sizeAttenuation;
  16360. this.morphTargets = source.morphTargets;
  16361. return this;
  16362. }
  16363. }
  16364. PointsMaterial.prototype.isPointsMaterial = true;
  16365. const _inverseMatrix = /*@__PURE__*/new Matrix4();
  16366. const _ray = /*@__PURE__*/new Ray();
  16367. const _sphere = /*@__PURE__*/new Sphere();
  16368. const _position$2 = /*@__PURE__*/new Vector3();
  16369. class Points extends Object3D {
  16370. constructor(geometry = new BufferGeometry(), material = new PointsMaterial()) {
  16371. super();
  16372. this.type = 'Points';
  16373. this.geometry = geometry;
  16374. this.material = material;
  16375. this.updateMorphTargets();
  16376. }
  16377. copy(source) {
  16378. super.copy(source);
  16379. this.material = source.material;
  16380. this.geometry = source.geometry;
  16381. return this;
  16382. }
  16383. raycast(raycaster, intersects) {
  16384. const geometry = this.geometry;
  16385. const matrixWorld = this.matrixWorld;
  16386. const threshold = raycaster.params.Points.threshold;
  16387. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  16388. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16389. _sphere.copy(geometry.boundingSphere);
  16390. _sphere.applyMatrix4(matrixWorld);
  16391. _sphere.radius += threshold;
  16392. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  16393. _inverseMatrix.copy(matrixWorld).invert();
  16394. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix);
  16395. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16396. const localThresholdSq = localThreshold * localThreshold;
  16397. if (geometry.isBufferGeometry) {
  16398. const index = geometry.index;
  16399. const attributes = geometry.attributes;
  16400. const positionAttribute = attributes.position;
  16401. if (index !== null) {
  16402. const start = Math.max(0, drawRange.start);
  16403. const end = Math.min(index.count, drawRange.start + drawRange.count);
  16404. for (let i = start, il = end; i < il; i++) {
  16405. const a = index.getX(i);
  16406. _position$2.fromBufferAttribute(positionAttribute, a);
  16407. testPoint(_position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  16408. }
  16409. } else {
  16410. const start = Math.max(0, drawRange.start);
  16411. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  16412. for (let i = start, l = end; i < l; i++) {
  16413. _position$2.fromBufferAttribute(positionAttribute, i);
  16414. testPoint(_position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  16415. }
  16416. }
  16417. } else {
  16418. console.error('THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16419. }
  16420. }
  16421. updateMorphTargets() {
  16422. const geometry = this.geometry;
  16423. if (geometry.isBufferGeometry) {
  16424. const morphAttributes = geometry.morphAttributes;
  16425. const keys = Object.keys(morphAttributes);
  16426. if (keys.length > 0) {
  16427. const morphAttribute = morphAttributes[keys[0]];
  16428. if (morphAttribute !== undefined) {
  16429. this.morphTargetInfluences = [];
  16430. this.morphTargetDictionary = {};
  16431. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  16432. const name = morphAttribute[m].name || String(m);
  16433. this.morphTargetInfluences.push(0);
  16434. this.morphTargetDictionary[name] = m;
  16435. }
  16436. }
  16437. }
  16438. } else {
  16439. const morphTargets = geometry.morphTargets;
  16440. if (morphTargets !== undefined && morphTargets.length > 0) {
  16441. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  16442. }
  16443. }
  16444. }
  16445. }
  16446. Points.prototype.isPoints = true;
  16447. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  16448. const rayPointDistanceSq = _ray.distanceSqToPoint(point);
  16449. if (rayPointDistanceSq < localThresholdSq) {
  16450. const intersectPoint = new Vector3();
  16451. _ray.closestPointToPoint(point, intersectPoint);
  16452. intersectPoint.applyMatrix4(matrixWorld);
  16453. const distance = raycaster.ray.origin.distanceTo(intersectPoint);
  16454. if (distance < raycaster.near || distance > raycaster.far) return;
  16455. intersects.push({
  16456. distance: distance,
  16457. distanceToRay: Math.sqrt(rayPointDistanceSq),
  16458. point: intersectPoint,
  16459. index: index,
  16460. face: null,
  16461. object: object
  16462. });
  16463. }
  16464. }
  16465. class VideoTexture extends Texture {
  16466. constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  16467. super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16468. this.format = format !== undefined ? format : RGBFormat;
  16469. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  16470. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  16471. this.generateMipmaps = false;
  16472. const scope = this;
  16473. function updateVideo() {
  16474. scope.needsUpdate = true;
  16475. video.requestVideoFrameCallback(updateVideo);
  16476. }
  16477. if ('requestVideoFrameCallback' in video) {
  16478. video.requestVideoFrameCallback(updateVideo);
  16479. }
  16480. }
  16481. clone() {
  16482. return new this.constructor(this.image).copy(this);
  16483. }
  16484. update() {
  16485. const video = this.image;
  16486. const hasVideoFrameCallback = ('requestVideoFrameCallback' in video);
  16487. if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
  16488. this.needsUpdate = true;
  16489. }
  16490. }
  16491. }
  16492. VideoTexture.prototype.isVideoTexture = true;
  16493. class CompressedTexture extends Texture {
  16494. constructor(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  16495. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  16496. this.image = {
  16497. width: width,
  16498. height: height
  16499. };
  16500. this.mipmaps = mipmaps; // no flipping for cube textures
  16501. // (also flipping doesn't work for compressed textures )
  16502. this.flipY = false; // can't generate mipmaps for compressed textures
  16503. // mips must be embedded in DDS files
  16504. this.generateMipmaps = false;
  16505. }
  16506. }
  16507. CompressedTexture.prototype.isCompressedTexture = true;
  16508. class CanvasTexture extends Texture {
  16509. constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  16510. super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16511. this.needsUpdate = true;
  16512. }
  16513. }
  16514. CanvasTexture.prototype.isCanvasTexture = true;
  16515. class DepthTexture extends Texture {
  16516. constructor(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  16517. format = format !== undefined ? format : DepthFormat;
  16518. if (format !== DepthFormat && format !== DepthStencilFormat) {
  16519. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  16520. }
  16521. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  16522. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  16523. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16524. this.image = {
  16525. width: width,
  16526. height: height
  16527. };
  16528. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  16529. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  16530. this.flipY = false;
  16531. this.generateMipmaps = false;
  16532. }
  16533. }
  16534. DepthTexture.prototype.isDepthTexture = true;
  16535. class CircleGeometry extends BufferGeometry {
  16536. constructor(radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2) {
  16537. super();
  16538. this.type = 'CircleGeometry';
  16539. this.parameters = {
  16540. radius: radius,
  16541. segments: segments,
  16542. thetaStart: thetaStart,
  16543. thetaLength: thetaLength
  16544. };
  16545. segments = Math.max(3, segments); // buffers
  16546. const indices = [];
  16547. const vertices = [];
  16548. const normals = [];
  16549. const uvs = []; // helper variables
  16550. const vertex = new Vector3();
  16551. const uv = new Vector2(); // center point
  16552. vertices.push(0, 0, 0);
  16553. normals.push(0, 0, 1);
  16554. uvs.push(0.5, 0.5);
  16555. for (let s = 0, i = 3; s <= segments; s++, i += 3) {
  16556. const segment = thetaStart + s / segments * thetaLength; // vertex
  16557. vertex.x = radius * Math.cos(segment);
  16558. vertex.y = radius * Math.sin(segment);
  16559. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  16560. normals.push(0, 0, 1); // uvs
  16561. uv.x = (vertices[i] / radius + 1) / 2;
  16562. uv.y = (vertices[i + 1] / radius + 1) / 2;
  16563. uvs.push(uv.x, uv.y);
  16564. } // indices
  16565. for (let i = 1; i <= segments; i++) {
  16566. indices.push(i, i + 1, 0);
  16567. } // build geometry
  16568. this.setIndex(indices);
  16569. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  16570. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  16571. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  16572. }
  16573. static fromJSON(data) {
  16574. return new CircleGeometry(data.radius, data.segments, data.thetaStart, data.thetaLength);
  16575. }
  16576. }
  16577. class CylinderGeometry extends BufferGeometry {
  16578. constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  16579. super();
  16580. this.type = 'CylinderGeometry';
  16581. this.parameters = {
  16582. radiusTop: radiusTop,
  16583. radiusBottom: radiusBottom,
  16584. height: height,
  16585. radialSegments: radialSegments,
  16586. heightSegments: heightSegments,
  16587. openEnded: openEnded,
  16588. thetaStart: thetaStart,
  16589. thetaLength: thetaLength
  16590. };
  16591. const scope = this;
  16592. radialSegments = Math.floor(radialSegments);
  16593. heightSegments = Math.floor(heightSegments); // buffers
  16594. const indices = [];
  16595. const vertices = [];
  16596. const normals = [];
  16597. const uvs = []; // helper variables
  16598. let index = 0;
  16599. const indexArray = [];
  16600. const halfHeight = height / 2;
  16601. let groupStart = 0; // generate geometry
  16602. generateTorso();
  16603. if (openEnded === false) {
  16604. if (radiusTop > 0) generateCap(true);
  16605. if (radiusBottom > 0) generateCap(false);
  16606. } // build geometry
  16607. this.setIndex(indices);
  16608. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  16609. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  16610. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  16611. function generateTorso() {
  16612. const normal = new Vector3();
  16613. const vertex = new Vector3();
  16614. let groupCount = 0; // this will be used to calculate the normal
  16615. const slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  16616. for (let y = 0; y <= heightSegments; y++) {
  16617. const indexRow = [];
  16618. const v = y / heightSegments; // calculate the radius of the current row
  16619. const radius = v * (radiusBottom - radiusTop) + radiusTop;
  16620. for (let x = 0; x <= radialSegments; x++) {
  16621. const u = x / radialSegments;
  16622. const theta = u * thetaLength + thetaStart;
  16623. const sinTheta = Math.sin(theta);
  16624. const cosTheta = Math.cos(theta); // vertex
  16625. vertex.x = radius * sinTheta;
  16626. vertex.y = -v * height + halfHeight;
  16627. vertex.z = radius * cosTheta;
  16628. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  16629. normal.set(sinTheta, slope, cosTheta).normalize();
  16630. normals.push(normal.x, normal.y, normal.z); // uv
  16631. uvs.push(u, 1 - v); // save index of vertex in respective row
  16632. indexRow.push(index++);
  16633. } // now save vertices of the row in our index array
  16634. indexArray.push(indexRow);
  16635. } // generate indices
  16636. for (let x = 0; x < radialSegments; x++) {
  16637. for (let y = 0; y < heightSegments; y++) {
  16638. // we use the index array to access the correct indices
  16639. const a = indexArray[y][x];
  16640. const b = indexArray[y + 1][x];
  16641. const c = indexArray[y + 1][x + 1];
  16642. const d = indexArray[y][x + 1]; // faces
  16643. indices.push(a, b, d);
  16644. indices.push(b, c, d); // update group counter
  16645. groupCount += 6;
  16646. }
  16647. } // add a group to the geometry. this will ensure multi material support
  16648. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  16649. groupStart += groupCount;
  16650. }
  16651. function generateCap(top) {
  16652. // save the index of the first center vertex
  16653. const centerIndexStart = index;
  16654. const uv = new Vector2();
  16655. const vertex = new Vector3();
  16656. let groupCount = 0;
  16657. const radius = top === true ? radiusTop : radiusBottom;
  16658. const sign = top === true ? 1 : -1; // first we generate the center vertex data of the cap.
  16659. // because the geometry needs one set of uvs per face,
  16660. // we must generate a center vertex per face/segment
  16661. for (let x = 1; x <= radialSegments; x++) {
  16662. // vertex
  16663. vertices.push(0, halfHeight * sign, 0); // normal
  16664. normals.push(0, sign, 0); // uv
  16665. uvs.push(0.5, 0.5); // increase index
  16666. index++;
  16667. } // save the index of the last center vertex
  16668. const centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  16669. for (let x = 0; x <= radialSegments; x++) {
  16670. const u = x / radialSegments;
  16671. const theta = u * thetaLength + thetaStart;
  16672. const cosTheta = Math.cos(theta);
  16673. const sinTheta = Math.sin(theta); // vertex
  16674. vertex.x = radius * sinTheta;
  16675. vertex.y = halfHeight * sign;
  16676. vertex.z = radius * cosTheta;
  16677. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  16678. normals.push(0, sign, 0); // uv
  16679. uv.x = cosTheta * 0.5 + 0.5;
  16680. uv.y = sinTheta * 0.5 * sign + 0.5;
  16681. uvs.push(uv.x, uv.y); // increase index
  16682. index++;
  16683. } // generate indices
  16684. for (let x = 0; x < radialSegments; x++) {
  16685. const c = centerIndexStart + x;
  16686. const i = centerIndexEnd + x;
  16687. if (top === true) {
  16688. // face top
  16689. indices.push(i, i + 1, c);
  16690. } else {
  16691. // face bottom
  16692. indices.push(i + 1, i, c);
  16693. }
  16694. groupCount += 3;
  16695. } // add a group to the geometry. this will ensure multi material support
  16696. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  16697. groupStart += groupCount;
  16698. }
  16699. }
  16700. static fromJSON(data) {
  16701. return new CylinderGeometry(data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  16702. }
  16703. }
  16704. class ConeGeometry extends CylinderGeometry {
  16705. constructor(radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  16706. super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  16707. this.type = 'ConeGeometry';
  16708. this.parameters = {
  16709. radius: radius,
  16710. height: height,
  16711. radialSegments: radialSegments,
  16712. heightSegments: heightSegments,
  16713. openEnded: openEnded,
  16714. thetaStart: thetaStart,
  16715. thetaLength: thetaLength
  16716. };
  16717. }
  16718. static fromJSON(data) {
  16719. return new ConeGeometry(data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  16720. }
  16721. }
  16722. class PolyhedronGeometry extends BufferGeometry {
  16723. constructor(vertices, indices, radius = 1, detail = 0) {
  16724. super();
  16725. this.type = 'PolyhedronGeometry';
  16726. this.parameters = {
  16727. vertices: vertices,
  16728. indices: indices,
  16729. radius: radius,
  16730. detail: detail
  16731. }; // default buffer data
  16732. const vertexBuffer = [];
  16733. const uvBuffer = []; // the subdivision creates the vertex buffer data
  16734. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  16735. applyRadius(radius); // finally, create the uv data
  16736. generateUVs(); // build non-indexed geometry
  16737. this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  16738. this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  16739. this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  16740. if (detail === 0) {
  16741. this.computeVertexNormals(); // flat normals
  16742. } else {
  16743. this.normalizeNormals(); // smooth normals
  16744. } // helper functions
  16745. function subdivide(detail) {
  16746. const a = new Vector3();
  16747. const b = new Vector3();
  16748. const c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  16749. for (let i = 0; i < indices.length; i += 3) {
  16750. // get the vertices of the face
  16751. getVertexByIndex(indices[i + 0], a);
  16752. getVertexByIndex(indices[i + 1], b);
  16753. getVertexByIndex(indices[i + 2], c); // perform subdivision
  16754. subdivideFace(a, b, c, detail);
  16755. }
  16756. }
  16757. function subdivideFace(a, b, c, detail) {
  16758. const cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision
  16759. const v = []; // construct all of the vertices for this subdivision
  16760. for (let i = 0; i <= cols; i++) {
  16761. v[i] = [];
  16762. const aj = a.clone().lerp(c, i / cols);
  16763. const bj = b.clone().lerp(c, i / cols);
  16764. const rows = cols - i;
  16765. for (let j = 0; j <= rows; j++) {
  16766. if (j === 0 && i === cols) {
  16767. v[i][j] = aj;
  16768. } else {
  16769. v[i][j] = aj.clone().lerp(bj, j / rows);
  16770. }
  16771. }
  16772. } // construct all of the faces
  16773. for (let i = 0; i < cols; i++) {
  16774. for (let j = 0; j < 2 * (cols - i) - 1; j++) {
  16775. const k = Math.floor(j / 2);
  16776. if (j % 2 === 0) {
  16777. pushVertex(v[i][k + 1]);
  16778. pushVertex(v[i + 1][k]);
  16779. pushVertex(v[i][k]);
  16780. } else {
  16781. pushVertex(v[i][k + 1]);
  16782. pushVertex(v[i + 1][k + 1]);
  16783. pushVertex(v[i + 1][k]);
  16784. }
  16785. }
  16786. }
  16787. }
  16788. function applyRadius(radius) {
  16789. const vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  16790. for (let i = 0; i < vertexBuffer.length; i += 3) {
  16791. vertex.x = vertexBuffer[i + 0];
  16792. vertex.y = vertexBuffer[i + 1];
  16793. vertex.z = vertexBuffer[i + 2];
  16794. vertex.normalize().multiplyScalar(radius);
  16795. vertexBuffer[i + 0] = vertex.x;
  16796. vertexBuffer[i + 1] = vertex.y;
  16797. vertexBuffer[i + 2] = vertex.z;
  16798. }
  16799. }
  16800. function generateUVs() {
  16801. const vertex = new Vector3();
  16802. for (let i = 0; i < vertexBuffer.length; i += 3) {
  16803. vertex.x = vertexBuffer[i + 0];
  16804. vertex.y = vertexBuffer[i + 1];
  16805. vertex.z = vertexBuffer[i + 2];
  16806. const u = azimuth(vertex) / 2 / Math.PI + 0.5;
  16807. const v = inclination(vertex) / Math.PI + 0.5;
  16808. uvBuffer.push(u, 1 - v);
  16809. }
  16810. correctUVs();
  16811. correctSeam();
  16812. }
  16813. function correctSeam() {
  16814. // handle case when face straddles the seam, see #3269
  16815. for (let i = 0; i < uvBuffer.length; i += 6) {
  16816. // uv data of a single face
  16817. const x0 = uvBuffer[i + 0];
  16818. const x1 = uvBuffer[i + 2];
  16819. const x2 = uvBuffer[i + 4];
  16820. const max = Math.max(x0, x1, x2);
  16821. const min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  16822. if (max > 0.9 && min < 0.1) {
  16823. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  16824. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  16825. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  16826. }
  16827. }
  16828. }
  16829. function pushVertex(vertex) {
  16830. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  16831. }
  16832. function getVertexByIndex(index, vertex) {
  16833. const stride = index * 3;
  16834. vertex.x = vertices[stride + 0];
  16835. vertex.y = vertices[stride + 1];
  16836. vertex.z = vertices[stride + 2];
  16837. }
  16838. function correctUVs() {
  16839. const a = new Vector3();
  16840. const b = new Vector3();
  16841. const c = new Vector3();
  16842. const centroid = new Vector3();
  16843. const uvA = new Vector2();
  16844. const uvB = new Vector2();
  16845. const uvC = new Vector2();
  16846. for (let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  16847. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  16848. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  16849. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  16850. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  16851. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  16852. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  16853. centroid.copy(a).add(b).add(c).divideScalar(3);
  16854. const azi = azimuth(centroid);
  16855. correctUV(uvA, j + 0, a, azi);
  16856. correctUV(uvB, j + 2, b, azi);
  16857. correctUV(uvC, j + 4, c, azi);
  16858. }
  16859. }
  16860. function correctUV(uv, stride, vector, azimuth) {
  16861. if (azimuth < 0 && uv.x === 1) {
  16862. uvBuffer[stride] = uv.x - 1;
  16863. }
  16864. if (vector.x === 0 && vector.z === 0) {
  16865. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  16866. }
  16867. } // Angle around the Y axis, counter-clockwise when looking from above.
  16868. function azimuth(vector) {
  16869. return Math.atan2(vector.z, -vector.x);
  16870. } // Angle above the XZ plane.
  16871. function inclination(vector) {
  16872. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  16873. }
  16874. }
  16875. static fromJSON(data) {
  16876. return new PolyhedronGeometry(data.vertices, data.indices, data.radius, data.details);
  16877. }
  16878. }
  16879. class DodecahedronGeometry extends PolyhedronGeometry {
  16880. constructor(radius = 1, detail = 0) {
  16881. const t = (1 + Math.sqrt(5)) / 2;
  16882. const r = 1 / t;
  16883. const vertices = [// (±1, ±1, ±1)
  16884. -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/φ, ±φ)
  16885. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  16886. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  16887. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  16888. 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];
  16889. super(vertices, indices, radius, detail);
  16890. this.type = 'DodecahedronGeometry';
  16891. this.parameters = {
  16892. radius: radius,
  16893. detail: detail
  16894. };
  16895. }
  16896. static fromJSON(data) {
  16897. return new DodecahedronGeometry(data.radius, data.detail);
  16898. }
  16899. }
  16900. const _v0 = new Vector3();
  16901. const _v1$1 = new Vector3();
  16902. const _normal = new Vector3();
  16903. const _triangle = new Triangle();
  16904. class EdgesGeometry extends BufferGeometry {
  16905. constructor(geometry, thresholdAngle) {
  16906. super();
  16907. this.type = 'EdgesGeometry';
  16908. this.parameters = {
  16909. thresholdAngle: thresholdAngle
  16910. };
  16911. thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1;
  16912. if (geometry.isGeometry === true) {
  16913. console.error('THREE.EdgesGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16914. return;
  16915. }
  16916. const precisionPoints = 4;
  16917. const precision = Math.pow(10, precisionPoints);
  16918. const thresholdDot = Math.cos(DEG2RAD * thresholdAngle);
  16919. const indexAttr = geometry.getIndex();
  16920. const positionAttr = geometry.getAttribute('position');
  16921. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  16922. const indexArr = [0, 0, 0];
  16923. const vertKeys = ['a', 'b', 'c'];
  16924. const hashes = new Array(3);
  16925. const edgeData = {};
  16926. const vertices = [];
  16927. for (let i = 0; i < indexCount; i += 3) {
  16928. if (indexAttr) {
  16929. indexArr[0] = indexAttr.getX(i);
  16930. indexArr[1] = indexAttr.getX(i + 1);
  16931. indexArr[2] = indexAttr.getX(i + 2);
  16932. } else {
  16933. indexArr[0] = i;
  16934. indexArr[1] = i + 1;
  16935. indexArr[2] = i + 2;
  16936. }
  16937. const {
  16938. a,
  16939. b,
  16940. c
  16941. } = _triangle;
  16942. a.fromBufferAttribute(positionAttr, indexArr[0]);
  16943. b.fromBufferAttribute(positionAttr, indexArr[1]);
  16944. c.fromBufferAttribute(positionAttr, indexArr[2]);
  16945. _triangle.getNormal(_normal); // create hashes for the edge from the vertices
  16946. hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`;
  16947. hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`;
  16948. hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`; // skip degenerate triangles
  16949. if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
  16950. continue;
  16951. } // iterate over every edge
  16952. for (let j = 0; j < 3; j++) {
  16953. // get the first and next vertex making up the edge
  16954. const jNext = (j + 1) % 3;
  16955. const vecHash0 = hashes[j];
  16956. const vecHash1 = hashes[jNext];
  16957. const v0 = _triangle[vertKeys[j]];
  16958. const v1 = _triangle[vertKeys[jNext]];
  16959. const hash = `${vecHash0}_${vecHash1}`;
  16960. const reverseHash = `${vecHash1}_${vecHash0}`;
  16961. if (reverseHash in edgeData && edgeData[reverseHash]) {
  16962. // if we found a sibling edge add it into the vertex array if
  16963. // it meets the angle threshold and delete the edge from the map.
  16964. if (_normal.dot(edgeData[reverseHash].normal) <= thresholdDot) {
  16965. vertices.push(v0.x, v0.y, v0.z);
  16966. vertices.push(v1.x, v1.y, v1.z);
  16967. }
  16968. edgeData[reverseHash] = null;
  16969. } else if (!(hash in edgeData)) {
  16970. // if we've already got an edge here then skip adding a new one
  16971. edgeData[hash] = {
  16972. index0: indexArr[j],
  16973. index1: indexArr[jNext],
  16974. normal: _normal.clone()
  16975. };
  16976. }
  16977. }
  16978. } // iterate over all remaining, unmatched edges and add them to the vertex array
  16979. for (const key in edgeData) {
  16980. if (edgeData[key]) {
  16981. const {
  16982. index0,
  16983. index1
  16984. } = edgeData[key];
  16985. _v0.fromBufferAttribute(positionAttr, index0);
  16986. _v1$1.fromBufferAttribute(positionAttr, index1);
  16987. vertices.push(_v0.x, _v0.y, _v0.z);
  16988. vertices.push(_v1$1.x, _v1$1.y, _v1$1.z);
  16989. }
  16990. }
  16991. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  16992. }
  16993. }
  16994. /**
  16995. * Extensible curve object.
  16996. *
  16997. * Some common of curve methods:
  16998. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  16999. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  17000. * .getPoints(), .getSpacedPoints()
  17001. * .getLength()
  17002. * .updateArcLengths()
  17003. *
  17004. * This following curves inherit from THREE.Curve:
  17005. *
  17006. * -- 2D curves --
  17007. * THREE.ArcCurve
  17008. * THREE.CubicBezierCurve
  17009. * THREE.EllipseCurve
  17010. * THREE.LineCurve
  17011. * THREE.QuadraticBezierCurve
  17012. * THREE.SplineCurve
  17013. *
  17014. * -- 3D curves --
  17015. * THREE.CatmullRomCurve3
  17016. * THREE.CubicBezierCurve3
  17017. * THREE.LineCurve3
  17018. * THREE.QuadraticBezierCurve3
  17019. *
  17020. * A series of curves can be represented as a THREE.CurvePath.
  17021. *
  17022. **/
  17023. class Curve {
  17024. constructor() {
  17025. this.type = 'Curve';
  17026. this.arcLengthDivisions = 200;
  17027. } // Virtual base class method to overwrite and implement in subclasses
  17028. // - t [0 .. 1]
  17029. getPoint()
  17030. /* t, optionalTarget */
  17031. {
  17032. console.warn('THREE.Curve: .getPoint() not implemented.');
  17033. return null;
  17034. } // Get point at relative position in curve according to arc length
  17035. // - u [0 .. 1]
  17036. getPointAt(u, optionalTarget) {
  17037. const t = this.getUtoTmapping(u);
  17038. return this.getPoint(t, optionalTarget);
  17039. } // Get sequence of points using getPoint( t )
  17040. getPoints(divisions = 5) {
  17041. const points = [];
  17042. for (let d = 0; d <= divisions; d++) {
  17043. points.push(this.getPoint(d / divisions));
  17044. }
  17045. return points;
  17046. } // Get sequence of points using getPointAt( u )
  17047. getSpacedPoints(divisions = 5) {
  17048. const points = [];
  17049. for (let d = 0; d <= divisions; d++) {
  17050. points.push(this.getPointAt(d / divisions));
  17051. }
  17052. return points;
  17053. } // Get total curve arc length
  17054. getLength() {
  17055. const lengths = this.getLengths();
  17056. return lengths[lengths.length - 1];
  17057. } // Get list of cumulative segment lengths
  17058. getLengths(divisions = this.arcLengthDivisions) {
  17059. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  17060. return this.cacheArcLengths;
  17061. }
  17062. this.needsUpdate = false;
  17063. const cache = [];
  17064. let current,
  17065. last = this.getPoint(0);
  17066. let sum = 0;
  17067. cache.push(0);
  17068. for (let p = 1; p <= divisions; p++) {
  17069. current = this.getPoint(p / divisions);
  17070. sum += current.distanceTo(last);
  17071. cache.push(sum);
  17072. last = current;
  17073. }
  17074. this.cacheArcLengths = cache;
  17075. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  17076. }
  17077. updateArcLengths() {
  17078. this.needsUpdate = true;
  17079. this.getLengths();
  17080. } // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  17081. getUtoTmapping(u, distance) {
  17082. const arcLengths = this.getLengths();
  17083. let i = 0;
  17084. const il = arcLengths.length;
  17085. let targetArcLength; // The targeted u distance value to get
  17086. if (distance) {
  17087. targetArcLength = distance;
  17088. } else {
  17089. targetArcLength = u * arcLengths[il - 1];
  17090. } // binary search for the index with largest value smaller than target u distance
  17091. let low = 0,
  17092. high = il - 1,
  17093. comparison;
  17094. while (low <= high) {
  17095. 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
  17096. comparison = arcLengths[i] - targetArcLength;
  17097. if (comparison < 0) {
  17098. low = i + 1;
  17099. } else if (comparison > 0) {
  17100. high = i - 1;
  17101. } else {
  17102. high = i;
  17103. break; // DONE
  17104. }
  17105. }
  17106. i = high;
  17107. if (arcLengths[i] === targetArcLength) {
  17108. return i / (il - 1);
  17109. } // we could get finer grain at lengths, or use simple interpolation between two points
  17110. const lengthBefore = arcLengths[i];
  17111. const lengthAfter = arcLengths[i + 1];
  17112. const segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  17113. const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  17114. const t = (i + segmentFraction) / (il - 1);
  17115. return t;
  17116. } // Returns a unit vector tangent at t
  17117. // In case any sub curve does not implement its tangent derivation,
  17118. // 2 points a small delta apart will be used to find its gradient
  17119. // which seems to give a reasonable approximation
  17120. getTangent(t, optionalTarget) {
  17121. const delta = 0.0001;
  17122. let t1 = t - delta;
  17123. let t2 = t + delta; // Capping in case of danger
  17124. if (t1 < 0) t1 = 0;
  17125. if (t2 > 1) t2 = 1;
  17126. const pt1 = this.getPoint(t1);
  17127. const pt2 = this.getPoint(t2);
  17128. const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
  17129. tangent.copy(pt2).sub(pt1).normalize();
  17130. return tangent;
  17131. }
  17132. getTangentAt(u, optionalTarget) {
  17133. const t = this.getUtoTmapping(u);
  17134. return this.getTangent(t, optionalTarget);
  17135. }
  17136. computeFrenetFrames(segments, closed) {
  17137. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  17138. const normal = new Vector3();
  17139. const tangents = [];
  17140. const normals = [];
  17141. const binormals = [];
  17142. const vec = new Vector3();
  17143. const mat = new Matrix4(); // compute the tangent vectors for each segment on the curve
  17144. for (let i = 0; i <= segments; i++) {
  17145. const u = i / segments;
  17146. tangents[i] = this.getTangentAt(u, new Vector3());
  17147. tangents[i].normalize();
  17148. } // select an initial normal vector perpendicular to the first tangent vector,
  17149. // and in the direction of the minimum tangent xyz component
  17150. normals[0] = new Vector3();
  17151. binormals[0] = new Vector3();
  17152. let min = Number.MAX_VALUE;
  17153. const tx = Math.abs(tangents[0].x);
  17154. const ty = Math.abs(tangents[0].y);
  17155. const tz = Math.abs(tangents[0].z);
  17156. if (tx <= min) {
  17157. min = tx;
  17158. normal.set(1, 0, 0);
  17159. }
  17160. if (ty <= min) {
  17161. min = ty;
  17162. normal.set(0, 1, 0);
  17163. }
  17164. if (tz <= min) {
  17165. normal.set(0, 0, 1);
  17166. }
  17167. vec.crossVectors(tangents[0], normal).normalize();
  17168. normals[0].crossVectors(tangents[0], vec);
  17169. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  17170. for (let i = 1; i <= segments; i++) {
  17171. normals[i] = normals[i - 1].clone();
  17172. binormals[i] = binormals[i - 1].clone();
  17173. vec.crossVectors(tangents[i - 1], tangents[i]);
  17174. if (vec.length() > Number.EPSILON) {
  17175. vec.normalize();
  17176. const theta = Math.acos(clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  17177. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  17178. }
  17179. binormals[i].crossVectors(tangents[i], normals[i]);
  17180. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  17181. if (closed === true) {
  17182. let theta = Math.acos(clamp(normals[0].dot(normals[segments]), -1, 1));
  17183. theta /= segments;
  17184. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  17185. theta = -theta;
  17186. }
  17187. for (let i = 1; i <= segments; i++) {
  17188. // twist a little...
  17189. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  17190. binormals[i].crossVectors(tangents[i], normals[i]);
  17191. }
  17192. }
  17193. return {
  17194. tangents: tangents,
  17195. normals: normals,
  17196. binormals: binormals
  17197. };
  17198. }
  17199. clone() {
  17200. return new this.constructor().copy(this);
  17201. }
  17202. copy(source) {
  17203. this.arcLengthDivisions = source.arcLengthDivisions;
  17204. return this;
  17205. }
  17206. toJSON() {
  17207. const data = {
  17208. metadata: {
  17209. version: 4.5,
  17210. type: 'Curve',
  17211. generator: 'Curve.toJSON'
  17212. }
  17213. };
  17214. data.arcLengthDivisions = this.arcLengthDivisions;
  17215. data.type = this.type;
  17216. return data;
  17217. }
  17218. fromJSON(json) {
  17219. this.arcLengthDivisions = json.arcLengthDivisions;
  17220. return this;
  17221. }
  17222. }
  17223. class EllipseCurve extends Curve {
  17224. constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) {
  17225. super();
  17226. this.type = 'EllipseCurve';
  17227. this.aX = aX;
  17228. this.aY = aY;
  17229. this.xRadius = xRadius;
  17230. this.yRadius = yRadius;
  17231. this.aStartAngle = aStartAngle;
  17232. this.aEndAngle = aEndAngle;
  17233. this.aClockwise = aClockwise;
  17234. this.aRotation = aRotation;
  17235. }
  17236. getPoint(t, optionalTarget) {
  17237. const point = optionalTarget || new Vector2();
  17238. const twoPi = Math.PI * 2;
  17239. let deltaAngle = this.aEndAngle - this.aStartAngle;
  17240. const samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  17241. while (deltaAngle < 0) deltaAngle += twoPi;
  17242. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  17243. if (deltaAngle < Number.EPSILON) {
  17244. if (samePoints) {
  17245. deltaAngle = 0;
  17246. } else {
  17247. deltaAngle = twoPi;
  17248. }
  17249. }
  17250. if (this.aClockwise === true && !samePoints) {
  17251. if (deltaAngle === twoPi) {
  17252. deltaAngle = -twoPi;
  17253. } else {
  17254. deltaAngle = deltaAngle - twoPi;
  17255. }
  17256. }
  17257. const angle = this.aStartAngle + t * deltaAngle;
  17258. let x = this.aX + this.xRadius * Math.cos(angle);
  17259. let y = this.aY + this.yRadius * Math.sin(angle);
  17260. if (this.aRotation !== 0) {
  17261. const cos = Math.cos(this.aRotation);
  17262. const sin = Math.sin(this.aRotation);
  17263. const tx = x - this.aX;
  17264. const ty = y - this.aY; // Rotate the point about the center of the ellipse.
  17265. x = tx * cos - ty * sin + this.aX;
  17266. y = tx * sin + ty * cos + this.aY;
  17267. }
  17268. return point.set(x, y);
  17269. }
  17270. copy(source) {
  17271. super.copy(source);
  17272. this.aX = source.aX;
  17273. this.aY = source.aY;
  17274. this.xRadius = source.xRadius;
  17275. this.yRadius = source.yRadius;
  17276. this.aStartAngle = source.aStartAngle;
  17277. this.aEndAngle = source.aEndAngle;
  17278. this.aClockwise = source.aClockwise;
  17279. this.aRotation = source.aRotation;
  17280. return this;
  17281. }
  17282. toJSON() {
  17283. const data = super.toJSON();
  17284. data.aX = this.aX;
  17285. data.aY = this.aY;
  17286. data.xRadius = this.xRadius;
  17287. data.yRadius = this.yRadius;
  17288. data.aStartAngle = this.aStartAngle;
  17289. data.aEndAngle = this.aEndAngle;
  17290. data.aClockwise = this.aClockwise;
  17291. data.aRotation = this.aRotation;
  17292. return data;
  17293. }
  17294. fromJSON(json) {
  17295. super.fromJSON(json);
  17296. this.aX = json.aX;
  17297. this.aY = json.aY;
  17298. this.xRadius = json.xRadius;
  17299. this.yRadius = json.yRadius;
  17300. this.aStartAngle = json.aStartAngle;
  17301. this.aEndAngle = json.aEndAngle;
  17302. this.aClockwise = json.aClockwise;
  17303. this.aRotation = json.aRotation;
  17304. return this;
  17305. }
  17306. }
  17307. EllipseCurve.prototype.isEllipseCurve = true;
  17308. class ArcCurve extends EllipseCurve {
  17309. constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  17310. super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  17311. this.type = 'ArcCurve';
  17312. }
  17313. }
  17314. ArcCurve.prototype.isArcCurve = true;
  17315. /**
  17316. * Centripetal CatmullRom Curve - which is useful for avoiding
  17317. * cusps and self-intersections in non-uniform catmull rom curves.
  17318. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  17319. *
  17320. * curve.type accepts centripetal(default), chordal and catmullrom
  17321. * curve.tension is used for catmullrom which defaults to 0.5
  17322. */
  17323. /*
  17324. Based on an optimized c++ solution in
  17325. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  17326. - http://ideone.com/NoEbVM
  17327. This CubicPoly class could be used for reusing some variables and calculations,
  17328. but for three.js curve use, it could be possible inlined and flatten into a single function call
  17329. which can be placed in CurveUtils.
  17330. */
  17331. function CubicPoly() {
  17332. let c0 = 0,
  17333. c1 = 0,
  17334. c2 = 0,
  17335. c3 = 0;
  17336. /*
  17337. * Compute coefficients for a cubic polynomial
  17338. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  17339. * such that
  17340. * p(0) = x0, p(1) = x1
  17341. * and
  17342. * p'(0) = t0, p'(1) = t1.
  17343. */
  17344. function init(x0, x1, t0, t1) {
  17345. c0 = x0;
  17346. c1 = t0;
  17347. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  17348. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  17349. }
  17350. return {
  17351. initCatmullRom: function (x0, x1, x2, x3, tension) {
  17352. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  17353. },
  17354. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  17355. // compute tangents when parameterized in [t1,t2]
  17356. let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  17357. let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  17358. t1 *= dt1;
  17359. t2 *= dt1;
  17360. init(x1, x2, t1, t2);
  17361. },
  17362. calc: function (t) {
  17363. const t2 = t * t;
  17364. const t3 = t2 * t;
  17365. return c0 + c1 * t + c2 * t2 + c3 * t3;
  17366. }
  17367. };
  17368. } //
  17369. const tmp = new Vector3();
  17370. const px = new CubicPoly(),
  17371. py = new CubicPoly(),
  17372. pz = new CubicPoly();
  17373. class CatmullRomCurve3 extends Curve {
  17374. constructor(points = [], closed = false, curveType = 'centripetal', tension = 0.5) {
  17375. super();
  17376. this.type = 'CatmullRomCurve3';
  17377. this.points = points;
  17378. this.closed = closed;
  17379. this.curveType = curveType;
  17380. this.tension = tension;
  17381. }
  17382. getPoint(t, optionalTarget = new Vector3()) {
  17383. const point = optionalTarget;
  17384. const points = this.points;
  17385. const l = points.length;
  17386. const p = (l - (this.closed ? 0 : 1)) * t;
  17387. let intPoint = Math.floor(p);
  17388. let weight = p - intPoint;
  17389. if (this.closed) {
  17390. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  17391. } else if (weight === 0 && intPoint === l - 1) {
  17392. intPoint = l - 2;
  17393. weight = 1;
  17394. }
  17395. let p0, p3; // 4 points (p1 & p2 defined below)
  17396. if (this.closed || intPoint > 0) {
  17397. p0 = points[(intPoint - 1) % l];
  17398. } else {
  17399. // extrapolate first point
  17400. tmp.subVectors(points[0], points[1]).add(points[0]);
  17401. p0 = tmp;
  17402. }
  17403. const p1 = points[intPoint % l];
  17404. const p2 = points[(intPoint + 1) % l];
  17405. if (this.closed || intPoint + 2 < l) {
  17406. p3 = points[(intPoint + 2) % l];
  17407. } else {
  17408. // extrapolate last point
  17409. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  17410. p3 = tmp;
  17411. }
  17412. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  17413. // init Centripetal / Chordal Catmull-Rom
  17414. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  17415. let dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  17416. let dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  17417. let dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  17418. if (dt1 < 1e-4) dt1 = 1.0;
  17419. if (dt0 < 1e-4) dt0 = dt1;
  17420. if (dt2 < 1e-4) dt2 = dt1;
  17421. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  17422. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  17423. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  17424. } else if (this.curveType === 'catmullrom') {
  17425. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  17426. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  17427. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  17428. }
  17429. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  17430. return point;
  17431. }
  17432. copy(source) {
  17433. super.copy(source);
  17434. this.points = [];
  17435. for (let i = 0, l = source.points.length; i < l; i++) {
  17436. const point = source.points[i];
  17437. this.points.push(point.clone());
  17438. }
  17439. this.closed = source.closed;
  17440. this.curveType = source.curveType;
  17441. this.tension = source.tension;
  17442. return this;
  17443. }
  17444. toJSON() {
  17445. const data = super.toJSON();
  17446. data.points = [];
  17447. for (let i = 0, l = this.points.length; i < l; i++) {
  17448. const point = this.points[i];
  17449. data.points.push(point.toArray());
  17450. }
  17451. data.closed = this.closed;
  17452. data.curveType = this.curveType;
  17453. data.tension = this.tension;
  17454. return data;
  17455. }
  17456. fromJSON(json) {
  17457. super.fromJSON(json);
  17458. this.points = [];
  17459. for (let i = 0, l = json.points.length; i < l; i++) {
  17460. const point = json.points[i];
  17461. this.points.push(new Vector3().fromArray(point));
  17462. }
  17463. this.closed = json.closed;
  17464. this.curveType = json.curveType;
  17465. this.tension = json.tension;
  17466. return this;
  17467. }
  17468. }
  17469. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  17470. /**
  17471. * Bezier Curves formulas obtained from
  17472. * http://en.wikipedia.org/wiki/Bézier_curve
  17473. */
  17474. function CatmullRom(t, p0, p1, p2, p3) {
  17475. const v0 = (p2 - p0) * 0.5;
  17476. const v1 = (p3 - p1) * 0.5;
  17477. const t2 = t * t;
  17478. const t3 = t * t2;
  17479. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  17480. } //
  17481. function QuadraticBezierP0(t, p) {
  17482. const k = 1 - t;
  17483. return k * k * p;
  17484. }
  17485. function QuadraticBezierP1(t, p) {
  17486. return 2 * (1 - t) * t * p;
  17487. }
  17488. function QuadraticBezierP2(t, p) {
  17489. return t * t * p;
  17490. }
  17491. function QuadraticBezier(t, p0, p1, p2) {
  17492. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  17493. } //
  17494. function CubicBezierP0(t, p) {
  17495. const k = 1 - t;
  17496. return k * k * k * p;
  17497. }
  17498. function CubicBezierP1(t, p) {
  17499. const k = 1 - t;
  17500. return 3 * k * k * t * p;
  17501. }
  17502. function CubicBezierP2(t, p) {
  17503. return 3 * (1 - t) * t * t * p;
  17504. }
  17505. function CubicBezierP3(t, p) {
  17506. return t * t * t * p;
  17507. }
  17508. function CubicBezier(t, p0, p1, p2, p3) {
  17509. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  17510. }
  17511. class CubicBezierCurve extends Curve {
  17512. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) {
  17513. super();
  17514. this.type = 'CubicBezierCurve';
  17515. this.v0 = v0;
  17516. this.v1 = v1;
  17517. this.v2 = v2;
  17518. this.v3 = v3;
  17519. }
  17520. getPoint(t, optionalTarget = new Vector2()) {
  17521. const point = optionalTarget;
  17522. const v0 = this.v0,
  17523. v1 = this.v1,
  17524. v2 = this.v2,
  17525. v3 = this.v3;
  17526. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  17527. return point;
  17528. }
  17529. copy(source) {
  17530. super.copy(source);
  17531. this.v0.copy(source.v0);
  17532. this.v1.copy(source.v1);
  17533. this.v2.copy(source.v2);
  17534. this.v3.copy(source.v3);
  17535. return this;
  17536. }
  17537. toJSON() {
  17538. const data = super.toJSON();
  17539. data.v0 = this.v0.toArray();
  17540. data.v1 = this.v1.toArray();
  17541. data.v2 = this.v2.toArray();
  17542. data.v3 = this.v3.toArray();
  17543. return data;
  17544. }
  17545. fromJSON(json) {
  17546. super.fromJSON(json);
  17547. this.v0.fromArray(json.v0);
  17548. this.v1.fromArray(json.v1);
  17549. this.v2.fromArray(json.v2);
  17550. this.v3.fromArray(json.v3);
  17551. return this;
  17552. }
  17553. }
  17554. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  17555. class CubicBezierCurve3 extends Curve {
  17556. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) {
  17557. super();
  17558. this.type = 'CubicBezierCurve3';
  17559. this.v0 = v0;
  17560. this.v1 = v1;
  17561. this.v2 = v2;
  17562. this.v3 = v3;
  17563. }
  17564. getPoint(t, optionalTarget = new Vector3()) {
  17565. const point = optionalTarget;
  17566. const v0 = this.v0,
  17567. v1 = this.v1,
  17568. v2 = this.v2,
  17569. v3 = this.v3;
  17570. 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));
  17571. return point;
  17572. }
  17573. copy(source) {
  17574. super.copy(source);
  17575. this.v0.copy(source.v0);
  17576. this.v1.copy(source.v1);
  17577. this.v2.copy(source.v2);
  17578. this.v3.copy(source.v3);
  17579. return this;
  17580. }
  17581. toJSON() {
  17582. const data = super.toJSON();
  17583. data.v0 = this.v0.toArray();
  17584. data.v1 = this.v1.toArray();
  17585. data.v2 = this.v2.toArray();
  17586. data.v3 = this.v3.toArray();
  17587. return data;
  17588. }
  17589. fromJSON(json) {
  17590. super.fromJSON(json);
  17591. this.v0.fromArray(json.v0);
  17592. this.v1.fromArray(json.v1);
  17593. this.v2.fromArray(json.v2);
  17594. this.v3.fromArray(json.v3);
  17595. return this;
  17596. }
  17597. }
  17598. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  17599. class LineCurve extends Curve {
  17600. constructor(v1 = new Vector2(), v2 = new Vector2()) {
  17601. super();
  17602. this.type = 'LineCurve';
  17603. this.v1 = v1;
  17604. this.v2 = v2;
  17605. }
  17606. getPoint(t, optionalTarget = new Vector2()) {
  17607. const point = optionalTarget;
  17608. if (t === 1) {
  17609. point.copy(this.v2);
  17610. } else {
  17611. point.copy(this.v2).sub(this.v1);
  17612. point.multiplyScalar(t).add(this.v1);
  17613. }
  17614. return point;
  17615. } // Line curve is linear, so we can overwrite default getPointAt
  17616. getPointAt(u, optionalTarget) {
  17617. return this.getPoint(u, optionalTarget);
  17618. }
  17619. getTangent(t, optionalTarget) {
  17620. const tangent = optionalTarget || new Vector2();
  17621. tangent.copy(this.v2).sub(this.v1).normalize();
  17622. return tangent;
  17623. }
  17624. copy(source) {
  17625. super.copy(source);
  17626. this.v1.copy(source.v1);
  17627. this.v2.copy(source.v2);
  17628. return this;
  17629. }
  17630. toJSON() {
  17631. const data = super.toJSON();
  17632. data.v1 = this.v1.toArray();
  17633. data.v2 = this.v2.toArray();
  17634. return data;
  17635. }
  17636. fromJSON(json) {
  17637. super.fromJSON(json);
  17638. this.v1.fromArray(json.v1);
  17639. this.v2.fromArray(json.v2);
  17640. return this;
  17641. }
  17642. }
  17643. LineCurve.prototype.isLineCurve = true;
  17644. class LineCurve3 extends Curve {
  17645. constructor(v1 = new Vector3(), v2 = new Vector3()) {
  17646. super();
  17647. this.type = 'LineCurve3';
  17648. this.isLineCurve3 = true;
  17649. this.v1 = v1;
  17650. this.v2 = v2;
  17651. }
  17652. getPoint(t, optionalTarget = new Vector3()) {
  17653. const point = optionalTarget;
  17654. if (t === 1) {
  17655. point.copy(this.v2);
  17656. } else {
  17657. point.copy(this.v2).sub(this.v1);
  17658. point.multiplyScalar(t).add(this.v1);
  17659. }
  17660. return point;
  17661. } // Line curve is linear, so we can overwrite default getPointAt
  17662. getPointAt(u, optionalTarget) {
  17663. return this.getPoint(u, optionalTarget);
  17664. }
  17665. copy(source) {
  17666. super.copy(source);
  17667. this.v1.copy(source.v1);
  17668. this.v2.copy(source.v2);
  17669. return this;
  17670. }
  17671. toJSON() {
  17672. const data = super.toJSON();
  17673. data.v1 = this.v1.toArray();
  17674. data.v2 = this.v2.toArray();
  17675. return data;
  17676. }
  17677. fromJSON(json) {
  17678. super.fromJSON(json);
  17679. this.v1.fromArray(json.v1);
  17680. this.v2.fromArray(json.v2);
  17681. return this;
  17682. }
  17683. }
  17684. class QuadraticBezierCurve extends Curve {
  17685. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) {
  17686. super();
  17687. this.type = 'QuadraticBezierCurve';
  17688. this.v0 = v0;
  17689. this.v1 = v1;
  17690. this.v2 = v2;
  17691. }
  17692. getPoint(t, optionalTarget = new Vector2()) {
  17693. const point = optionalTarget;
  17694. const v0 = this.v0,
  17695. v1 = this.v1,
  17696. v2 = this.v2;
  17697. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  17698. return point;
  17699. }
  17700. copy(source) {
  17701. super.copy(source);
  17702. this.v0.copy(source.v0);
  17703. this.v1.copy(source.v1);
  17704. this.v2.copy(source.v2);
  17705. return this;
  17706. }
  17707. toJSON() {
  17708. const data = super.toJSON();
  17709. data.v0 = this.v0.toArray();
  17710. data.v1 = this.v1.toArray();
  17711. data.v2 = this.v2.toArray();
  17712. return data;
  17713. }
  17714. fromJSON(json) {
  17715. super.fromJSON(json);
  17716. this.v0.fromArray(json.v0);
  17717. this.v1.fromArray(json.v1);
  17718. this.v2.fromArray(json.v2);
  17719. return this;
  17720. }
  17721. }
  17722. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  17723. class QuadraticBezierCurve3 extends Curve {
  17724. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) {
  17725. super();
  17726. this.type = 'QuadraticBezierCurve3';
  17727. this.v0 = v0;
  17728. this.v1 = v1;
  17729. this.v2 = v2;
  17730. }
  17731. getPoint(t, optionalTarget = new Vector3()) {
  17732. const point = optionalTarget;
  17733. const v0 = this.v0,
  17734. v1 = this.v1,
  17735. v2 = this.v2;
  17736. 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));
  17737. return point;
  17738. }
  17739. copy(source) {
  17740. super.copy(source);
  17741. this.v0.copy(source.v0);
  17742. this.v1.copy(source.v1);
  17743. this.v2.copy(source.v2);
  17744. return this;
  17745. }
  17746. toJSON() {
  17747. const data = super.toJSON();
  17748. data.v0 = this.v0.toArray();
  17749. data.v1 = this.v1.toArray();
  17750. data.v2 = this.v2.toArray();
  17751. return data;
  17752. }
  17753. fromJSON(json) {
  17754. super.fromJSON(json);
  17755. this.v0.fromArray(json.v0);
  17756. this.v1.fromArray(json.v1);
  17757. this.v2.fromArray(json.v2);
  17758. return this;
  17759. }
  17760. }
  17761. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  17762. class SplineCurve extends Curve {
  17763. constructor(points = []) {
  17764. super();
  17765. this.type = 'SplineCurve';
  17766. this.points = points;
  17767. }
  17768. getPoint(t, optionalTarget = new Vector2()) {
  17769. const point = optionalTarget;
  17770. const points = this.points;
  17771. const p = (points.length - 1) * t;
  17772. const intPoint = Math.floor(p);
  17773. const weight = p - intPoint;
  17774. const p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  17775. const p1 = points[intPoint];
  17776. const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  17777. const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  17778. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  17779. return point;
  17780. }
  17781. copy(source) {
  17782. super.copy(source);
  17783. this.points = [];
  17784. for (let i = 0, l = source.points.length; i < l; i++) {
  17785. const point = source.points[i];
  17786. this.points.push(point.clone());
  17787. }
  17788. return this;
  17789. }
  17790. toJSON() {
  17791. const data = super.toJSON();
  17792. data.points = [];
  17793. for (let i = 0, l = this.points.length; i < l; i++) {
  17794. const point = this.points[i];
  17795. data.points.push(point.toArray());
  17796. }
  17797. return data;
  17798. }
  17799. fromJSON(json) {
  17800. super.fromJSON(json);
  17801. this.points = [];
  17802. for (let i = 0, l = json.points.length; i < l; i++) {
  17803. const point = json.points[i];
  17804. this.points.push(new Vector2().fromArray(point));
  17805. }
  17806. return this;
  17807. }
  17808. }
  17809. SplineCurve.prototype.isSplineCurve = true;
  17810. var Curves = /*#__PURE__*/Object.freeze({
  17811. __proto__: null,
  17812. ArcCurve: ArcCurve,
  17813. CatmullRomCurve3: CatmullRomCurve3,
  17814. CubicBezierCurve: CubicBezierCurve,
  17815. CubicBezierCurve3: CubicBezierCurve3,
  17816. EllipseCurve: EllipseCurve,
  17817. LineCurve: LineCurve,
  17818. LineCurve3: LineCurve3,
  17819. QuadraticBezierCurve: QuadraticBezierCurve,
  17820. QuadraticBezierCurve3: QuadraticBezierCurve3,
  17821. SplineCurve: SplineCurve
  17822. });
  17823. /**
  17824. * Port from https://github.com/mapbox/earcut (v2.2.2)
  17825. */
  17826. const Earcut = {
  17827. triangulate: function (data, holeIndices, dim = 2) {
  17828. const hasHoles = holeIndices && holeIndices.length;
  17829. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  17830. let outerNode = linkedList(data, 0, outerLen, dim, true);
  17831. const triangles = [];
  17832. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  17833. let minX, minY, maxX, maxY, x, y, invSize;
  17834. 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
  17835. if (data.length > 80 * dim) {
  17836. minX = maxX = data[0];
  17837. minY = maxY = data[1];
  17838. for (let i = dim; i < outerLen; i += dim) {
  17839. x = data[i];
  17840. y = data[i + 1];
  17841. if (x < minX) minX = x;
  17842. if (y < minY) minY = y;
  17843. if (x > maxX) maxX = x;
  17844. if (y > maxY) maxY = y;
  17845. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  17846. invSize = Math.max(maxX - minX, maxY - minY);
  17847. invSize = invSize !== 0 ? 1 / invSize : 0;
  17848. }
  17849. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  17850. return triangles;
  17851. }
  17852. }; // create a circular doubly linked list from polygon points in the specified winding order
  17853. function linkedList(data, start, end, dim, clockwise) {
  17854. let i, last;
  17855. if (clockwise === signedArea(data, start, end, dim) > 0) {
  17856. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  17857. } else {
  17858. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  17859. }
  17860. if (last && equals(last, last.next)) {
  17861. removeNode(last);
  17862. last = last.next;
  17863. }
  17864. return last;
  17865. } // eliminate colinear or duplicate points
  17866. function filterPoints(start, end) {
  17867. if (!start) return start;
  17868. if (!end) end = start;
  17869. let p = start,
  17870. again;
  17871. do {
  17872. again = false;
  17873. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  17874. removeNode(p);
  17875. p = end = p.prev;
  17876. if (p === p.next) break;
  17877. again = true;
  17878. } else {
  17879. p = p.next;
  17880. }
  17881. } while (again || p !== end);
  17882. return end;
  17883. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  17884. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  17885. if (!ear) return; // interlink polygon nodes in z-order
  17886. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  17887. let stop = ear,
  17888. prev,
  17889. next; // iterate through ears, slicing them one by one
  17890. while (ear.prev !== ear.next) {
  17891. prev = ear.prev;
  17892. next = ear.next;
  17893. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  17894. // cut off the triangle
  17895. triangles.push(prev.i / dim);
  17896. triangles.push(ear.i / dim);
  17897. triangles.push(next.i / dim);
  17898. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  17899. ear = next.next;
  17900. stop = next.next;
  17901. continue;
  17902. }
  17903. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  17904. if (ear === stop) {
  17905. // try filtering points and slicing again
  17906. if (!pass) {
  17907. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  17908. } else if (pass === 1) {
  17909. ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
  17910. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  17911. } else if (pass === 2) {
  17912. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  17913. }
  17914. break;
  17915. }
  17916. }
  17917. } // check whether a polygon node forms a valid ear with adjacent nodes
  17918. function isEar(ear) {
  17919. const a = ear.prev,
  17920. b = ear,
  17921. c = ear.next;
  17922. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  17923. // now make sure we don't have other points inside the potential ear
  17924. let p = ear.next.next;
  17925. while (p !== ear.prev) {
  17926. 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;
  17927. p = p.next;
  17928. }
  17929. return true;
  17930. }
  17931. function isEarHashed(ear, minX, minY, invSize) {
  17932. const a = ear.prev,
  17933. b = ear,
  17934. c = ear.next;
  17935. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  17936. // triangle bbox; min & max are calculated like this for speed
  17937. const minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  17938. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  17939. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  17940. 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;
  17941. const minZ = zOrder(minTX, minTY, minX, minY, invSize),
  17942. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  17943. let p = ear.prevZ,
  17944. n = ear.nextZ; // look for points inside the triangle in both directions
  17945. while (p && p.z >= minZ && n && n.z <= maxZ) {
  17946. 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;
  17947. p = p.prevZ;
  17948. 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;
  17949. n = n.nextZ;
  17950. } // look for remaining points in decreasing z-order
  17951. while (p && p.z >= minZ) {
  17952. 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;
  17953. p = p.prevZ;
  17954. } // look for remaining points in increasing z-order
  17955. while (n && n.z <= maxZ) {
  17956. 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;
  17957. n = n.nextZ;
  17958. }
  17959. return true;
  17960. } // go through all polygon nodes and cure small local self-intersections
  17961. function cureLocalIntersections(start, triangles, dim) {
  17962. let p = start;
  17963. do {
  17964. const a = p.prev,
  17965. b = p.next.next;
  17966. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  17967. triangles.push(a.i / dim);
  17968. triangles.push(p.i / dim);
  17969. triangles.push(b.i / dim); // remove two nodes involved
  17970. removeNode(p);
  17971. removeNode(p.next);
  17972. p = start = b;
  17973. }
  17974. p = p.next;
  17975. } while (p !== start);
  17976. return filterPoints(p);
  17977. } // try splitting polygon into two and triangulate them independently
  17978. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  17979. // look for a valid diagonal that divides the polygon into two
  17980. let a = start;
  17981. do {
  17982. let b = a.next.next;
  17983. while (b !== a.prev) {
  17984. if (a.i !== b.i && isValidDiagonal(a, b)) {
  17985. // split the polygon in two by the diagonal
  17986. let c = splitPolygon(a, b); // filter colinear points around the cuts
  17987. a = filterPoints(a, a.next);
  17988. c = filterPoints(c, c.next); // run earcut on each half
  17989. earcutLinked(a, triangles, dim, minX, minY, invSize);
  17990. earcutLinked(c, triangles, dim, minX, minY, invSize);
  17991. return;
  17992. }
  17993. b = b.next;
  17994. }
  17995. a = a.next;
  17996. } while (a !== start);
  17997. } // link every hole into the outer loop, producing a single-ring polygon without holes
  17998. function eliminateHoles(data, holeIndices, outerNode, dim) {
  17999. const queue = [];
  18000. let i, len, start, end, list;
  18001. for (i = 0, len = holeIndices.length; i < len; i++) {
  18002. start = holeIndices[i] * dim;
  18003. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  18004. list = linkedList(data, start, end, dim, false);
  18005. if (list === list.next) list.steiner = true;
  18006. queue.push(getLeftmost(list));
  18007. }
  18008. queue.sort(compareX); // process holes from left to right
  18009. for (i = 0; i < queue.length; i++) {
  18010. eliminateHole(queue[i], outerNode);
  18011. outerNode = filterPoints(outerNode, outerNode.next);
  18012. }
  18013. return outerNode;
  18014. }
  18015. function compareX(a, b) {
  18016. return a.x - b.x;
  18017. } // find a bridge between vertices that connects hole with an outer ring and and link it
  18018. function eliminateHole(hole, outerNode) {
  18019. outerNode = findHoleBridge(hole, outerNode);
  18020. if (outerNode) {
  18021. const b = splitPolygon(outerNode, hole); // filter collinear points around the cuts
  18022. filterPoints(outerNode, outerNode.next);
  18023. filterPoints(b, b.next);
  18024. }
  18025. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  18026. function findHoleBridge(hole, outerNode) {
  18027. let p = outerNode;
  18028. const hx = hole.x;
  18029. const hy = hole.y;
  18030. let qx = -Infinity,
  18031. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  18032. // segment's endpoint with lesser x will be potential connection point
  18033. do {
  18034. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  18035. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  18036. if (x <= hx && x > qx) {
  18037. qx = x;
  18038. if (x === hx) {
  18039. if (hy === p.y) return p;
  18040. if (hy === p.next.y) return p.next;
  18041. }
  18042. m = p.x < p.next.x ? p : p.next;
  18043. }
  18044. }
  18045. p = p.next;
  18046. } while (p !== outerNode);
  18047. if (!m) return null;
  18048. if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint
  18049. // look for points inside the triangle of hole point, segment intersection and endpoint;
  18050. // if there are no points found, we have a valid connection;
  18051. // otherwise choose the point of the minimum angle with the ray as connection point
  18052. const stop = m,
  18053. mx = m.x,
  18054. my = m.y;
  18055. let tanMin = Infinity,
  18056. tan;
  18057. p = m;
  18058. do {
  18059. 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)) {
  18060. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  18061. if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
  18062. m = p;
  18063. tanMin = tan;
  18064. }
  18065. }
  18066. p = p.next;
  18067. } while (p !== stop);
  18068. return m;
  18069. } // whether sector in vertex m contains sector in vertex p in the same coordinates
  18070. function sectorContainsSector(m, p) {
  18071. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  18072. } // interlink polygon nodes in z-order
  18073. function indexCurve(start, minX, minY, invSize) {
  18074. let p = start;
  18075. do {
  18076. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  18077. p.prevZ = p.prev;
  18078. p.nextZ = p.next;
  18079. p = p.next;
  18080. } while (p !== start);
  18081. p.prevZ.nextZ = null;
  18082. p.prevZ = null;
  18083. sortLinked(p);
  18084. } // Simon Tatham's linked list merge sort algorithm
  18085. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  18086. function sortLinked(list) {
  18087. let i,
  18088. p,
  18089. q,
  18090. e,
  18091. tail,
  18092. numMerges,
  18093. pSize,
  18094. qSize,
  18095. inSize = 1;
  18096. do {
  18097. p = list;
  18098. list = null;
  18099. tail = null;
  18100. numMerges = 0;
  18101. while (p) {
  18102. numMerges++;
  18103. q = p;
  18104. pSize = 0;
  18105. for (i = 0; i < inSize; i++) {
  18106. pSize++;
  18107. q = q.nextZ;
  18108. if (!q) break;
  18109. }
  18110. qSize = inSize;
  18111. while (pSize > 0 || qSize > 0 && q) {
  18112. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  18113. e = p;
  18114. p = p.nextZ;
  18115. pSize--;
  18116. } else {
  18117. e = q;
  18118. q = q.nextZ;
  18119. qSize--;
  18120. }
  18121. if (tail) tail.nextZ = e;else list = e;
  18122. e.prevZ = tail;
  18123. tail = e;
  18124. }
  18125. p = q;
  18126. }
  18127. tail.nextZ = null;
  18128. inSize *= 2;
  18129. } while (numMerges > 1);
  18130. return list;
  18131. } // z-order of a point given coords and inverse of the longer side of data bbox
  18132. function zOrder(x, y, minX, minY, invSize) {
  18133. // coords are transformed into non-negative 15-bit integer range
  18134. x = 32767 * (x - minX) * invSize;
  18135. y = 32767 * (y - minY) * invSize;
  18136. x = (x | x << 8) & 0x00FF00FF;
  18137. x = (x | x << 4) & 0x0F0F0F0F;
  18138. x = (x | x << 2) & 0x33333333;
  18139. x = (x | x << 1) & 0x55555555;
  18140. y = (y | y << 8) & 0x00FF00FF;
  18141. y = (y | y << 4) & 0x0F0F0F0F;
  18142. y = (y | y << 2) & 0x33333333;
  18143. y = (y | y << 1) & 0x55555555;
  18144. return x | y << 1;
  18145. } // find the leftmost node of a polygon ring
  18146. function getLeftmost(start) {
  18147. let p = start,
  18148. leftmost = start;
  18149. do {
  18150. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  18151. p = p.next;
  18152. } while (p !== start);
  18153. return leftmost;
  18154. } // check if a point lies within a convex triangle
  18155. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  18156. 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;
  18157. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  18158. function isValidDiagonal(a, b) {
  18159. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && ( // dones't intersect other edges
  18160. locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && ( // locally visible
  18161. area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  18162. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  18163. } // signed area of a triangle
  18164. function area(p, q, r) {
  18165. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  18166. } // check if two points are equal
  18167. function equals(p1, p2) {
  18168. return p1.x === p2.x && p1.y === p2.y;
  18169. } // check if two segments intersect
  18170. function intersects(p1, q1, p2, q2) {
  18171. const o1 = sign(area(p1, q1, p2));
  18172. const o2 = sign(area(p1, q1, q2));
  18173. const o3 = sign(area(p2, q2, p1));
  18174. const o4 = sign(area(p2, q2, q1));
  18175. if (o1 !== o2 && o3 !== o4) return true; // general case
  18176. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  18177. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  18178. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  18179. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  18180. return false;
  18181. } // for collinear points p, q, r, check if point q lies on segment pr
  18182. function onSegment(p, q, r) {
  18183. 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);
  18184. }
  18185. function sign(num) {
  18186. return num > 0 ? 1 : num < 0 ? -1 : 0;
  18187. } // check if a polygon diagonal intersects any polygon segments
  18188. function intersectsPolygon(a, b) {
  18189. let p = a;
  18190. do {
  18191. 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;
  18192. p = p.next;
  18193. } while (p !== a);
  18194. return false;
  18195. } // check if a polygon diagonal is locally inside the polygon
  18196. function locallyInside(a, b) {
  18197. 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;
  18198. } // check if the middle point of a polygon diagonal is inside the polygon
  18199. function middleInside(a, b) {
  18200. let p = a,
  18201. inside = false;
  18202. const px = (a.x + b.x) / 2,
  18203. py = (a.y + b.y) / 2;
  18204. do {
  18205. 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;
  18206. p = p.next;
  18207. } while (p !== a);
  18208. return inside;
  18209. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  18210. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  18211. function splitPolygon(a, b) {
  18212. const a2 = new Node(a.i, a.x, a.y),
  18213. b2 = new Node(b.i, b.x, b.y),
  18214. an = a.next,
  18215. bp = b.prev;
  18216. a.next = b;
  18217. b.prev = a;
  18218. a2.next = an;
  18219. an.prev = a2;
  18220. b2.next = a2;
  18221. a2.prev = b2;
  18222. bp.next = b2;
  18223. b2.prev = bp;
  18224. return b2;
  18225. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  18226. function insertNode(i, x, y, last) {
  18227. const p = new Node(i, x, y);
  18228. if (!last) {
  18229. p.prev = p;
  18230. p.next = p;
  18231. } else {
  18232. p.next = last.next;
  18233. p.prev = last;
  18234. last.next.prev = p;
  18235. last.next = p;
  18236. }
  18237. return p;
  18238. }
  18239. function removeNode(p) {
  18240. p.next.prev = p.prev;
  18241. p.prev.next = p.next;
  18242. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  18243. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  18244. }
  18245. function Node(i, x, y) {
  18246. // vertex index in coordinates array
  18247. this.i = i; // vertex coordinates
  18248. this.x = x;
  18249. this.y = y; // previous and next vertex nodes in a polygon ring
  18250. this.prev = null;
  18251. this.next = null; // z-order curve value
  18252. this.z = null; // previous and next nodes in z-order
  18253. this.prevZ = null;
  18254. this.nextZ = null; // indicates whether this is a steiner point
  18255. this.steiner = false;
  18256. }
  18257. function signedArea(data, start, end, dim) {
  18258. let sum = 0;
  18259. for (let i = start, j = end - dim; i < end; i += dim) {
  18260. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  18261. j = i;
  18262. }
  18263. return sum;
  18264. }
  18265. class ShapeUtils {
  18266. // calculate area of the contour polygon
  18267. static area(contour) {
  18268. const n = contour.length;
  18269. let a = 0.0;
  18270. for (let p = n - 1, q = 0; q < n; p = q++) {
  18271. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  18272. }
  18273. return a * 0.5;
  18274. }
  18275. static isClockWise(pts) {
  18276. return ShapeUtils.area(pts) < 0;
  18277. }
  18278. static triangulateShape(contour, holes) {
  18279. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  18280. const holeIndices = []; // array of hole indices
  18281. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  18282. removeDupEndPts(contour);
  18283. addContour(vertices, contour); //
  18284. let holeIndex = contour.length;
  18285. holes.forEach(removeDupEndPts);
  18286. for (let i = 0; i < holes.length; i++) {
  18287. holeIndices.push(holeIndex);
  18288. holeIndex += holes[i].length;
  18289. addContour(vertices, holes[i]);
  18290. } //
  18291. const triangles = Earcut.triangulate(vertices, holeIndices); //
  18292. for (let i = 0; i < triangles.length; i += 3) {
  18293. faces.push(triangles.slice(i, i + 3));
  18294. }
  18295. return faces;
  18296. }
  18297. }
  18298. function removeDupEndPts(points) {
  18299. const l = points.length;
  18300. if (l > 2 && points[l - 1].equals(points[0])) {
  18301. points.pop();
  18302. }
  18303. }
  18304. function addContour(vertices, contour) {
  18305. for (let i = 0; i < contour.length; i++) {
  18306. vertices.push(contour[i].x);
  18307. vertices.push(contour[i].y);
  18308. }
  18309. }
  18310. /**
  18311. * Creates extruded geometry from a path shape.
  18312. *
  18313. * parameters = {
  18314. *
  18315. * curveSegments: <int>, // number of points on the curves
  18316. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  18317. * depth: <float>, // Depth to extrude the shape
  18318. *
  18319. * bevelEnabled: <bool>, // turn on bevel
  18320. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18321. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  18322. * bevelOffset: <float>, // how far from shape outline does bevel start
  18323. * bevelSegments: <int>, // number of bevel layers
  18324. *
  18325. * extrudePath: <THREE.Curve> // curve to extrude shape along
  18326. *
  18327. * UVGenerator: <Object> // object that provides UV generator functions
  18328. *
  18329. * }
  18330. */
  18331. class ExtrudeGeometry extends BufferGeometry {
  18332. constructor(shapes, options) {
  18333. super();
  18334. this.type = 'ExtrudeGeometry';
  18335. this.parameters = {
  18336. shapes: shapes,
  18337. options: options
  18338. };
  18339. shapes = Array.isArray(shapes) ? shapes : [shapes];
  18340. const scope = this;
  18341. const verticesArray = [];
  18342. const uvArray = [];
  18343. for (let i = 0, l = shapes.length; i < l; i++) {
  18344. const shape = shapes[i];
  18345. addShape(shape);
  18346. } // build geometry
  18347. this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  18348. this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  18349. this.computeVertexNormals(); // functions
  18350. function addShape(shape) {
  18351. const placeholder = []; // options
  18352. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18353. const steps = options.steps !== undefined ? options.steps : 1;
  18354. let depth = options.depth !== undefined ? options.depth : 100;
  18355. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  18356. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  18357. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  18358. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  18359. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18360. const extrudePath = options.extrudePath;
  18361. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  18362. if (options.amount !== undefined) {
  18363. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  18364. depth = options.amount;
  18365. } //
  18366. let extrudePts,
  18367. extrudeByPath = false;
  18368. let splineTube, binormal, normal, position2;
  18369. if (extrudePath) {
  18370. extrudePts = extrudePath.getSpacedPoints(steps);
  18371. extrudeByPath = true;
  18372. bevelEnabled = false; // bevels not supported for path extrusion
  18373. // SETUP TNB variables
  18374. // TODO1 - have a .isClosed in spline?
  18375. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18376. binormal = new Vector3();
  18377. normal = new Vector3();
  18378. position2 = new Vector3();
  18379. } // Safeguards if bevels are not enabled
  18380. if (!bevelEnabled) {
  18381. bevelSegments = 0;
  18382. bevelThickness = 0;
  18383. bevelSize = 0;
  18384. bevelOffset = 0;
  18385. } // Variables initialization
  18386. const shapePoints = shape.extractPoints(curveSegments);
  18387. let vertices = shapePoints.shape;
  18388. const holes = shapePoints.holes;
  18389. const reverse = !ShapeUtils.isClockWise(vertices);
  18390. if (reverse) {
  18391. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18392. for (let h = 0, hl = holes.length; h < hl; h++) {
  18393. const ahole = holes[h];
  18394. if (ShapeUtils.isClockWise(ahole)) {
  18395. holes[h] = ahole.reverse();
  18396. }
  18397. }
  18398. }
  18399. const faces = ShapeUtils.triangulateShape(vertices, holes);
  18400. /* Vertices */
  18401. const contour = vertices; // vertices has all points but contour has only points of circumference
  18402. for (let h = 0, hl = holes.length; h < hl; h++) {
  18403. const ahole = holes[h];
  18404. vertices = vertices.concat(ahole);
  18405. }
  18406. function scalePt2(pt, vec, size) {
  18407. if (!vec) console.error('THREE.ExtrudeGeometry: vec does not exist');
  18408. return vec.clone().multiplyScalar(size).add(pt);
  18409. }
  18410. const vlen = vertices.length,
  18411. flen = faces.length; // Find directions for point movement
  18412. function getBevelVec(inPt, inPrev, inNext) {
  18413. // computes for inPt the corresponding point inPt' on a new contour
  18414. // shifted by 1 unit (length of normalized vector) to the left
  18415. // if we walk along contour clockwise, this new contour is outside the old one
  18416. //
  18417. // inPt' is the intersection of the two lines parallel to the two
  18418. // adjacent edges of inPt at a distance of 1 unit on the left side.
  18419. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  18420. // good reading for geometry algorithms (here: line-line intersection)
  18421. // http://geomalgorithms.com/a05-_intersect-1.html
  18422. const v_prev_x = inPt.x - inPrev.x,
  18423. v_prev_y = inPt.y - inPrev.y;
  18424. const v_next_x = inNext.x - inPt.x,
  18425. v_next_y = inNext.y - inPt.y;
  18426. const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  18427. const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  18428. if (Math.abs(collinear0) > Number.EPSILON) {
  18429. // not collinear
  18430. // length of vectors for normalizing
  18431. const v_prev_len = Math.sqrt(v_prev_lensq);
  18432. 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
  18433. const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  18434. const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  18435. const ptNextShift_x = inNext.x - v_next_y / v_next_len;
  18436. const ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  18437. 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
  18438. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  18439. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  18440. // but prevent crazy spikes
  18441. const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  18442. if (v_trans_lensq <= 2) {
  18443. return new Vector2(v_trans_x, v_trans_y);
  18444. } else {
  18445. shrink_by = Math.sqrt(v_trans_lensq / 2);
  18446. }
  18447. } else {
  18448. // handle special case of collinear edges
  18449. let direction_eq = false; // assumes: opposite
  18450. if (v_prev_x > Number.EPSILON) {
  18451. if (v_next_x > Number.EPSILON) {
  18452. direction_eq = true;
  18453. }
  18454. } else {
  18455. if (v_prev_x < -Number.EPSILON) {
  18456. if (v_next_x < -Number.EPSILON) {
  18457. direction_eq = true;
  18458. }
  18459. } else {
  18460. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  18461. direction_eq = true;
  18462. }
  18463. }
  18464. }
  18465. if (direction_eq) {
  18466. // console.log("Warning: lines are a straight sequence");
  18467. v_trans_x = -v_prev_y;
  18468. v_trans_y = v_prev_x;
  18469. shrink_by = Math.sqrt(v_prev_lensq);
  18470. } else {
  18471. // console.log("Warning: lines are a straight spike");
  18472. v_trans_x = v_prev_x;
  18473. v_trans_y = v_prev_y;
  18474. shrink_by = Math.sqrt(v_prev_lensq / 2);
  18475. }
  18476. }
  18477. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  18478. }
  18479. const contourMovements = [];
  18480. for (let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  18481. if (j === il) j = 0;
  18482. if (k === il) k = 0; // (j)---(i)---(k)
  18483. // console.log('i,j,k', i, j , k)
  18484. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  18485. }
  18486. const holesMovements = [];
  18487. let oneHoleMovements,
  18488. verticesMovements = contourMovements.concat();
  18489. for (let h = 0, hl = holes.length; h < hl; h++) {
  18490. const ahole = holes[h];
  18491. oneHoleMovements = [];
  18492. for (let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  18493. if (j === il) j = 0;
  18494. if (k === il) k = 0; // (j)---(i)---(k)
  18495. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  18496. }
  18497. holesMovements.push(oneHoleMovements);
  18498. verticesMovements = verticesMovements.concat(oneHoleMovements);
  18499. } // Loop bevelSegments, 1 for the front, 1 for the back
  18500. for (let b = 0; b < bevelSegments; b++) {
  18501. //for ( b = bevelSegments; b > 0; b -- ) {
  18502. const t = b / bevelSegments;
  18503. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  18504. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  18505. for (let i = 0, il = contour.length; i < il; i++) {
  18506. const vert = scalePt2(contour[i], contourMovements[i], bs);
  18507. v(vert.x, vert.y, -z);
  18508. } // expand holes
  18509. for (let h = 0, hl = holes.length; h < hl; h++) {
  18510. const ahole = holes[h];
  18511. oneHoleMovements = holesMovements[h];
  18512. for (let i = 0, il = ahole.length; i < il; i++) {
  18513. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  18514. v(vert.x, vert.y, -z);
  18515. }
  18516. }
  18517. }
  18518. const bs = bevelSize + bevelOffset; // Back facing vertices
  18519. for (let i = 0; i < vlen; i++) {
  18520. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  18521. if (!extrudeByPath) {
  18522. v(vert.x, vert.y, 0);
  18523. } else {
  18524. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18525. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  18526. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  18527. position2.copy(extrudePts[0]).add(normal).add(binormal);
  18528. v(position2.x, position2.y, position2.z);
  18529. }
  18530. } // Add stepped vertices...
  18531. // Including front facing vertices
  18532. for (let s = 1; s <= steps; s++) {
  18533. for (let i = 0; i < vlen; i++) {
  18534. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  18535. if (!extrudeByPath) {
  18536. v(vert.x, vert.y, depth / steps * s);
  18537. } else {
  18538. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18539. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  18540. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  18541. position2.copy(extrudePts[s]).add(normal).add(binormal);
  18542. v(position2.x, position2.y, position2.z);
  18543. }
  18544. }
  18545. } // Add bevel segments planes
  18546. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18547. for (let b = bevelSegments - 1; b >= 0; b--) {
  18548. const t = b / bevelSegments;
  18549. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  18550. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  18551. for (let i = 0, il = contour.length; i < il; i++) {
  18552. const vert = scalePt2(contour[i], contourMovements[i], bs);
  18553. v(vert.x, vert.y, depth + z);
  18554. } // expand holes
  18555. for (let h = 0, hl = holes.length; h < hl; h++) {
  18556. const ahole = holes[h];
  18557. oneHoleMovements = holesMovements[h];
  18558. for (let i = 0, il = ahole.length; i < il; i++) {
  18559. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  18560. if (!extrudeByPath) {
  18561. v(vert.x, vert.y, depth + z);
  18562. } else {
  18563. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  18564. }
  18565. }
  18566. }
  18567. }
  18568. /* Faces */
  18569. // Top and bottom faces
  18570. buildLidFaces(); // Sides faces
  18571. buildSideFaces(); ///// Internal functions
  18572. function buildLidFaces() {
  18573. const start = verticesArray.length / 3;
  18574. if (bevelEnabled) {
  18575. let layer = 0; // steps + 1
  18576. let offset = vlen * layer; // Bottom faces
  18577. for (let i = 0; i < flen; i++) {
  18578. const face = faces[i];
  18579. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  18580. }
  18581. layer = steps + bevelSegments * 2;
  18582. offset = vlen * layer; // Top faces
  18583. for (let i = 0; i < flen; i++) {
  18584. const face = faces[i];
  18585. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  18586. }
  18587. } else {
  18588. // Bottom faces
  18589. for (let i = 0; i < flen; i++) {
  18590. const face = faces[i];
  18591. f3(face[2], face[1], face[0]);
  18592. } // Top faces
  18593. for (let i = 0; i < flen; i++) {
  18594. const face = faces[i];
  18595. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  18596. }
  18597. }
  18598. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  18599. } // Create faces for the z-sides of the shape
  18600. function buildSideFaces() {
  18601. const start = verticesArray.length / 3;
  18602. let layeroffset = 0;
  18603. sidewalls(contour, layeroffset);
  18604. layeroffset += contour.length;
  18605. for (let h = 0, hl = holes.length; h < hl; h++) {
  18606. const ahole = holes[h];
  18607. sidewalls(ahole, layeroffset); //, true
  18608. layeroffset += ahole.length;
  18609. }
  18610. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  18611. }
  18612. function sidewalls(contour, layeroffset) {
  18613. let i = contour.length;
  18614. while (--i >= 0) {
  18615. const j = i;
  18616. let k = i - 1;
  18617. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  18618. for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) {
  18619. const slen1 = vlen * s;
  18620. const slen2 = vlen * (s + 1);
  18621. const a = layeroffset + j + slen1,
  18622. b = layeroffset + k + slen1,
  18623. c = layeroffset + k + slen2,
  18624. d = layeroffset + j + slen2;
  18625. f4(a, b, c, d);
  18626. }
  18627. }
  18628. }
  18629. function v(x, y, z) {
  18630. placeholder.push(x);
  18631. placeholder.push(y);
  18632. placeholder.push(z);
  18633. }
  18634. function f3(a, b, c) {
  18635. addVertex(a);
  18636. addVertex(b);
  18637. addVertex(c);
  18638. const nextIndex = verticesArray.length / 3;
  18639. const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  18640. addUV(uvs[0]);
  18641. addUV(uvs[1]);
  18642. addUV(uvs[2]);
  18643. }
  18644. function f4(a, b, c, d) {
  18645. addVertex(a);
  18646. addVertex(b);
  18647. addVertex(d);
  18648. addVertex(b);
  18649. addVertex(c);
  18650. addVertex(d);
  18651. const nextIndex = verticesArray.length / 3;
  18652. const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  18653. addUV(uvs[0]);
  18654. addUV(uvs[1]);
  18655. addUV(uvs[3]);
  18656. addUV(uvs[1]);
  18657. addUV(uvs[2]);
  18658. addUV(uvs[3]);
  18659. }
  18660. function addVertex(index) {
  18661. verticesArray.push(placeholder[index * 3 + 0]);
  18662. verticesArray.push(placeholder[index * 3 + 1]);
  18663. verticesArray.push(placeholder[index * 3 + 2]);
  18664. }
  18665. function addUV(vector2) {
  18666. uvArray.push(vector2.x);
  18667. uvArray.push(vector2.y);
  18668. }
  18669. }
  18670. }
  18671. toJSON() {
  18672. const data = super.toJSON();
  18673. const shapes = this.parameters.shapes;
  18674. const options = this.parameters.options;
  18675. return toJSON$1(shapes, options, data);
  18676. }
  18677. static fromJSON(data, shapes) {
  18678. const geometryShapes = [];
  18679. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  18680. const shape = shapes[data.shapes[j]];
  18681. geometryShapes.push(shape);
  18682. }
  18683. const extrudePath = data.options.extrudePath;
  18684. if (extrudePath !== undefined) {
  18685. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  18686. }
  18687. return new ExtrudeGeometry(geometryShapes, data.options);
  18688. }
  18689. }
  18690. const WorldUVGenerator = {
  18691. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  18692. const a_x = vertices[indexA * 3];
  18693. const a_y = vertices[indexA * 3 + 1];
  18694. const b_x = vertices[indexB * 3];
  18695. const b_y = vertices[indexB * 3 + 1];
  18696. const c_x = vertices[indexC * 3];
  18697. const c_y = vertices[indexC * 3 + 1];
  18698. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  18699. },
  18700. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  18701. const a_x = vertices[indexA * 3];
  18702. const a_y = vertices[indexA * 3 + 1];
  18703. const a_z = vertices[indexA * 3 + 2];
  18704. const b_x = vertices[indexB * 3];
  18705. const b_y = vertices[indexB * 3 + 1];
  18706. const b_z = vertices[indexB * 3 + 2];
  18707. const c_x = vertices[indexC * 3];
  18708. const c_y = vertices[indexC * 3 + 1];
  18709. const c_z = vertices[indexC * 3 + 2];
  18710. const d_x = vertices[indexD * 3];
  18711. const d_y = vertices[indexD * 3 + 1];
  18712. const d_z = vertices[indexD * 3 + 2];
  18713. if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) {
  18714. 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)];
  18715. } else {
  18716. 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)];
  18717. }
  18718. }
  18719. };
  18720. function toJSON$1(shapes, options, data) {
  18721. data.shapes = [];
  18722. if (Array.isArray(shapes)) {
  18723. for (let i = 0, l = shapes.length; i < l; i++) {
  18724. const shape = shapes[i];
  18725. data.shapes.push(shape.uuid);
  18726. }
  18727. } else {
  18728. data.shapes.push(shapes.uuid);
  18729. }
  18730. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  18731. return data;
  18732. }
  18733. class IcosahedronGeometry extends PolyhedronGeometry {
  18734. constructor(radius = 1, detail = 0) {
  18735. const t = (1 + Math.sqrt(5)) / 2;
  18736. 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];
  18737. 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];
  18738. super(vertices, indices, radius, detail);
  18739. this.type = 'IcosahedronGeometry';
  18740. this.parameters = {
  18741. radius: radius,
  18742. detail: detail
  18743. };
  18744. }
  18745. static fromJSON(data) {
  18746. return new IcosahedronGeometry(data.radius, data.detail);
  18747. }
  18748. }
  18749. class LatheGeometry extends BufferGeometry {
  18750. constructor(points, segments = 12, phiStart = 0, phiLength = Math.PI * 2) {
  18751. super();
  18752. this.type = 'LatheGeometry';
  18753. this.parameters = {
  18754. points: points,
  18755. segments: segments,
  18756. phiStart: phiStart,
  18757. phiLength: phiLength
  18758. };
  18759. segments = Math.floor(segments); // clamp phiLength so it's in range of [ 0, 2PI ]
  18760. phiLength = clamp(phiLength, 0, Math.PI * 2); // buffers
  18761. const indices = [];
  18762. const vertices = [];
  18763. const uvs = []; // helper variables
  18764. const inverseSegments = 1.0 / segments;
  18765. const vertex = new Vector3();
  18766. const uv = new Vector2(); // generate vertices and uvs
  18767. for (let i = 0; i <= segments; i++) {
  18768. const phi = phiStart + i * inverseSegments * phiLength;
  18769. const sin = Math.sin(phi);
  18770. const cos = Math.cos(phi);
  18771. for (let j = 0; j <= points.length - 1; j++) {
  18772. // vertex
  18773. vertex.x = points[j].x * sin;
  18774. vertex.y = points[j].y;
  18775. vertex.z = points[j].x * cos;
  18776. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  18777. uv.x = i / segments;
  18778. uv.y = j / (points.length - 1);
  18779. uvs.push(uv.x, uv.y);
  18780. }
  18781. } // indices
  18782. for (let i = 0; i < segments; i++) {
  18783. for (let j = 0; j < points.length - 1; j++) {
  18784. const base = j + i * points.length;
  18785. const a = base;
  18786. const b = base + points.length;
  18787. const c = base + points.length + 1;
  18788. const d = base + 1; // faces
  18789. indices.push(a, b, d);
  18790. indices.push(b, c, d);
  18791. }
  18792. } // build geometry
  18793. this.setIndex(indices);
  18794. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18795. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
  18796. this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
  18797. // because the corresponding vertices are identical (but still have different UVs).
  18798. if (phiLength === Math.PI * 2) {
  18799. const normals = this.attributes.normal.array;
  18800. const n1 = new Vector3();
  18801. const n2 = new Vector3();
  18802. const n = new Vector3(); // this is the buffer offset for the last line of vertices
  18803. const base = segments * points.length * 3;
  18804. for (let i = 0, j = 0; i < points.length; i++, j += 3) {
  18805. // select the normal of the vertex in the first line
  18806. n1.x = normals[j + 0];
  18807. n1.y = normals[j + 1];
  18808. n1.z = normals[j + 2]; // select the normal of the vertex in the last line
  18809. n2.x = normals[base + j + 0];
  18810. n2.y = normals[base + j + 1];
  18811. n2.z = normals[base + j + 2]; // average normals
  18812. n.addVectors(n1, n2).normalize(); // assign the new values to both normals
  18813. normals[j + 0] = normals[base + j + 0] = n.x;
  18814. normals[j + 1] = normals[base + j + 1] = n.y;
  18815. normals[j + 2] = normals[base + j + 2] = n.z;
  18816. }
  18817. }
  18818. }
  18819. static fromJSON(data) {
  18820. return new LatheGeometry(data.points, data.segments, data.phiStart, data.phiLength);
  18821. }
  18822. }
  18823. class OctahedronGeometry extends PolyhedronGeometry {
  18824. constructor(radius = 1, detail = 0) {
  18825. const vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  18826. 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];
  18827. super(vertices, indices, radius, detail);
  18828. this.type = 'OctahedronGeometry';
  18829. this.parameters = {
  18830. radius: radius,
  18831. detail: detail
  18832. };
  18833. }
  18834. static fromJSON(data) {
  18835. return new OctahedronGeometry(data.radius, data.detail);
  18836. }
  18837. }
  18838. /**
  18839. * Parametric Surfaces Geometry
  18840. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  18841. */
  18842. class ParametricGeometry extends BufferGeometry {
  18843. constructor(func, slices, stacks) {
  18844. super();
  18845. this.type = 'ParametricGeometry';
  18846. this.parameters = {
  18847. func: func,
  18848. slices: slices,
  18849. stacks: stacks
  18850. }; // buffers
  18851. const indices = [];
  18852. const vertices = [];
  18853. const normals = [];
  18854. const uvs = [];
  18855. const EPS = 0.00001;
  18856. const normal = new Vector3();
  18857. const p0 = new Vector3(),
  18858. p1 = new Vector3();
  18859. const pu = new Vector3(),
  18860. pv = new Vector3();
  18861. if (func.length < 3) {
  18862. console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');
  18863. } // generate vertices, normals and uvs
  18864. const sliceCount = slices + 1;
  18865. for (let i = 0; i <= stacks; i++) {
  18866. const v = i / stacks;
  18867. for (let j = 0; j <= slices; j++) {
  18868. const u = j / slices; // vertex
  18869. func(u, v, p0);
  18870. vertices.push(p0.x, p0.y, p0.z); // normal
  18871. // approximate tangent vectors via finite differences
  18872. if (u - EPS >= 0) {
  18873. func(u - EPS, v, p1);
  18874. pu.subVectors(p0, p1);
  18875. } else {
  18876. func(u + EPS, v, p1);
  18877. pu.subVectors(p1, p0);
  18878. }
  18879. if (v - EPS >= 0) {
  18880. func(u, v - EPS, p1);
  18881. pv.subVectors(p0, p1);
  18882. } else {
  18883. func(u, v + EPS, p1);
  18884. pv.subVectors(p1, p0);
  18885. } // cross product of tangent vectors returns surface normal
  18886. normal.crossVectors(pu, pv).normalize();
  18887. normals.push(normal.x, normal.y, normal.z); // uv
  18888. uvs.push(u, v);
  18889. }
  18890. } // generate indices
  18891. for (let i = 0; i < stacks; i++) {
  18892. for (let j = 0; j < slices; j++) {
  18893. const a = i * sliceCount + j;
  18894. const b = i * sliceCount + j + 1;
  18895. const c = (i + 1) * sliceCount + j + 1;
  18896. const d = (i + 1) * sliceCount + j; // faces one and two
  18897. indices.push(a, b, d);
  18898. indices.push(b, c, d);
  18899. }
  18900. } // build geometry
  18901. this.setIndex(indices);
  18902. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18903. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18904. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18905. }
  18906. }
  18907. class RingGeometry extends BufferGeometry {
  18908. constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) {
  18909. super();
  18910. this.type = 'RingGeometry';
  18911. this.parameters = {
  18912. innerRadius: innerRadius,
  18913. outerRadius: outerRadius,
  18914. thetaSegments: thetaSegments,
  18915. phiSegments: phiSegments,
  18916. thetaStart: thetaStart,
  18917. thetaLength: thetaLength
  18918. };
  18919. thetaSegments = Math.max(3, thetaSegments);
  18920. phiSegments = Math.max(1, phiSegments); // buffers
  18921. const indices = [];
  18922. const vertices = [];
  18923. const normals = [];
  18924. const uvs = []; // some helper variables
  18925. let radius = innerRadius;
  18926. const radiusStep = (outerRadius - innerRadius) / phiSegments;
  18927. const vertex = new Vector3();
  18928. const uv = new Vector2(); // generate vertices, normals and uvs
  18929. for (let j = 0; j <= phiSegments; j++) {
  18930. for (let i = 0; i <= thetaSegments; i++) {
  18931. // values are generate from the inside of the ring to the outside
  18932. const segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  18933. vertex.x = radius * Math.cos(segment);
  18934. vertex.y = radius * Math.sin(segment);
  18935. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18936. normals.push(0, 0, 1); // uv
  18937. uv.x = (vertex.x / outerRadius + 1) / 2;
  18938. uv.y = (vertex.y / outerRadius + 1) / 2;
  18939. uvs.push(uv.x, uv.y);
  18940. } // increase the radius for next row of vertices
  18941. radius += radiusStep;
  18942. } // indices
  18943. for (let j = 0; j < phiSegments; j++) {
  18944. const thetaSegmentLevel = j * (thetaSegments + 1);
  18945. for (let i = 0; i < thetaSegments; i++) {
  18946. const segment = i + thetaSegmentLevel;
  18947. const a = segment;
  18948. const b = segment + thetaSegments + 1;
  18949. const c = segment + thetaSegments + 2;
  18950. const d = segment + 1; // faces
  18951. indices.push(a, b, d);
  18952. indices.push(b, c, d);
  18953. }
  18954. } // build geometry
  18955. this.setIndex(indices);
  18956. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18957. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18958. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18959. }
  18960. static fromJSON(data) {
  18961. return new RingGeometry(data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  18962. }
  18963. }
  18964. class ShapeGeometry extends BufferGeometry {
  18965. constructor(shapes, curveSegments = 12) {
  18966. super();
  18967. this.type = 'ShapeGeometry';
  18968. this.parameters = {
  18969. shapes: shapes,
  18970. curveSegments: curveSegments
  18971. }; // buffers
  18972. const indices = [];
  18973. const vertices = [];
  18974. const normals = [];
  18975. const uvs = []; // helper variables
  18976. let groupStart = 0;
  18977. let groupCount = 0; // allow single and array values for "shapes" parameter
  18978. if (Array.isArray(shapes) === false) {
  18979. addShape(shapes);
  18980. } else {
  18981. for (let i = 0; i < shapes.length; i++) {
  18982. addShape(shapes[i]);
  18983. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  18984. groupStart += groupCount;
  18985. groupCount = 0;
  18986. }
  18987. } // build geometry
  18988. this.setIndex(indices);
  18989. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18990. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18991. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  18992. function addShape(shape) {
  18993. const indexOffset = vertices.length / 3;
  18994. const points = shape.extractPoints(curveSegments);
  18995. let shapeVertices = points.shape;
  18996. const shapeHoles = points.holes; // check direction of vertices
  18997. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  18998. shapeVertices = shapeVertices.reverse();
  18999. }
  19000. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  19001. const shapeHole = shapeHoles[i];
  19002. if (ShapeUtils.isClockWise(shapeHole) === true) {
  19003. shapeHoles[i] = shapeHole.reverse();
  19004. }
  19005. }
  19006. const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  19007. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  19008. const shapeHole = shapeHoles[i];
  19009. shapeVertices = shapeVertices.concat(shapeHole);
  19010. } // vertices, normals, uvs
  19011. for (let i = 0, l = shapeVertices.length; i < l; i++) {
  19012. const vertex = shapeVertices[i];
  19013. vertices.push(vertex.x, vertex.y, 0);
  19014. normals.push(0, 0, 1);
  19015. uvs.push(vertex.x, vertex.y); // world uvs
  19016. } // incides
  19017. for (let i = 0, l = faces.length; i < l; i++) {
  19018. const face = faces[i];
  19019. const a = face[0] + indexOffset;
  19020. const b = face[1] + indexOffset;
  19021. const c = face[2] + indexOffset;
  19022. indices.push(a, b, c);
  19023. groupCount += 3;
  19024. }
  19025. }
  19026. }
  19027. toJSON() {
  19028. const data = super.toJSON();
  19029. const shapes = this.parameters.shapes;
  19030. return toJSON(shapes, data);
  19031. }
  19032. static fromJSON(data, shapes) {
  19033. const geometryShapes = [];
  19034. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  19035. const shape = shapes[data.shapes[j]];
  19036. geometryShapes.push(shape);
  19037. }
  19038. return new ShapeGeometry(geometryShapes, data.curveSegments);
  19039. }
  19040. }
  19041. function toJSON(shapes, data) {
  19042. data.shapes = [];
  19043. if (Array.isArray(shapes)) {
  19044. for (let i = 0, l = shapes.length; i < l; i++) {
  19045. const shape = shapes[i];
  19046. data.shapes.push(shape.uuid);
  19047. }
  19048. } else {
  19049. data.shapes.push(shapes.uuid);
  19050. }
  19051. return data;
  19052. }
  19053. class SphereGeometry extends BufferGeometry {
  19054. constructor(radius = 1, widthSegments = 8, heightSegments = 6, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) {
  19055. super();
  19056. this.type = 'SphereGeometry';
  19057. this.parameters = {
  19058. radius: radius,
  19059. widthSegments: widthSegments,
  19060. heightSegments: heightSegments,
  19061. phiStart: phiStart,
  19062. phiLength: phiLength,
  19063. thetaStart: thetaStart,
  19064. thetaLength: thetaLength
  19065. };
  19066. widthSegments = Math.max(3, Math.floor(widthSegments));
  19067. heightSegments = Math.max(2, Math.floor(heightSegments));
  19068. const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  19069. let index = 0;
  19070. const grid = [];
  19071. const vertex = new Vector3();
  19072. const normal = new Vector3(); // buffers
  19073. const indices = [];
  19074. const vertices = [];
  19075. const normals = [];
  19076. const uvs = []; // generate vertices, normals and uvs
  19077. for (let iy = 0; iy <= heightSegments; iy++) {
  19078. const verticesRow = [];
  19079. const v = iy / heightSegments; // special case for the poles
  19080. let uOffset = 0;
  19081. if (iy == 0 && thetaStart == 0) {
  19082. uOffset = 0.5 / widthSegments;
  19083. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  19084. uOffset = -0.5 / widthSegments;
  19085. }
  19086. for (let ix = 0; ix <= widthSegments; ix++) {
  19087. const u = ix / widthSegments; // vertex
  19088. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  19089. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  19090. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  19091. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19092. normal.copy(vertex).normalize();
  19093. normals.push(normal.x, normal.y, normal.z); // uv
  19094. uvs.push(u + uOffset, 1 - v);
  19095. verticesRow.push(index++);
  19096. }
  19097. grid.push(verticesRow);
  19098. } // indices
  19099. for (let iy = 0; iy < heightSegments; iy++) {
  19100. for (let ix = 0; ix < widthSegments; ix++) {
  19101. const a = grid[iy][ix + 1];
  19102. const b = grid[iy][ix];
  19103. const c = grid[iy + 1][ix];
  19104. const d = grid[iy + 1][ix + 1];
  19105. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  19106. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  19107. }
  19108. } // build geometry
  19109. this.setIndex(indices);
  19110. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19111. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19112. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19113. }
  19114. static fromJSON(data) {
  19115. return new SphereGeometry(data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  19116. }
  19117. }
  19118. class TetrahedronGeometry extends PolyhedronGeometry {
  19119. constructor(radius = 1, detail = 0) {
  19120. const vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  19121. const indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  19122. super(vertices, indices, radius, detail);
  19123. this.type = 'TetrahedronGeometry';
  19124. this.parameters = {
  19125. radius: radius,
  19126. detail: detail
  19127. };
  19128. }
  19129. static fromJSON(data) {
  19130. return new TetrahedronGeometry(data.radius, data.detail);
  19131. }
  19132. }
  19133. /**
  19134. * Text = 3D Text
  19135. *
  19136. * parameters = {
  19137. * font: <THREE.Font>, // font
  19138. *
  19139. * size: <float>, // size of the text
  19140. * height: <float>, // thickness to extrude text
  19141. * curveSegments: <int>, // number of points on the curves
  19142. *
  19143. * bevelEnabled: <bool>, // turn on bevel
  19144. * bevelThickness: <float>, // how deep into text bevel goes
  19145. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  19146. * bevelOffset: <float> // how far from text outline does bevel start
  19147. * }
  19148. */
  19149. class TextGeometry extends ExtrudeGeometry {
  19150. constructor(text, parameters = {}) {
  19151. const font = parameters.font;
  19152. if (!(font && font.isFont)) {
  19153. console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');
  19154. return new BufferGeometry();
  19155. }
  19156. const shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry API
  19157. parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults
  19158. if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;
  19159. if (parameters.bevelSize === undefined) parameters.bevelSize = 8;
  19160. if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;
  19161. super(shapes, parameters);
  19162. this.type = 'TextGeometry';
  19163. }
  19164. }
  19165. class TorusGeometry extends BufferGeometry {
  19166. constructor(radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) {
  19167. super();
  19168. this.type = 'TorusGeometry';
  19169. this.parameters = {
  19170. radius: radius,
  19171. tube: tube,
  19172. radialSegments: radialSegments,
  19173. tubularSegments: tubularSegments,
  19174. arc: arc
  19175. };
  19176. radialSegments = Math.floor(radialSegments);
  19177. tubularSegments = Math.floor(tubularSegments); // buffers
  19178. const indices = [];
  19179. const vertices = [];
  19180. const normals = [];
  19181. const uvs = []; // helper variables
  19182. const center = new Vector3();
  19183. const vertex = new Vector3();
  19184. const normal = new Vector3(); // generate vertices, normals and uvs
  19185. for (let j = 0; j <= radialSegments; j++) {
  19186. for (let i = 0; i <= tubularSegments; i++) {
  19187. const u = i / tubularSegments * arc;
  19188. const v = j / radialSegments * Math.PI * 2; // vertex
  19189. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  19190. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  19191. vertex.z = tube * Math.sin(v);
  19192. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19193. center.x = radius * Math.cos(u);
  19194. center.y = radius * Math.sin(u);
  19195. normal.subVectors(vertex, center).normalize();
  19196. normals.push(normal.x, normal.y, normal.z); // uv
  19197. uvs.push(i / tubularSegments);
  19198. uvs.push(j / radialSegments);
  19199. }
  19200. } // generate indices
  19201. for (let j = 1; j <= radialSegments; j++) {
  19202. for (let i = 1; i <= tubularSegments; i++) {
  19203. // indices
  19204. const a = (tubularSegments + 1) * j + i - 1;
  19205. const b = (tubularSegments + 1) * (j - 1) + i - 1;
  19206. const c = (tubularSegments + 1) * (j - 1) + i;
  19207. const d = (tubularSegments + 1) * j + i; // faces
  19208. indices.push(a, b, d);
  19209. indices.push(b, c, d);
  19210. }
  19211. } // build geometry
  19212. this.setIndex(indices);
  19213. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19214. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19215. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19216. }
  19217. static fromJSON(data) {
  19218. return new TorusGeometry(data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  19219. }
  19220. }
  19221. class TorusKnotGeometry extends BufferGeometry {
  19222. constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) {
  19223. super();
  19224. this.type = 'TorusKnotGeometry';
  19225. this.parameters = {
  19226. radius: radius,
  19227. tube: tube,
  19228. tubularSegments: tubularSegments,
  19229. radialSegments: radialSegments,
  19230. p: p,
  19231. q: q
  19232. };
  19233. tubularSegments = Math.floor(tubularSegments);
  19234. radialSegments = Math.floor(radialSegments); // buffers
  19235. const indices = [];
  19236. const vertices = [];
  19237. const normals = [];
  19238. const uvs = []; // helper variables
  19239. const vertex = new Vector3();
  19240. const normal = new Vector3();
  19241. const P1 = new Vector3();
  19242. const P2 = new Vector3();
  19243. const B = new Vector3();
  19244. const T = new Vector3();
  19245. const N = new Vector3(); // generate vertices, normals and uvs
  19246. for (let i = 0; i <= tubularSegments; ++i) {
  19247. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  19248. 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.
  19249. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  19250. calculatePositionOnCurve(u, p, q, radius, P1);
  19251. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  19252. T.subVectors(P2, P1);
  19253. N.addVectors(P2, P1);
  19254. B.crossVectors(T, N);
  19255. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  19256. B.normalize();
  19257. N.normalize();
  19258. for (let j = 0; j <= radialSegments; ++j) {
  19259. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  19260. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  19261. const v = j / radialSegments * Math.PI * 2;
  19262. const cx = -tube * Math.cos(v);
  19263. const cy = tube * Math.sin(v); // now calculate the final vertex position.
  19264. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  19265. vertex.x = P1.x + (cx * N.x + cy * B.x);
  19266. vertex.y = P1.y + (cx * N.y + cy * B.y);
  19267. vertex.z = P1.z + (cx * N.z + cy * B.z);
  19268. 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)
  19269. normal.subVectors(vertex, P1).normalize();
  19270. normals.push(normal.x, normal.y, normal.z); // uv
  19271. uvs.push(i / tubularSegments);
  19272. uvs.push(j / radialSegments);
  19273. }
  19274. } // generate indices
  19275. for (let j = 1; j <= tubularSegments; j++) {
  19276. for (let i = 1; i <= radialSegments; i++) {
  19277. // indices
  19278. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  19279. const b = (radialSegments + 1) * j + (i - 1);
  19280. const c = (radialSegments + 1) * j + i;
  19281. const d = (radialSegments + 1) * (j - 1) + i; // faces
  19282. indices.push(a, b, d);
  19283. indices.push(b, c, d);
  19284. }
  19285. } // build geometry
  19286. this.setIndex(indices);
  19287. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19288. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19289. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  19290. function calculatePositionOnCurve(u, p, q, radius, position) {
  19291. const cu = Math.cos(u);
  19292. const su = Math.sin(u);
  19293. const quOverP = q / p * u;
  19294. const cs = Math.cos(quOverP);
  19295. position.x = radius * (2 + cs) * 0.5 * cu;
  19296. position.y = radius * (2 + cs) * su * 0.5;
  19297. position.z = radius * Math.sin(quOverP) * 0.5;
  19298. }
  19299. }
  19300. static fromJSON(data) {
  19301. return new TorusKnotGeometry(data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  19302. }
  19303. }
  19304. class TubeGeometry extends BufferGeometry {
  19305. constructor(path, tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) {
  19306. super();
  19307. this.type = 'TubeGeometry';
  19308. this.parameters = {
  19309. path: path,
  19310. tubularSegments: tubularSegments,
  19311. radius: radius,
  19312. radialSegments: radialSegments,
  19313. closed: closed
  19314. };
  19315. const frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  19316. this.tangents = frames.tangents;
  19317. this.normals = frames.normals;
  19318. this.binormals = frames.binormals; // helper variables
  19319. const vertex = new Vector3();
  19320. const normal = new Vector3();
  19321. const uv = new Vector2();
  19322. let P = new Vector3(); // buffer
  19323. const vertices = [];
  19324. const normals = [];
  19325. const uvs = [];
  19326. const indices = []; // create buffer data
  19327. generateBufferData(); // build geometry
  19328. this.setIndex(indices);
  19329. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19330. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19331. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  19332. function generateBufferData() {
  19333. for (let i = 0; i < tubularSegments; i++) {
  19334. generateSegment(i);
  19335. } // if the geometry is not closed, generate the last row of vertices and normals
  19336. // at the regular position on the given path
  19337. //
  19338. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  19339. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  19340. // this makes it easy compute correct values for closed geometries
  19341. generateUVs(); // finally create faces
  19342. generateIndices();
  19343. }
  19344. function generateSegment(i) {
  19345. // we use getPointAt to sample evenly distributed points from the given path
  19346. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  19347. const N = frames.normals[i];
  19348. const B = frames.binormals[i]; // generate normals and vertices for the current segment
  19349. for (let j = 0; j <= radialSegments; j++) {
  19350. const v = j / radialSegments * Math.PI * 2;
  19351. const sin = Math.sin(v);
  19352. const cos = -Math.cos(v); // normal
  19353. normal.x = cos * N.x + sin * B.x;
  19354. normal.y = cos * N.y + sin * B.y;
  19355. normal.z = cos * N.z + sin * B.z;
  19356. normal.normalize();
  19357. normals.push(normal.x, normal.y, normal.z); // vertex
  19358. vertex.x = P.x + radius * normal.x;
  19359. vertex.y = P.y + radius * normal.y;
  19360. vertex.z = P.z + radius * normal.z;
  19361. vertices.push(vertex.x, vertex.y, vertex.z);
  19362. }
  19363. }
  19364. function generateIndices() {
  19365. for (let j = 1; j <= tubularSegments; j++) {
  19366. for (let i = 1; i <= radialSegments; i++) {
  19367. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  19368. const b = (radialSegments + 1) * j + (i - 1);
  19369. const c = (radialSegments + 1) * j + i;
  19370. const d = (radialSegments + 1) * (j - 1) + i; // faces
  19371. indices.push(a, b, d);
  19372. indices.push(b, c, d);
  19373. }
  19374. }
  19375. }
  19376. function generateUVs() {
  19377. for (let i = 0; i <= tubularSegments; i++) {
  19378. for (let j = 0; j <= radialSegments; j++) {
  19379. uv.x = i / tubularSegments;
  19380. uv.y = j / radialSegments;
  19381. uvs.push(uv.x, uv.y);
  19382. }
  19383. }
  19384. }
  19385. }
  19386. toJSON() {
  19387. const data = super.toJSON();
  19388. data.path = this.parameters.path.toJSON();
  19389. return data;
  19390. }
  19391. static fromJSON(data) {
  19392. // This only works for built-in curves (e.g. CatmullRomCurve3).
  19393. // User defined curves or instances of CurvePath will not be deserialized.
  19394. return new TubeGeometry(new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  19395. }
  19396. }
  19397. class WireframeGeometry extends BufferGeometry {
  19398. constructor(geometry) {
  19399. super();
  19400. this.type = 'WireframeGeometry';
  19401. if (geometry.isGeometry === true) {
  19402. console.error('THREE.WireframeGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  19403. return;
  19404. } // buffer
  19405. const vertices = []; // helper variables
  19406. const edge = [0, 0],
  19407. edges = {};
  19408. const vertex = new Vector3();
  19409. if (geometry.index !== null) {
  19410. // indexed BufferGeometry
  19411. const position = geometry.attributes.position;
  19412. const indices = geometry.index;
  19413. let groups = geometry.groups;
  19414. if (groups.length === 0) {
  19415. groups = [{
  19416. start: 0,
  19417. count: indices.count,
  19418. materialIndex: 0
  19419. }];
  19420. } // create a data structure that contains all eges without duplicates
  19421. for (let o = 0, ol = groups.length; o < ol; ++o) {
  19422. const group = groups[o];
  19423. const start = group.start;
  19424. const count = group.count;
  19425. for (let i = start, l = start + count; i < l; i += 3) {
  19426. for (let j = 0; j < 3; j++) {
  19427. const edge1 = indices.getX(i + j);
  19428. const edge2 = indices.getX(i + (j + 1) % 3);
  19429. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  19430. edge[1] = Math.max(edge1, edge2);
  19431. const key = edge[0] + ',' + edge[1];
  19432. if (edges[key] === undefined) {
  19433. edges[key] = {
  19434. index1: edge[0],
  19435. index2: edge[1]
  19436. };
  19437. }
  19438. }
  19439. }
  19440. } // generate vertices
  19441. for (const key in edges) {
  19442. const e = edges[key];
  19443. vertex.fromBufferAttribute(position, e.index1);
  19444. vertices.push(vertex.x, vertex.y, vertex.z);
  19445. vertex.fromBufferAttribute(position, e.index2);
  19446. vertices.push(vertex.x, vertex.y, vertex.z);
  19447. }
  19448. } else {
  19449. // non-indexed BufferGeometry
  19450. const position = geometry.attributes.position;
  19451. for (let i = 0, l = position.count / 3; i < l; i++) {
  19452. for (let j = 0; j < 3; j++) {
  19453. // three edges per triangle, an edge is represented as (index1, index2)
  19454. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  19455. const index1 = 3 * i + j;
  19456. vertex.fromBufferAttribute(position, index1);
  19457. vertices.push(vertex.x, vertex.y, vertex.z);
  19458. const index2 = 3 * i + (j + 1) % 3;
  19459. vertex.fromBufferAttribute(position, index2);
  19460. vertices.push(vertex.x, vertex.y, vertex.z);
  19461. }
  19462. }
  19463. } // build geometry
  19464. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19465. }
  19466. }
  19467. var Geometries = /*#__PURE__*/Object.freeze({
  19468. __proto__: null,
  19469. BoxGeometry: BoxGeometry,
  19470. BoxBufferGeometry: BoxGeometry,
  19471. CircleGeometry: CircleGeometry,
  19472. CircleBufferGeometry: CircleGeometry,
  19473. ConeGeometry: ConeGeometry,
  19474. ConeBufferGeometry: ConeGeometry,
  19475. CylinderGeometry: CylinderGeometry,
  19476. CylinderBufferGeometry: CylinderGeometry,
  19477. DodecahedronGeometry: DodecahedronGeometry,
  19478. DodecahedronBufferGeometry: DodecahedronGeometry,
  19479. EdgesGeometry: EdgesGeometry,
  19480. ExtrudeGeometry: ExtrudeGeometry,
  19481. ExtrudeBufferGeometry: ExtrudeGeometry,
  19482. IcosahedronGeometry: IcosahedronGeometry,
  19483. IcosahedronBufferGeometry: IcosahedronGeometry,
  19484. LatheGeometry: LatheGeometry,
  19485. LatheBufferGeometry: LatheGeometry,
  19486. OctahedronGeometry: OctahedronGeometry,
  19487. OctahedronBufferGeometry: OctahedronGeometry,
  19488. ParametricGeometry: ParametricGeometry,
  19489. ParametricBufferGeometry: ParametricGeometry,
  19490. PlaneGeometry: PlaneGeometry,
  19491. PlaneBufferGeometry: PlaneGeometry,
  19492. PolyhedronGeometry: PolyhedronGeometry,
  19493. PolyhedronBufferGeometry: PolyhedronGeometry,
  19494. RingGeometry: RingGeometry,
  19495. RingBufferGeometry: RingGeometry,
  19496. ShapeGeometry: ShapeGeometry,
  19497. ShapeBufferGeometry: ShapeGeometry,
  19498. SphereGeometry: SphereGeometry,
  19499. SphereBufferGeometry: SphereGeometry,
  19500. TetrahedronGeometry: TetrahedronGeometry,
  19501. TetrahedronBufferGeometry: TetrahedronGeometry,
  19502. TextGeometry: TextGeometry,
  19503. TextBufferGeometry: TextGeometry,
  19504. TorusGeometry: TorusGeometry,
  19505. TorusBufferGeometry: TorusGeometry,
  19506. TorusKnotGeometry: TorusKnotGeometry,
  19507. TorusKnotBufferGeometry: TorusKnotGeometry,
  19508. TubeGeometry: TubeGeometry,
  19509. TubeBufferGeometry: TubeGeometry,
  19510. WireframeGeometry: WireframeGeometry
  19511. });
  19512. /**
  19513. * parameters = {
  19514. * color: <THREE.Color>
  19515. * }
  19516. */
  19517. class ShadowMaterial extends Material {
  19518. constructor(parameters) {
  19519. super();
  19520. this.type = 'ShadowMaterial';
  19521. this.color = new Color(0x000000);
  19522. this.transparent = true;
  19523. this.setValues(parameters);
  19524. }
  19525. copy(source) {
  19526. super.copy(source);
  19527. this.color.copy(source.color);
  19528. return this;
  19529. }
  19530. }
  19531. ShadowMaterial.prototype.isShadowMaterial = true;
  19532. class RawShaderMaterial extends ShaderMaterial {
  19533. constructor(parameters) {
  19534. super(parameters);
  19535. this.type = 'RawShaderMaterial';
  19536. }
  19537. }
  19538. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  19539. /**
  19540. * parameters = {
  19541. * color: <hex>,
  19542. * roughness: <float>,
  19543. * metalness: <float>,
  19544. * opacity: <float>,
  19545. *
  19546. * map: new THREE.Texture( <Image> ),
  19547. *
  19548. * lightMap: new THREE.Texture( <Image> ),
  19549. * lightMapIntensity: <float>
  19550. *
  19551. * aoMap: new THREE.Texture( <Image> ),
  19552. * aoMapIntensity: <float>
  19553. *
  19554. * emissive: <hex>,
  19555. * emissiveIntensity: <float>
  19556. * emissiveMap: new THREE.Texture( <Image> ),
  19557. *
  19558. * bumpMap: new THREE.Texture( <Image> ),
  19559. * bumpScale: <float>,
  19560. *
  19561. * normalMap: new THREE.Texture( <Image> ),
  19562. * normalMapType: THREE.TangentSpaceNormalMap,
  19563. * normalScale: <Vector2>,
  19564. *
  19565. * displacementMap: new THREE.Texture( <Image> ),
  19566. * displacementScale: <float>,
  19567. * displacementBias: <float>,
  19568. *
  19569. * roughnessMap: new THREE.Texture( <Image> ),
  19570. *
  19571. * metalnessMap: new THREE.Texture( <Image> ),
  19572. *
  19573. * alphaMap: new THREE.Texture( <Image> ),
  19574. *
  19575. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  19576. * envMapIntensity: <float>
  19577. *
  19578. * refractionRatio: <float>,
  19579. *
  19580. * wireframe: <boolean>,
  19581. * wireframeLinewidth: <float>,
  19582. *
  19583. * morphTargets: <bool>,
  19584. * morphNormals: <bool>,
  19585. *
  19586. * flatShading: <bool>
  19587. * }
  19588. */
  19589. class MeshStandardMaterial extends Material {
  19590. constructor(parameters) {
  19591. super();
  19592. this.defines = {
  19593. 'STANDARD': ''
  19594. };
  19595. this.type = 'MeshStandardMaterial';
  19596. this.color = new Color(0xffffff); // diffuse
  19597. this.roughness = 1.0;
  19598. this.metalness = 0.0;
  19599. this.map = null;
  19600. this.lightMap = null;
  19601. this.lightMapIntensity = 1.0;
  19602. this.aoMap = null;
  19603. this.aoMapIntensity = 1.0;
  19604. this.emissive = new Color(0x000000);
  19605. this.emissiveIntensity = 1.0;
  19606. this.emissiveMap = null;
  19607. this.bumpMap = null;
  19608. this.bumpScale = 1;
  19609. this.normalMap = null;
  19610. this.normalMapType = TangentSpaceNormalMap;
  19611. this.normalScale = new Vector2(1, 1);
  19612. this.displacementMap = null;
  19613. this.displacementScale = 1;
  19614. this.displacementBias = 0;
  19615. this.roughnessMap = null;
  19616. this.metalnessMap = null;
  19617. this.alphaMap = null;
  19618. this.envMap = null;
  19619. this.envMapIntensity = 1.0;
  19620. this.refractionRatio = 0.98;
  19621. this.wireframe = false;
  19622. this.wireframeLinewidth = 1;
  19623. this.wireframeLinecap = 'round';
  19624. this.wireframeLinejoin = 'round';
  19625. this.morphTargets = false;
  19626. this.morphNormals = false;
  19627. this.flatShading = false;
  19628. this.vertexTangents = false;
  19629. this.setValues(parameters);
  19630. }
  19631. copy(source) {
  19632. super.copy(source);
  19633. this.defines = {
  19634. 'STANDARD': ''
  19635. };
  19636. this.color.copy(source.color);
  19637. this.roughness = source.roughness;
  19638. this.metalness = source.metalness;
  19639. this.map = source.map;
  19640. this.lightMap = source.lightMap;
  19641. this.lightMapIntensity = source.lightMapIntensity;
  19642. this.aoMap = source.aoMap;
  19643. this.aoMapIntensity = source.aoMapIntensity;
  19644. this.emissive.copy(source.emissive);
  19645. this.emissiveMap = source.emissiveMap;
  19646. this.emissiveIntensity = source.emissiveIntensity;
  19647. this.bumpMap = source.bumpMap;
  19648. this.bumpScale = source.bumpScale;
  19649. this.normalMap = source.normalMap;
  19650. this.normalMapType = source.normalMapType;
  19651. this.normalScale.copy(source.normalScale);
  19652. this.displacementMap = source.displacementMap;
  19653. this.displacementScale = source.displacementScale;
  19654. this.displacementBias = source.displacementBias;
  19655. this.roughnessMap = source.roughnessMap;
  19656. this.metalnessMap = source.metalnessMap;
  19657. this.alphaMap = source.alphaMap;
  19658. this.envMap = source.envMap;
  19659. this.envMapIntensity = source.envMapIntensity;
  19660. this.refractionRatio = source.refractionRatio;
  19661. this.wireframe = source.wireframe;
  19662. this.wireframeLinewidth = source.wireframeLinewidth;
  19663. this.wireframeLinecap = source.wireframeLinecap;
  19664. this.wireframeLinejoin = source.wireframeLinejoin;
  19665. this.morphTargets = source.morphTargets;
  19666. this.morphNormals = source.morphNormals;
  19667. this.flatShading = source.flatShading;
  19668. this.vertexTangents = source.vertexTangents;
  19669. return this;
  19670. }
  19671. }
  19672. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  19673. /**
  19674. * parameters = {
  19675. * clearcoat: <float>,
  19676. * clearcoatMap: new THREE.Texture( <Image> ),
  19677. * clearcoatRoughness: <float>,
  19678. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  19679. * clearcoatNormalScale: <Vector2>,
  19680. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  19681. *
  19682. * reflectivity: <float>,
  19683. * ior: <float>,
  19684. *
  19685. * sheen: <Color>,
  19686. *
  19687. * transmission: <float>,
  19688. * transmissionMap: new THREE.Texture( <Image> ),
  19689. *
  19690. * thickness: <float>,
  19691. * thicknessMap: new THREE.Texture( <Image> ),
  19692. * attenuationDistance: <float>,
  19693. * attenuationColor: <Color>
  19694. * }
  19695. */
  19696. class MeshPhysicalMaterial extends MeshStandardMaterial {
  19697. constructor(parameters) {
  19698. super();
  19699. this.defines = {
  19700. 'STANDARD': '',
  19701. 'PHYSICAL': ''
  19702. };
  19703. this.type = 'MeshPhysicalMaterial';
  19704. this.clearcoat = 0.0;
  19705. this.clearcoatMap = null;
  19706. this.clearcoatRoughness = 0.0;
  19707. this.clearcoatRoughnessMap = null;
  19708. this.clearcoatNormalScale = new Vector2(1, 1);
  19709. this.clearcoatNormalMap = null;
  19710. this.reflectivity = 0.5; // maps to F0 = 0.04
  19711. Object.defineProperty(this, 'ior', {
  19712. get: function () {
  19713. return (1 + 0.4 * this.reflectivity) / (1 - 0.4 * this.reflectivity);
  19714. },
  19715. set: function (ior) {
  19716. this.reflectivity = clamp(2.5 * (ior - 1) / (ior + 1), 0, 1);
  19717. }
  19718. });
  19719. this.sheen = null; // null will disable sheen bsdf
  19720. this.transmission = 0.0;
  19721. this.transmissionMap = null;
  19722. this.thickness = 0.01;
  19723. this.thicknessMap = null;
  19724. this.attenuationDistance = 0.0;
  19725. this.attenuationColor = new Color(1, 1, 1);
  19726. this.setValues(parameters);
  19727. }
  19728. copy(source) {
  19729. super.copy(source);
  19730. this.defines = {
  19731. 'STANDARD': '',
  19732. 'PHYSICAL': ''
  19733. };
  19734. this.clearcoat = source.clearcoat;
  19735. this.clearcoatMap = source.clearcoatMap;
  19736. this.clearcoatRoughness = source.clearcoatRoughness;
  19737. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  19738. this.clearcoatNormalMap = source.clearcoatNormalMap;
  19739. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  19740. this.reflectivity = source.reflectivity;
  19741. if (source.sheen) {
  19742. this.sheen = (this.sheen || new Color()).copy(source.sheen);
  19743. } else {
  19744. this.sheen = null;
  19745. }
  19746. this.transmission = source.transmission;
  19747. this.transmissionMap = source.transmissionMap;
  19748. this.thickness = source.thickness;
  19749. this.thicknessMap = source.thicknessMap;
  19750. this.attenuationDistance = source.attenuationDistance;
  19751. this.attenuationColor.copy(source.attenuationColor);
  19752. return this;
  19753. }
  19754. }
  19755. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  19756. /**
  19757. * parameters = {
  19758. * color: <hex>,
  19759. * specular: <hex>,
  19760. * shininess: <float>,
  19761. * opacity: <float>,
  19762. *
  19763. * map: new THREE.Texture( <Image> ),
  19764. *
  19765. * lightMap: new THREE.Texture( <Image> ),
  19766. * lightMapIntensity: <float>
  19767. *
  19768. * aoMap: new THREE.Texture( <Image> ),
  19769. * aoMapIntensity: <float>
  19770. *
  19771. * emissive: <hex>,
  19772. * emissiveIntensity: <float>
  19773. * emissiveMap: new THREE.Texture( <Image> ),
  19774. *
  19775. * bumpMap: new THREE.Texture( <Image> ),
  19776. * bumpScale: <float>,
  19777. *
  19778. * normalMap: new THREE.Texture( <Image> ),
  19779. * normalMapType: THREE.TangentSpaceNormalMap,
  19780. * normalScale: <Vector2>,
  19781. *
  19782. * displacementMap: new THREE.Texture( <Image> ),
  19783. * displacementScale: <float>,
  19784. * displacementBias: <float>,
  19785. *
  19786. * specularMap: new THREE.Texture( <Image> ),
  19787. *
  19788. * alphaMap: new THREE.Texture( <Image> ),
  19789. *
  19790. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  19791. * combine: THREE.MultiplyOperation,
  19792. * reflectivity: <float>,
  19793. * refractionRatio: <float>,
  19794. *
  19795. * wireframe: <boolean>,
  19796. * wireframeLinewidth: <float>,
  19797. *
  19798. * morphTargets: <bool>,
  19799. * morphNormals: <bool>,
  19800. *
  19801. * flatShading: <bool>
  19802. * }
  19803. */
  19804. class MeshPhongMaterial extends Material {
  19805. constructor(parameters) {
  19806. super();
  19807. this.type = 'MeshPhongMaterial';
  19808. this.color = new Color(0xffffff); // diffuse
  19809. this.specular = new Color(0x111111);
  19810. this.shininess = 30;
  19811. this.map = null;
  19812. this.lightMap = null;
  19813. this.lightMapIntensity = 1.0;
  19814. this.aoMap = null;
  19815. this.aoMapIntensity = 1.0;
  19816. this.emissive = new Color(0x000000);
  19817. this.emissiveIntensity = 1.0;
  19818. this.emissiveMap = null;
  19819. this.bumpMap = null;
  19820. this.bumpScale = 1;
  19821. this.normalMap = null;
  19822. this.normalMapType = TangentSpaceNormalMap;
  19823. this.normalScale = new Vector2(1, 1);
  19824. this.displacementMap = null;
  19825. this.displacementScale = 1;
  19826. this.displacementBias = 0;
  19827. this.specularMap = null;
  19828. this.alphaMap = null;
  19829. this.envMap = null;
  19830. this.combine = MultiplyOperation;
  19831. this.reflectivity = 1;
  19832. this.refractionRatio = 0.98;
  19833. this.wireframe = false;
  19834. this.wireframeLinewidth = 1;
  19835. this.wireframeLinecap = 'round';
  19836. this.wireframeLinejoin = 'round';
  19837. this.morphTargets = false;
  19838. this.morphNormals = false;
  19839. this.flatShading = false;
  19840. this.setValues(parameters);
  19841. }
  19842. copy(source) {
  19843. super.copy(source);
  19844. this.color.copy(source.color);
  19845. this.specular.copy(source.specular);
  19846. this.shininess = source.shininess;
  19847. this.map = source.map;
  19848. this.lightMap = source.lightMap;
  19849. this.lightMapIntensity = source.lightMapIntensity;
  19850. this.aoMap = source.aoMap;
  19851. this.aoMapIntensity = source.aoMapIntensity;
  19852. this.emissive.copy(source.emissive);
  19853. this.emissiveMap = source.emissiveMap;
  19854. this.emissiveIntensity = source.emissiveIntensity;
  19855. this.bumpMap = source.bumpMap;
  19856. this.bumpScale = source.bumpScale;
  19857. this.normalMap = source.normalMap;
  19858. this.normalMapType = source.normalMapType;
  19859. this.normalScale.copy(source.normalScale);
  19860. this.displacementMap = source.displacementMap;
  19861. this.displacementScale = source.displacementScale;
  19862. this.displacementBias = source.displacementBias;
  19863. this.specularMap = source.specularMap;
  19864. this.alphaMap = source.alphaMap;
  19865. this.envMap = source.envMap;
  19866. this.combine = source.combine;
  19867. this.reflectivity = source.reflectivity;
  19868. this.refractionRatio = source.refractionRatio;
  19869. this.wireframe = source.wireframe;
  19870. this.wireframeLinewidth = source.wireframeLinewidth;
  19871. this.wireframeLinecap = source.wireframeLinecap;
  19872. this.wireframeLinejoin = source.wireframeLinejoin;
  19873. this.morphTargets = source.morphTargets;
  19874. this.morphNormals = source.morphNormals;
  19875. this.flatShading = source.flatShading;
  19876. return this;
  19877. }
  19878. }
  19879. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  19880. /**
  19881. * parameters = {
  19882. * color: <hex>,
  19883. *
  19884. * map: new THREE.Texture( <Image> ),
  19885. * gradientMap: new THREE.Texture( <Image> ),
  19886. *
  19887. * lightMap: new THREE.Texture( <Image> ),
  19888. * lightMapIntensity: <float>
  19889. *
  19890. * aoMap: new THREE.Texture( <Image> ),
  19891. * aoMapIntensity: <float>
  19892. *
  19893. * emissive: <hex>,
  19894. * emissiveIntensity: <float>
  19895. * emissiveMap: new THREE.Texture( <Image> ),
  19896. *
  19897. * bumpMap: new THREE.Texture( <Image> ),
  19898. * bumpScale: <float>,
  19899. *
  19900. * normalMap: new THREE.Texture( <Image> ),
  19901. * normalMapType: THREE.TangentSpaceNormalMap,
  19902. * normalScale: <Vector2>,
  19903. *
  19904. * displacementMap: new THREE.Texture( <Image> ),
  19905. * displacementScale: <float>,
  19906. * displacementBias: <float>,
  19907. *
  19908. * alphaMap: new THREE.Texture( <Image> ),
  19909. *
  19910. * wireframe: <boolean>,
  19911. * wireframeLinewidth: <float>,
  19912. *
  19913. * morphTargets: <bool>,
  19914. * morphNormals: <bool>
  19915. * }
  19916. */
  19917. class MeshToonMaterial extends Material {
  19918. constructor(parameters) {
  19919. super();
  19920. this.defines = {
  19921. 'TOON': ''
  19922. };
  19923. this.type = 'MeshToonMaterial';
  19924. this.color = new Color(0xffffff);
  19925. this.map = null;
  19926. this.gradientMap = null;
  19927. this.lightMap = null;
  19928. this.lightMapIntensity = 1.0;
  19929. this.aoMap = null;
  19930. this.aoMapIntensity = 1.0;
  19931. this.emissive = new Color(0x000000);
  19932. this.emissiveIntensity = 1.0;
  19933. this.emissiveMap = null;
  19934. this.bumpMap = null;
  19935. this.bumpScale = 1;
  19936. this.normalMap = null;
  19937. this.normalMapType = TangentSpaceNormalMap;
  19938. this.normalScale = new Vector2(1, 1);
  19939. this.displacementMap = null;
  19940. this.displacementScale = 1;
  19941. this.displacementBias = 0;
  19942. this.alphaMap = null;
  19943. this.wireframe = false;
  19944. this.wireframeLinewidth = 1;
  19945. this.wireframeLinecap = 'round';
  19946. this.wireframeLinejoin = 'round';
  19947. this.morphTargets = false;
  19948. this.morphNormals = false;
  19949. this.setValues(parameters);
  19950. }
  19951. copy(source) {
  19952. super.copy(source);
  19953. this.color.copy(source.color);
  19954. this.map = source.map;
  19955. this.gradientMap = source.gradientMap;
  19956. this.lightMap = source.lightMap;
  19957. this.lightMapIntensity = source.lightMapIntensity;
  19958. this.aoMap = source.aoMap;
  19959. this.aoMapIntensity = source.aoMapIntensity;
  19960. this.emissive.copy(source.emissive);
  19961. this.emissiveMap = source.emissiveMap;
  19962. this.emissiveIntensity = source.emissiveIntensity;
  19963. this.bumpMap = source.bumpMap;
  19964. this.bumpScale = source.bumpScale;
  19965. this.normalMap = source.normalMap;
  19966. this.normalMapType = source.normalMapType;
  19967. this.normalScale.copy(source.normalScale);
  19968. this.displacementMap = source.displacementMap;
  19969. this.displacementScale = source.displacementScale;
  19970. this.displacementBias = source.displacementBias;
  19971. this.alphaMap = source.alphaMap;
  19972. this.wireframe = source.wireframe;
  19973. this.wireframeLinewidth = source.wireframeLinewidth;
  19974. this.wireframeLinecap = source.wireframeLinecap;
  19975. this.wireframeLinejoin = source.wireframeLinejoin;
  19976. this.morphTargets = source.morphTargets;
  19977. this.morphNormals = source.morphNormals;
  19978. return this;
  19979. }
  19980. }
  19981. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  19982. /**
  19983. * parameters = {
  19984. * opacity: <float>,
  19985. *
  19986. * bumpMap: new THREE.Texture( <Image> ),
  19987. * bumpScale: <float>,
  19988. *
  19989. * normalMap: new THREE.Texture( <Image> ),
  19990. * normalMapType: THREE.TangentSpaceNormalMap,
  19991. * normalScale: <Vector2>,
  19992. *
  19993. * displacementMap: new THREE.Texture( <Image> ),
  19994. * displacementScale: <float>,
  19995. * displacementBias: <float>,
  19996. *
  19997. * wireframe: <boolean>,
  19998. * wireframeLinewidth: <float>
  19999. *
  20000. * morphTargets: <bool>,
  20001. * morphNormals: <bool>,
  20002. *
  20003. * flatShading: <bool>
  20004. * }
  20005. */
  20006. class MeshNormalMaterial extends Material {
  20007. constructor(parameters) {
  20008. super();
  20009. this.type = 'MeshNormalMaterial';
  20010. this.bumpMap = null;
  20011. this.bumpScale = 1;
  20012. this.normalMap = null;
  20013. this.normalMapType = TangentSpaceNormalMap;
  20014. this.normalScale = new Vector2(1, 1);
  20015. this.displacementMap = null;
  20016. this.displacementScale = 1;
  20017. this.displacementBias = 0;
  20018. this.wireframe = false;
  20019. this.wireframeLinewidth = 1;
  20020. this.fog = false;
  20021. this.morphTargets = false;
  20022. this.morphNormals = false;
  20023. this.flatShading = false;
  20024. this.setValues(parameters);
  20025. }
  20026. copy(source) {
  20027. super.copy(source);
  20028. this.bumpMap = source.bumpMap;
  20029. this.bumpScale = source.bumpScale;
  20030. this.normalMap = source.normalMap;
  20031. this.normalMapType = source.normalMapType;
  20032. this.normalScale.copy(source.normalScale);
  20033. this.displacementMap = source.displacementMap;
  20034. this.displacementScale = source.displacementScale;
  20035. this.displacementBias = source.displacementBias;
  20036. this.wireframe = source.wireframe;
  20037. this.wireframeLinewidth = source.wireframeLinewidth;
  20038. this.morphTargets = source.morphTargets;
  20039. this.morphNormals = source.morphNormals;
  20040. this.flatShading = source.flatShading;
  20041. return this;
  20042. }
  20043. }
  20044. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  20045. /**
  20046. * parameters = {
  20047. * color: <hex>,
  20048. * opacity: <float>,
  20049. *
  20050. * map: new THREE.Texture( <Image> ),
  20051. *
  20052. * lightMap: new THREE.Texture( <Image> ),
  20053. * lightMapIntensity: <float>
  20054. *
  20055. * aoMap: new THREE.Texture( <Image> ),
  20056. * aoMapIntensity: <float>
  20057. *
  20058. * emissive: <hex>,
  20059. * emissiveIntensity: <float>
  20060. * emissiveMap: new THREE.Texture( <Image> ),
  20061. *
  20062. * specularMap: new THREE.Texture( <Image> ),
  20063. *
  20064. * alphaMap: new THREE.Texture( <Image> ),
  20065. *
  20066. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20067. * combine: THREE.Multiply,
  20068. * reflectivity: <float>,
  20069. * refractionRatio: <float>,
  20070. *
  20071. * wireframe: <boolean>,
  20072. * wireframeLinewidth: <float>,
  20073. *
  20074. * morphTargets: <bool>,
  20075. * morphNormals: <bool>
  20076. * }
  20077. */
  20078. class MeshLambertMaterial extends Material {
  20079. constructor(parameters) {
  20080. super();
  20081. this.type = 'MeshLambertMaterial';
  20082. this.color = new Color(0xffffff); // diffuse
  20083. this.map = null;
  20084. this.lightMap = null;
  20085. this.lightMapIntensity = 1.0;
  20086. this.aoMap = null;
  20087. this.aoMapIntensity = 1.0;
  20088. this.emissive = new Color(0x000000);
  20089. this.emissiveIntensity = 1.0;
  20090. this.emissiveMap = null;
  20091. this.specularMap = null;
  20092. this.alphaMap = null;
  20093. this.envMap = null;
  20094. this.combine = MultiplyOperation;
  20095. this.reflectivity = 1;
  20096. this.refractionRatio = 0.98;
  20097. this.wireframe = false;
  20098. this.wireframeLinewidth = 1;
  20099. this.wireframeLinecap = 'round';
  20100. this.wireframeLinejoin = 'round';
  20101. this.morphTargets = false;
  20102. this.morphNormals = false;
  20103. this.setValues(parameters);
  20104. }
  20105. copy(source) {
  20106. super.copy(source);
  20107. this.color.copy(source.color);
  20108. this.map = source.map;
  20109. this.lightMap = source.lightMap;
  20110. this.lightMapIntensity = source.lightMapIntensity;
  20111. this.aoMap = source.aoMap;
  20112. this.aoMapIntensity = source.aoMapIntensity;
  20113. this.emissive.copy(source.emissive);
  20114. this.emissiveMap = source.emissiveMap;
  20115. this.emissiveIntensity = source.emissiveIntensity;
  20116. this.specularMap = source.specularMap;
  20117. this.alphaMap = source.alphaMap;
  20118. this.envMap = source.envMap;
  20119. this.combine = source.combine;
  20120. this.reflectivity = source.reflectivity;
  20121. this.refractionRatio = source.refractionRatio;
  20122. this.wireframe = source.wireframe;
  20123. this.wireframeLinewidth = source.wireframeLinewidth;
  20124. this.wireframeLinecap = source.wireframeLinecap;
  20125. this.wireframeLinejoin = source.wireframeLinejoin;
  20126. this.morphTargets = source.morphTargets;
  20127. this.morphNormals = source.morphNormals;
  20128. return this;
  20129. }
  20130. }
  20131. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  20132. /**
  20133. * parameters = {
  20134. * color: <hex>,
  20135. * opacity: <float>,
  20136. *
  20137. * matcap: new THREE.Texture( <Image> ),
  20138. *
  20139. * map: new THREE.Texture( <Image> ),
  20140. *
  20141. * bumpMap: new THREE.Texture( <Image> ),
  20142. * bumpScale: <float>,
  20143. *
  20144. * normalMap: new THREE.Texture( <Image> ),
  20145. * normalMapType: THREE.TangentSpaceNormalMap,
  20146. * normalScale: <Vector2>,
  20147. *
  20148. * displacementMap: new THREE.Texture( <Image> ),
  20149. * displacementScale: <float>,
  20150. * displacementBias: <float>,
  20151. *
  20152. * alphaMap: new THREE.Texture( <Image> ),
  20153. *
  20154. * morphTargets: <bool>,
  20155. * morphNormals: <bool>
  20156. *
  20157. * flatShading: <bool>
  20158. * }
  20159. */
  20160. class MeshMatcapMaterial extends Material {
  20161. constructor(parameters) {
  20162. super();
  20163. this.defines = {
  20164. 'MATCAP': ''
  20165. };
  20166. this.type = 'MeshMatcapMaterial';
  20167. this.color = new Color(0xffffff); // diffuse
  20168. this.matcap = null;
  20169. this.map = null;
  20170. this.bumpMap = null;
  20171. this.bumpScale = 1;
  20172. this.normalMap = null;
  20173. this.normalMapType = TangentSpaceNormalMap;
  20174. this.normalScale = new Vector2(1, 1);
  20175. this.displacementMap = null;
  20176. this.displacementScale = 1;
  20177. this.displacementBias = 0;
  20178. this.alphaMap = null;
  20179. this.morphTargets = false;
  20180. this.morphNormals = false;
  20181. this.flatShading = false;
  20182. this.setValues(parameters);
  20183. }
  20184. copy(source) {
  20185. super.copy(source);
  20186. this.defines = {
  20187. 'MATCAP': ''
  20188. };
  20189. this.color.copy(source.color);
  20190. this.matcap = source.matcap;
  20191. this.map = source.map;
  20192. this.bumpMap = source.bumpMap;
  20193. this.bumpScale = source.bumpScale;
  20194. this.normalMap = source.normalMap;
  20195. this.normalMapType = source.normalMapType;
  20196. this.normalScale.copy(source.normalScale);
  20197. this.displacementMap = source.displacementMap;
  20198. this.displacementScale = source.displacementScale;
  20199. this.displacementBias = source.displacementBias;
  20200. this.alphaMap = source.alphaMap;
  20201. this.morphTargets = source.morphTargets;
  20202. this.morphNormals = source.morphNormals;
  20203. this.flatShading = source.flatShading;
  20204. return this;
  20205. }
  20206. }
  20207. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  20208. /**
  20209. * parameters = {
  20210. * color: <hex>,
  20211. * opacity: <float>,
  20212. *
  20213. * linewidth: <float>,
  20214. *
  20215. * scale: <float>,
  20216. * dashSize: <float>,
  20217. * gapSize: <float>
  20218. * }
  20219. */
  20220. class LineDashedMaterial extends LineBasicMaterial {
  20221. constructor(parameters) {
  20222. super();
  20223. this.type = 'LineDashedMaterial';
  20224. this.scale = 1;
  20225. this.dashSize = 3;
  20226. this.gapSize = 1;
  20227. this.setValues(parameters);
  20228. }
  20229. copy(source) {
  20230. super.copy(source);
  20231. this.scale = source.scale;
  20232. this.dashSize = source.dashSize;
  20233. this.gapSize = source.gapSize;
  20234. return this;
  20235. }
  20236. }
  20237. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  20238. var Materials = /*#__PURE__*/Object.freeze({
  20239. __proto__: null,
  20240. ShadowMaterial: ShadowMaterial,
  20241. SpriteMaterial: SpriteMaterial,
  20242. RawShaderMaterial: RawShaderMaterial,
  20243. ShaderMaterial: ShaderMaterial,
  20244. PointsMaterial: PointsMaterial,
  20245. MeshPhysicalMaterial: MeshPhysicalMaterial,
  20246. MeshStandardMaterial: MeshStandardMaterial,
  20247. MeshPhongMaterial: MeshPhongMaterial,
  20248. MeshToonMaterial: MeshToonMaterial,
  20249. MeshNormalMaterial: MeshNormalMaterial,
  20250. MeshLambertMaterial: MeshLambertMaterial,
  20251. MeshDepthMaterial: MeshDepthMaterial,
  20252. MeshDistanceMaterial: MeshDistanceMaterial,
  20253. MeshBasicMaterial: MeshBasicMaterial,
  20254. MeshMatcapMaterial: MeshMatcapMaterial,
  20255. LineDashedMaterial: LineDashedMaterial,
  20256. LineBasicMaterial: LineBasicMaterial,
  20257. Material: Material
  20258. });
  20259. const AnimationUtils = {
  20260. // same as Array.prototype.slice, but also works on typed arrays
  20261. arraySlice: function (array, from, to) {
  20262. if (AnimationUtils.isTypedArray(array)) {
  20263. // in ios9 array.subarray(from, undefined) will return empty array
  20264. // but array.subarray(from) or array.subarray(from, len) is correct
  20265. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  20266. }
  20267. return array.slice(from, to);
  20268. },
  20269. // converts an array to a specific type
  20270. convertArray: function (array, type, forceClone) {
  20271. if (!array || // let 'undefined' and 'null' pass
  20272. !forceClone && array.constructor === type) return array;
  20273. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  20274. return new type(array); // create typed array
  20275. }
  20276. return Array.prototype.slice.call(array); // create Array
  20277. },
  20278. isTypedArray: function (object) {
  20279. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  20280. },
  20281. // returns an array by which times and values can be sorted
  20282. getKeyframeOrder: function (times) {
  20283. function compareTime(i, j) {
  20284. return times[i] - times[j];
  20285. }
  20286. const n = times.length;
  20287. const result = new Array(n);
  20288. for (let i = 0; i !== n; ++i) result[i] = i;
  20289. result.sort(compareTime);
  20290. return result;
  20291. },
  20292. // uses the array previously returned by 'getKeyframeOrder' to sort data
  20293. sortedArray: function (values, stride, order) {
  20294. const nValues = values.length;
  20295. const result = new values.constructor(nValues);
  20296. for (let i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  20297. const srcOffset = order[i] * stride;
  20298. for (let j = 0; j !== stride; ++j) {
  20299. result[dstOffset++] = values[srcOffset + j];
  20300. }
  20301. }
  20302. return result;
  20303. },
  20304. // function for parsing AOS keyframe formats
  20305. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  20306. let i = 1,
  20307. key = jsonKeys[0];
  20308. while (key !== undefined && key[valuePropertyName] === undefined) {
  20309. key = jsonKeys[i++];
  20310. }
  20311. if (key === undefined) return; // no data
  20312. let value = key[valuePropertyName];
  20313. if (value === undefined) return; // no data
  20314. if (Array.isArray(value)) {
  20315. do {
  20316. value = key[valuePropertyName];
  20317. if (value !== undefined) {
  20318. times.push(key.time);
  20319. values.push.apply(values, value); // push all elements
  20320. }
  20321. key = jsonKeys[i++];
  20322. } while (key !== undefined);
  20323. } else if (value.toArray !== undefined) {
  20324. // ...assume THREE.Math-ish
  20325. do {
  20326. value = key[valuePropertyName];
  20327. if (value !== undefined) {
  20328. times.push(key.time);
  20329. value.toArray(values, values.length);
  20330. }
  20331. key = jsonKeys[i++];
  20332. } while (key !== undefined);
  20333. } else {
  20334. // otherwise push as-is
  20335. do {
  20336. value = key[valuePropertyName];
  20337. if (value !== undefined) {
  20338. times.push(key.time);
  20339. values.push(value);
  20340. }
  20341. key = jsonKeys[i++];
  20342. } while (key !== undefined);
  20343. }
  20344. },
  20345. subclip: function (sourceClip, name, startFrame, endFrame, fps = 30) {
  20346. const clip = sourceClip.clone();
  20347. clip.name = name;
  20348. const tracks = [];
  20349. for (let i = 0; i < clip.tracks.length; ++i) {
  20350. const track = clip.tracks[i];
  20351. const valueSize = track.getValueSize();
  20352. const times = [];
  20353. const values = [];
  20354. for (let j = 0; j < track.times.length; ++j) {
  20355. const frame = track.times[j] * fps;
  20356. if (frame < startFrame || frame >= endFrame) continue;
  20357. times.push(track.times[j]);
  20358. for (let k = 0; k < valueSize; ++k) {
  20359. values.push(track.values[j * valueSize + k]);
  20360. }
  20361. }
  20362. if (times.length === 0) continue;
  20363. track.times = AnimationUtils.convertArray(times, track.times.constructor);
  20364. track.values = AnimationUtils.convertArray(values, track.values.constructor);
  20365. tracks.push(track);
  20366. }
  20367. clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
  20368. let minStartTime = Infinity;
  20369. for (let i = 0; i < clip.tracks.length; ++i) {
  20370. if (minStartTime > clip.tracks[i].times[0]) {
  20371. minStartTime = clip.tracks[i].times[0];
  20372. }
  20373. } // shift all tracks such that clip begins at t=0
  20374. for (let i = 0; i < clip.tracks.length; ++i) {
  20375. clip.tracks[i].shift(-1 * minStartTime);
  20376. }
  20377. clip.resetDuration();
  20378. return clip;
  20379. },
  20380. makeClipAdditive: function (targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) {
  20381. if (fps <= 0) fps = 30;
  20382. const numTracks = referenceClip.tracks.length;
  20383. const referenceTime = referenceFrame / fps; // Make each track's values relative to the values at the reference frame
  20384. for (let i = 0; i < numTracks; ++i) {
  20385. const referenceTrack = referenceClip.tracks[i];
  20386. const referenceTrackType = referenceTrack.ValueTypeName; // Skip this track if it's non-numeric
  20387. if (referenceTrackType === 'bool' || referenceTrackType === 'string') continue; // Find the track in the target clip whose name and type matches the reference track
  20388. const targetTrack = targetClip.tracks.find(function (track) {
  20389. return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
  20390. });
  20391. if (targetTrack === undefined) continue;
  20392. let referenceOffset = 0;
  20393. const referenceValueSize = referenceTrack.getValueSize();
  20394. if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  20395. referenceOffset = referenceValueSize / 3;
  20396. }
  20397. let targetOffset = 0;
  20398. const targetValueSize = targetTrack.getValueSize();
  20399. if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  20400. targetOffset = targetValueSize / 3;
  20401. }
  20402. const lastIndex = referenceTrack.times.length - 1;
  20403. let referenceValue; // Find the value to subtract out of the track
  20404. if (referenceTime <= referenceTrack.times[0]) {
  20405. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  20406. const startIndex = referenceOffset;
  20407. const endIndex = referenceValueSize - referenceOffset;
  20408. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  20409. } else if (referenceTime >= referenceTrack.times[lastIndex]) {
  20410. // Reference frame is after the last keyframe, so just use the last keyframe
  20411. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  20412. const endIndex = startIndex + referenceValueSize - referenceOffset;
  20413. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  20414. } else {
  20415. // Interpolate to the reference value
  20416. const interpolant = referenceTrack.createInterpolant();
  20417. const startIndex = referenceOffset;
  20418. const endIndex = referenceValueSize - referenceOffset;
  20419. interpolant.evaluate(referenceTime);
  20420. referenceValue = AnimationUtils.arraySlice(interpolant.resultBuffer, startIndex, endIndex);
  20421. } // Conjugate the quaternion
  20422. if (referenceTrackType === 'quaternion') {
  20423. const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
  20424. referenceQuat.toArray(referenceValue);
  20425. } // Subtract the reference value from all of the track values
  20426. const numTimes = targetTrack.times.length;
  20427. for (let j = 0; j < numTimes; ++j) {
  20428. const valueStart = j * targetValueSize + targetOffset;
  20429. if (referenceTrackType === 'quaternion') {
  20430. // Multiply the conjugate for quaternion track types
  20431. Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
  20432. } else {
  20433. const valueEnd = targetValueSize - targetOffset * 2; // Subtract each value for all other numeric track types
  20434. for (let k = 0; k < valueEnd; ++k) {
  20435. targetTrack.values[valueStart + k] -= referenceValue[k];
  20436. }
  20437. }
  20438. }
  20439. }
  20440. targetClip.blendMode = AdditiveAnimationBlendMode;
  20441. return targetClip;
  20442. }
  20443. };
  20444. /**
  20445. * Abstract base class of interpolants over parametric samples.
  20446. *
  20447. * The parameter domain is one dimensional, typically the time or a path
  20448. * along a curve defined by the data.
  20449. *
  20450. * The sample values can have any dimensionality and derived classes may
  20451. * apply special interpretations to the data.
  20452. *
  20453. * This class provides the interval seek in a Template Method, deferring
  20454. * the actual interpolation to derived classes.
  20455. *
  20456. * Time complexity is O(1) for linear access crossing at most two points
  20457. * and O(log N) for random access, where N is the number of positions.
  20458. *
  20459. * References:
  20460. *
  20461. * http://www.oodesign.com/template-method-pattern.html
  20462. *
  20463. */
  20464. class Interpolant {
  20465. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20466. this.parameterPositions = parameterPositions;
  20467. this._cachedIndex = 0;
  20468. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  20469. this.sampleValues = sampleValues;
  20470. this.valueSize = sampleSize;
  20471. this.settings = null;
  20472. this.DefaultSettings_ = {};
  20473. }
  20474. evaluate(t) {
  20475. const pp = this.parameterPositions;
  20476. let i1 = this._cachedIndex,
  20477. t1 = pp[i1],
  20478. t0 = pp[i1 - 1];
  20479. validate_interval: {
  20480. seek: {
  20481. let right;
  20482. linear_scan: {
  20483. //- See http://jsperf.com/comparison-to-undefined/3
  20484. //- slower code:
  20485. //-
  20486. //- if ( t >= t1 || t1 === undefined ) {
  20487. forward_scan: if (!(t < t1)) {
  20488. for (let giveUpAt = i1 + 2;;) {
  20489. if (t1 === undefined) {
  20490. if (t < t0) break forward_scan; // after end
  20491. i1 = pp.length;
  20492. this._cachedIndex = i1;
  20493. return this.afterEnd_(i1 - 1, t, t0);
  20494. }
  20495. if (i1 === giveUpAt) break; // this loop
  20496. t0 = t1;
  20497. t1 = pp[++i1];
  20498. if (t < t1) {
  20499. // we have arrived at the sought interval
  20500. break seek;
  20501. }
  20502. } // prepare binary search on the right side of the index
  20503. right = pp.length;
  20504. break linear_scan;
  20505. } //- slower code:
  20506. //- if ( t < t0 || t0 === undefined ) {
  20507. if (!(t >= t0)) {
  20508. // looping?
  20509. const t1global = pp[1];
  20510. if (t < t1global) {
  20511. i1 = 2; // + 1, using the scan for the details
  20512. t0 = t1global;
  20513. } // linear reverse scan
  20514. for (let giveUpAt = i1 - 2;;) {
  20515. if (t0 === undefined) {
  20516. // before start
  20517. this._cachedIndex = 0;
  20518. return this.beforeStart_(0, t, t1);
  20519. }
  20520. if (i1 === giveUpAt) break; // this loop
  20521. t1 = t0;
  20522. t0 = pp[--i1 - 1];
  20523. if (t >= t0) {
  20524. // we have arrived at the sought interval
  20525. break seek;
  20526. }
  20527. } // prepare binary search on the left side of the index
  20528. right = i1;
  20529. i1 = 0;
  20530. break linear_scan;
  20531. } // the interval is valid
  20532. break validate_interval;
  20533. } // linear scan
  20534. // binary search
  20535. while (i1 < right) {
  20536. const mid = i1 + right >>> 1;
  20537. if (t < pp[mid]) {
  20538. right = mid;
  20539. } else {
  20540. i1 = mid + 1;
  20541. }
  20542. }
  20543. t1 = pp[i1];
  20544. t0 = pp[i1 - 1]; // check boundary cases, again
  20545. if (t0 === undefined) {
  20546. this._cachedIndex = 0;
  20547. return this.beforeStart_(0, t, t1);
  20548. }
  20549. if (t1 === undefined) {
  20550. i1 = pp.length;
  20551. this._cachedIndex = i1;
  20552. return this.afterEnd_(i1 - 1, t0, t);
  20553. }
  20554. } // seek
  20555. this._cachedIndex = i1;
  20556. this.intervalChanged_(i1, t0, t1);
  20557. } // validate_interval
  20558. return this.interpolate_(i1, t0, t, t1);
  20559. }
  20560. getSettings_() {
  20561. return this.settings || this.DefaultSettings_;
  20562. }
  20563. copySampleValue_(index) {
  20564. // copies a sample value to the result buffer
  20565. const result = this.resultBuffer,
  20566. values = this.sampleValues,
  20567. stride = this.valueSize,
  20568. offset = index * stride;
  20569. for (let i = 0; i !== stride; ++i) {
  20570. result[i] = values[offset + i];
  20571. }
  20572. return result;
  20573. } // Template methods for derived classes:
  20574. interpolate_()
  20575. /* i1, t0, t, t1 */
  20576. {
  20577. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  20578. }
  20579. intervalChanged_()
  20580. /* i1, t0, t1 */
  20581. {// empty
  20582. }
  20583. } // ALIAS DEFINITIONS
  20584. Interpolant.prototype.beforeStart_ = Interpolant.prototype.copySampleValue_;
  20585. Interpolant.prototype.afterEnd_ = Interpolant.prototype.copySampleValue_;
  20586. /**
  20587. * Fast and simple cubic spline interpolant.
  20588. *
  20589. * It was derived from a Hermitian construction setting the first derivative
  20590. * at each sample position to the linear slope between neighboring positions
  20591. * over their parameter interval.
  20592. */
  20593. class CubicInterpolant extends Interpolant {
  20594. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20595. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  20596. this._weightPrev = -0;
  20597. this._offsetPrev = -0;
  20598. this._weightNext = -0;
  20599. this._offsetNext = -0;
  20600. this.DefaultSettings_ = {
  20601. endingStart: ZeroCurvatureEnding,
  20602. endingEnd: ZeroCurvatureEnding
  20603. };
  20604. }
  20605. intervalChanged_(i1, t0, t1) {
  20606. const pp = this.parameterPositions;
  20607. let iPrev = i1 - 2,
  20608. iNext = i1 + 1,
  20609. tPrev = pp[iPrev],
  20610. tNext = pp[iNext];
  20611. if (tPrev === undefined) {
  20612. switch (this.getSettings_().endingStart) {
  20613. case ZeroSlopeEnding:
  20614. // f'(t0) = 0
  20615. iPrev = i1;
  20616. tPrev = 2 * t0 - t1;
  20617. break;
  20618. case WrapAroundEnding:
  20619. // use the other end of the curve
  20620. iPrev = pp.length - 2;
  20621. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  20622. break;
  20623. default:
  20624. // ZeroCurvatureEnding
  20625. // f''(t0) = 0 a.k.a. Natural Spline
  20626. iPrev = i1;
  20627. tPrev = t1;
  20628. }
  20629. }
  20630. if (tNext === undefined) {
  20631. switch (this.getSettings_().endingEnd) {
  20632. case ZeroSlopeEnding:
  20633. // f'(tN) = 0
  20634. iNext = i1;
  20635. tNext = 2 * t1 - t0;
  20636. break;
  20637. case WrapAroundEnding:
  20638. // use the other end of the curve
  20639. iNext = 1;
  20640. tNext = t1 + pp[1] - pp[0];
  20641. break;
  20642. default:
  20643. // ZeroCurvatureEnding
  20644. // f''(tN) = 0, a.k.a. Natural Spline
  20645. iNext = i1 - 1;
  20646. tNext = t0;
  20647. }
  20648. }
  20649. const halfDt = (t1 - t0) * 0.5,
  20650. stride = this.valueSize;
  20651. this._weightPrev = halfDt / (t0 - tPrev);
  20652. this._weightNext = halfDt / (tNext - t1);
  20653. this._offsetPrev = iPrev * stride;
  20654. this._offsetNext = iNext * stride;
  20655. }
  20656. interpolate_(i1, t0, t, t1) {
  20657. const result = this.resultBuffer,
  20658. values = this.sampleValues,
  20659. stride = this.valueSize,
  20660. o1 = i1 * stride,
  20661. o0 = o1 - stride,
  20662. oP = this._offsetPrev,
  20663. oN = this._offsetNext,
  20664. wP = this._weightPrev,
  20665. wN = this._weightNext,
  20666. p = (t - t0) / (t1 - t0),
  20667. pp = p * p,
  20668. ppp = pp * p; // evaluate polynomials
  20669. const sP = -wP * ppp + 2 * wP * pp - wP * p;
  20670. const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  20671. const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  20672. const sN = wN * ppp - wN * pp; // combine data linearly
  20673. for (let i = 0; i !== stride; ++i) {
  20674. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  20675. }
  20676. return result;
  20677. }
  20678. }
  20679. class LinearInterpolant extends Interpolant {
  20680. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20681. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  20682. }
  20683. interpolate_(i1, t0, t, t1) {
  20684. const result = this.resultBuffer,
  20685. values = this.sampleValues,
  20686. stride = this.valueSize,
  20687. offset1 = i1 * stride,
  20688. offset0 = offset1 - stride,
  20689. weight1 = (t - t0) / (t1 - t0),
  20690. weight0 = 1 - weight1;
  20691. for (let i = 0; i !== stride; ++i) {
  20692. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  20693. }
  20694. return result;
  20695. }
  20696. }
  20697. /**
  20698. *
  20699. * Interpolant that evaluates to the sample value at the position preceeding
  20700. * the parameter.
  20701. */
  20702. class DiscreteInterpolant extends Interpolant {
  20703. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20704. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  20705. }
  20706. interpolate_(i1
  20707. /*, t0, t, t1 */
  20708. ) {
  20709. return this.copySampleValue_(i1 - 1);
  20710. }
  20711. }
  20712. class KeyframeTrack {
  20713. constructor(name, times, values, interpolation) {
  20714. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  20715. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  20716. this.name = name;
  20717. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  20718. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  20719. this.setInterpolation(interpolation || this.DefaultInterpolation);
  20720. } // Serialization (in static context, because of constructor invocation
  20721. // and automatic invocation of .toJSON):
  20722. static toJSON(track) {
  20723. const trackType = track.constructor;
  20724. let json; // derived classes can define a static toJSON method
  20725. if (trackType.toJSON !== this.toJSON) {
  20726. json = trackType.toJSON(track);
  20727. } else {
  20728. // by default, we assume the data can be serialized as-is
  20729. json = {
  20730. 'name': track.name,
  20731. 'times': AnimationUtils.convertArray(track.times, Array),
  20732. 'values': AnimationUtils.convertArray(track.values, Array)
  20733. };
  20734. const interpolation = track.getInterpolation();
  20735. if (interpolation !== track.DefaultInterpolation) {
  20736. json.interpolation = interpolation;
  20737. }
  20738. }
  20739. json.type = track.ValueTypeName; // mandatory
  20740. return json;
  20741. }
  20742. InterpolantFactoryMethodDiscrete(result) {
  20743. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  20744. }
  20745. InterpolantFactoryMethodLinear(result) {
  20746. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  20747. }
  20748. InterpolantFactoryMethodSmooth(result) {
  20749. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  20750. }
  20751. setInterpolation(interpolation) {
  20752. let factoryMethod;
  20753. switch (interpolation) {
  20754. case InterpolateDiscrete:
  20755. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  20756. break;
  20757. case InterpolateLinear:
  20758. factoryMethod = this.InterpolantFactoryMethodLinear;
  20759. break;
  20760. case InterpolateSmooth:
  20761. factoryMethod = this.InterpolantFactoryMethodSmooth;
  20762. break;
  20763. }
  20764. if (factoryMethod === undefined) {
  20765. const message = 'unsupported interpolation for ' + this.ValueTypeName + ' keyframe track named ' + this.name;
  20766. if (this.createInterpolant === undefined) {
  20767. // fall back to default, unless the default itself is messed up
  20768. if (interpolation !== this.DefaultInterpolation) {
  20769. this.setInterpolation(this.DefaultInterpolation);
  20770. } else {
  20771. throw new Error(message); // fatal, in this case
  20772. }
  20773. }
  20774. console.warn('THREE.KeyframeTrack:', message);
  20775. return this;
  20776. }
  20777. this.createInterpolant = factoryMethod;
  20778. return this;
  20779. }
  20780. getInterpolation() {
  20781. switch (this.createInterpolant) {
  20782. case this.InterpolantFactoryMethodDiscrete:
  20783. return InterpolateDiscrete;
  20784. case this.InterpolantFactoryMethodLinear:
  20785. return InterpolateLinear;
  20786. case this.InterpolantFactoryMethodSmooth:
  20787. return InterpolateSmooth;
  20788. }
  20789. }
  20790. getValueSize() {
  20791. return this.values.length / this.times.length;
  20792. } // move all keyframes either forwards or backwards in time
  20793. shift(timeOffset) {
  20794. if (timeOffset !== 0.0) {
  20795. const times = this.times;
  20796. for (let i = 0, n = times.length; i !== n; ++i) {
  20797. times[i] += timeOffset;
  20798. }
  20799. }
  20800. return this;
  20801. } // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  20802. scale(timeScale) {
  20803. if (timeScale !== 1.0) {
  20804. const times = this.times;
  20805. for (let i = 0, n = times.length; i !== n; ++i) {
  20806. times[i] *= timeScale;
  20807. }
  20808. }
  20809. return this;
  20810. } // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  20811. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  20812. trim(startTime, endTime) {
  20813. const times = this.times,
  20814. nKeys = times.length;
  20815. let from = 0,
  20816. to = nKeys - 1;
  20817. while (from !== nKeys && times[from] < startTime) {
  20818. ++from;
  20819. }
  20820. while (to !== -1 && times[to] > endTime) {
  20821. --to;
  20822. }
  20823. ++to; // inclusive -> exclusive bound
  20824. if (from !== 0 || to !== nKeys) {
  20825. // empty tracks are forbidden, so keep at least one keyframe
  20826. if (from >= to) {
  20827. to = Math.max(to, 1);
  20828. from = to - 1;
  20829. }
  20830. const stride = this.getValueSize();
  20831. this.times = AnimationUtils.arraySlice(times, from, to);
  20832. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  20833. }
  20834. return this;
  20835. } // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  20836. validate() {
  20837. let valid = true;
  20838. const valueSize = this.getValueSize();
  20839. if (valueSize - Math.floor(valueSize) !== 0) {
  20840. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  20841. valid = false;
  20842. }
  20843. const times = this.times,
  20844. values = this.values,
  20845. nKeys = times.length;
  20846. if (nKeys === 0) {
  20847. console.error('THREE.KeyframeTrack: Track is empty.', this);
  20848. valid = false;
  20849. }
  20850. let prevTime = null;
  20851. for (let i = 0; i !== nKeys; i++) {
  20852. const currTime = times[i];
  20853. if (typeof currTime === 'number' && isNaN(currTime)) {
  20854. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  20855. valid = false;
  20856. break;
  20857. }
  20858. if (prevTime !== null && prevTime > currTime) {
  20859. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  20860. valid = false;
  20861. break;
  20862. }
  20863. prevTime = currTime;
  20864. }
  20865. if (values !== undefined) {
  20866. if (AnimationUtils.isTypedArray(values)) {
  20867. for (let i = 0, n = values.length; i !== n; ++i) {
  20868. const value = values[i];
  20869. if (isNaN(value)) {
  20870. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  20871. valid = false;
  20872. break;
  20873. }
  20874. }
  20875. }
  20876. }
  20877. return valid;
  20878. } // removes equivalent sequential keys as common in morph target sequences
  20879. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  20880. optimize() {
  20881. // times or values may be shared with other tracks, so overwriting is unsafe
  20882. const times = AnimationUtils.arraySlice(this.times),
  20883. values = AnimationUtils.arraySlice(this.values),
  20884. stride = this.getValueSize(),
  20885. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  20886. lastIndex = times.length - 1;
  20887. let writeIndex = 1;
  20888. for (let i = 1; i < lastIndex; ++i) {
  20889. let keep = false;
  20890. const time = times[i];
  20891. const timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  20892. if (time !== timeNext && (i !== 1 || time !== times[0])) {
  20893. if (!smoothInterpolation) {
  20894. // remove unnecessary keyframes same as their neighbors
  20895. const offset = i * stride,
  20896. offsetP = offset - stride,
  20897. offsetN = offset + stride;
  20898. for (let j = 0; j !== stride; ++j) {
  20899. const value = values[offset + j];
  20900. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  20901. keep = true;
  20902. break;
  20903. }
  20904. }
  20905. } else {
  20906. keep = true;
  20907. }
  20908. } // in-place compaction
  20909. if (keep) {
  20910. if (i !== writeIndex) {
  20911. times[writeIndex] = times[i];
  20912. const readOffset = i * stride,
  20913. writeOffset = writeIndex * stride;
  20914. for (let j = 0; j !== stride; ++j) {
  20915. values[writeOffset + j] = values[readOffset + j];
  20916. }
  20917. }
  20918. ++writeIndex;
  20919. }
  20920. } // flush last keyframe (compaction looks ahead)
  20921. if (lastIndex > 0) {
  20922. times[writeIndex] = times[lastIndex];
  20923. for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  20924. values[writeOffset + j] = values[readOffset + j];
  20925. }
  20926. ++writeIndex;
  20927. }
  20928. if (writeIndex !== times.length) {
  20929. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  20930. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  20931. } else {
  20932. this.times = times;
  20933. this.values = values;
  20934. }
  20935. return this;
  20936. }
  20937. clone() {
  20938. const times = AnimationUtils.arraySlice(this.times, 0);
  20939. const values = AnimationUtils.arraySlice(this.values, 0);
  20940. const TypedKeyframeTrack = this.constructor;
  20941. const track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  20942. track.createInterpolant = this.createInterpolant;
  20943. return track;
  20944. }
  20945. }
  20946. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  20947. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  20948. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  20949. /**
  20950. * A Track of Boolean keyframe values.
  20951. */
  20952. class BooleanKeyframeTrack extends KeyframeTrack {}
  20953. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  20954. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  20955. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  20956. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  20957. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; // Note: Actually this track could have a optimized / compressed
  20958. /**
  20959. * A Track of keyframe values that represent color.
  20960. */
  20961. class ColorKeyframeTrack extends KeyframeTrack {}
  20962. ColorKeyframeTrack.prototype.ValueTypeName = 'color'; // ValueBufferType is inherited
  20963. /**
  20964. * A Track of numeric keyframe values.
  20965. */
  20966. class NumberKeyframeTrack extends KeyframeTrack {}
  20967. NumberKeyframeTrack.prototype.ValueTypeName = 'number'; // ValueBufferType is inherited
  20968. /**
  20969. * Spherical linear unit quaternion interpolant.
  20970. */
  20971. class QuaternionLinearInterpolant extends Interpolant {
  20972. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20973. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  20974. }
  20975. interpolate_(i1, t0, t, t1) {
  20976. const result = this.resultBuffer,
  20977. values = this.sampleValues,
  20978. stride = this.valueSize,
  20979. alpha = (t - t0) / (t1 - t0);
  20980. let offset = i1 * stride;
  20981. for (let end = offset + stride; offset !== end; offset += 4) {
  20982. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  20983. }
  20984. return result;
  20985. }
  20986. }
  20987. /**
  20988. * A Track of quaternion keyframe values.
  20989. */
  20990. class QuaternionKeyframeTrack extends KeyframeTrack {
  20991. InterpolantFactoryMethodLinear(result) {
  20992. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  20993. }
  20994. }
  20995. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion'; // ValueBufferType is inherited
  20996. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  20997. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  20998. /**
  20999. * A Track that interpolates Strings
  21000. */
  21001. class StringKeyframeTrack extends KeyframeTrack {}
  21002. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  21003. StringKeyframeTrack.prototype.ValueBufferType = Array;
  21004. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  21005. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  21006. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  21007. /**
  21008. * A Track of vectored keyframe values.
  21009. */
  21010. class VectorKeyframeTrack extends KeyframeTrack {}
  21011. VectorKeyframeTrack.prototype.ValueTypeName = 'vector'; // ValueBufferType is inherited
  21012. class AnimationClip {
  21013. constructor(name, duration = -1, tracks, blendMode = NormalAnimationBlendMode) {
  21014. this.name = name;
  21015. this.tracks = tracks;
  21016. this.duration = duration;
  21017. this.blendMode = blendMode;
  21018. this.uuid = generateUUID(); // this means it should figure out its duration by scanning the tracks
  21019. if (this.duration < 0) {
  21020. this.resetDuration();
  21021. }
  21022. }
  21023. static parse(json) {
  21024. const tracks = [],
  21025. jsonTracks = json.tracks,
  21026. frameTime = 1.0 / (json.fps || 1.0);
  21027. for (let i = 0, n = jsonTracks.length; i !== n; ++i) {
  21028. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  21029. }
  21030. const clip = new this(json.name, json.duration, tracks, json.blendMode);
  21031. clip.uuid = json.uuid;
  21032. return clip;
  21033. }
  21034. static toJSON(clip) {
  21035. const tracks = [],
  21036. clipTracks = clip.tracks;
  21037. const json = {
  21038. 'name': clip.name,
  21039. 'duration': clip.duration,
  21040. 'tracks': tracks,
  21041. 'uuid': clip.uuid,
  21042. 'blendMode': clip.blendMode
  21043. };
  21044. for (let i = 0, n = clipTracks.length; i !== n; ++i) {
  21045. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  21046. }
  21047. return json;
  21048. }
  21049. static CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) {
  21050. const numMorphTargets = morphTargetSequence.length;
  21051. const tracks = [];
  21052. for (let i = 0; i < numMorphTargets; i++) {
  21053. let times = [];
  21054. let values = [];
  21055. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  21056. values.push(0, 1, 0);
  21057. const order = AnimationUtils.getKeyframeOrder(times);
  21058. times = AnimationUtils.sortedArray(times, 1, order);
  21059. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  21060. // last frame as well for perfect loop.
  21061. if (!noLoop && times[0] === 0) {
  21062. times.push(numMorphTargets);
  21063. values.push(values[0]);
  21064. }
  21065. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  21066. }
  21067. return new this(name, -1, tracks);
  21068. }
  21069. static findByName(objectOrClipArray, name) {
  21070. let clipArray = objectOrClipArray;
  21071. if (!Array.isArray(objectOrClipArray)) {
  21072. const o = objectOrClipArray;
  21073. clipArray = o.geometry && o.geometry.animations || o.animations;
  21074. }
  21075. for (let i = 0; i < clipArray.length; i++) {
  21076. if (clipArray[i].name === name) {
  21077. return clipArray[i];
  21078. }
  21079. }
  21080. return null;
  21081. }
  21082. static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {
  21083. const animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  21084. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  21085. const pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  21086. // patterns like Walk_001, Walk_002, Run_001, Run_002
  21087. for (let i = 0, il = morphTargets.length; i < il; i++) {
  21088. const morphTarget = morphTargets[i];
  21089. const parts = morphTarget.name.match(pattern);
  21090. if (parts && parts.length > 1) {
  21091. const name = parts[1];
  21092. let animationMorphTargets = animationToMorphTargets[name];
  21093. if (!animationMorphTargets) {
  21094. animationToMorphTargets[name] = animationMorphTargets = [];
  21095. }
  21096. animationMorphTargets.push(morphTarget);
  21097. }
  21098. }
  21099. const clips = [];
  21100. for (const name in animationToMorphTargets) {
  21101. clips.push(this.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  21102. }
  21103. return clips;
  21104. } // parse the animation.hierarchy format
  21105. static parseAnimation(animation, bones) {
  21106. if (!animation) {
  21107. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  21108. return null;
  21109. }
  21110. const addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  21111. // only return track if there are actually keys.
  21112. if (animationKeys.length !== 0) {
  21113. const times = [];
  21114. const values = [];
  21115. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  21116. if (times.length !== 0) {
  21117. destTracks.push(new trackType(trackName, times, values));
  21118. }
  21119. }
  21120. };
  21121. const tracks = [];
  21122. const clipName = animation.name || 'default';
  21123. const fps = animation.fps || 30;
  21124. const blendMode = animation.blendMode; // automatic length determination in AnimationClip.
  21125. let duration = animation.length || -1;
  21126. const hierarchyTracks = animation.hierarchy || [];
  21127. for (let h = 0; h < hierarchyTracks.length; h++) {
  21128. const animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  21129. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  21130. if (animationKeys[0].morphTargets) {
  21131. // figure out all morph targets used in this track
  21132. const morphTargetNames = {};
  21133. let k;
  21134. for (k = 0; k < animationKeys.length; k++) {
  21135. if (animationKeys[k].morphTargets) {
  21136. for (let m = 0; m < animationKeys[k].morphTargets.length; m++) {
  21137. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  21138. }
  21139. }
  21140. } // create a track for each morph target with all zero
  21141. // morphTargetInfluences except for the keys in which
  21142. // the morphTarget is named.
  21143. for (const morphTargetName in morphTargetNames) {
  21144. const times = [];
  21145. const values = [];
  21146. for (let m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  21147. const animationKey = animationKeys[k];
  21148. times.push(animationKey.time);
  21149. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  21150. }
  21151. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  21152. }
  21153. duration = morphTargetNames.length * (fps || 1.0);
  21154. } else {
  21155. // ...assume skeletal animation
  21156. const boneName = '.bones[' + bones[h].name + ']';
  21157. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  21158. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  21159. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  21160. }
  21161. }
  21162. if (tracks.length === 0) {
  21163. return null;
  21164. }
  21165. const clip = new this(clipName, duration, tracks, blendMode);
  21166. return clip;
  21167. }
  21168. resetDuration() {
  21169. const tracks = this.tracks;
  21170. let duration = 0;
  21171. for (let i = 0, n = tracks.length; i !== n; ++i) {
  21172. const track = this.tracks[i];
  21173. duration = Math.max(duration, track.times[track.times.length - 1]);
  21174. }
  21175. this.duration = duration;
  21176. return this;
  21177. }
  21178. trim() {
  21179. for (let i = 0; i < this.tracks.length; i++) {
  21180. this.tracks[i].trim(0, this.duration);
  21181. }
  21182. return this;
  21183. }
  21184. validate() {
  21185. let valid = true;
  21186. for (let i = 0; i < this.tracks.length; i++) {
  21187. valid = valid && this.tracks[i].validate();
  21188. }
  21189. return valid;
  21190. }
  21191. optimize() {
  21192. for (let i = 0; i < this.tracks.length; i++) {
  21193. this.tracks[i].optimize();
  21194. }
  21195. return this;
  21196. }
  21197. clone() {
  21198. const tracks = [];
  21199. for (let i = 0; i < this.tracks.length; i++) {
  21200. tracks.push(this.tracks[i].clone());
  21201. }
  21202. return new this.constructor(this.name, this.duration, tracks, this.blendMode);
  21203. }
  21204. toJSON() {
  21205. return this.constructor.toJSON(this);
  21206. }
  21207. }
  21208. function getTrackTypeForValueTypeName(typeName) {
  21209. switch (typeName.toLowerCase()) {
  21210. case 'scalar':
  21211. case 'double':
  21212. case 'float':
  21213. case 'number':
  21214. case 'integer':
  21215. return NumberKeyframeTrack;
  21216. case 'vector':
  21217. case 'vector2':
  21218. case 'vector3':
  21219. case 'vector4':
  21220. return VectorKeyframeTrack;
  21221. case 'color':
  21222. return ColorKeyframeTrack;
  21223. case 'quaternion':
  21224. return QuaternionKeyframeTrack;
  21225. case 'bool':
  21226. case 'boolean':
  21227. return BooleanKeyframeTrack;
  21228. case 'string':
  21229. return StringKeyframeTrack;
  21230. }
  21231. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  21232. }
  21233. function parseKeyframeTrack(json) {
  21234. if (json.type === undefined) {
  21235. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  21236. }
  21237. const trackType = getTrackTypeForValueTypeName(json.type);
  21238. if (json.times === undefined) {
  21239. const times = [],
  21240. values = [];
  21241. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  21242. json.times = times;
  21243. json.values = values;
  21244. } // derived classes can define a static parse method
  21245. if (trackType.parse !== undefined) {
  21246. return trackType.parse(json);
  21247. } else {
  21248. // by default, we assume a constructor compatible with the base
  21249. return new trackType(json.name, json.times, json.values, json.interpolation);
  21250. }
  21251. }
  21252. const Cache = {
  21253. enabled: false,
  21254. files: {},
  21255. add: function (key, file) {
  21256. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  21257. this.files[key] = file;
  21258. },
  21259. get: function (key) {
  21260. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  21261. return this.files[key];
  21262. },
  21263. remove: function (key) {
  21264. delete this.files[key];
  21265. },
  21266. clear: function () {
  21267. this.files = {};
  21268. }
  21269. };
  21270. class LoadingManager {
  21271. constructor(onLoad, onProgress, onError) {
  21272. const scope = this;
  21273. let isLoading = false;
  21274. let itemsLoaded = 0;
  21275. let itemsTotal = 0;
  21276. let urlModifier = undefined;
  21277. const handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  21278. // in the constructor
  21279. this.onStart = undefined;
  21280. this.onLoad = onLoad;
  21281. this.onProgress = onProgress;
  21282. this.onError = onError;
  21283. this.itemStart = function (url) {
  21284. itemsTotal++;
  21285. if (isLoading === false) {
  21286. if (scope.onStart !== undefined) {
  21287. scope.onStart(url, itemsLoaded, itemsTotal);
  21288. }
  21289. }
  21290. isLoading = true;
  21291. };
  21292. this.itemEnd = function (url) {
  21293. itemsLoaded++;
  21294. if (scope.onProgress !== undefined) {
  21295. scope.onProgress(url, itemsLoaded, itemsTotal);
  21296. }
  21297. if (itemsLoaded === itemsTotal) {
  21298. isLoading = false;
  21299. if (scope.onLoad !== undefined) {
  21300. scope.onLoad();
  21301. }
  21302. }
  21303. };
  21304. this.itemError = function (url) {
  21305. if (scope.onError !== undefined) {
  21306. scope.onError(url);
  21307. }
  21308. };
  21309. this.resolveURL = function (url) {
  21310. if (urlModifier) {
  21311. return urlModifier(url);
  21312. }
  21313. return url;
  21314. };
  21315. this.setURLModifier = function (transform) {
  21316. urlModifier = transform;
  21317. return this;
  21318. };
  21319. this.addHandler = function (regex, loader) {
  21320. handlers.push(regex, loader);
  21321. return this;
  21322. };
  21323. this.removeHandler = function (regex) {
  21324. const index = handlers.indexOf(regex);
  21325. if (index !== -1) {
  21326. handlers.splice(index, 2);
  21327. }
  21328. return this;
  21329. };
  21330. this.getHandler = function (file) {
  21331. for (let i = 0, l = handlers.length; i < l; i += 2) {
  21332. const regex = handlers[i];
  21333. const loader = handlers[i + 1];
  21334. if (regex.global) regex.lastIndex = 0; // see #17920
  21335. if (regex.test(file)) {
  21336. return loader;
  21337. }
  21338. }
  21339. return null;
  21340. };
  21341. }
  21342. }
  21343. const DefaultLoadingManager = new LoadingManager();
  21344. class Loader {
  21345. constructor(manager) {
  21346. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  21347. this.crossOrigin = 'anonymous';
  21348. this.withCredentials = false;
  21349. this.path = '';
  21350. this.resourcePath = '';
  21351. this.requestHeader = {};
  21352. }
  21353. load()
  21354. /* url, onLoad, onProgress, onError */
  21355. {}
  21356. loadAsync(url, onProgress) {
  21357. const scope = this;
  21358. return new Promise(function (resolve, reject) {
  21359. scope.load(url, resolve, onProgress, reject);
  21360. });
  21361. }
  21362. parse()
  21363. /* data */
  21364. {}
  21365. setCrossOrigin(crossOrigin) {
  21366. this.crossOrigin = crossOrigin;
  21367. return this;
  21368. }
  21369. setWithCredentials(value) {
  21370. this.withCredentials = value;
  21371. return this;
  21372. }
  21373. setPath(path) {
  21374. this.path = path;
  21375. return this;
  21376. }
  21377. setResourcePath(resourcePath) {
  21378. this.resourcePath = resourcePath;
  21379. return this;
  21380. }
  21381. setRequestHeader(requestHeader) {
  21382. this.requestHeader = requestHeader;
  21383. return this;
  21384. }
  21385. }
  21386. const loading = {};
  21387. class FileLoader extends Loader {
  21388. constructor(manager) {
  21389. super(manager);
  21390. }
  21391. load(url, onLoad, onProgress, onError) {
  21392. if (url === undefined) url = '';
  21393. if (this.path !== undefined) url = this.path + url;
  21394. url = this.manager.resolveURL(url);
  21395. const scope = this;
  21396. const cached = Cache.get(url);
  21397. if (cached !== undefined) {
  21398. scope.manager.itemStart(url);
  21399. setTimeout(function () {
  21400. if (onLoad) onLoad(cached);
  21401. scope.manager.itemEnd(url);
  21402. }, 0);
  21403. return cached;
  21404. } // Check if request is duplicate
  21405. if (loading[url] !== undefined) {
  21406. loading[url].push({
  21407. onLoad: onLoad,
  21408. onProgress: onProgress,
  21409. onError: onError
  21410. });
  21411. return;
  21412. } // Check for data: URI
  21413. const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  21414. const dataUriRegexResult = url.match(dataUriRegex);
  21415. let request; // Safari can not handle Data URIs through XMLHttpRequest so process manually
  21416. if (dataUriRegexResult) {
  21417. const mimeType = dataUriRegexResult[1];
  21418. const isBase64 = !!dataUriRegexResult[2];
  21419. let data = dataUriRegexResult[3];
  21420. data = decodeURIComponent(data);
  21421. if (isBase64) data = atob(data);
  21422. try {
  21423. let response;
  21424. const responseType = (this.responseType || '').toLowerCase();
  21425. switch (responseType) {
  21426. case 'arraybuffer':
  21427. case 'blob':
  21428. const view = new Uint8Array(data.length);
  21429. for (let i = 0; i < data.length; i++) {
  21430. view[i] = data.charCodeAt(i);
  21431. }
  21432. if (responseType === 'blob') {
  21433. response = new Blob([view.buffer], {
  21434. type: mimeType
  21435. });
  21436. } else {
  21437. response = view.buffer;
  21438. }
  21439. break;
  21440. case 'document':
  21441. const parser = new DOMParser();
  21442. response = parser.parseFromString(data, mimeType);
  21443. break;
  21444. case 'json':
  21445. response = JSON.parse(data);
  21446. break;
  21447. default:
  21448. // 'text' or other
  21449. response = data;
  21450. break;
  21451. } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  21452. setTimeout(function () {
  21453. if (onLoad) onLoad(response);
  21454. scope.manager.itemEnd(url);
  21455. }, 0);
  21456. } catch (error) {
  21457. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  21458. setTimeout(function () {
  21459. if (onError) onError(error);
  21460. scope.manager.itemError(url);
  21461. scope.manager.itemEnd(url);
  21462. }, 0);
  21463. }
  21464. } else {
  21465. // Initialise array for duplicate requests
  21466. loading[url] = [];
  21467. loading[url].push({
  21468. onLoad: onLoad,
  21469. onProgress: onProgress,
  21470. onError: onError
  21471. });
  21472. request = new XMLHttpRequest();
  21473. request.open('GET', url, true);
  21474. request.addEventListener('load', function (event) {
  21475. const response = this.response;
  21476. const callbacks = loading[url];
  21477. delete loading[url];
  21478. if (this.status === 200 || this.status === 0) {
  21479. // Some browsers return HTTP Status 0 when using non-http protocol
  21480. // e.g. 'file://' or 'data://'. Handle as success.
  21481. 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
  21482. // error response bodies as proper responses to requests.
  21483. Cache.add(url, response);
  21484. for (let i = 0, il = callbacks.length; i < il; i++) {
  21485. const callback = callbacks[i];
  21486. if (callback.onLoad) callback.onLoad(response);
  21487. }
  21488. scope.manager.itemEnd(url);
  21489. } else {
  21490. for (let i = 0, il = callbacks.length; i < il; i++) {
  21491. const callback = callbacks[i];
  21492. if (callback.onError) callback.onError(event);
  21493. }
  21494. scope.manager.itemError(url);
  21495. scope.manager.itemEnd(url);
  21496. }
  21497. }, false);
  21498. request.addEventListener('progress', function (event) {
  21499. const callbacks = loading[url];
  21500. for (let i = 0, il = callbacks.length; i < il; i++) {
  21501. const callback = callbacks[i];
  21502. if (callback.onProgress) callback.onProgress(event);
  21503. }
  21504. }, false);
  21505. request.addEventListener('error', function (event) {
  21506. const callbacks = loading[url];
  21507. delete loading[url];
  21508. for (let i = 0, il = callbacks.length; i < il; i++) {
  21509. const callback = callbacks[i];
  21510. if (callback.onError) callback.onError(event);
  21511. }
  21512. scope.manager.itemError(url);
  21513. scope.manager.itemEnd(url);
  21514. }, false);
  21515. request.addEventListener('abort', function (event) {
  21516. const callbacks = loading[url];
  21517. delete loading[url];
  21518. for (let i = 0, il = callbacks.length; i < il; i++) {
  21519. const callback = callbacks[i];
  21520. if (callback.onError) callback.onError(event);
  21521. }
  21522. scope.manager.itemError(url);
  21523. scope.manager.itemEnd(url);
  21524. }, false);
  21525. if (this.responseType !== undefined) request.responseType = this.responseType;
  21526. if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
  21527. if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
  21528. for (const header in this.requestHeader) {
  21529. request.setRequestHeader(header, this.requestHeader[header]);
  21530. }
  21531. request.send(null);
  21532. }
  21533. scope.manager.itemStart(url);
  21534. return request;
  21535. }
  21536. setResponseType(value) {
  21537. this.responseType = value;
  21538. return this;
  21539. }
  21540. setMimeType(value) {
  21541. this.mimeType = value;
  21542. return this;
  21543. }
  21544. }
  21545. class AnimationLoader extends Loader {
  21546. constructor(manager) {
  21547. super(manager);
  21548. }
  21549. load(url, onLoad, onProgress, onError) {
  21550. const scope = this;
  21551. const loader = new FileLoader(this.manager);
  21552. loader.setPath(this.path);
  21553. loader.setRequestHeader(this.requestHeader);
  21554. loader.setWithCredentials(this.withCredentials);
  21555. loader.load(url, function (text) {
  21556. try {
  21557. onLoad(scope.parse(JSON.parse(text)));
  21558. } catch (e) {
  21559. if (onError) {
  21560. onError(e);
  21561. } else {
  21562. console.error(e);
  21563. }
  21564. scope.manager.itemError(url);
  21565. }
  21566. }, onProgress, onError);
  21567. }
  21568. parse(json) {
  21569. const animations = [];
  21570. for (let i = 0; i < json.length; i++) {
  21571. const clip = AnimationClip.parse(json[i]);
  21572. animations.push(clip);
  21573. }
  21574. return animations;
  21575. }
  21576. }
  21577. /**
  21578. * Abstract Base class to block based textures loader (dds, pvr, ...)
  21579. *
  21580. * Sub classes have to implement the parse() method which will be used in load().
  21581. */
  21582. class CompressedTextureLoader extends Loader {
  21583. constructor(manager) {
  21584. super(manager);
  21585. }
  21586. load(url, onLoad, onProgress, onError) {
  21587. const scope = this;
  21588. const images = [];
  21589. const texture = new CompressedTexture();
  21590. const loader = new FileLoader(this.manager);
  21591. loader.setPath(this.path);
  21592. loader.setResponseType('arraybuffer');
  21593. loader.setRequestHeader(this.requestHeader);
  21594. loader.setWithCredentials(scope.withCredentials);
  21595. let loaded = 0;
  21596. function loadTexture(i) {
  21597. loader.load(url[i], function (buffer) {
  21598. const texDatas = scope.parse(buffer, true);
  21599. images[i] = {
  21600. width: texDatas.width,
  21601. height: texDatas.height,
  21602. format: texDatas.format,
  21603. mipmaps: texDatas.mipmaps
  21604. };
  21605. loaded += 1;
  21606. if (loaded === 6) {
  21607. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  21608. texture.image = images;
  21609. texture.format = texDatas.format;
  21610. texture.needsUpdate = true;
  21611. if (onLoad) onLoad(texture);
  21612. }
  21613. }, onProgress, onError);
  21614. }
  21615. if (Array.isArray(url)) {
  21616. for (let i = 0, il = url.length; i < il; ++i) {
  21617. loadTexture(i);
  21618. }
  21619. } else {
  21620. // compressed cubemap texture stored in a single DDS file
  21621. loader.load(url, function (buffer) {
  21622. const texDatas = scope.parse(buffer, true);
  21623. if (texDatas.isCubemap) {
  21624. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  21625. for (let f = 0; f < faces; f++) {
  21626. images[f] = {
  21627. mipmaps: []
  21628. };
  21629. for (let i = 0; i < texDatas.mipmapCount; i++) {
  21630. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  21631. images[f].format = texDatas.format;
  21632. images[f].width = texDatas.width;
  21633. images[f].height = texDatas.height;
  21634. }
  21635. }
  21636. texture.image = images;
  21637. } else {
  21638. texture.image.width = texDatas.width;
  21639. texture.image.height = texDatas.height;
  21640. texture.mipmaps = texDatas.mipmaps;
  21641. }
  21642. if (texDatas.mipmapCount === 1) {
  21643. texture.minFilter = LinearFilter;
  21644. }
  21645. texture.format = texDatas.format;
  21646. texture.needsUpdate = true;
  21647. if (onLoad) onLoad(texture);
  21648. }, onProgress, onError);
  21649. }
  21650. return texture;
  21651. }
  21652. }
  21653. class ImageLoader extends Loader {
  21654. constructor(manager) {
  21655. super(manager);
  21656. }
  21657. load(url, onLoad, onProgress, onError) {
  21658. if (this.path !== undefined) url = this.path + url;
  21659. url = this.manager.resolveURL(url);
  21660. const scope = this;
  21661. const cached = Cache.get(url);
  21662. if (cached !== undefined) {
  21663. scope.manager.itemStart(url);
  21664. setTimeout(function () {
  21665. if (onLoad) onLoad(cached);
  21666. scope.manager.itemEnd(url);
  21667. }, 0);
  21668. return cached;
  21669. }
  21670. const image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
  21671. function onImageLoad() {
  21672. image.removeEventListener('load', onImageLoad, false);
  21673. image.removeEventListener('error', onImageError, false);
  21674. Cache.add(url, this);
  21675. if (onLoad) onLoad(this);
  21676. scope.manager.itemEnd(url);
  21677. }
  21678. function onImageError(event) {
  21679. image.removeEventListener('load', onImageLoad, false);
  21680. image.removeEventListener('error', onImageError, false);
  21681. if (onError) onError(event);
  21682. scope.manager.itemError(url);
  21683. scope.manager.itemEnd(url);
  21684. }
  21685. image.addEventListener('load', onImageLoad, false);
  21686. image.addEventListener('error', onImageError, false);
  21687. if (url.substr(0, 5) !== 'data:') {
  21688. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  21689. }
  21690. scope.manager.itemStart(url);
  21691. image.src = url;
  21692. return image;
  21693. }
  21694. }
  21695. class CubeTextureLoader extends Loader {
  21696. constructor(manager) {
  21697. super(manager);
  21698. }
  21699. load(urls, onLoad, onProgress, onError) {
  21700. const texture = new CubeTexture();
  21701. const loader = new ImageLoader(this.manager);
  21702. loader.setCrossOrigin(this.crossOrigin);
  21703. loader.setPath(this.path);
  21704. let loaded = 0;
  21705. function loadTexture(i) {
  21706. loader.load(urls[i], function (image) {
  21707. texture.images[i] = image;
  21708. loaded++;
  21709. if (loaded === 6) {
  21710. texture.needsUpdate = true;
  21711. if (onLoad) onLoad(texture);
  21712. }
  21713. }, undefined, onError);
  21714. }
  21715. for (let i = 0; i < urls.length; ++i) {
  21716. loadTexture(i);
  21717. }
  21718. return texture;
  21719. }
  21720. }
  21721. /**
  21722. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  21723. *
  21724. * Sub classes have to implement the parse() method which will be used in load().
  21725. */
  21726. class DataTextureLoader extends Loader {
  21727. constructor(manager) {
  21728. super(manager);
  21729. }
  21730. load(url, onLoad, onProgress, onError) {
  21731. const scope = this;
  21732. const texture = new DataTexture();
  21733. const loader = new FileLoader(this.manager);
  21734. loader.setResponseType('arraybuffer');
  21735. loader.setRequestHeader(this.requestHeader);
  21736. loader.setPath(this.path);
  21737. loader.setWithCredentials(scope.withCredentials);
  21738. loader.load(url, function (buffer) {
  21739. const texData = scope.parse(buffer);
  21740. if (!texData) return;
  21741. if (texData.image !== undefined) {
  21742. texture.image = texData.image;
  21743. } else if (texData.data !== undefined) {
  21744. texture.image.width = texData.width;
  21745. texture.image.height = texData.height;
  21746. texture.image.data = texData.data;
  21747. }
  21748. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  21749. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  21750. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  21751. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  21752. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  21753. if (texData.encoding !== undefined) {
  21754. texture.encoding = texData.encoding;
  21755. }
  21756. if (texData.flipY !== undefined) {
  21757. texture.flipY = texData.flipY;
  21758. }
  21759. if (texData.format !== undefined) {
  21760. texture.format = texData.format;
  21761. }
  21762. if (texData.type !== undefined) {
  21763. texture.type = texData.type;
  21764. }
  21765. if (texData.mipmaps !== undefined) {
  21766. texture.mipmaps = texData.mipmaps;
  21767. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  21768. }
  21769. if (texData.mipmapCount === 1) {
  21770. texture.minFilter = LinearFilter;
  21771. }
  21772. if (texData.generateMipmaps !== undefined) {
  21773. texture.generateMipmaps = texData.generateMipmaps;
  21774. }
  21775. texture.needsUpdate = true;
  21776. if (onLoad) onLoad(texture, texData);
  21777. }, onProgress, onError);
  21778. return texture;
  21779. }
  21780. }
  21781. class TextureLoader extends Loader {
  21782. constructor(manager) {
  21783. super(manager);
  21784. }
  21785. load(url, onLoad, onProgress, onError) {
  21786. const texture = new Texture();
  21787. const loader = new ImageLoader(this.manager);
  21788. loader.setCrossOrigin(this.crossOrigin);
  21789. loader.setPath(this.path);
  21790. loader.load(url, function (image) {
  21791. texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  21792. const isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;
  21793. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  21794. texture.needsUpdate = true;
  21795. if (onLoad !== undefined) {
  21796. onLoad(texture);
  21797. }
  21798. }, onProgress, onError);
  21799. return texture;
  21800. }
  21801. }
  21802. /**************************************************************
  21803. * Curved Path - a curve path is simply a array of connected
  21804. * curves, but retains the api of a curve
  21805. **************************************************************/
  21806. class CurvePath extends Curve {
  21807. constructor() {
  21808. super();
  21809. this.type = 'CurvePath';
  21810. this.curves = [];
  21811. this.autoClose = false; // Automatically closes the path
  21812. }
  21813. add(curve) {
  21814. this.curves.push(curve);
  21815. }
  21816. closePath() {
  21817. // Add a line curve if start and end of lines are not connected
  21818. const startPoint = this.curves[0].getPoint(0);
  21819. const endPoint = this.curves[this.curves.length - 1].getPoint(1);
  21820. if (!startPoint.equals(endPoint)) {
  21821. this.curves.push(new LineCurve(endPoint, startPoint));
  21822. }
  21823. } // To get accurate point with reference to
  21824. // entire path distance at time t,
  21825. // following has to be done:
  21826. // 1. Length of each sub path have to be known
  21827. // 2. Locate and identify type of curve
  21828. // 3. Get t for the curve
  21829. // 4. Return curve.getPointAt(t')
  21830. getPoint(t) {
  21831. const d = t * this.getLength();
  21832. const curveLengths = this.getCurveLengths();
  21833. let i = 0; // To think about boundaries points.
  21834. while (i < curveLengths.length) {
  21835. if (curveLengths[i] >= d) {
  21836. const diff = curveLengths[i] - d;
  21837. const curve = this.curves[i];
  21838. const segmentLength = curve.getLength();
  21839. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  21840. return curve.getPointAt(u);
  21841. }
  21842. i++;
  21843. }
  21844. return null; // loop where sum != 0, sum > d , sum+1 <d
  21845. } // We cannot use the default THREE.Curve getPoint() with getLength() because in
  21846. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  21847. // getPoint() depends on getLength
  21848. getLength() {
  21849. const lens = this.getCurveLengths();
  21850. return lens[lens.length - 1];
  21851. } // cacheLengths must be recalculated.
  21852. updateArcLengths() {
  21853. this.needsUpdate = true;
  21854. this.cacheLengths = null;
  21855. this.getCurveLengths();
  21856. } // Compute lengths and cache them
  21857. // We cannot overwrite getLengths() because UtoT mapping uses it.
  21858. getCurveLengths() {
  21859. // We use cache values if curves and cache array are same length
  21860. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  21861. return this.cacheLengths;
  21862. } // Get length of sub-curve
  21863. // Push sums into cached array
  21864. const lengths = [];
  21865. let sums = 0;
  21866. for (let i = 0, l = this.curves.length; i < l; i++) {
  21867. sums += this.curves[i].getLength();
  21868. lengths.push(sums);
  21869. }
  21870. this.cacheLengths = lengths;
  21871. return lengths;
  21872. }
  21873. getSpacedPoints(divisions = 40) {
  21874. const points = [];
  21875. for (let i = 0; i <= divisions; i++) {
  21876. points.push(this.getPoint(i / divisions));
  21877. }
  21878. if (this.autoClose) {
  21879. points.push(points[0]);
  21880. }
  21881. return points;
  21882. }
  21883. getPoints(divisions = 12) {
  21884. const points = [];
  21885. let last;
  21886. for (let i = 0, curves = this.curves; i < curves.length; i++) {
  21887. const curve = curves[i];
  21888. const resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  21889. const pts = curve.getPoints(resolution);
  21890. for (let j = 0; j < pts.length; j++) {
  21891. const point = pts[j];
  21892. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  21893. points.push(point);
  21894. last = point;
  21895. }
  21896. }
  21897. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  21898. points.push(points[0]);
  21899. }
  21900. return points;
  21901. }
  21902. copy(source) {
  21903. super.copy(source);
  21904. this.curves = [];
  21905. for (let i = 0, l = source.curves.length; i < l; i++) {
  21906. const curve = source.curves[i];
  21907. this.curves.push(curve.clone());
  21908. }
  21909. this.autoClose = source.autoClose;
  21910. return this;
  21911. }
  21912. toJSON() {
  21913. const data = super.toJSON();
  21914. data.autoClose = this.autoClose;
  21915. data.curves = [];
  21916. for (let i = 0, l = this.curves.length; i < l; i++) {
  21917. const curve = this.curves[i];
  21918. data.curves.push(curve.toJSON());
  21919. }
  21920. return data;
  21921. }
  21922. fromJSON(json) {
  21923. super.fromJSON(json);
  21924. this.autoClose = json.autoClose;
  21925. this.curves = [];
  21926. for (let i = 0, l = json.curves.length; i < l; i++) {
  21927. const curve = json.curves[i];
  21928. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  21929. }
  21930. return this;
  21931. }
  21932. }
  21933. class Path extends CurvePath {
  21934. constructor(points) {
  21935. super();
  21936. this.type = 'Path';
  21937. this.currentPoint = new Vector2();
  21938. if (points) {
  21939. this.setFromPoints(points);
  21940. }
  21941. }
  21942. setFromPoints(points) {
  21943. this.moveTo(points[0].x, points[0].y);
  21944. for (let i = 1, l = points.length; i < l; i++) {
  21945. this.lineTo(points[i].x, points[i].y);
  21946. }
  21947. return this;
  21948. }
  21949. moveTo(x, y) {
  21950. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  21951. return this;
  21952. }
  21953. lineTo(x, y) {
  21954. const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  21955. this.curves.push(curve);
  21956. this.currentPoint.set(x, y);
  21957. return this;
  21958. }
  21959. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  21960. const curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  21961. this.curves.push(curve);
  21962. this.currentPoint.set(aX, aY);
  21963. return this;
  21964. }
  21965. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  21966. const curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  21967. this.curves.push(curve);
  21968. this.currentPoint.set(aX, aY);
  21969. return this;
  21970. }
  21971. splineThru(pts
  21972. /*Array of Vector*/
  21973. ) {
  21974. const npts = [this.currentPoint.clone()].concat(pts);
  21975. const curve = new SplineCurve(npts);
  21976. this.curves.push(curve);
  21977. this.currentPoint.copy(pts[pts.length - 1]);
  21978. return this;
  21979. }
  21980. arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  21981. const x0 = this.currentPoint.x;
  21982. const y0 = this.currentPoint.y;
  21983. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  21984. return this;
  21985. }
  21986. absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  21987. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  21988. return this;
  21989. }
  21990. ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  21991. const x0 = this.currentPoint.x;
  21992. const y0 = this.currentPoint.y;
  21993. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  21994. return this;
  21995. }
  21996. absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  21997. const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  21998. if (this.curves.length > 0) {
  21999. // if a previous curve is present, attempt to join
  22000. const firstPoint = curve.getPoint(0);
  22001. if (!firstPoint.equals(this.currentPoint)) {
  22002. this.lineTo(firstPoint.x, firstPoint.y);
  22003. }
  22004. }
  22005. this.curves.push(curve);
  22006. const lastPoint = curve.getPoint(1);
  22007. this.currentPoint.copy(lastPoint);
  22008. return this;
  22009. }
  22010. copy(source) {
  22011. super.copy(source);
  22012. this.currentPoint.copy(source.currentPoint);
  22013. return this;
  22014. }
  22015. toJSON() {
  22016. const data = super.toJSON();
  22017. data.currentPoint = this.currentPoint.toArray();
  22018. return data;
  22019. }
  22020. fromJSON(json) {
  22021. super.fromJSON(json);
  22022. this.currentPoint.fromArray(json.currentPoint);
  22023. return this;
  22024. }
  22025. }
  22026. class Shape extends Path {
  22027. constructor(points) {
  22028. super(points);
  22029. this.uuid = generateUUID();
  22030. this.type = 'Shape';
  22031. this.holes = [];
  22032. }
  22033. getPointsHoles(divisions) {
  22034. const holesPts = [];
  22035. for (let i = 0, l = this.holes.length; i < l; i++) {
  22036. holesPts[i] = this.holes[i].getPoints(divisions);
  22037. }
  22038. return holesPts;
  22039. } // get points of shape and holes (keypoints based on segments parameter)
  22040. extractPoints(divisions) {
  22041. return {
  22042. shape: this.getPoints(divisions),
  22043. holes: this.getPointsHoles(divisions)
  22044. };
  22045. }
  22046. copy(source) {
  22047. super.copy(source);
  22048. this.holes = [];
  22049. for (let i = 0, l = source.holes.length; i < l; i++) {
  22050. const hole = source.holes[i];
  22051. this.holes.push(hole.clone());
  22052. }
  22053. return this;
  22054. }
  22055. toJSON() {
  22056. const data = super.toJSON();
  22057. data.uuid = this.uuid;
  22058. data.holes = [];
  22059. for (let i = 0, l = this.holes.length; i < l; i++) {
  22060. const hole = this.holes[i];
  22061. data.holes.push(hole.toJSON());
  22062. }
  22063. return data;
  22064. }
  22065. fromJSON(json) {
  22066. super.fromJSON(json);
  22067. this.uuid = json.uuid;
  22068. this.holes = [];
  22069. for (let i = 0, l = json.holes.length; i < l; i++) {
  22070. const hole = json.holes[i];
  22071. this.holes.push(new Path().fromJSON(hole));
  22072. }
  22073. return this;
  22074. }
  22075. }
  22076. class Light extends Object3D {
  22077. constructor(color, intensity = 1) {
  22078. super();
  22079. this.type = 'Light';
  22080. this.color = new Color(color);
  22081. this.intensity = intensity;
  22082. }
  22083. dispose() {// Empty here in base class; some subclasses override.
  22084. }
  22085. copy(source) {
  22086. super.copy(source);
  22087. this.color.copy(source.color);
  22088. this.intensity = source.intensity;
  22089. return this;
  22090. }
  22091. toJSON(meta) {
  22092. const data = super.toJSON(meta);
  22093. data.object.color = this.color.getHex();
  22094. data.object.intensity = this.intensity;
  22095. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  22096. if (this.distance !== undefined) data.object.distance = this.distance;
  22097. if (this.angle !== undefined) data.object.angle = this.angle;
  22098. if (this.decay !== undefined) data.object.decay = this.decay;
  22099. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  22100. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  22101. return data;
  22102. }
  22103. }
  22104. Light.prototype.isLight = true;
  22105. class HemisphereLight extends Light {
  22106. constructor(skyColor, groundColor, intensity) {
  22107. super(skyColor, intensity);
  22108. this.type = 'HemisphereLight';
  22109. this.position.copy(Object3D.DefaultUp);
  22110. this.updateMatrix();
  22111. this.groundColor = new Color(groundColor);
  22112. }
  22113. copy(source) {
  22114. Light.prototype.copy.call(this, source);
  22115. this.groundColor.copy(source.groundColor);
  22116. return this;
  22117. }
  22118. }
  22119. HemisphereLight.prototype.isHemisphereLight = true;
  22120. const _projScreenMatrix$1 = /*@__PURE__*/new Matrix4();
  22121. const _lightPositionWorld$1 = /*@__PURE__*/new Vector3();
  22122. const _lookTarget$1 = /*@__PURE__*/new Vector3();
  22123. class LightShadow {
  22124. constructor(camera) {
  22125. this.camera = camera;
  22126. this.bias = 0;
  22127. this.normalBias = 0;
  22128. this.radius = 1;
  22129. this.mapSize = new Vector2(512, 512);
  22130. this.map = null;
  22131. this.mapPass = null;
  22132. this.matrix = new Matrix4();
  22133. this.autoUpdate = true;
  22134. this.needsUpdate = false;
  22135. this._frustum = new Frustum();
  22136. this._frameExtents = new Vector2(1, 1);
  22137. this._viewportCount = 1;
  22138. this._viewports = [new Vector4(0, 0, 1, 1)];
  22139. }
  22140. getViewportCount() {
  22141. return this._viewportCount;
  22142. }
  22143. getFrustum() {
  22144. return this._frustum;
  22145. }
  22146. updateMatrices(light) {
  22147. const shadowCamera = this.camera;
  22148. const shadowMatrix = this.matrix;
  22149. _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld);
  22150. shadowCamera.position.copy(_lightPositionWorld$1);
  22151. _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld);
  22152. shadowCamera.lookAt(_lookTarget$1);
  22153. shadowCamera.updateMatrixWorld();
  22154. _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  22155. this._frustum.setFromProjectionMatrix(_projScreenMatrix$1);
  22156. 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);
  22157. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  22158. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  22159. }
  22160. getViewport(viewportIndex) {
  22161. return this._viewports[viewportIndex];
  22162. }
  22163. getFrameExtents() {
  22164. return this._frameExtents;
  22165. }
  22166. dispose() {
  22167. if (this.map) {
  22168. this.map.dispose();
  22169. }
  22170. if (this.mapPass) {
  22171. this.mapPass.dispose();
  22172. }
  22173. }
  22174. copy(source) {
  22175. this.camera = source.camera.clone();
  22176. this.bias = source.bias;
  22177. this.radius = source.radius;
  22178. this.mapSize.copy(source.mapSize);
  22179. return this;
  22180. }
  22181. clone() {
  22182. return new this.constructor().copy(this);
  22183. }
  22184. toJSON() {
  22185. const object = {};
  22186. if (this.bias !== 0) object.bias = this.bias;
  22187. if (this.normalBias !== 0) object.normalBias = this.normalBias;
  22188. if (this.radius !== 1) object.radius = this.radius;
  22189. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  22190. object.camera = this.camera.toJSON(false).object;
  22191. delete object.camera.matrix;
  22192. return object;
  22193. }
  22194. }
  22195. class SpotLightShadow extends LightShadow {
  22196. constructor() {
  22197. super(new PerspectiveCamera(50, 1, 0.5, 500));
  22198. this.focus = 1;
  22199. }
  22200. updateMatrices(light) {
  22201. const camera = this.camera;
  22202. const fov = RAD2DEG * 2 * light.angle * this.focus;
  22203. const aspect = this.mapSize.width / this.mapSize.height;
  22204. const far = light.distance || camera.far;
  22205. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  22206. camera.fov = fov;
  22207. camera.aspect = aspect;
  22208. camera.far = far;
  22209. camera.updateProjectionMatrix();
  22210. }
  22211. super.updateMatrices(light);
  22212. }
  22213. copy(source) {
  22214. super.copy(source);
  22215. this.focus = source.focus;
  22216. return this;
  22217. }
  22218. }
  22219. SpotLightShadow.prototype.isSpotLightShadow = true;
  22220. class SpotLight extends Light {
  22221. constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1) {
  22222. super(color, intensity);
  22223. this.type = 'SpotLight';
  22224. this.position.copy(Object3D.DefaultUp);
  22225. this.updateMatrix();
  22226. this.target = new Object3D();
  22227. this.distance = distance;
  22228. this.angle = angle;
  22229. this.penumbra = penumbra;
  22230. this.decay = decay; // for physically correct lights, should be 2.
  22231. this.shadow = new SpotLightShadow();
  22232. }
  22233. get power() {
  22234. // intensity = power per solid angle.
  22235. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22236. return this.intensity * Math.PI;
  22237. }
  22238. set power(power) {
  22239. // intensity = power per solid angle.
  22240. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22241. this.intensity = power / Math.PI;
  22242. }
  22243. dispose() {
  22244. this.shadow.dispose();
  22245. }
  22246. copy(source) {
  22247. super.copy(source);
  22248. this.distance = source.distance;
  22249. this.angle = source.angle;
  22250. this.penumbra = source.penumbra;
  22251. this.decay = source.decay;
  22252. this.target = source.target.clone();
  22253. this.shadow = source.shadow.clone();
  22254. return this;
  22255. }
  22256. }
  22257. SpotLight.prototype.isSpotLight = true;
  22258. const _projScreenMatrix = /*@__PURE__*/new Matrix4();
  22259. const _lightPositionWorld = /*@__PURE__*/new Vector3();
  22260. const _lookTarget = /*@__PURE__*/new Vector3();
  22261. class PointLightShadow extends LightShadow {
  22262. constructor() {
  22263. super(new PerspectiveCamera(90, 1, 0.5, 500));
  22264. this._frameExtents = new Vector2(4, 2);
  22265. this._viewportCount = 6;
  22266. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  22267. // following orientation:
  22268. //
  22269. // xzXZ
  22270. // y Y
  22271. //
  22272. // X - Positive x direction
  22273. // x - Negative x direction
  22274. // Y - Positive y direction
  22275. // y - Negative y direction
  22276. // Z - Positive z direction
  22277. // z - Negative z direction
  22278. // positive X
  22279. new Vector4(2, 1, 1, 1), // negative X
  22280. new Vector4(0, 1, 1, 1), // positive Z
  22281. new Vector4(3, 1, 1, 1), // negative Z
  22282. new Vector4(1, 1, 1, 1), // positive Y
  22283. new Vector4(3, 0, 1, 1), // negative Y
  22284. new Vector4(1, 0, 1, 1)];
  22285. 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)];
  22286. 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)];
  22287. }
  22288. updateMatrices(light, viewportIndex = 0) {
  22289. const camera = this.camera;
  22290. const shadowMatrix = this.matrix;
  22291. const far = light.distance || camera.far;
  22292. if (far !== camera.far) {
  22293. camera.far = far;
  22294. camera.updateProjectionMatrix();
  22295. }
  22296. _lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  22297. camera.position.copy(_lightPositionWorld);
  22298. _lookTarget.copy(camera.position);
  22299. _lookTarget.add(this._cubeDirections[viewportIndex]);
  22300. camera.up.copy(this._cubeUps[viewportIndex]);
  22301. camera.lookAt(_lookTarget);
  22302. camera.updateMatrixWorld();
  22303. shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z);
  22304. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  22305. this._frustum.setFromProjectionMatrix(_projScreenMatrix);
  22306. }
  22307. }
  22308. PointLightShadow.prototype.isPointLightShadow = true;
  22309. class PointLight extends Light {
  22310. constructor(color, intensity, distance = 0, decay = 1) {
  22311. super(color, intensity);
  22312. this.type = 'PointLight';
  22313. this.distance = distance;
  22314. this.decay = decay; // for physically correct lights, should be 2.
  22315. this.shadow = new PointLightShadow();
  22316. }
  22317. get power() {
  22318. // intensity = power per solid angle.
  22319. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22320. return this.intensity * 4 * Math.PI;
  22321. }
  22322. set power(power) {
  22323. // intensity = power per solid angle.
  22324. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22325. this.intensity = power / (4 * Math.PI);
  22326. }
  22327. dispose() {
  22328. this.shadow.dispose();
  22329. }
  22330. copy(source) {
  22331. super.copy(source);
  22332. this.distance = source.distance;
  22333. this.decay = source.decay;
  22334. this.shadow = source.shadow.clone();
  22335. return this;
  22336. }
  22337. }
  22338. PointLight.prototype.isPointLight = true;
  22339. class OrthographicCamera extends Camera {
  22340. constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) {
  22341. super();
  22342. this.type = 'OrthographicCamera';
  22343. this.zoom = 1;
  22344. this.view = null;
  22345. this.left = left;
  22346. this.right = right;
  22347. this.top = top;
  22348. this.bottom = bottom;
  22349. this.near = near;
  22350. this.far = far;
  22351. this.updateProjectionMatrix();
  22352. }
  22353. copy(source, recursive) {
  22354. super.copy(source, recursive);
  22355. this.left = source.left;
  22356. this.right = source.right;
  22357. this.top = source.top;
  22358. this.bottom = source.bottom;
  22359. this.near = source.near;
  22360. this.far = source.far;
  22361. this.zoom = source.zoom;
  22362. this.view = source.view === null ? null : Object.assign({}, source.view);
  22363. return this;
  22364. }
  22365. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  22366. if (this.view === null) {
  22367. this.view = {
  22368. enabled: true,
  22369. fullWidth: 1,
  22370. fullHeight: 1,
  22371. offsetX: 0,
  22372. offsetY: 0,
  22373. width: 1,
  22374. height: 1
  22375. };
  22376. }
  22377. this.view.enabled = true;
  22378. this.view.fullWidth = fullWidth;
  22379. this.view.fullHeight = fullHeight;
  22380. this.view.offsetX = x;
  22381. this.view.offsetY = y;
  22382. this.view.width = width;
  22383. this.view.height = height;
  22384. this.updateProjectionMatrix();
  22385. }
  22386. clearViewOffset() {
  22387. if (this.view !== null) {
  22388. this.view.enabled = false;
  22389. }
  22390. this.updateProjectionMatrix();
  22391. }
  22392. updateProjectionMatrix() {
  22393. const dx = (this.right - this.left) / (2 * this.zoom);
  22394. const dy = (this.top - this.bottom) / (2 * this.zoom);
  22395. const cx = (this.right + this.left) / 2;
  22396. const cy = (this.top + this.bottom) / 2;
  22397. let left = cx - dx;
  22398. let right = cx + dx;
  22399. let top = cy + dy;
  22400. let bottom = cy - dy;
  22401. if (this.view !== null && this.view.enabled) {
  22402. const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  22403. const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  22404. left += scaleW * this.view.offsetX;
  22405. right = left + scaleW * this.view.width;
  22406. top -= scaleH * this.view.offsetY;
  22407. bottom = top - scaleH * this.view.height;
  22408. }
  22409. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  22410. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  22411. }
  22412. toJSON(meta) {
  22413. const data = super.toJSON(meta);
  22414. data.object.zoom = this.zoom;
  22415. data.object.left = this.left;
  22416. data.object.right = this.right;
  22417. data.object.top = this.top;
  22418. data.object.bottom = this.bottom;
  22419. data.object.near = this.near;
  22420. data.object.far = this.far;
  22421. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  22422. return data;
  22423. }
  22424. }
  22425. OrthographicCamera.prototype.isOrthographicCamera = true;
  22426. class DirectionalLightShadow extends LightShadow {
  22427. constructor() {
  22428. super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  22429. }
  22430. }
  22431. DirectionalLightShadow.prototype.isDirectionalLightShadow = true;
  22432. class DirectionalLight extends Light {
  22433. constructor(color, intensity) {
  22434. super(color, intensity);
  22435. this.type = 'DirectionalLight';
  22436. this.position.copy(Object3D.DefaultUp);
  22437. this.updateMatrix();
  22438. this.target = new Object3D();
  22439. this.shadow = new DirectionalLightShadow();
  22440. }
  22441. dispose() {
  22442. this.shadow.dispose();
  22443. }
  22444. copy(source) {
  22445. super.copy(source);
  22446. this.target = source.target.clone();
  22447. this.shadow = source.shadow.clone();
  22448. return this;
  22449. }
  22450. }
  22451. DirectionalLight.prototype.isDirectionalLight = true;
  22452. class AmbientLight extends Light {
  22453. constructor(color, intensity) {
  22454. super(color, intensity);
  22455. this.type = 'AmbientLight';
  22456. }
  22457. }
  22458. AmbientLight.prototype.isAmbientLight = true;
  22459. class RectAreaLight extends Light {
  22460. constructor(color, intensity, width = 10, height = 10) {
  22461. super(color, intensity);
  22462. this.type = 'RectAreaLight';
  22463. this.width = width;
  22464. this.height = height;
  22465. }
  22466. copy(source) {
  22467. super.copy(source);
  22468. this.width = source.width;
  22469. this.height = source.height;
  22470. return this;
  22471. }
  22472. toJSON(meta) {
  22473. const data = super.toJSON(meta);
  22474. data.object.width = this.width;
  22475. data.object.height = this.height;
  22476. return data;
  22477. }
  22478. }
  22479. RectAreaLight.prototype.isRectAreaLight = true;
  22480. /**
  22481. * Primary reference:
  22482. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  22483. *
  22484. * Secondary reference:
  22485. * https://www.ppsloan.org/publications/StupidSH36.pdf
  22486. */
  22487. // 3-band SH defined by 9 coefficients
  22488. class SphericalHarmonics3 {
  22489. constructor() {
  22490. this.coefficients = [];
  22491. for (let i = 0; i < 9; i++) {
  22492. this.coefficients.push(new Vector3());
  22493. }
  22494. }
  22495. set(coefficients) {
  22496. for (let i = 0; i < 9; i++) {
  22497. this.coefficients[i].copy(coefficients[i]);
  22498. }
  22499. return this;
  22500. }
  22501. zero() {
  22502. for (let i = 0; i < 9; i++) {
  22503. this.coefficients[i].set(0, 0, 0);
  22504. }
  22505. return this;
  22506. } // get the radiance in the direction of the normal
  22507. // target is a Vector3
  22508. getAt(normal, target) {
  22509. // normal is assumed to be unit length
  22510. const x = normal.x,
  22511. y = normal.y,
  22512. z = normal.z;
  22513. const coeff = this.coefficients; // band 0
  22514. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  22515. target.addScaledVector(coeff[1], 0.488603 * y);
  22516. target.addScaledVector(coeff[2], 0.488603 * z);
  22517. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  22518. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  22519. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  22520. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  22521. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  22522. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  22523. return target;
  22524. } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  22525. // target is a Vector3
  22526. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  22527. getIrradianceAt(normal, target) {
  22528. // normal is assumed to be unit length
  22529. const x = normal.x,
  22530. y = normal.y,
  22531. z = normal.z;
  22532. const coeff = this.coefficients; // band 0
  22533. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  22534. // band 1
  22535. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  22536. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  22537. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  22538. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  22539. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  22540. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  22541. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  22542. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  22543. return target;
  22544. }
  22545. add(sh) {
  22546. for (let i = 0; i < 9; i++) {
  22547. this.coefficients[i].add(sh.coefficients[i]);
  22548. }
  22549. return this;
  22550. }
  22551. addScaledSH(sh, s) {
  22552. for (let i = 0; i < 9; i++) {
  22553. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  22554. }
  22555. return this;
  22556. }
  22557. scale(s) {
  22558. for (let i = 0; i < 9; i++) {
  22559. this.coefficients[i].multiplyScalar(s);
  22560. }
  22561. return this;
  22562. }
  22563. lerp(sh, alpha) {
  22564. for (let i = 0; i < 9; i++) {
  22565. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  22566. }
  22567. return this;
  22568. }
  22569. equals(sh) {
  22570. for (let i = 0; i < 9; i++) {
  22571. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  22572. return false;
  22573. }
  22574. }
  22575. return true;
  22576. }
  22577. copy(sh) {
  22578. return this.set(sh.coefficients);
  22579. }
  22580. clone() {
  22581. return new this.constructor().copy(this);
  22582. }
  22583. fromArray(array, offset = 0) {
  22584. const coefficients = this.coefficients;
  22585. for (let i = 0; i < 9; i++) {
  22586. coefficients[i].fromArray(array, offset + i * 3);
  22587. }
  22588. return this;
  22589. }
  22590. toArray(array = [], offset = 0) {
  22591. const coefficients = this.coefficients;
  22592. for (let i = 0; i < 9; i++) {
  22593. coefficients[i].toArray(array, offset + i * 3);
  22594. }
  22595. return array;
  22596. } // evaluate the basis functions
  22597. // shBasis is an Array[ 9 ]
  22598. static getBasisAt(normal, shBasis) {
  22599. // normal is assumed to be unit length
  22600. const x = normal.x,
  22601. y = normal.y,
  22602. z = normal.z; // band 0
  22603. shBasis[0] = 0.282095; // band 1
  22604. shBasis[1] = 0.488603 * y;
  22605. shBasis[2] = 0.488603 * z;
  22606. shBasis[3] = 0.488603 * x; // band 2
  22607. shBasis[4] = 1.092548 * x * y;
  22608. shBasis[5] = 1.092548 * y * z;
  22609. shBasis[6] = 0.315392 * (3 * z * z - 1);
  22610. shBasis[7] = 1.092548 * x * z;
  22611. shBasis[8] = 0.546274 * (x * x - y * y);
  22612. }
  22613. }
  22614. SphericalHarmonics3.prototype.isSphericalHarmonics3 = true;
  22615. class LightProbe extends Light {
  22616. constructor(sh = new SphericalHarmonics3(), intensity = 1) {
  22617. super(undefined, intensity);
  22618. this.sh = sh;
  22619. }
  22620. copy(source) {
  22621. super.copy(source);
  22622. this.sh.copy(source.sh);
  22623. return this;
  22624. }
  22625. fromJSON(json) {
  22626. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  22627. this.sh.fromArray(json.sh);
  22628. return this;
  22629. }
  22630. toJSON(meta) {
  22631. const data = super.toJSON(meta);
  22632. data.object.sh = this.sh.toArray();
  22633. return data;
  22634. }
  22635. }
  22636. LightProbe.prototype.isLightProbe = true;
  22637. class MaterialLoader extends Loader {
  22638. constructor(manager) {
  22639. super(manager);
  22640. this.textures = {};
  22641. }
  22642. load(url, onLoad, onProgress, onError) {
  22643. const scope = this;
  22644. const loader = new FileLoader(scope.manager);
  22645. loader.setPath(scope.path);
  22646. loader.setRequestHeader(scope.requestHeader);
  22647. loader.setWithCredentials(scope.withCredentials);
  22648. loader.load(url, function (text) {
  22649. try {
  22650. onLoad(scope.parse(JSON.parse(text)));
  22651. } catch (e) {
  22652. if (onError) {
  22653. onError(e);
  22654. } else {
  22655. console.error(e);
  22656. }
  22657. scope.manager.itemError(url);
  22658. }
  22659. }, onProgress, onError);
  22660. }
  22661. parse(json) {
  22662. const textures = this.textures;
  22663. function getTexture(name) {
  22664. if (textures[name] === undefined) {
  22665. console.warn('THREE.MaterialLoader: Undefined texture', name);
  22666. }
  22667. return textures[name];
  22668. }
  22669. const material = new Materials[json.type]();
  22670. if (json.uuid !== undefined) material.uuid = json.uuid;
  22671. if (json.name !== undefined) material.name = json.name;
  22672. if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
  22673. if (json.roughness !== undefined) material.roughness = json.roughness;
  22674. if (json.metalness !== undefined) material.metalness = json.metalness;
  22675. if (json.sheen !== undefined) material.sheen = new Color().setHex(json.sheen);
  22676. if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
  22677. if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
  22678. if (json.shininess !== undefined) material.shininess = json.shininess;
  22679. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  22680. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  22681. if (json.transmission !== undefined) material.transmission = json.transmission;
  22682. if (json.thickness !== undefined) material.thickness = json.thickness;
  22683. if (json.attenuationDistance !== undefined) material.attenuationDistance = json.attenuationDistance;
  22684. if (json.attenuationColor !== undefined && material.attenuationColor !== undefined) material.attenuationColor.setHex(json.attenuationColor);
  22685. if (json.fog !== undefined) material.fog = json.fog;
  22686. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  22687. if (json.blending !== undefined) material.blending = json.blending;
  22688. if (json.combine !== undefined) material.combine = json.combine;
  22689. if (json.side !== undefined) material.side = json.side;
  22690. if (json.shadowSide !== undefined) material.shadowSide = json.shadowSide;
  22691. if (json.opacity !== undefined) material.opacity = json.opacity;
  22692. if (json.transparent !== undefined) material.transparent = json.transparent;
  22693. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  22694. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  22695. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  22696. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  22697. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  22698. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  22699. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  22700. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  22701. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  22702. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  22703. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  22704. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  22705. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  22706. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  22707. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  22708. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  22709. if (json.rotation !== undefined) material.rotation = json.rotation;
  22710. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  22711. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  22712. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  22713. if (json.scale !== undefined) material.scale = json.scale;
  22714. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  22715. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  22716. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  22717. if (json.morphTargets !== undefined) material.morphTargets = json.morphTargets;
  22718. if (json.morphNormals !== undefined) material.morphNormals = json.morphNormals;
  22719. if (json.dithering !== undefined) material.dithering = json.dithering;
  22720. if (json.alphaToCoverage !== undefined) material.alphaToCoverage = json.alphaToCoverage;
  22721. if (json.premultipliedAlpha !== undefined) material.premultipliedAlpha = json.premultipliedAlpha;
  22722. if (json.vertexTangents !== undefined) material.vertexTangents = json.vertexTangents;
  22723. if (json.visible !== undefined) material.visible = json.visible;
  22724. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  22725. if (json.userData !== undefined) material.userData = json.userData;
  22726. if (json.vertexColors !== undefined) {
  22727. if (typeof json.vertexColors === 'number') {
  22728. material.vertexColors = json.vertexColors > 0 ? true : false;
  22729. } else {
  22730. material.vertexColors = json.vertexColors;
  22731. }
  22732. } // Shader Material
  22733. if (json.uniforms !== undefined) {
  22734. for (const name in json.uniforms) {
  22735. const uniform = json.uniforms[name];
  22736. material.uniforms[name] = {};
  22737. switch (uniform.type) {
  22738. case 't':
  22739. material.uniforms[name].value = getTexture(uniform.value);
  22740. break;
  22741. case 'c':
  22742. material.uniforms[name].value = new Color().setHex(uniform.value);
  22743. break;
  22744. case 'v2':
  22745. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  22746. break;
  22747. case 'v3':
  22748. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  22749. break;
  22750. case 'v4':
  22751. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  22752. break;
  22753. case 'm3':
  22754. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  22755. break;
  22756. case 'm4':
  22757. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  22758. break;
  22759. default:
  22760. material.uniforms[name].value = uniform.value;
  22761. }
  22762. }
  22763. }
  22764. if (json.defines !== undefined) material.defines = json.defines;
  22765. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  22766. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  22767. if (json.extensions !== undefined) {
  22768. for (const key in json.extensions) {
  22769. material.extensions[key] = json.extensions[key];
  22770. }
  22771. } // Deprecated
  22772. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  22773. // for PointsMaterial
  22774. if (json.size !== undefined) material.size = json.size;
  22775. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  22776. if (json.map !== undefined) material.map = getTexture(json.map);
  22777. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  22778. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  22779. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  22780. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  22781. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  22782. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  22783. if (json.normalScale !== undefined) {
  22784. let normalScale = json.normalScale;
  22785. if (Array.isArray(normalScale) === false) {
  22786. // Blender exporter used to export a scalar. See #7459
  22787. normalScale = [normalScale, normalScale];
  22788. }
  22789. material.normalScale = new Vector2().fromArray(normalScale);
  22790. }
  22791. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  22792. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  22793. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  22794. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  22795. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  22796. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  22797. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  22798. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  22799. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  22800. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  22801. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  22802. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  22803. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  22804. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  22805. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  22806. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  22807. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  22808. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  22809. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  22810. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  22811. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  22812. if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
  22813. if (json.thicknessMap !== undefined) material.thicknessMap = getTexture(json.thicknessMap);
  22814. return material;
  22815. }
  22816. setTextures(value) {
  22817. this.textures = value;
  22818. return this;
  22819. }
  22820. }
  22821. class LoaderUtils {
  22822. static decodeText(array) {
  22823. if (typeof TextDecoder !== 'undefined') {
  22824. return new TextDecoder().decode(array);
  22825. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  22826. // throws a "maximum call stack size exceeded" error for large arrays.
  22827. let s = '';
  22828. for (let i = 0, il = array.length; i < il; i++) {
  22829. // Implicitly assumes little-endian.
  22830. s += String.fromCharCode(array[i]);
  22831. }
  22832. try {
  22833. // merges multi-byte utf-8 characters.
  22834. return decodeURIComponent(escape(s));
  22835. } catch (e) {
  22836. // see #16358
  22837. return s;
  22838. }
  22839. }
  22840. static extractUrlBase(url) {
  22841. const index = url.lastIndexOf('/');
  22842. if (index === -1) return './';
  22843. return url.substr(0, index + 1);
  22844. }
  22845. }
  22846. class InstancedBufferGeometry extends BufferGeometry {
  22847. constructor() {
  22848. super();
  22849. this.type = 'InstancedBufferGeometry';
  22850. this.instanceCount = Infinity;
  22851. }
  22852. copy(source) {
  22853. super.copy(source);
  22854. this.instanceCount = source.instanceCount;
  22855. return this;
  22856. }
  22857. clone() {
  22858. return new this.constructor().copy(this);
  22859. }
  22860. toJSON() {
  22861. const data = super.toJSON(this);
  22862. data.instanceCount = this.instanceCount;
  22863. data.isInstancedBufferGeometry = true;
  22864. return data;
  22865. }
  22866. }
  22867. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  22868. class InstancedBufferAttribute extends BufferAttribute {
  22869. constructor(array, itemSize, normalized, meshPerAttribute = 1) {
  22870. if (typeof normalized === 'number') {
  22871. meshPerAttribute = normalized;
  22872. normalized = false;
  22873. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  22874. }
  22875. super(array, itemSize, normalized);
  22876. this.meshPerAttribute = meshPerAttribute;
  22877. }
  22878. copy(source) {
  22879. super.copy(source);
  22880. this.meshPerAttribute = source.meshPerAttribute;
  22881. return this;
  22882. }
  22883. toJSON() {
  22884. const data = super.toJSON();
  22885. data.meshPerAttribute = this.meshPerAttribute;
  22886. data.isInstancedBufferAttribute = true;
  22887. return data;
  22888. }
  22889. }
  22890. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  22891. class BufferGeometryLoader extends Loader {
  22892. constructor(manager) {
  22893. super(manager);
  22894. }
  22895. load(url, onLoad, onProgress, onError) {
  22896. const scope = this;
  22897. const loader = new FileLoader(scope.manager);
  22898. loader.setPath(scope.path);
  22899. loader.setRequestHeader(scope.requestHeader);
  22900. loader.setWithCredentials(scope.withCredentials);
  22901. loader.load(url, function (text) {
  22902. try {
  22903. onLoad(scope.parse(JSON.parse(text)));
  22904. } catch (e) {
  22905. if (onError) {
  22906. onError(e);
  22907. } else {
  22908. console.error(e);
  22909. }
  22910. scope.manager.itemError(url);
  22911. }
  22912. }, onProgress, onError);
  22913. }
  22914. parse(json) {
  22915. const interleavedBufferMap = {};
  22916. const arrayBufferMap = {};
  22917. function getInterleavedBuffer(json, uuid) {
  22918. if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
  22919. const interleavedBuffers = json.interleavedBuffers;
  22920. const interleavedBuffer = interleavedBuffers[uuid];
  22921. const buffer = getArrayBuffer(json, interleavedBuffer.buffer);
  22922. const array = getTypedArray(interleavedBuffer.type, buffer);
  22923. const ib = new InterleavedBuffer(array, interleavedBuffer.stride);
  22924. ib.uuid = interleavedBuffer.uuid;
  22925. interleavedBufferMap[uuid] = ib;
  22926. return ib;
  22927. }
  22928. function getArrayBuffer(json, uuid) {
  22929. if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
  22930. const arrayBuffers = json.arrayBuffers;
  22931. const arrayBuffer = arrayBuffers[uuid];
  22932. const ab = new Uint32Array(arrayBuffer).buffer;
  22933. arrayBufferMap[uuid] = ab;
  22934. return ab;
  22935. }
  22936. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  22937. const index = json.data.index;
  22938. if (index !== undefined) {
  22939. const typedArray = getTypedArray(index.type, index.array);
  22940. geometry.setIndex(new BufferAttribute(typedArray, 1));
  22941. }
  22942. const attributes = json.data.attributes;
  22943. for (const key in attributes) {
  22944. const attribute = attributes[key];
  22945. let bufferAttribute;
  22946. if (attribute.isInterleavedBufferAttribute) {
  22947. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  22948. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  22949. } else {
  22950. const typedArray = getTypedArray(attribute.type, attribute.array);
  22951. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  22952. bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  22953. }
  22954. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  22955. if (attribute.usage !== undefined) bufferAttribute.setUsage(attribute.usage);
  22956. if (attribute.updateRange !== undefined) {
  22957. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  22958. bufferAttribute.updateRange.count = attribute.updateRange.count;
  22959. }
  22960. geometry.setAttribute(key, bufferAttribute);
  22961. }
  22962. const morphAttributes = json.data.morphAttributes;
  22963. if (morphAttributes) {
  22964. for (const key in morphAttributes) {
  22965. const attributeArray = morphAttributes[key];
  22966. const array = [];
  22967. for (let i = 0, il = attributeArray.length; i < il; i++) {
  22968. const attribute = attributeArray[i];
  22969. let bufferAttribute;
  22970. if (attribute.isInterleavedBufferAttribute) {
  22971. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  22972. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  22973. } else {
  22974. const typedArray = getTypedArray(attribute.type, attribute.array);
  22975. bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  22976. }
  22977. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  22978. array.push(bufferAttribute);
  22979. }
  22980. geometry.morphAttributes[key] = array;
  22981. }
  22982. }
  22983. const morphTargetsRelative = json.data.morphTargetsRelative;
  22984. if (morphTargetsRelative) {
  22985. geometry.morphTargetsRelative = true;
  22986. }
  22987. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  22988. if (groups !== undefined) {
  22989. for (let i = 0, n = groups.length; i !== n; ++i) {
  22990. const group = groups[i];
  22991. geometry.addGroup(group.start, group.count, group.materialIndex);
  22992. }
  22993. }
  22994. const boundingSphere = json.data.boundingSphere;
  22995. if (boundingSphere !== undefined) {
  22996. const center = new Vector3();
  22997. if (boundingSphere.center !== undefined) {
  22998. center.fromArray(boundingSphere.center);
  22999. }
  23000. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  23001. }
  23002. if (json.name) geometry.name = json.name;
  23003. if (json.userData) geometry.userData = json.userData;
  23004. return geometry;
  23005. }
  23006. }
  23007. class ObjectLoader extends Loader {
  23008. constructor(manager) {
  23009. super(manager);
  23010. }
  23011. load(url, onLoad, onProgress, onError) {
  23012. const scope = this;
  23013. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  23014. this.resourcePath = this.resourcePath || path;
  23015. const loader = new FileLoader(this.manager);
  23016. loader.setPath(this.path);
  23017. loader.setRequestHeader(this.requestHeader);
  23018. loader.setWithCredentials(this.withCredentials);
  23019. loader.load(url, function (text) {
  23020. let json = null;
  23021. try {
  23022. json = JSON.parse(text);
  23023. } catch (error) {
  23024. if (onError !== undefined) onError(error);
  23025. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  23026. return;
  23027. }
  23028. const metadata = json.metadata;
  23029. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  23030. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  23031. return;
  23032. }
  23033. scope.parse(json, onLoad);
  23034. }, onProgress, onError);
  23035. }
  23036. async loadAsync(url, onProgress) {
  23037. const scope = this;
  23038. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  23039. this.resourcePath = this.resourcePath || path;
  23040. const loader = new FileLoader(this.manager);
  23041. loader.setPath(this.path);
  23042. loader.setRequestHeader(this.requestHeader);
  23043. loader.setWithCredentials(this.withCredentials);
  23044. const text = await loader.loadAsync(url, onProgress);
  23045. const json = JSON.parse(text);
  23046. const metadata = json.metadata;
  23047. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  23048. throw new Error('THREE.ObjectLoader: Can\'t load ' + url);
  23049. }
  23050. return await scope.parseAsync(json);
  23051. }
  23052. parse(json, onLoad) {
  23053. const animations = this.parseAnimations(json.animations);
  23054. const shapes = this.parseShapes(json.shapes);
  23055. const geometries = this.parseGeometries(json.geometries, shapes);
  23056. const images = this.parseImages(json.images, function () {
  23057. if (onLoad !== undefined) onLoad(object);
  23058. });
  23059. const textures = this.parseTextures(json.textures, images);
  23060. const materials = this.parseMaterials(json.materials, textures);
  23061. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  23062. const skeletons = this.parseSkeletons(json.skeletons, object);
  23063. this.bindSkeletons(object, skeletons); //
  23064. if (onLoad !== undefined) {
  23065. let hasImages = false;
  23066. for (const uuid in images) {
  23067. if (images[uuid] instanceof HTMLImageElement) {
  23068. hasImages = true;
  23069. break;
  23070. }
  23071. }
  23072. if (hasImages === false) onLoad(object);
  23073. }
  23074. return object;
  23075. }
  23076. async parseAsync(json) {
  23077. const animations = this.parseAnimations(json.animations);
  23078. const shapes = this.parseShapes(json.shapes);
  23079. const geometries = this.parseGeometries(json.geometries, shapes);
  23080. const images = await this.parseImagesAsync(json.images);
  23081. const textures = this.parseTextures(json.textures, images);
  23082. const materials = this.parseMaterials(json.materials, textures);
  23083. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  23084. const skeletons = this.parseSkeletons(json.skeletons, object);
  23085. this.bindSkeletons(object, skeletons);
  23086. return object;
  23087. }
  23088. parseShapes(json) {
  23089. const shapes = {};
  23090. if (json !== undefined) {
  23091. for (let i = 0, l = json.length; i < l; i++) {
  23092. const shape = new Shape().fromJSON(json[i]);
  23093. shapes[shape.uuid] = shape;
  23094. }
  23095. }
  23096. return shapes;
  23097. }
  23098. parseSkeletons(json, object) {
  23099. const skeletons = {};
  23100. const bones = {}; // generate bone lookup table
  23101. object.traverse(function (child) {
  23102. if (child.isBone) bones[child.uuid] = child;
  23103. }); // create skeletons
  23104. if (json !== undefined) {
  23105. for (let i = 0, l = json.length; i < l; i++) {
  23106. const skeleton = new Skeleton().fromJSON(json[i], bones);
  23107. skeletons[skeleton.uuid] = skeleton;
  23108. }
  23109. }
  23110. return skeletons;
  23111. }
  23112. parseGeometries(json, shapes) {
  23113. const geometries = {};
  23114. if (json !== undefined) {
  23115. const bufferGeometryLoader = new BufferGeometryLoader();
  23116. for (let i = 0, l = json.length; i < l; i++) {
  23117. let geometry;
  23118. const data = json[i];
  23119. switch (data.type) {
  23120. case 'BufferGeometry':
  23121. case 'InstancedBufferGeometry':
  23122. geometry = bufferGeometryLoader.parse(data);
  23123. break;
  23124. case 'Geometry':
  23125. console.error('THREE.ObjectLoader: The legacy Geometry type is no longer supported.');
  23126. break;
  23127. default:
  23128. if (data.type in Geometries) {
  23129. geometry = Geometries[data.type].fromJSON(data, shapes);
  23130. } else {
  23131. console.warn(`THREE.ObjectLoader: Unsupported geometry type "${data.type}"`);
  23132. }
  23133. }
  23134. geometry.uuid = data.uuid;
  23135. if (data.name !== undefined) geometry.name = data.name;
  23136. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  23137. geometries[data.uuid] = geometry;
  23138. }
  23139. }
  23140. return geometries;
  23141. }
  23142. parseMaterials(json, textures) {
  23143. const cache = {}; // MultiMaterial
  23144. const materials = {};
  23145. if (json !== undefined) {
  23146. const loader = new MaterialLoader();
  23147. loader.setTextures(textures);
  23148. for (let i = 0, l = json.length; i < l; i++) {
  23149. const data = json[i];
  23150. if (data.type === 'MultiMaterial') {
  23151. // Deprecated
  23152. const array = [];
  23153. for (let j = 0; j < data.materials.length; j++) {
  23154. const material = data.materials[j];
  23155. if (cache[material.uuid] === undefined) {
  23156. cache[material.uuid] = loader.parse(material);
  23157. }
  23158. array.push(cache[material.uuid]);
  23159. }
  23160. materials[data.uuid] = array;
  23161. } else {
  23162. if (cache[data.uuid] === undefined) {
  23163. cache[data.uuid] = loader.parse(data);
  23164. }
  23165. materials[data.uuid] = cache[data.uuid];
  23166. }
  23167. }
  23168. }
  23169. return materials;
  23170. }
  23171. parseAnimations(json) {
  23172. const animations = {};
  23173. if (json !== undefined) {
  23174. for (let i = 0; i < json.length; i++) {
  23175. const data = json[i];
  23176. const clip = AnimationClip.parse(data);
  23177. animations[clip.uuid] = clip;
  23178. }
  23179. }
  23180. return animations;
  23181. }
  23182. parseImages(json, onLoad) {
  23183. const scope = this;
  23184. const images = {};
  23185. let loader;
  23186. function loadImage(url) {
  23187. scope.manager.itemStart(url);
  23188. return loader.load(url, function () {
  23189. scope.manager.itemEnd(url);
  23190. }, undefined, function () {
  23191. scope.manager.itemError(url);
  23192. scope.manager.itemEnd(url);
  23193. });
  23194. }
  23195. function deserializeImage(image) {
  23196. if (typeof image === 'string') {
  23197. const url = image;
  23198. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  23199. return loadImage(path);
  23200. } else {
  23201. if (image.data) {
  23202. return {
  23203. data: getTypedArray(image.type, image.data),
  23204. width: image.width,
  23205. height: image.height
  23206. };
  23207. } else {
  23208. return null;
  23209. }
  23210. }
  23211. }
  23212. if (json !== undefined && json.length > 0) {
  23213. const manager = new LoadingManager(onLoad);
  23214. loader = new ImageLoader(manager);
  23215. loader.setCrossOrigin(this.crossOrigin);
  23216. for (let i = 0, il = json.length; i < il; i++) {
  23217. const image = json[i];
  23218. const url = image.url;
  23219. if (Array.isArray(url)) {
  23220. // load array of images e.g CubeTexture
  23221. images[image.uuid] = [];
  23222. for (let j = 0, jl = url.length; j < jl; j++) {
  23223. const currentUrl = url[j];
  23224. const deserializedImage = deserializeImage(currentUrl);
  23225. if (deserializedImage !== null) {
  23226. if (deserializedImage instanceof HTMLImageElement) {
  23227. images[image.uuid].push(deserializedImage);
  23228. } else {
  23229. // special case: handle array of data textures for cube textures
  23230. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  23231. }
  23232. }
  23233. }
  23234. } else {
  23235. // load single image
  23236. const deserializedImage = deserializeImage(image.url);
  23237. if (deserializedImage !== null) {
  23238. images[image.uuid] = deserializedImage;
  23239. }
  23240. }
  23241. }
  23242. }
  23243. return images;
  23244. }
  23245. async parseImagesAsync(json) {
  23246. const scope = this;
  23247. const images = {};
  23248. let loader;
  23249. async function deserializeImage(image) {
  23250. if (typeof image === 'string') {
  23251. const url = image;
  23252. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  23253. return await loader.loadAsync(path);
  23254. } else {
  23255. if (image.data) {
  23256. return {
  23257. data: getTypedArray(image.type, image.data),
  23258. width: image.width,
  23259. height: image.height
  23260. };
  23261. } else {
  23262. return null;
  23263. }
  23264. }
  23265. }
  23266. if (json !== undefined && json.length > 0) {
  23267. loader = new ImageLoader(this.manager);
  23268. loader.setCrossOrigin(this.crossOrigin);
  23269. for (let i = 0, il = json.length; i < il; i++) {
  23270. const image = json[i];
  23271. const url = image.url;
  23272. if (Array.isArray(url)) {
  23273. // load array of images e.g CubeTexture
  23274. images[image.uuid] = [];
  23275. for (let j = 0, jl = url.length; j < jl; j++) {
  23276. const currentUrl = url[j];
  23277. const deserializedImage = await deserializeImage(currentUrl);
  23278. if (deserializedImage !== null) {
  23279. if (deserializedImage instanceof HTMLImageElement) {
  23280. images[image.uuid].push(deserializedImage);
  23281. } else {
  23282. // special case: handle array of data textures for cube textures
  23283. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  23284. }
  23285. }
  23286. }
  23287. } else {
  23288. // load single image
  23289. const deserializedImage = await deserializeImage(image.url);
  23290. if (deserializedImage !== null) {
  23291. images[image.uuid] = deserializedImage;
  23292. }
  23293. }
  23294. }
  23295. }
  23296. return images;
  23297. }
  23298. parseTextures(json, images) {
  23299. function parseConstant(value, type) {
  23300. if (typeof value === 'number') return value;
  23301. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  23302. return type[value];
  23303. }
  23304. const textures = {};
  23305. if (json !== undefined) {
  23306. for (let i = 0, l = json.length; i < l; i++) {
  23307. const data = json[i];
  23308. if (data.image === undefined) {
  23309. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  23310. }
  23311. if (images[data.image] === undefined) {
  23312. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  23313. }
  23314. let texture;
  23315. const image = images[data.image];
  23316. if (Array.isArray(image)) {
  23317. texture = new CubeTexture(image);
  23318. if (image.length === 6) texture.needsUpdate = true;
  23319. } else {
  23320. if (image && image.data) {
  23321. texture = new DataTexture(image.data, image.width, image.height);
  23322. } else {
  23323. texture = new Texture(image);
  23324. }
  23325. if (image) texture.needsUpdate = true; // textures can have undefined image data
  23326. }
  23327. texture.uuid = data.uuid;
  23328. if (data.name !== undefined) texture.name = data.name;
  23329. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  23330. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  23331. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  23332. if (data.center !== undefined) texture.center.fromArray(data.center);
  23333. if (data.rotation !== undefined) texture.rotation = data.rotation;
  23334. if (data.wrap !== undefined) {
  23335. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  23336. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  23337. }
  23338. if (data.format !== undefined) texture.format = data.format;
  23339. if (data.type !== undefined) texture.type = data.type;
  23340. if (data.encoding !== undefined) texture.encoding = data.encoding;
  23341. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  23342. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  23343. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  23344. if (data.flipY !== undefined) texture.flipY = data.flipY;
  23345. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  23346. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  23347. textures[data.uuid] = texture;
  23348. }
  23349. }
  23350. return textures;
  23351. }
  23352. parseObject(data, geometries, materials, textures, animations) {
  23353. let object;
  23354. function getGeometry(name) {
  23355. if (geometries[name] === undefined) {
  23356. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  23357. }
  23358. return geometries[name];
  23359. }
  23360. function getMaterial(name) {
  23361. if (name === undefined) return undefined;
  23362. if (Array.isArray(name)) {
  23363. const array = [];
  23364. for (let i = 0, l = name.length; i < l; i++) {
  23365. const uuid = name[i];
  23366. if (materials[uuid] === undefined) {
  23367. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  23368. }
  23369. array.push(materials[uuid]);
  23370. }
  23371. return array;
  23372. }
  23373. if (materials[name] === undefined) {
  23374. console.warn('THREE.ObjectLoader: Undefined material', name);
  23375. }
  23376. return materials[name];
  23377. }
  23378. function getTexture(uuid) {
  23379. if (textures[uuid] === undefined) {
  23380. console.warn('THREE.ObjectLoader: Undefined texture', uuid);
  23381. }
  23382. return textures[uuid];
  23383. }
  23384. let geometry, material;
  23385. switch (data.type) {
  23386. case 'Scene':
  23387. object = new Scene();
  23388. if (data.background !== undefined) {
  23389. if (Number.isInteger(data.background)) {
  23390. object.background = new Color(data.background);
  23391. } else {
  23392. object.background = getTexture(data.background);
  23393. }
  23394. }
  23395. if (data.environment !== undefined) object.environment = getTexture(data.environment);
  23396. if (data.fog !== undefined) {
  23397. if (data.fog.type === 'Fog') {
  23398. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  23399. } else if (data.fog.type === 'FogExp2') {
  23400. object.fog = new FogExp2(data.fog.color, data.fog.density);
  23401. }
  23402. }
  23403. break;
  23404. case 'PerspectiveCamera':
  23405. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  23406. if (data.focus !== undefined) object.focus = data.focus;
  23407. if (data.zoom !== undefined) object.zoom = data.zoom;
  23408. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  23409. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  23410. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  23411. break;
  23412. case 'OrthographicCamera':
  23413. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  23414. if (data.zoom !== undefined) object.zoom = data.zoom;
  23415. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  23416. break;
  23417. case 'AmbientLight':
  23418. object = new AmbientLight(data.color, data.intensity);
  23419. break;
  23420. case 'DirectionalLight':
  23421. object = new DirectionalLight(data.color, data.intensity);
  23422. break;
  23423. case 'PointLight':
  23424. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  23425. break;
  23426. case 'RectAreaLight':
  23427. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  23428. break;
  23429. case 'SpotLight':
  23430. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  23431. break;
  23432. case 'HemisphereLight':
  23433. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  23434. break;
  23435. case 'LightProbe':
  23436. object = new LightProbe().fromJSON(data);
  23437. break;
  23438. case 'SkinnedMesh':
  23439. geometry = getGeometry(data.geometry);
  23440. material = getMaterial(data.material);
  23441. object = new SkinnedMesh(geometry, material);
  23442. if (data.bindMode !== undefined) object.bindMode = data.bindMode;
  23443. if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
  23444. if (data.skeleton !== undefined) object.skeleton = data.skeleton;
  23445. break;
  23446. case 'Mesh':
  23447. geometry = getGeometry(data.geometry);
  23448. material = getMaterial(data.material);
  23449. object = new Mesh(geometry, material);
  23450. break;
  23451. case 'InstancedMesh':
  23452. geometry = getGeometry(data.geometry);
  23453. material = getMaterial(data.material);
  23454. const count = data.count;
  23455. const instanceMatrix = data.instanceMatrix;
  23456. const instanceColor = data.instanceColor;
  23457. object = new InstancedMesh(geometry, material, count);
  23458. object.instanceMatrix = new BufferAttribute(new Float32Array(instanceMatrix.array), 16);
  23459. if (instanceColor !== undefined) object.instanceColor = new BufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize);
  23460. break;
  23461. case 'LOD':
  23462. object = new LOD();
  23463. break;
  23464. case 'Line':
  23465. object = new Line(getGeometry(data.geometry), getMaterial(data.material));
  23466. break;
  23467. case 'LineLoop':
  23468. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  23469. break;
  23470. case 'LineSegments':
  23471. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  23472. break;
  23473. case 'PointCloud':
  23474. case 'Points':
  23475. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  23476. break;
  23477. case 'Sprite':
  23478. object = new Sprite(getMaterial(data.material));
  23479. break;
  23480. case 'Group':
  23481. object = new Group();
  23482. break;
  23483. case 'Bone':
  23484. object = new Bone();
  23485. break;
  23486. default:
  23487. object = new Object3D();
  23488. }
  23489. object.uuid = data.uuid;
  23490. if (data.name !== undefined) object.name = data.name;
  23491. if (data.matrix !== undefined) {
  23492. object.matrix.fromArray(data.matrix);
  23493. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  23494. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  23495. } else {
  23496. if (data.position !== undefined) object.position.fromArray(data.position);
  23497. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  23498. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  23499. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  23500. }
  23501. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  23502. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  23503. if (data.shadow) {
  23504. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  23505. if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
  23506. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  23507. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  23508. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  23509. }
  23510. if (data.visible !== undefined) object.visible = data.visible;
  23511. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  23512. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  23513. if (data.userData !== undefined) object.userData = data.userData;
  23514. if (data.layers !== undefined) object.layers.mask = data.layers;
  23515. if (data.children !== undefined) {
  23516. const children = data.children;
  23517. for (let i = 0; i < children.length; i++) {
  23518. object.add(this.parseObject(children[i], geometries, materials, textures, animations));
  23519. }
  23520. }
  23521. if (data.animations !== undefined) {
  23522. const objectAnimations = data.animations;
  23523. for (let i = 0; i < objectAnimations.length; i++) {
  23524. const uuid = objectAnimations[i];
  23525. object.animations.push(animations[uuid]);
  23526. }
  23527. }
  23528. if (data.type === 'LOD') {
  23529. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  23530. const levels = data.levels;
  23531. for (let l = 0; l < levels.length; l++) {
  23532. const level = levels[l];
  23533. const child = object.getObjectByProperty('uuid', level.object);
  23534. if (child !== undefined) {
  23535. object.addLevel(child, level.distance);
  23536. }
  23537. }
  23538. }
  23539. return object;
  23540. }
  23541. bindSkeletons(object, skeletons) {
  23542. if (Object.keys(skeletons).length === 0) return;
  23543. object.traverse(function (child) {
  23544. if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
  23545. const skeleton = skeletons[child.skeleton];
  23546. if (skeleton === undefined) {
  23547. console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
  23548. } else {
  23549. child.bind(skeleton, child.bindMatrix);
  23550. }
  23551. }
  23552. });
  23553. }
  23554. /* DEPRECATED */
  23555. setTexturePath(value) {
  23556. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  23557. return this.setResourcePath(value);
  23558. }
  23559. }
  23560. const TEXTURE_MAPPING = {
  23561. UVMapping: UVMapping,
  23562. CubeReflectionMapping: CubeReflectionMapping,
  23563. CubeRefractionMapping: CubeRefractionMapping,
  23564. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  23565. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  23566. CubeUVReflectionMapping: CubeUVReflectionMapping,
  23567. CubeUVRefractionMapping: CubeUVRefractionMapping
  23568. };
  23569. const TEXTURE_WRAPPING = {
  23570. RepeatWrapping: RepeatWrapping,
  23571. ClampToEdgeWrapping: ClampToEdgeWrapping,
  23572. MirroredRepeatWrapping: MirroredRepeatWrapping
  23573. };
  23574. const TEXTURE_FILTER = {
  23575. NearestFilter: NearestFilter,
  23576. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  23577. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  23578. LinearFilter: LinearFilter,
  23579. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  23580. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  23581. };
  23582. class ImageBitmapLoader extends Loader {
  23583. constructor(manager) {
  23584. super(manager);
  23585. if (typeof createImageBitmap === 'undefined') {
  23586. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  23587. }
  23588. if (typeof fetch === 'undefined') {
  23589. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  23590. }
  23591. this.options = {
  23592. premultiplyAlpha: 'none'
  23593. };
  23594. }
  23595. setOptions(options) {
  23596. this.options = options;
  23597. return this;
  23598. }
  23599. load(url, onLoad, onProgress, onError) {
  23600. if (url === undefined) url = '';
  23601. if (this.path !== undefined) url = this.path + url;
  23602. url = this.manager.resolveURL(url);
  23603. const scope = this;
  23604. const cached = Cache.get(url);
  23605. if (cached !== undefined) {
  23606. scope.manager.itemStart(url);
  23607. setTimeout(function () {
  23608. if (onLoad) onLoad(cached);
  23609. scope.manager.itemEnd(url);
  23610. }, 0);
  23611. return cached;
  23612. }
  23613. const fetchOptions = {};
  23614. fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
  23615. fetchOptions.headers = this.requestHeader;
  23616. fetch(url, fetchOptions).then(function (res) {
  23617. return res.blob();
  23618. }).then(function (blob) {
  23619. return createImageBitmap(blob, Object.assign(scope.options, {
  23620. colorSpaceConversion: 'none'
  23621. }));
  23622. }).then(function (imageBitmap) {
  23623. Cache.add(url, imageBitmap);
  23624. if (onLoad) onLoad(imageBitmap);
  23625. scope.manager.itemEnd(url);
  23626. }).catch(function (e) {
  23627. if (onError) onError(e);
  23628. scope.manager.itemError(url);
  23629. scope.manager.itemEnd(url);
  23630. });
  23631. scope.manager.itemStart(url);
  23632. }
  23633. }
  23634. ImageBitmapLoader.prototype.isImageBitmapLoader = true;
  23635. class ShapePath {
  23636. constructor() {
  23637. this.type = 'ShapePath';
  23638. this.color = new Color();
  23639. this.subPaths = [];
  23640. this.currentPath = null;
  23641. }
  23642. moveTo(x, y) {
  23643. this.currentPath = new Path();
  23644. this.subPaths.push(this.currentPath);
  23645. this.currentPath.moveTo(x, y);
  23646. return this;
  23647. }
  23648. lineTo(x, y) {
  23649. this.currentPath.lineTo(x, y);
  23650. return this;
  23651. }
  23652. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  23653. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  23654. return this;
  23655. }
  23656. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  23657. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  23658. return this;
  23659. }
  23660. splineThru(pts) {
  23661. this.currentPath.splineThru(pts);
  23662. return this;
  23663. }
  23664. toShapes(isCCW, noHoles) {
  23665. function toShapesNoHoles(inSubpaths) {
  23666. const shapes = [];
  23667. for (let i = 0, l = inSubpaths.length; i < l; i++) {
  23668. const tmpPath = inSubpaths[i];
  23669. const tmpShape = new Shape();
  23670. tmpShape.curves = tmpPath.curves;
  23671. shapes.push(tmpShape);
  23672. }
  23673. return shapes;
  23674. }
  23675. function isPointInsidePolygon(inPt, inPolygon) {
  23676. const polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  23677. // toggling of inside/outside at every single! intersection point of an edge
  23678. // with the horizontal line through inPt, left of inPt
  23679. // not counting lowerY endpoints of edges and whole edges on that line
  23680. let inside = false;
  23681. for (let p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  23682. let edgeLowPt = inPolygon[p];
  23683. let edgeHighPt = inPolygon[q];
  23684. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  23685. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  23686. if (Math.abs(edgeDy) > Number.EPSILON) {
  23687. // not parallel
  23688. if (edgeDy < 0) {
  23689. edgeLowPt = inPolygon[q];
  23690. edgeDx = -edgeDx;
  23691. edgeHighPt = inPolygon[p];
  23692. edgeDy = -edgeDy;
  23693. }
  23694. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  23695. if (inPt.y === edgeLowPt.y) {
  23696. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  23697. // continue; // no intersection or edgeLowPt => doesn't count !!!
  23698. } else {
  23699. const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  23700. if (perpEdge === 0) return true; // inPt is on contour ?
  23701. if (perpEdge < 0) continue;
  23702. inside = !inside; // true intersection left of inPt
  23703. }
  23704. } else {
  23705. // parallel or collinear
  23706. if (inPt.y !== edgeLowPt.y) continue; // parallel
  23707. // edge lies on the same horizontal line as inPt
  23708. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  23709. // continue;
  23710. }
  23711. }
  23712. return inside;
  23713. }
  23714. const isClockWise = ShapeUtils.isClockWise;
  23715. const subPaths = this.subPaths;
  23716. if (subPaths.length === 0) return [];
  23717. if (noHoles === true) return toShapesNoHoles(subPaths);
  23718. let solid, tmpPath, tmpShape;
  23719. const shapes = [];
  23720. if (subPaths.length === 1) {
  23721. tmpPath = subPaths[0];
  23722. tmpShape = new Shape();
  23723. tmpShape.curves = tmpPath.curves;
  23724. shapes.push(tmpShape);
  23725. return shapes;
  23726. }
  23727. let holesFirst = !isClockWise(subPaths[0].getPoints());
  23728. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  23729. const betterShapeHoles = [];
  23730. const newShapes = [];
  23731. let newShapeHoles = [];
  23732. let mainIdx = 0;
  23733. let tmpPoints;
  23734. newShapes[mainIdx] = undefined;
  23735. newShapeHoles[mainIdx] = [];
  23736. for (let i = 0, l = subPaths.length; i < l; i++) {
  23737. tmpPath = subPaths[i];
  23738. tmpPoints = tmpPath.getPoints();
  23739. solid = isClockWise(tmpPoints);
  23740. solid = isCCW ? !solid : solid;
  23741. if (solid) {
  23742. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  23743. newShapes[mainIdx] = {
  23744. s: new Shape(),
  23745. p: tmpPoints
  23746. };
  23747. newShapes[mainIdx].s.curves = tmpPath.curves;
  23748. if (holesFirst) mainIdx++;
  23749. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  23750. } else {
  23751. newShapeHoles[mainIdx].push({
  23752. h: tmpPath,
  23753. p: tmpPoints[0]
  23754. }); //console.log('ccw', i);
  23755. }
  23756. } // only Holes? -> probably all Shapes with wrong orientation
  23757. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  23758. if (newShapes.length > 1) {
  23759. let ambiguous = false;
  23760. const toChange = [];
  23761. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  23762. betterShapeHoles[sIdx] = [];
  23763. }
  23764. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  23765. const sho = newShapeHoles[sIdx];
  23766. for (let hIdx = 0; hIdx < sho.length; hIdx++) {
  23767. const ho = sho[hIdx];
  23768. let hole_unassigned = true;
  23769. for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  23770. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  23771. if (sIdx !== s2Idx) toChange.push({
  23772. froms: sIdx,
  23773. tos: s2Idx,
  23774. hole: hIdx
  23775. });
  23776. if (hole_unassigned) {
  23777. hole_unassigned = false;
  23778. betterShapeHoles[s2Idx].push(ho);
  23779. } else {
  23780. ambiguous = true;
  23781. }
  23782. }
  23783. }
  23784. if (hole_unassigned) {
  23785. betterShapeHoles[sIdx].push(ho);
  23786. }
  23787. }
  23788. } // console.log("ambiguous: ", ambiguous);
  23789. if (toChange.length > 0) {
  23790. // console.log("to change: ", toChange);
  23791. if (!ambiguous) newShapeHoles = betterShapeHoles;
  23792. }
  23793. }
  23794. let tmpHoles;
  23795. for (let i = 0, il = newShapes.length; i < il; i++) {
  23796. tmpShape = newShapes[i].s;
  23797. shapes.push(tmpShape);
  23798. tmpHoles = newShapeHoles[i];
  23799. for (let j = 0, jl = tmpHoles.length; j < jl; j++) {
  23800. tmpShape.holes.push(tmpHoles[j].h);
  23801. }
  23802. } //console.log("shape", shapes);
  23803. return shapes;
  23804. }
  23805. }
  23806. class Font {
  23807. constructor(data) {
  23808. this.type = 'Font';
  23809. this.data = data;
  23810. }
  23811. generateShapes(text, size = 100) {
  23812. const shapes = [];
  23813. const paths = createPaths(text, size, this.data);
  23814. for (let p = 0, pl = paths.length; p < pl; p++) {
  23815. Array.prototype.push.apply(shapes, paths[p].toShapes());
  23816. }
  23817. return shapes;
  23818. }
  23819. }
  23820. function createPaths(text, size, data) {
  23821. const chars = Array.from(text);
  23822. const scale = size / data.resolution;
  23823. const line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
  23824. const paths = [];
  23825. let offsetX = 0,
  23826. offsetY = 0;
  23827. for (let i = 0; i < chars.length; i++) {
  23828. const char = chars[i];
  23829. if (char === '\n') {
  23830. offsetX = 0;
  23831. offsetY -= line_height;
  23832. } else {
  23833. const ret = createPath(char, scale, offsetX, offsetY, data);
  23834. offsetX += ret.offsetX;
  23835. paths.push(ret.path);
  23836. }
  23837. }
  23838. return paths;
  23839. }
  23840. function createPath(char, scale, offsetX, offsetY, data) {
  23841. const glyph = data.glyphs[char] || data.glyphs['?'];
  23842. if (!glyph) {
  23843. console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
  23844. return;
  23845. }
  23846. const path = new ShapePath();
  23847. let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  23848. if (glyph.o) {
  23849. const outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
  23850. for (let i = 0, l = outline.length; i < l;) {
  23851. const action = outline[i++];
  23852. switch (action) {
  23853. case 'm':
  23854. // moveTo
  23855. x = outline[i++] * scale + offsetX;
  23856. y = outline[i++] * scale + offsetY;
  23857. path.moveTo(x, y);
  23858. break;
  23859. case 'l':
  23860. // lineTo
  23861. x = outline[i++] * scale + offsetX;
  23862. y = outline[i++] * scale + offsetY;
  23863. path.lineTo(x, y);
  23864. break;
  23865. case 'q':
  23866. // quadraticCurveTo
  23867. cpx = outline[i++] * scale + offsetX;
  23868. cpy = outline[i++] * scale + offsetY;
  23869. cpx1 = outline[i++] * scale + offsetX;
  23870. cpy1 = outline[i++] * scale + offsetY;
  23871. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  23872. break;
  23873. case 'b':
  23874. // bezierCurveTo
  23875. cpx = outline[i++] * scale + offsetX;
  23876. cpy = outline[i++] * scale + offsetY;
  23877. cpx1 = outline[i++] * scale + offsetX;
  23878. cpy1 = outline[i++] * scale + offsetY;
  23879. cpx2 = outline[i++] * scale + offsetX;
  23880. cpy2 = outline[i++] * scale + offsetY;
  23881. path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
  23882. break;
  23883. }
  23884. }
  23885. }
  23886. return {
  23887. offsetX: glyph.ha * scale,
  23888. path: path
  23889. };
  23890. }
  23891. Font.prototype.isFont = true;
  23892. class FontLoader extends Loader {
  23893. constructor(manager) {
  23894. super(manager);
  23895. }
  23896. load(url, onLoad, onProgress, onError) {
  23897. const scope = this;
  23898. const loader = new FileLoader(this.manager);
  23899. loader.setPath(this.path);
  23900. loader.setRequestHeader(this.requestHeader);
  23901. loader.setWithCredentials(scope.withCredentials);
  23902. loader.load(url, function (text) {
  23903. let json;
  23904. try {
  23905. json = JSON.parse(text);
  23906. } catch (e) {
  23907. console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
  23908. json = JSON.parse(text.substring(65, text.length - 2));
  23909. }
  23910. const font = scope.parse(json);
  23911. if (onLoad) onLoad(font);
  23912. }, onProgress, onError);
  23913. }
  23914. parse(json) {
  23915. return new Font(json);
  23916. }
  23917. }
  23918. let _context;
  23919. const AudioContext = {
  23920. getContext: function () {
  23921. if (_context === undefined) {
  23922. _context = new (window.AudioContext || window.webkitAudioContext)();
  23923. }
  23924. return _context;
  23925. },
  23926. setContext: function (value) {
  23927. _context = value;
  23928. }
  23929. };
  23930. class AudioLoader extends Loader {
  23931. constructor(manager) {
  23932. super(manager);
  23933. }
  23934. load(url, onLoad, onProgress, onError) {
  23935. const scope = this;
  23936. const loader = new FileLoader(this.manager);
  23937. loader.setResponseType('arraybuffer');
  23938. loader.setPath(this.path);
  23939. loader.setRequestHeader(this.requestHeader);
  23940. loader.setWithCredentials(this.withCredentials);
  23941. loader.load(url, function (buffer) {
  23942. try {
  23943. // Create a copy of the buffer. The `decodeAudioData` method
  23944. // detaches the buffer when complete, preventing reuse.
  23945. const bufferCopy = buffer.slice(0);
  23946. const context = AudioContext.getContext();
  23947. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  23948. onLoad(audioBuffer);
  23949. });
  23950. } catch (e) {
  23951. if (onError) {
  23952. onError(e);
  23953. } else {
  23954. console.error(e);
  23955. }
  23956. scope.manager.itemError(url);
  23957. }
  23958. }, onProgress, onError);
  23959. }
  23960. }
  23961. class HemisphereLightProbe extends LightProbe {
  23962. constructor(skyColor, groundColor, intensity = 1) {
  23963. super(undefined, intensity);
  23964. const color1 = new Color().set(skyColor);
  23965. const color2 = new Color().set(groundColor);
  23966. const sky = new Vector3(color1.r, color1.g, color1.b);
  23967. const ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  23968. const c0 = Math.sqrt(Math.PI);
  23969. const c1 = c0 * Math.sqrt(0.75);
  23970. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  23971. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  23972. }
  23973. }
  23974. HemisphereLightProbe.prototype.isHemisphereLightProbe = true;
  23975. class AmbientLightProbe extends LightProbe {
  23976. constructor(color, intensity = 1) {
  23977. super(undefined, intensity);
  23978. const color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  23979. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  23980. }
  23981. }
  23982. AmbientLightProbe.prototype.isAmbientLightProbe = true;
  23983. const _eyeRight = /*@__PURE__*/new Matrix4();
  23984. const _eyeLeft = /*@__PURE__*/new Matrix4();
  23985. class StereoCamera {
  23986. constructor() {
  23987. this.type = 'StereoCamera';
  23988. this.aspect = 1;
  23989. this.eyeSep = 0.064;
  23990. this.cameraL = new PerspectiveCamera();
  23991. this.cameraL.layers.enable(1);
  23992. this.cameraL.matrixAutoUpdate = false;
  23993. this.cameraR = new PerspectiveCamera();
  23994. this.cameraR.layers.enable(2);
  23995. this.cameraR.matrixAutoUpdate = false;
  23996. this._cache = {
  23997. focus: null,
  23998. fov: null,
  23999. aspect: null,
  24000. near: null,
  24001. far: null,
  24002. zoom: null,
  24003. eyeSep: null
  24004. };
  24005. }
  24006. update(camera) {
  24007. const cache = this._cache;
  24008. 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;
  24009. if (needsUpdate) {
  24010. cache.focus = camera.focus;
  24011. cache.fov = camera.fov;
  24012. cache.aspect = camera.aspect * this.aspect;
  24013. cache.near = camera.near;
  24014. cache.far = camera.far;
  24015. cache.zoom = camera.zoom;
  24016. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  24017. // http://paulbourke.net/stereographics/stereorender/
  24018. const projectionMatrix = camera.projectionMatrix.clone();
  24019. const eyeSepHalf = cache.eyeSep / 2;
  24020. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  24021. const ymax = cache.near * Math.tan(DEG2RAD * cache.fov * 0.5) / cache.zoom;
  24022. let xmin, xmax; // translate xOffset
  24023. _eyeLeft.elements[12] = -eyeSepHalf;
  24024. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  24025. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  24026. xmax = ymax * cache.aspect + eyeSepOnProjection;
  24027. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  24028. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  24029. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  24030. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  24031. xmax = ymax * cache.aspect - eyeSepOnProjection;
  24032. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  24033. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  24034. this.cameraR.projectionMatrix.copy(projectionMatrix);
  24035. }
  24036. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  24037. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  24038. }
  24039. }
  24040. class Clock {
  24041. constructor(autoStart = true) {
  24042. this.autoStart = autoStart;
  24043. this.startTime = 0;
  24044. this.oldTime = 0;
  24045. this.elapsedTime = 0;
  24046. this.running = false;
  24047. }
  24048. start() {
  24049. this.startTime = now();
  24050. this.oldTime = this.startTime;
  24051. this.elapsedTime = 0;
  24052. this.running = true;
  24053. }
  24054. stop() {
  24055. this.getElapsedTime();
  24056. this.running = false;
  24057. this.autoStart = false;
  24058. }
  24059. getElapsedTime() {
  24060. this.getDelta();
  24061. return this.elapsedTime;
  24062. }
  24063. getDelta() {
  24064. let diff = 0;
  24065. if (this.autoStart && !this.running) {
  24066. this.start();
  24067. return 0;
  24068. }
  24069. if (this.running) {
  24070. const newTime = now();
  24071. diff = (newTime - this.oldTime) / 1000;
  24072. this.oldTime = newTime;
  24073. this.elapsedTime += diff;
  24074. }
  24075. return diff;
  24076. }
  24077. }
  24078. function now() {
  24079. return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  24080. }
  24081. const _position$1 = /*@__PURE__*/new Vector3();
  24082. const _quaternion$1 = /*@__PURE__*/new Quaternion();
  24083. const _scale$1 = /*@__PURE__*/new Vector3();
  24084. const _orientation$1 = /*@__PURE__*/new Vector3();
  24085. class AudioListener extends Object3D {
  24086. constructor() {
  24087. super();
  24088. this.type = 'AudioListener';
  24089. this.context = AudioContext.getContext();
  24090. this.gain = this.context.createGain();
  24091. this.gain.connect(this.context.destination);
  24092. this.filter = null;
  24093. this.timeDelta = 0; // private
  24094. this._clock = new Clock();
  24095. }
  24096. getInput() {
  24097. return this.gain;
  24098. }
  24099. removeFilter() {
  24100. if (this.filter !== null) {
  24101. this.gain.disconnect(this.filter);
  24102. this.filter.disconnect(this.context.destination);
  24103. this.gain.connect(this.context.destination);
  24104. this.filter = null;
  24105. }
  24106. return this;
  24107. }
  24108. getFilter() {
  24109. return this.filter;
  24110. }
  24111. setFilter(value) {
  24112. if (this.filter !== null) {
  24113. this.gain.disconnect(this.filter);
  24114. this.filter.disconnect(this.context.destination);
  24115. } else {
  24116. this.gain.disconnect(this.context.destination);
  24117. }
  24118. this.filter = value;
  24119. this.gain.connect(this.filter);
  24120. this.filter.connect(this.context.destination);
  24121. return this;
  24122. }
  24123. getMasterVolume() {
  24124. return this.gain.gain.value;
  24125. }
  24126. setMasterVolume(value) {
  24127. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  24128. return this;
  24129. }
  24130. updateMatrixWorld(force) {
  24131. super.updateMatrixWorld(force);
  24132. const listener = this.context.listener;
  24133. const up = this.up;
  24134. this.timeDelta = this._clock.getDelta();
  24135. this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1);
  24136. _orientation$1.set(0, 0, -1).applyQuaternion(_quaternion$1);
  24137. if (listener.positionX) {
  24138. // code path for Chrome (see #14393)
  24139. const endTime = this.context.currentTime + this.timeDelta;
  24140. listener.positionX.linearRampToValueAtTime(_position$1.x, endTime);
  24141. listener.positionY.linearRampToValueAtTime(_position$1.y, endTime);
  24142. listener.positionZ.linearRampToValueAtTime(_position$1.z, endTime);
  24143. listener.forwardX.linearRampToValueAtTime(_orientation$1.x, endTime);
  24144. listener.forwardY.linearRampToValueAtTime(_orientation$1.y, endTime);
  24145. listener.forwardZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  24146. listener.upX.linearRampToValueAtTime(up.x, endTime);
  24147. listener.upY.linearRampToValueAtTime(up.y, endTime);
  24148. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  24149. } else {
  24150. listener.setPosition(_position$1.x, _position$1.y, _position$1.z);
  24151. listener.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z);
  24152. }
  24153. }
  24154. }
  24155. class Audio extends Object3D {
  24156. constructor(listener) {
  24157. super();
  24158. this.type = 'Audio';
  24159. this.listener = listener;
  24160. this.context = listener.context;
  24161. this.gain = this.context.createGain();
  24162. this.gain.connect(listener.getInput());
  24163. this.autoplay = false;
  24164. this.buffer = null;
  24165. this.detune = 0;
  24166. this.loop = false;
  24167. this.loopStart = 0;
  24168. this.loopEnd = 0;
  24169. this.offset = 0;
  24170. this.duration = undefined;
  24171. this.playbackRate = 1;
  24172. this.isPlaying = false;
  24173. this.hasPlaybackControl = true;
  24174. this.source = null;
  24175. this.sourceType = 'empty';
  24176. this._startedAt = 0;
  24177. this._progress = 0;
  24178. this._connected = false;
  24179. this.filters = [];
  24180. }
  24181. getOutput() {
  24182. return this.gain;
  24183. }
  24184. setNodeSource(audioNode) {
  24185. this.hasPlaybackControl = false;
  24186. this.sourceType = 'audioNode';
  24187. this.source = audioNode;
  24188. this.connect();
  24189. return this;
  24190. }
  24191. setMediaElementSource(mediaElement) {
  24192. this.hasPlaybackControl = false;
  24193. this.sourceType = 'mediaNode';
  24194. this.source = this.context.createMediaElementSource(mediaElement);
  24195. this.connect();
  24196. return this;
  24197. }
  24198. setMediaStreamSource(mediaStream) {
  24199. this.hasPlaybackControl = false;
  24200. this.sourceType = 'mediaStreamNode';
  24201. this.source = this.context.createMediaStreamSource(mediaStream);
  24202. this.connect();
  24203. return this;
  24204. }
  24205. setBuffer(audioBuffer) {
  24206. this.buffer = audioBuffer;
  24207. this.sourceType = 'buffer';
  24208. if (this.autoplay) this.play();
  24209. return this;
  24210. }
  24211. play(delay = 0) {
  24212. if (this.isPlaying === true) {
  24213. console.warn('THREE.Audio: Audio is already playing.');
  24214. return;
  24215. }
  24216. if (this.hasPlaybackControl === false) {
  24217. console.warn('THREE.Audio: this Audio has no playback control.');
  24218. return;
  24219. }
  24220. this._startedAt = this.context.currentTime + delay;
  24221. const source = this.context.createBufferSource();
  24222. source.buffer = this.buffer;
  24223. source.loop = this.loop;
  24224. source.loopStart = this.loopStart;
  24225. source.loopEnd = this.loopEnd;
  24226. source.onended = this.onEnded.bind(this);
  24227. source.start(this._startedAt, this._progress + this.offset, this.duration);
  24228. this.isPlaying = true;
  24229. this.source = source;
  24230. this.setDetune(this.detune);
  24231. this.setPlaybackRate(this.playbackRate);
  24232. return this.connect();
  24233. }
  24234. pause() {
  24235. if (this.hasPlaybackControl === false) {
  24236. console.warn('THREE.Audio: this Audio has no playback control.');
  24237. return;
  24238. }
  24239. if (this.isPlaying === true) {
  24240. // update current progress
  24241. this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  24242. if (this.loop === true) {
  24243. // ensure _progress does not exceed duration with looped audios
  24244. this._progress = this._progress % (this.duration || this.buffer.duration);
  24245. }
  24246. this.source.stop();
  24247. this.source.onended = null;
  24248. this.isPlaying = false;
  24249. }
  24250. return this;
  24251. }
  24252. stop() {
  24253. if (this.hasPlaybackControl === false) {
  24254. console.warn('THREE.Audio: this Audio has no playback control.');
  24255. return;
  24256. }
  24257. this._progress = 0;
  24258. this.source.stop();
  24259. this.source.onended = null;
  24260. this.isPlaying = false;
  24261. return this;
  24262. }
  24263. connect() {
  24264. if (this.filters.length > 0) {
  24265. this.source.connect(this.filters[0]);
  24266. for (let i = 1, l = this.filters.length; i < l; i++) {
  24267. this.filters[i - 1].connect(this.filters[i]);
  24268. }
  24269. this.filters[this.filters.length - 1].connect(this.getOutput());
  24270. } else {
  24271. this.source.connect(this.getOutput());
  24272. }
  24273. this._connected = true;
  24274. return this;
  24275. }
  24276. disconnect() {
  24277. if (this.filters.length > 0) {
  24278. this.source.disconnect(this.filters[0]);
  24279. for (let i = 1, l = this.filters.length; i < l; i++) {
  24280. this.filters[i - 1].disconnect(this.filters[i]);
  24281. }
  24282. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  24283. } else {
  24284. this.source.disconnect(this.getOutput());
  24285. }
  24286. this._connected = false;
  24287. return this;
  24288. }
  24289. getFilters() {
  24290. return this.filters;
  24291. }
  24292. setFilters(value) {
  24293. if (!value) value = [];
  24294. if (this._connected === true) {
  24295. this.disconnect();
  24296. this.filters = value.slice();
  24297. this.connect();
  24298. } else {
  24299. this.filters = value.slice();
  24300. }
  24301. return this;
  24302. }
  24303. setDetune(value) {
  24304. this.detune = value;
  24305. if (this.source.detune === undefined) return; // only set detune when available
  24306. if (this.isPlaying === true) {
  24307. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  24308. }
  24309. return this;
  24310. }
  24311. getDetune() {
  24312. return this.detune;
  24313. }
  24314. getFilter() {
  24315. return this.getFilters()[0];
  24316. }
  24317. setFilter(filter) {
  24318. return this.setFilters(filter ? [filter] : []);
  24319. }
  24320. setPlaybackRate(value) {
  24321. if (this.hasPlaybackControl === false) {
  24322. console.warn('THREE.Audio: this Audio has no playback control.');
  24323. return;
  24324. }
  24325. this.playbackRate = value;
  24326. if (this.isPlaying === true) {
  24327. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  24328. }
  24329. return this;
  24330. }
  24331. getPlaybackRate() {
  24332. return this.playbackRate;
  24333. }
  24334. onEnded() {
  24335. this.isPlaying = false;
  24336. }
  24337. getLoop() {
  24338. if (this.hasPlaybackControl === false) {
  24339. console.warn('THREE.Audio: this Audio has no playback control.');
  24340. return false;
  24341. }
  24342. return this.loop;
  24343. }
  24344. setLoop(value) {
  24345. if (this.hasPlaybackControl === false) {
  24346. console.warn('THREE.Audio: this Audio has no playback control.');
  24347. return;
  24348. }
  24349. this.loop = value;
  24350. if (this.isPlaying === true) {
  24351. this.source.loop = this.loop;
  24352. }
  24353. return this;
  24354. }
  24355. setLoopStart(value) {
  24356. this.loopStart = value;
  24357. return this;
  24358. }
  24359. setLoopEnd(value) {
  24360. this.loopEnd = value;
  24361. return this;
  24362. }
  24363. getVolume() {
  24364. return this.gain.gain.value;
  24365. }
  24366. setVolume(value) {
  24367. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  24368. return this;
  24369. }
  24370. }
  24371. const _position = /*@__PURE__*/new Vector3();
  24372. const _quaternion = /*@__PURE__*/new Quaternion();
  24373. const _scale = /*@__PURE__*/new Vector3();
  24374. const _orientation = /*@__PURE__*/new Vector3();
  24375. class PositionalAudio extends Audio {
  24376. constructor(listener) {
  24377. super(listener);
  24378. this.panner = this.context.createPanner();
  24379. this.panner.panningModel = 'HRTF';
  24380. this.panner.connect(this.gain);
  24381. }
  24382. getOutput() {
  24383. return this.panner;
  24384. }
  24385. getRefDistance() {
  24386. return this.panner.refDistance;
  24387. }
  24388. setRefDistance(value) {
  24389. this.panner.refDistance = value;
  24390. return this;
  24391. }
  24392. getRolloffFactor() {
  24393. return this.panner.rolloffFactor;
  24394. }
  24395. setRolloffFactor(value) {
  24396. this.panner.rolloffFactor = value;
  24397. return this;
  24398. }
  24399. getDistanceModel() {
  24400. return this.panner.distanceModel;
  24401. }
  24402. setDistanceModel(value) {
  24403. this.panner.distanceModel = value;
  24404. return this;
  24405. }
  24406. getMaxDistance() {
  24407. return this.panner.maxDistance;
  24408. }
  24409. setMaxDistance(value) {
  24410. this.panner.maxDistance = value;
  24411. return this;
  24412. }
  24413. setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  24414. this.panner.coneInnerAngle = coneInnerAngle;
  24415. this.panner.coneOuterAngle = coneOuterAngle;
  24416. this.panner.coneOuterGain = coneOuterGain;
  24417. return this;
  24418. }
  24419. updateMatrixWorld(force) {
  24420. super.updateMatrixWorld(force);
  24421. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  24422. this.matrixWorld.decompose(_position, _quaternion, _scale);
  24423. _orientation.set(0, 0, 1).applyQuaternion(_quaternion);
  24424. const panner = this.panner;
  24425. if (panner.positionX) {
  24426. // code path for Chrome and Firefox (see #14393)
  24427. const endTime = this.context.currentTime + this.listener.timeDelta;
  24428. panner.positionX.linearRampToValueAtTime(_position.x, endTime);
  24429. panner.positionY.linearRampToValueAtTime(_position.y, endTime);
  24430. panner.positionZ.linearRampToValueAtTime(_position.z, endTime);
  24431. panner.orientationX.linearRampToValueAtTime(_orientation.x, endTime);
  24432. panner.orientationY.linearRampToValueAtTime(_orientation.y, endTime);
  24433. panner.orientationZ.linearRampToValueAtTime(_orientation.z, endTime);
  24434. } else {
  24435. panner.setPosition(_position.x, _position.y, _position.z);
  24436. panner.setOrientation(_orientation.x, _orientation.y, _orientation.z);
  24437. }
  24438. }
  24439. }
  24440. class AudioAnalyser {
  24441. constructor(audio, fftSize = 2048) {
  24442. this.analyser = audio.context.createAnalyser();
  24443. this.analyser.fftSize = fftSize;
  24444. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  24445. audio.getOutput().connect(this.analyser);
  24446. }
  24447. getFrequencyData() {
  24448. this.analyser.getByteFrequencyData(this.data);
  24449. return this.data;
  24450. }
  24451. getAverageFrequency() {
  24452. let value = 0;
  24453. const data = this.getFrequencyData();
  24454. for (let i = 0; i < data.length; i++) {
  24455. value += data[i];
  24456. }
  24457. return value / data.length;
  24458. }
  24459. }
  24460. class PropertyMixer {
  24461. constructor(binding, typeName, valueSize) {
  24462. this.binding = binding;
  24463. this.valueSize = valueSize;
  24464. let mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  24465. //
  24466. // interpolators can use .buffer as their .result
  24467. // the data then goes to 'incoming'
  24468. //
  24469. // 'accu0' and 'accu1' are used frame-interleaved for
  24470. // the cumulative result and are compared to detect
  24471. // changes
  24472. //
  24473. // 'orig' stores the original state of the property
  24474. //
  24475. // 'add' is used for additive cumulative results
  24476. //
  24477. // 'work' is optional and is only present for quaternion types. It is used
  24478. // to store intermediate quaternion multiplication results
  24479. switch (typeName) {
  24480. case 'quaternion':
  24481. mixFunction = this._slerp;
  24482. mixFunctionAdditive = this._slerpAdditive;
  24483. setIdentity = this._setAdditiveIdentityQuaternion;
  24484. this.buffer = new Float64Array(valueSize * 6);
  24485. this._workIndex = 5;
  24486. break;
  24487. case 'string':
  24488. case 'bool':
  24489. mixFunction = this._select; // Use the regular mix function and for additive on these types,
  24490. // additive is not relevant for non-numeric types
  24491. mixFunctionAdditive = this._select;
  24492. setIdentity = this._setAdditiveIdentityOther;
  24493. this.buffer = new Array(valueSize * 5);
  24494. break;
  24495. default:
  24496. mixFunction = this._lerp;
  24497. mixFunctionAdditive = this._lerpAdditive;
  24498. setIdentity = this._setAdditiveIdentityNumeric;
  24499. this.buffer = new Float64Array(valueSize * 5);
  24500. }
  24501. this._mixBufferRegion = mixFunction;
  24502. this._mixBufferRegionAdditive = mixFunctionAdditive;
  24503. this._setIdentity = setIdentity;
  24504. this._origIndex = 3;
  24505. this._addIndex = 4;
  24506. this.cumulativeWeight = 0;
  24507. this.cumulativeWeightAdditive = 0;
  24508. this.useCount = 0;
  24509. this.referenceCount = 0;
  24510. } // accumulate data in the 'incoming' region into 'accu<i>'
  24511. accumulate(accuIndex, weight) {
  24512. // note: happily accumulating nothing when weight = 0, the caller knows
  24513. // the weight and shouldn't have made the call in the first place
  24514. const buffer = this.buffer,
  24515. stride = this.valueSize,
  24516. offset = accuIndex * stride + stride;
  24517. let currentWeight = this.cumulativeWeight;
  24518. if (currentWeight === 0) {
  24519. // accuN := incoming * weight
  24520. for (let i = 0; i !== stride; ++i) {
  24521. buffer[offset + i] = buffer[i];
  24522. }
  24523. currentWeight = weight;
  24524. } else {
  24525. // accuN := accuN + incoming * weight
  24526. currentWeight += weight;
  24527. const mix = weight / currentWeight;
  24528. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  24529. }
  24530. this.cumulativeWeight = currentWeight;
  24531. } // accumulate data in the 'incoming' region into 'add'
  24532. accumulateAdditive(weight) {
  24533. const buffer = this.buffer,
  24534. stride = this.valueSize,
  24535. offset = stride * this._addIndex;
  24536. if (this.cumulativeWeightAdditive === 0) {
  24537. // add = identity
  24538. this._setIdentity();
  24539. } // add := add + incoming * weight
  24540. this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
  24541. this.cumulativeWeightAdditive += weight;
  24542. } // apply the state of 'accu<i>' to the binding when accus differ
  24543. apply(accuIndex) {
  24544. const stride = this.valueSize,
  24545. buffer = this.buffer,
  24546. offset = accuIndex * stride + stride,
  24547. weight = this.cumulativeWeight,
  24548. weightAdditive = this.cumulativeWeightAdditive,
  24549. binding = this.binding;
  24550. this.cumulativeWeight = 0;
  24551. this.cumulativeWeightAdditive = 0;
  24552. if (weight < 1) {
  24553. // accuN := accuN + original * ( 1 - cumulativeWeight )
  24554. const originalValueOffset = stride * this._origIndex;
  24555. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  24556. }
  24557. if (weightAdditive > 0) {
  24558. // accuN := accuN + additive accuN
  24559. this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
  24560. }
  24561. for (let i = stride, e = stride + stride; i !== e; ++i) {
  24562. if (buffer[i] !== buffer[i + stride]) {
  24563. // value has changed -> update scene graph
  24564. binding.setValue(buffer, offset);
  24565. break;
  24566. }
  24567. }
  24568. } // remember the state of the bound property and copy it to both accus
  24569. saveOriginalState() {
  24570. const binding = this.binding;
  24571. const buffer = this.buffer,
  24572. stride = this.valueSize,
  24573. originalValueOffset = stride * this._origIndex;
  24574. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  24575. for (let i = stride, e = originalValueOffset; i !== e; ++i) {
  24576. buffer[i] = buffer[originalValueOffset + i % stride];
  24577. } // Add to identity for additive
  24578. this._setIdentity();
  24579. this.cumulativeWeight = 0;
  24580. this.cumulativeWeightAdditive = 0;
  24581. } // apply the state previously taken via 'saveOriginalState' to the binding
  24582. restoreOriginalState() {
  24583. const originalValueOffset = this.valueSize * 3;
  24584. this.binding.setValue(this.buffer, originalValueOffset);
  24585. }
  24586. _setAdditiveIdentityNumeric() {
  24587. const startIndex = this._addIndex * this.valueSize;
  24588. const endIndex = startIndex + this.valueSize;
  24589. for (let i = startIndex; i < endIndex; i++) {
  24590. this.buffer[i] = 0;
  24591. }
  24592. }
  24593. _setAdditiveIdentityQuaternion() {
  24594. this._setAdditiveIdentityNumeric();
  24595. this.buffer[this._addIndex * this.valueSize + 3] = 1;
  24596. }
  24597. _setAdditiveIdentityOther() {
  24598. const startIndex = this._origIndex * this.valueSize;
  24599. const targetIndex = this._addIndex * this.valueSize;
  24600. for (let i = 0; i < this.valueSize; i++) {
  24601. this.buffer[targetIndex + i] = this.buffer[startIndex + i];
  24602. }
  24603. } // mix functions
  24604. _select(buffer, dstOffset, srcOffset, t, stride) {
  24605. if (t >= 0.5) {
  24606. for (let i = 0; i !== stride; ++i) {
  24607. buffer[dstOffset + i] = buffer[srcOffset + i];
  24608. }
  24609. }
  24610. }
  24611. _slerp(buffer, dstOffset, srcOffset, t) {
  24612. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  24613. }
  24614. _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  24615. const workOffset = this._workIndex * stride; // Store result in intermediate buffer offset
  24616. Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
  24617. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
  24618. }
  24619. _lerp(buffer, dstOffset, srcOffset, t, stride) {
  24620. const s = 1 - t;
  24621. for (let i = 0; i !== stride; ++i) {
  24622. const j = dstOffset + i;
  24623. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  24624. }
  24625. }
  24626. _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  24627. for (let i = 0; i !== stride; ++i) {
  24628. const j = dstOffset + i;
  24629. buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
  24630. }
  24631. }
  24632. }
  24633. // Characters [].:/ are reserved for track binding syntax.
  24634. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  24635. const _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  24636. // only latin characters, and the unicode \p{L} is not yet supported. So
  24637. // instead, we exclude reserved characters and match everything else.
  24638. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  24639. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  24640. // be matched to parse the rest of the track name.
  24641. const _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  24642. const _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  24643. // characters. Accessor may contain any character except closing bracket.
  24644. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  24645. // contain any non-bracket characters.
  24646. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  24647. const _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  24648. const _supportedObjectNames = ['material', 'materials', 'bones'];
  24649. class Composite {
  24650. constructor(targetGroup, path, optionalParsedPath) {
  24651. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  24652. this._targetGroup = targetGroup;
  24653. this._bindings = targetGroup.subscribe_(path, parsedPath);
  24654. }
  24655. getValue(array, offset) {
  24656. this.bind(); // bind all binding
  24657. const firstValidIndex = this._targetGroup.nCachedObjects_,
  24658. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  24659. if (binding !== undefined) binding.getValue(array, offset);
  24660. }
  24661. setValue(array, offset) {
  24662. const bindings = this._bindings;
  24663. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  24664. bindings[i].setValue(array, offset);
  24665. }
  24666. }
  24667. bind() {
  24668. const bindings = this._bindings;
  24669. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  24670. bindings[i].bind();
  24671. }
  24672. }
  24673. unbind() {
  24674. const bindings = this._bindings;
  24675. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  24676. bindings[i].unbind();
  24677. }
  24678. }
  24679. } // Note: This class uses a State pattern on a per-method basis:
  24680. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  24681. // prototype version of these methods with one that represents
  24682. // the bound state. When the property is not found, the methods
  24683. // become no-ops.
  24684. class PropertyBinding {
  24685. constructor(rootNode, path, parsedPath) {
  24686. this.path = path;
  24687. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  24688. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  24689. this.rootNode = rootNode; // initial state of these methods that calls 'bind'
  24690. this.getValue = this._getValue_unbound;
  24691. this.setValue = this._setValue_unbound;
  24692. }
  24693. static create(root, path, parsedPath) {
  24694. if (!(root && root.isAnimationObjectGroup)) {
  24695. return new PropertyBinding(root, path, parsedPath);
  24696. } else {
  24697. return new PropertyBinding.Composite(root, path, parsedPath);
  24698. }
  24699. }
  24700. /**
  24701. * Replaces spaces with underscores and removes unsupported characters from
  24702. * node names, to ensure compatibility with parseTrackName().
  24703. *
  24704. * @param {string} name Node name to be sanitized.
  24705. * @return {string}
  24706. */
  24707. static sanitizeNodeName(name) {
  24708. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  24709. }
  24710. static parseTrackName(trackName) {
  24711. const matches = _trackRe.exec(trackName);
  24712. if (!matches) {
  24713. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  24714. }
  24715. const results = {
  24716. // directoryName: matches[ 1 ], // (tschw) currently unused
  24717. nodeName: matches[2],
  24718. objectName: matches[3],
  24719. objectIndex: matches[4],
  24720. propertyName: matches[5],
  24721. // required
  24722. propertyIndex: matches[6]
  24723. };
  24724. const lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  24725. if (lastDot !== undefined && lastDot !== -1) {
  24726. const objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
  24727. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  24728. // 'bar' could be the objectName, or part of a nodeName (which can
  24729. // include '.' characters).
  24730. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  24731. results.nodeName = results.nodeName.substring(0, lastDot);
  24732. results.objectName = objectName;
  24733. }
  24734. }
  24735. if (results.propertyName === null || results.propertyName.length === 0) {
  24736. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  24737. }
  24738. return results;
  24739. }
  24740. static findNode(root, nodeName) {
  24741. if (!nodeName || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  24742. return root;
  24743. } // search into skeleton bones.
  24744. if (root.skeleton) {
  24745. const bone = root.skeleton.getBoneByName(nodeName);
  24746. if (bone !== undefined) {
  24747. return bone;
  24748. }
  24749. } // search into node subtree.
  24750. if (root.children) {
  24751. const searchNodeSubtree = function (children) {
  24752. for (let i = 0; i < children.length; i++) {
  24753. const childNode = children[i];
  24754. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  24755. return childNode;
  24756. }
  24757. const result = searchNodeSubtree(childNode.children);
  24758. if (result) return result;
  24759. }
  24760. return null;
  24761. };
  24762. const subTreeNode = searchNodeSubtree(root.children);
  24763. if (subTreeNode) {
  24764. return subTreeNode;
  24765. }
  24766. }
  24767. return null;
  24768. } // these are used to "bind" a nonexistent property
  24769. _getValue_unavailable() {}
  24770. _setValue_unavailable() {} // Getters
  24771. _getValue_direct(buffer, offset) {
  24772. buffer[offset] = this.node[this.propertyName];
  24773. }
  24774. _getValue_array(buffer, offset) {
  24775. const source = this.resolvedProperty;
  24776. for (let i = 0, n = source.length; i !== n; ++i) {
  24777. buffer[offset++] = source[i];
  24778. }
  24779. }
  24780. _getValue_arrayElement(buffer, offset) {
  24781. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  24782. }
  24783. _getValue_toArray(buffer, offset) {
  24784. this.resolvedProperty.toArray(buffer, offset);
  24785. } // Direct
  24786. _setValue_direct(buffer, offset) {
  24787. this.targetObject[this.propertyName] = buffer[offset];
  24788. }
  24789. _setValue_direct_setNeedsUpdate(buffer, offset) {
  24790. this.targetObject[this.propertyName] = buffer[offset];
  24791. this.targetObject.needsUpdate = true;
  24792. }
  24793. _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  24794. this.targetObject[this.propertyName] = buffer[offset];
  24795. this.targetObject.matrixWorldNeedsUpdate = true;
  24796. } // EntireArray
  24797. _setValue_array(buffer, offset) {
  24798. const dest = this.resolvedProperty;
  24799. for (let i = 0, n = dest.length; i !== n; ++i) {
  24800. dest[i] = buffer[offset++];
  24801. }
  24802. }
  24803. _setValue_array_setNeedsUpdate(buffer, offset) {
  24804. const dest = this.resolvedProperty;
  24805. for (let i = 0, n = dest.length; i !== n; ++i) {
  24806. dest[i] = buffer[offset++];
  24807. }
  24808. this.targetObject.needsUpdate = true;
  24809. }
  24810. _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  24811. const dest = this.resolvedProperty;
  24812. for (let i = 0, n = dest.length; i !== n; ++i) {
  24813. dest[i] = buffer[offset++];
  24814. }
  24815. this.targetObject.matrixWorldNeedsUpdate = true;
  24816. } // ArrayElement
  24817. _setValue_arrayElement(buffer, offset) {
  24818. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  24819. }
  24820. _setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  24821. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  24822. this.targetObject.needsUpdate = true;
  24823. }
  24824. _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  24825. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  24826. this.targetObject.matrixWorldNeedsUpdate = true;
  24827. } // HasToFromArray
  24828. _setValue_fromArray(buffer, offset) {
  24829. this.resolvedProperty.fromArray(buffer, offset);
  24830. }
  24831. _setValue_fromArray_setNeedsUpdate(buffer, offset) {
  24832. this.resolvedProperty.fromArray(buffer, offset);
  24833. this.targetObject.needsUpdate = true;
  24834. }
  24835. _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  24836. this.resolvedProperty.fromArray(buffer, offset);
  24837. this.targetObject.matrixWorldNeedsUpdate = true;
  24838. }
  24839. _getValue_unbound(targetArray, offset) {
  24840. this.bind();
  24841. this.getValue(targetArray, offset);
  24842. }
  24843. _setValue_unbound(sourceArray, offset) {
  24844. this.bind();
  24845. this.setValue(sourceArray, offset);
  24846. } // create getter / setter pair for a property in the scene graph
  24847. bind() {
  24848. let targetObject = this.node;
  24849. const parsedPath = this.parsedPath;
  24850. const objectName = parsedPath.objectName;
  24851. const propertyName = parsedPath.propertyName;
  24852. let propertyIndex = parsedPath.propertyIndex;
  24853. if (!targetObject) {
  24854. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  24855. this.node = targetObject;
  24856. } // set fail state so we can just 'return' on error
  24857. this.getValue = this._getValue_unavailable;
  24858. this.setValue = this._setValue_unavailable; // ensure there is a value node
  24859. if (!targetObject) {
  24860. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  24861. return;
  24862. }
  24863. if (objectName) {
  24864. let objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  24865. switch (objectName) {
  24866. case 'materials':
  24867. if (!targetObject.material) {
  24868. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  24869. return;
  24870. }
  24871. if (!targetObject.material.materials) {
  24872. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  24873. return;
  24874. }
  24875. targetObject = targetObject.material.materials;
  24876. break;
  24877. case 'bones':
  24878. if (!targetObject.skeleton) {
  24879. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  24880. return;
  24881. } // potential future optimization: skip this if propertyIndex is already an integer
  24882. // and convert the integer string to a true integer.
  24883. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  24884. for (let i = 0; i < targetObject.length; i++) {
  24885. if (targetObject[i].name === objectIndex) {
  24886. objectIndex = i;
  24887. break;
  24888. }
  24889. }
  24890. break;
  24891. default:
  24892. if (targetObject[objectName] === undefined) {
  24893. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  24894. return;
  24895. }
  24896. targetObject = targetObject[objectName];
  24897. }
  24898. if (objectIndex !== undefined) {
  24899. if (targetObject[objectIndex] === undefined) {
  24900. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  24901. return;
  24902. }
  24903. targetObject = targetObject[objectIndex];
  24904. }
  24905. } // resolve property
  24906. const nodeProperty = targetObject[propertyName];
  24907. if (nodeProperty === undefined) {
  24908. const nodeName = parsedPath.nodeName;
  24909. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  24910. return;
  24911. } // determine versioning scheme
  24912. let versioning = this.Versioning.None;
  24913. this.targetObject = targetObject;
  24914. if (targetObject.needsUpdate !== undefined) {
  24915. // material
  24916. versioning = this.Versioning.NeedsUpdate;
  24917. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  24918. // node transform
  24919. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  24920. } // determine how the property gets bound
  24921. let bindingType = this.BindingType.Direct;
  24922. if (propertyIndex !== undefined) {
  24923. // access a sub element of the property array (only primitives are supported right now)
  24924. if (propertyName === 'morphTargetInfluences') {
  24925. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  24926. // support resolving morphTarget names into indices.
  24927. if (!targetObject.geometry) {
  24928. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  24929. return;
  24930. }
  24931. if (targetObject.geometry.isBufferGeometry) {
  24932. if (!targetObject.geometry.morphAttributes) {
  24933. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  24934. return;
  24935. }
  24936. if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
  24937. propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
  24938. }
  24939. } else {
  24940. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this);
  24941. return;
  24942. }
  24943. }
  24944. bindingType = this.BindingType.ArrayElement;
  24945. this.resolvedProperty = nodeProperty;
  24946. this.propertyIndex = propertyIndex;
  24947. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  24948. // must use copy for Object3D.Euler/Quaternion
  24949. bindingType = this.BindingType.HasFromToArray;
  24950. this.resolvedProperty = nodeProperty;
  24951. } else if (Array.isArray(nodeProperty)) {
  24952. bindingType = this.BindingType.EntireArray;
  24953. this.resolvedProperty = nodeProperty;
  24954. } else {
  24955. this.propertyName = propertyName;
  24956. } // select getter / setter
  24957. this.getValue = this.GetterByBindingType[bindingType];
  24958. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  24959. }
  24960. unbind() {
  24961. this.node = null; // back to the prototype version of getValue / setValue
  24962. // note: avoiding to mutate the shape of 'this' via 'delete'
  24963. this.getValue = this._getValue_unbound;
  24964. this.setValue = this._setValue_unbound;
  24965. }
  24966. }
  24967. PropertyBinding.Composite = Composite;
  24968. PropertyBinding.prototype.BindingType = {
  24969. Direct: 0,
  24970. EntireArray: 1,
  24971. ArrayElement: 2,
  24972. HasFromToArray: 3
  24973. };
  24974. PropertyBinding.prototype.Versioning = {
  24975. None: 0,
  24976. NeedsUpdate: 1,
  24977. MatrixWorldNeedsUpdate: 2
  24978. };
  24979. PropertyBinding.prototype.GetterByBindingType = [PropertyBinding.prototype._getValue_direct, PropertyBinding.prototype._getValue_array, PropertyBinding.prototype._getValue_arrayElement, PropertyBinding.prototype._getValue_toArray];
  24980. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [[// Direct
  24981. PropertyBinding.prototype._setValue_direct, PropertyBinding.prototype._setValue_direct_setNeedsUpdate, PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate], [// EntireArray
  24982. PropertyBinding.prototype._setValue_array, PropertyBinding.prototype._setValue_array_setNeedsUpdate, PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate], [// ArrayElement
  24983. PropertyBinding.prototype._setValue_arrayElement, PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate], [// HasToFromArray
  24984. PropertyBinding.prototype._setValue_fromArray, PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];
  24985. /**
  24986. *
  24987. * A group of objects that receives a shared animation state.
  24988. *
  24989. * Usage:
  24990. *
  24991. * - Add objects you would otherwise pass as 'root' to the
  24992. * constructor or the .clipAction method of AnimationMixer.
  24993. *
  24994. * - Instead pass this object as 'root'.
  24995. *
  24996. * - You can also add and remove objects later when the mixer
  24997. * is running.
  24998. *
  24999. * Note:
  25000. *
  25001. * Objects of this class appear as one object to the mixer,
  25002. * so cache control of the individual objects must be done
  25003. * on the group.
  25004. *
  25005. * Limitation:
  25006. *
  25007. * - The animated properties must be compatible among the
  25008. * all objects in the group.
  25009. *
  25010. * - A single property can either be controlled through a
  25011. * target group or directly, but not both.
  25012. */
  25013. class AnimationObjectGroup {
  25014. constructor() {
  25015. this.uuid = generateUUID(); // cached objects followed by the active ones
  25016. this._objects = Array.prototype.slice.call(arguments);
  25017. this.nCachedObjects_ = 0; // threshold
  25018. // note: read by PropertyBinding.Composite
  25019. const indices = {};
  25020. this._indicesByUUID = indices; // for bookkeeping
  25021. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25022. indices[arguments[i].uuid] = i;
  25023. }
  25024. this._paths = []; // inside: string
  25025. this._parsedPaths = []; // inside: { we don't care, here }
  25026. this._bindings = []; // inside: Array< PropertyBinding >
  25027. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  25028. const scope = this;
  25029. this.stats = {
  25030. objects: {
  25031. get total() {
  25032. return scope._objects.length;
  25033. },
  25034. get inUse() {
  25035. return this.total - scope.nCachedObjects_;
  25036. }
  25037. },
  25038. get bindingsPerObject() {
  25039. return scope._bindings.length;
  25040. }
  25041. };
  25042. }
  25043. add() {
  25044. const objects = this._objects,
  25045. indicesByUUID = this._indicesByUUID,
  25046. paths = this._paths,
  25047. parsedPaths = this._parsedPaths,
  25048. bindings = this._bindings,
  25049. nBindings = bindings.length;
  25050. let knownObject = undefined,
  25051. nObjects = objects.length,
  25052. nCachedObjects = this.nCachedObjects_;
  25053. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25054. const object = arguments[i],
  25055. uuid = object.uuid;
  25056. let index = indicesByUUID[uuid];
  25057. if (index === undefined) {
  25058. // unknown object -> add it to the ACTIVE region
  25059. index = nObjects++;
  25060. indicesByUUID[uuid] = index;
  25061. objects.push(object); // accounting is done, now do the same for all bindings
  25062. for (let j = 0, m = nBindings; j !== m; ++j) {
  25063. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  25064. }
  25065. } else if (index < nCachedObjects) {
  25066. knownObject = objects[index]; // move existing object to the ACTIVE region
  25067. const firstActiveIndex = --nCachedObjects,
  25068. lastCachedObject = objects[firstActiveIndex];
  25069. indicesByUUID[lastCachedObject.uuid] = index;
  25070. objects[index] = lastCachedObject;
  25071. indicesByUUID[uuid] = firstActiveIndex;
  25072. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  25073. for (let j = 0, m = nBindings; j !== m; ++j) {
  25074. const bindingsForPath = bindings[j],
  25075. lastCached = bindingsForPath[firstActiveIndex];
  25076. let binding = bindingsForPath[index];
  25077. bindingsForPath[index] = lastCached;
  25078. if (binding === undefined) {
  25079. // since we do not bother to create new bindings
  25080. // for objects that are cached, the binding may
  25081. // or may not exist
  25082. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  25083. }
  25084. bindingsForPath[firstActiveIndex] = binding;
  25085. }
  25086. } else if (objects[index] !== knownObject) {
  25087. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  25088. } // else the object is already where we want it to be
  25089. } // for arguments
  25090. this.nCachedObjects_ = nCachedObjects;
  25091. }
  25092. remove() {
  25093. const objects = this._objects,
  25094. indicesByUUID = this._indicesByUUID,
  25095. bindings = this._bindings,
  25096. nBindings = bindings.length;
  25097. let nCachedObjects = this.nCachedObjects_;
  25098. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25099. const object = arguments[i],
  25100. uuid = object.uuid,
  25101. index = indicesByUUID[uuid];
  25102. if (index !== undefined && index >= nCachedObjects) {
  25103. // move existing object into the CACHED region
  25104. const lastCachedIndex = nCachedObjects++,
  25105. firstActiveObject = objects[lastCachedIndex];
  25106. indicesByUUID[firstActiveObject.uuid] = index;
  25107. objects[index] = firstActiveObject;
  25108. indicesByUUID[uuid] = lastCachedIndex;
  25109. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  25110. for (let j = 0, m = nBindings; j !== m; ++j) {
  25111. const bindingsForPath = bindings[j],
  25112. firstActive = bindingsForPath[lastCachedIndex],
  25113. binding = bindingsForPath[index];
  25114. bindingsForPath[index] = firstActive;
  25115. bindingsForPath[lastCachedIndex] = binding;
  25116. }
  25117. }
  25118. } // for arguments
  25119. this.nCachedObjects_ = nCachedObjects;
  25120. } // remove & forget
  25121. uncache() {
  25122. const objects = this._objects,
  25123. indicesByUUID = this._indicesByUUID,
  25124. bindings = this._bindings,
  25125. nBindings = bindings.length;
  25126. let nCachedObjects = this.nCachedObjects_,
  25127. nObjects = objects.length;
  25128. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25129. const object = arguments[i],
  25130. uuid = object.uuid,
  25131. index = indicesByUUID[uuid];
  25132. if (index !== undefined) {
  25133. delete indicesByUUID[uuid];
  25134. if (index < nCachedObjects) {
  25135. // object is cached, shrink the CACHED region
  25136. const firstActiveIndex = --nCachedObjects,
  25137. lastCachedObject = objects[firstActiveIndex],
  25138. lastIndex = --nObjects,
  25139. lastObject = objects[lastIndex]; // last cached object takes this object's place
  25140. indicesByUUID[lastCachedObject.uuid] = index;
  25141. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  25142. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  25143. objects[firstActiveIndex] = lastObject;
  25144. objects.pop(); // accounting is done, now do the same for all bindings
  25145. for (let j = 0, m = nBindings; j !== m; ++j) {
  25146. const bindingsForPath = bindings[j],
  25147. lastCached = bindingsForPath[firstActiveIndex],
  25148. last = bindingsForPath[lastIndex];
  25149. bindingsForPath[index] = lastCached;
  25150. bindingsForPath[firstActiveIndex] = last;
  25151. bindingsForPath.pop();
  25152. }
  25153. } else {
  25154. // object is active, just swap with the last and pop
  25155. const lastIndex = --nObjects,
  25156. lastObject = objects[lastIndex];
  25157. if (lastIndex > 0) {
  25158. indicesByUUID[lastObject.uuid] = index;
  25159. }
  25160. objects[index] = lastObject;
  25161. objects.pop(); // accounting is done, now do the same for all bindings
  25162. for (let j = 0, m = nBindings; j !== m; ++j) {
  25163. const bindingsForPath = bindings[j];
  25164. bindingsForPath[index] = bindingsForPath[lastIndex];
  25165. bindingsForPath.pop();
  25166. }
  25167. } // cached or active
  25168. } // if object is known
  25169. } // for arguments
  25170. this.nCachedObjects_ = nCachedObjects;
  25171. } // Internal interface used by befriended PropertyBinding.Composite:
  25172. subscribe_(path, parsedPath) {
  25173. // returns an array of bindings for the given path that is changed
  25174. // according to the contained objects in the group
  25175. const indicesByPath = this._bindingsIndicesByPath;
  25176. let index = indicesByPath[path];
  25177. const bindings = this._bindings;
  25178. if (index !== undefined) return bindings[index];
  25179. const paths = this._paths,
  25180. parsedPaths = this._parsedPaths,
  25181. objects = this._objects,
  25182. nObjects = objects.length,
  25183. nCachedObjects = this.nCachedObjects_,
  25184. bindingsForPath = new Array(nObjects);
  25185. index = bindings.length;
  25186. indicesByPath[path] = index;
  25187. paths.push(path);
  25188. parsedPaths.push(parsedPath);
  25189. bindings.push(bindingsForPath);
  25190. for (let i = nCachedObjects, n = objects.length; i !== n; ++i) {
  25191. const object = objects[i];
  25192. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  25193. }
  25194. return bindingsForPath;
  25195. }
  25196. unsubscribe_(path) {
  25197. // tells the group to forget about a property path and no longer
  25198. // update the array previously obtained with 'subscribe_'
  25199. const indicesByPath = this._bindingsIndicesByPath,
  25200. index = indicesByPath[path];
  25201. if (index !== undefined) {
  25202. const paths = this._paths,
  25203. parsedPaths = this._parsedPaths,
  25204. bindings = this._bindings,
  25205. lastBindingsIndex = bindings.length - 1,
  25206. lastBindings = bindings[lastBindingsIndex],
  25207. lastBindingsPath = path[lastBindingsIndex];
  25208. indicesByPath[lastBindingsPath] = index;
  25209. bindings[index] = lastBindings;
  25210. bindings.pop();
  25211. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  25212. parsedPaths.pop();
  25213. paths[index] = paths[lastBindingsIndex];
  25214. paths.pop();
  25215. }
  25216. }
  25217. }
  25218. AnimationObjectGroup.prototype.isAnimationObjectGroup = true;
  25219. class AnimationAction {
  25220. constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) {
  25221. this._mixer = mixer;
  25222. this._clip = clip;
  25223. this._localRoot = localRoot;
  25224. this.blendMode = blendMode;
  25225. const tracks = clip.tracks,
  25226. nTracks = tracks.length,
  25227. interpolants = new Array(nTracks);
  25228. const interpolantSettings = {
  25229. endingStart: ZeroCurvatureEnding,
  25230. endingEnd: ZeroCurvatureEnding
  25231. };
  25232. for (let i = 0; i !== nTracks; ++i) {
  25233. const interpolant = tracks[i].createInterpolant(null);
  25234. interpolants[i] = interpolant;
  25235. interpolant.settings = interpolantSettings;
  25236. }
  25237. this._interpolantSettings = interpolantSettings;
  25238. this._interpolants = interpolants; // bound by the mixer
  25239. // inside: PropertyMixer (managed by the mixer)
  25240. this._propertyBindings = new Array(nTracks);
  25241. this._cacheIndex = null; // for the memory manager
  25242. this._byClipCacheIndex = null; // for the memory manager
  25243. this._timeScaleInterpolant = null;
  25244. this._weightInterpolant = null;
  25245. this.loop = LoopRepeat;
  25246. this._loopCount = -1; // global mixer time when the action is to be started
  25247. // it's set back to 'null' upon start of the action
  25248. this._startTime = null; // scaled local time of the action
  25249. // gets clamped or wrapped to 0..clip.duration according to loop
  25250. this.time = 0;
  25251. this.timeScale = 1;
  25252. this._effectiveTimeScale = 1;
  25253. this.weight = 1;
  25254. this._effectiveWeight = 1;
  25255. this.repetitions = Infinity; // no. of repetitions when looping
  25256. this.paused = false; // true -> zero effective time scale
  25257. this.enabled = true; // false -> zero effective weight
  25258. this.clampWhenFinished = false; // keep feeding the last frame?
  25259. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  25260. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  25261. } // State & Scheduling
  25262. play() {
  25263. this._mixer._activateAction(this);
  25264. return this;
  25265. }
  25266. stop() {
  25267. this._mixer._deactivateAction(this);
  25268. return this.reset();
  25269. }
  25270. reset() {
  25271. this.paused = false;
  25272. this.enabled = true;
  25273. this.time = 0; // restart clip
  25274. this._loopCount = -1; // forget previous loops
  25275. this._startTime = null; // forget scheduling
  25276. return this.stopFading().stopWarping();
  25277. }
  25278. isRunning() {
  25279. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  25280. } // return true when play has been called
  25281. isScheduled() {
  25282. return this._mixer._isActiveAction(this);
  25283. }
  25284. startAt(time) {
  25285. this._startTime = time;
  25286. return this;
  25287. }
  25288. setLoop(mode, repetitions) {
  25289. this.loop = mode;
  25290. this.repetitions = repetitions;
  25291. return this;
  25292. } // Weight
  25293. // set the weight stopping any scheduled fading
  25294. // although .enabled = false yields an effective weight of zero, this
  25295. // method does *not* change .enabled, because it would be confusing
  25296. setEffectiveWeight(weight) {
  25297. this.weight = weight; // note: same logic as when updated at runtime
  25298. this._effectiveWeight = this.enabled ? weight : 0;
  25299. return this.stopFading();
  25300. } // return the weight considering fading and .enabled
  25301. getEffectiveWeight() {
  25302. return this._effectiveWeight;
  25303. }
  25304. fadeIn(duration) {
  25305. return this._scheduleFading(duration, 0, 1);
  25306. }
  25307. fadeOut(duration) {
  25308. return this._scheduleFading(duration, 1, 0);
  25309. }
  25310. crossFadeFrom(fadeOutAction, duration, warp) {
  25311. fadeOutAction.fadeOut(duration);
  25312. this.fadeIn(duration);
  25313. if (warp) {
  25314. const fadeInDuration = this._clip.duration,
  25315. fadeOutDuration = fadeOutAction._clip.duration,
  25316. startEndRatio = fadeOutDuration / fadeInDuration,
  25317. endStartRatio = fadeInDuration / fadeOutDuration;
  25318. fadeOutAction.warp(1.0, startEndRatio, duration);
  25319. this.warp(endStartRatio, 1.0, duration);
  25320. }
  25321. return this;
  25322. }
  25323. crossFadeTo(fadeInAction, duration, warp) {
  25324. return fadeInAction.crossFadeFrom(this, duration, warp);
  25325. }
  25326. stopFading() {
  25327. const weightInterpolant = this._weightInterpolant;
  25328. if (weightInterpolant !== null) {
  25329. this._weightInterpolant = null;
  25330. this._mixer._takeBackControlInterpolant(weightInterpolant);
  25331. }
  25332. return this;
  25333. } // Time Scale Control
  25334. // set the time scale stopping any scheduled warping
  25335. // although .paused = true yields an effective time scale of zero, this
  25336. // method does *not* change .paused, because it would be confusing
  25337. setEffectiveTimeScale(timeScale) {
  25338. this.timeScale = timeScale;
  25339. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  25340. return this.stopWarping();
  25341. } // return the time scale considering warping and .paused
  25342. getEffectiveTimeScale() {
  25343. return this._effectiveTimeScale;
  25344. }
  25345. setDuration(duration) {
  25346. this.timeScale = this._clip.duration / duration;
  25347. return this.stopWarping();
  25348. }
  25349. syncWith(action) {
  25350. this.time = action.time;
  25351. this.timeScale = action.timeScale;
  25352. return this.stopWarping();
  25353. }
  25354. halt(duration) {
  25355. return this.warp(this._effectiveTimeScale, 0, duration);
  25356. }
  25357. warp(startTimeScale, endTimeScale, duration) {
  25358. const mixer = this._mixer,
  25359. now = mixer.time,
  25360. timeScale = this.timeScale;
  25361. let interpolant = this._timeScaleInterpolant;
  25362. if (interpolant === null) {
  25363. interpolant = mixer._lendControlInterpolant();
  25364. this._timeScaleInterpolant = interpolant;
  25365. }
  25366. const times = interpolant.parameterPositions,
  25367. values = interpolant.sampleValues;
  25368. times[0] = now;
  25369. times[1] = now + duration;
  25370. values[0] = startTimeScale / timeScale;
  25371. values[1] = endTimeScale / timeScale;
  25372. return this;
  25373. }
  25374. stopWarping() {
  25375. const timeScaleInterpolant = this._timeScaleInterpolant;
  25376. if (timeScaleInterpolant !== null) {
  25377. this._timeScaleInterpolant = null;
  25378. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  25379. }
  25380. return this;
  25381. } // Object Accessors
  25382. getMixer() {
  25383. return this._mixer;
  25384. }
  25385. getClip() {
  25386. return this._clip;
  25387. }
  25388. getRoot() {
  25389. return this._localRoot || this._mixer._root;
  25390. } // Interna
  25391. _update(time, deltaTime, timeDirection, accuIndex) {
  25392. // called by the mixer
  25393. if (!this.enabled) {
  25394. // call ._updateWeight() to update ._effectiveWeight
  25395. this._updateWeight(time);
  25396. return;
  25397. }
  25398. const startTime = this._startTime;
  25399. if (startTime !== null) {
  25400. // check for scheduled start of action
  25401. const timeRunning = (time - startTime) * timeDirection;
  25402. if (timeRunning < 0 || timeDirection === 0) {
  25403. return; // yet to come / don't decide when delta = 0
  25404. } // start
  25405. this._startTime = null; // unschedule
  25406. deltaTime = timeDirection * timeRunning;
  25407. } // apply time scale and advance time
  25408. deltaTime *= this._updateTimeScale(time);
  25409. const clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  25410. // an effective weight of 0
  25411. const weight = this._updateWeight(time);
  25412. if (weight > 0) {
  25413. const interpolants = this._interpolants;
  25414. const propertyMixers = this._propertyBindings;
  25415. switch (this.blendMode) {
  25416. case AdditiveAnimationBlendMode:
  25417. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  25418. interpolants[j].evaluate(clipTime);
  25419. propertyMixers[j].accumulateAdditive(weight);
  25420. }
  25421. break;
  25422. case NormalAnimationBlendMode:
  25423. default:
  25424. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  25425. interpolants[j].evaluate(clipTime);
  25426. propertyMixers[j].accumulate(accuIndex, weight);
  25427. }
  25428. }
  25429. }
  25430. }
  25431. _updateWeight(time) {
  25432. let weight = 0;
  25433. if (this.enabled) {
  25434. weight = this.weight;
  25435. const interpolant = this._weightInterpolant;
  25436. if (interpolant !== null) {
  25437. const interpolantValue = interpolant.evaluate(time)[0];
  25438. weight *= interpolantValue;
  25439. if (time > interpolant.parameterPositions[1]) {
  25440. this.stopFading();
  25441. if (interpolantValue === 0) {
  25442. // faded out, disable
  25443. this.enabled = false;
  25444. }
  25445. }
  25446. }
  25447. }
  25448. this._effectiveWeight = weight;
  25449. return weight;
  25450. }
  25451. _updateTimeScale(time) {
  25452. let timeScale = 0;
  25453. if (!this.paused) {
  25454. timeScale = this.timeScale;
  25455. const interpolant = this._timeScaleInterpolant;
  25456. if (interpolant !== null) {
  25457. const interpolantValue = interpolant.evaluate(time)[0];
  25458. timeScale *= interpolantValue;
  25459. if (time > interpolant.parameterPositions[1]) {
  25460. this.stopWarping();
  25461. if (timeScale === 0) {
  25462. // motion has halted, pause
  25463. this.paused = true;
  25464. } else {
  25465. // warp done - apply final time scale
  25466. this.timeScale = timeScale;
  25467. }
  25468. }
  25469. }
  25470. }
  25471. this._effectiveTimeScale = timeScale;
  25472. return timeScale;
  25473. }
  25474. _updateTime(deltaTime) {
  25475. const duration = this._clip.duration;
  25476. const loop = this.loop;
  25477. let time = this.time + deltaTime;
  25478. let loopCount = this._loopCount;
  25479. const pingPong = loop === LoopPingPong;
  25480. if (deltaTime === 0) {
  25481. if (loopCount === -1) return time;
  25482. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  25483. }
  25484. if (loop === LoopOnce) {
  25485. if (loopCount === -1) {
  25486. // just started
  25487. this._loopCount = 0;
  25488. this._setEndings(true, true, false);
  25489. }
  25490. handle_stop: {
  25491. if (time >= duration) {
  25492. time = duration;
  25493. } else if (time < 0) {
  25494. time = 0;
  25495. } else {
  25496. this.time = time;
  25497. break handle_stop;
  25498. }
  25499. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  25500. this.time = time;
  25501. this._mixer.dispatchEvent({
  25502. type: 'finished',
  25503. action: this,
  25504. direction: deltaTime < 0 ? -1 : 1
  25505. });
  25506. }
  25507. } else {
  25508. // repetitive Repeat or PingPong
  25509. if (loopCount === -1) {
  25510. // just started
  25511. if (deltaTime >= 0) {
  25512. loopCount = 0;
  25513. this._setEndings(true, this.repetitions === 0, pingPong);
  25514. } else {
  25515. // when looping in reverse direction, the initial
  25516. // transition through zero counts as a repetition,
  25517. // so leave loopCount at -1
  25518. this._setEndings(this.repetitions === 0, true, pingPong);
  25519. }
  25520. }
  25521. if (time >= duration || time < 0) {
  25522. // wrap around
  25523. const loopDelta = Math.floor(time / duration); // signed
  25524. time -= duration * loopDelta;
  25525. loopCount += Math.abs(loopDelta);
  25526. const pending = this.repetitions - loopCount;
  25527. if (pending <= 0) {
  25528. // have to stop (switch state, clamp time, fire event)
  25529. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  25530. time = deltaTime > 0 ? duration : 0;
  25531. this.time = time;
  25532. this._mixer.dispatchEvent({
  25533. type: 'finished',
  25534. action: this,
  25535. direction: deltaTime > 0 ? 1 : -1
  25536. });
  25537. } else {
  25538. // keep running
  25539. if (pending === 1) {
  25540. // entering the last round
  25541. const atStart = deltaTime < 0;
  25542. this._setEndings(atStart, !atStart, pingPong);
  25543. } else {
  25544. this._setEndings(false, false, pingPong);
  25545. }
  25546. this._loopCount = loopCount;
  25547. this.time = time;
  25548. this._mixer.dispatchEvent({
  25549. type: 'loop',
  25550. action: this,
  25551. loopDelta: loopDelta
  25552. });
  25553. }
  25554. } else {
  25555. this.time = time;
  25556. }
  25557. if (pingPong && (loopCount & 1) === 1) {
  25558. // invert time for the "pong round"
  25559. return duration - time;
  25560. }
  25561. }
  25562. return time;
  25563. }
  25564. _setEndings(atStart, atEnd, pingPong) {
  25565. const settings = this._interpolantSettings;
  25566. if (pingPong) {
  25567. settings.endingStart = ZeroSlopeEnding;
  25568. settings.endingEnd = ZeroSlopeEnding;
  25569. } else {
  25570. // assuming for LoopOnce atStart == atEnd == true
  25571. if (atStart) {
  25572. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  25573. } else {
  25574. settings.endingStart = WrapAroundEnding;
  25575. }
  25576. if (atEnd) {
  25577. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  25578. } else {
  25579. settings.endingEnd = WrapAroundEnding;
  25580. }
  25581. }
  25582. }
  25583. _scheduleFading(duration, weightNow, weightThen) {
  25584. const mixer = this._mixer,
  25585. now = mixer.time;
  25586. let interpolant = this._weightInterpolant;
  25587. if (interpolant === null) {
  25588. interpolant = mixer._lendControlInterpolant();
  25589. this._weightInterpolant = interpolant;
  25590. }
  25591. const times = interpolant.parameterPositions,
  25592. values = interpolant.sampleValues;
  25593. times[0] = now;
  25594. values[0] = weightNow;
  25595. times[1] = now + duration;
  25596. values[1] = weightThen;
  25597. return this;
  25598. }
  25599. }
  25600. class AnimationMixer extends EventDispatcher {
  25601. constructor(root) {
  25602. super();
  25603. this._root = root;
  25604. this._initMemoryManager();
  25605. this._accuIndex = 0;
  25606. this.time = 0;
  25607. this.timeScale = 1.0;
  25608. }
  25609. _bindAction(action, prototypeAction) {
  25610. const root = action._localRoot || this._root,
  25611. tracks = action._clip.tracks,
  25612. nTracks = tracks.length,
  25613. bindings = action._propertyBindings,
  25614. interpolants = action._interpolants,
  25615. rootUuid = root.uuid,
  25616. bindingsByRoot = this._bindingsByRootAndName;
  25617. let bindingsByName = bindingsByRoot[rootUuid];
  25618. if (bindingsByName === undefined) {
  25619. bindingsByName = {};
  25620. bindingsByRoot[rootUuid] = bindingsByName;
  25621. }
  25622. for (let i = 0; i !== nTracks; ++i) {
  25623. const track = tracks[i],
  25624. trackName = track.name;
  25625. let binding = bindingsByName[trackName];
  25626. if (binding !== undefined) {
  25627. bindings[i] = binding;
  25628. } else {
  25629. binding = bindings[i];
  25630. if (binding !== undefined) {
  25631. // existing binding, make sure the cache knows
  25632. if (binding._cacheIndex === null) {
  25633. ++binding.referenceCount;
  25634. this._addInactiveBinding(binding, rootUuid, trackName);
  25635. }
  25636. continue;
  25637. }
  25638. const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  25639. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  25640. ++binding.referenceCount;
  25641. this._addInactiveBinding(binding, rootUuid, trackName);
  25642. bindings[i] = binding;
  25643. }
  25644. interpolants[i].resultBuffer = binding.buffer;
  25645. }
  25646. }
  25647. _activateAction(action) {
  25648. if (!this._isActiveAction(action)) {
  25649. if (action._cacheIndex === null) {
  25650. // this action has been forgotten by the cache, but the user
  25651. // appears to be still using it -> rebind
  25652. const rootUuid = (action._localRoot || this._root).uuid,
  25653. clipUuid = action._clip.uuid,
  25654. actionsForClip = this._actionsByClip[clipUuid];
  25655. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  25656. this._addInactiveAction(action, clipUuid, rootUuid);
  25657. }
  25658. const bindings = action._propertyBindings; // increment reference counts / sort out state
  25659. for (let i = 0, n = bindings.length; i !== n; ++i) {
  25660. const binding = bindings[i];
  25661. if (binding.useCount++ === 0) {
  25662. this._lendBinding(binding);
  25663. binding.saveOriginalState();
  25664. }
  25665. }
  25666. this._lendAction(action);
  25667. }
  25668. }
  25669. _deactivateAction(action) {
  25670. if (this._isActiveAction(action)) {
  25671. const bindings = action._propertyBindings; // decrement reference counts / sort out state
  25672. for (let i = 0, n = bindings.length; i !== n; ++i) {
  25673. const binding = bindings[i];
  25674. if (--binding.useCount === 0) {
  25675. binding.restoreOriginalState();
  25676. this._takeBackBinding(binding);
  25677. }
  25678. }
  25679. this._takeBackAction(action);
  25680. }
  25681. } // Memory manager
  25682. _initMemoryManager() {
  25683. this._actions = []; // 'nActiveActions' followed by inactive ones
  25684. this._nActiveActions = 0;
  25685. this._actionsByClip = {}; // inside:
  25686. // {
  25687. // knownActions: Array< AnimationAction > - used as prototypes
  25688. // actionByRoot: AnimationAction - lookup
  25689. // }
  25690. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  25691. this._nActiveBindings = 0;
  25692. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  25693. this._controlInterpolants = []; // same game as above
  25694. this._nActiveControlInterpolants = 0;
  25695. const scope = this;
  25696. this.stats = {
  25697. actions: {
  25698. get total() {
  25699. return scope._actions.length;
  25700. },
  25701. get inUse() {
  25702. return scope._nActiveActions;
  25703. }
  25704. },
  25705. bindings: {
  25706. get total() {
  25707. return scope._bindings.length;
  25708. },
  25709. get inUse() {
  25710. return scope._nActiveBindings;
  25711. }
  25712. },
  25713. controlInterpolants: {
  25714. get total() {
  25715. return scope._controlInterpolants.length;
  25716. },
  25717. get inUse() {
  25718. return scope._nActiveControlInterpolants;
  25719. }
  25720. }
  25721. };
  25722. } // Memory management for AnimationAction objects
  25723. _isActiveAction(action) {
  25724. const index = action._cacheIndex;
  25725. return index !== null && index < this._nActiveActions;
  25726. }
  25727. _addInactiveAction(action, clipUuid, rootUuid) {
  25728. const actions = this._actions,
  25729. actionsByClip = this._actionsByClip;
  25730. let actionsForClip = actionsByClip[clipUuid];
  25731. if (actionsForClip === undefined) {
  25732. actionsForClip = {
  25733. knownActions: [action],
  25734. actionByRoot: {}
  25735. };
  25736. action._byClipCacheIndex = 0;
  25737. actionsByClip[clipUuid] = actionsForClip;
  25738. } else {
  25739. const knownActions = actionsForClip.knownActions;
  25740. action._byClipCacheIndex = knownActions.length;
  25741. knownActions.push(action);
  25742. }
  25743. action._cacheIndex = actions.length;
  25744. actions.push(action);
  25745. actionsForClip.actionByRoot[rootUuid] = action;
  25746. }
  25747. _removeInactiveAction(action) {
  25748. const actions = this._actions,
  25749. lastInactiveAction = actions[actions.length - 1],
  25750. cacheIndex = action._cacheIndex;
  25751. lastInactiveAction._cacheIndex = cacheIndex;
  25752. actions[cacheIndex] = lastInactiveAction;
  25753. actions.pop();
  25754. action._cacheIndex = null;
  25755. const clipUuid = action._clip.uuid,
  25756. actionsByClip = this._actionsByClip,
  25757. actionsForClip = actionsByClip[clipUuid],
  25758. knownActionsForClip = actionsForClip.knownActions,
  25759. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  25760. byClipCacheIndex = action._byClipCacheIndex;
  25761. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  25762. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  25763. knownActionsForClip.pop();
  25764. action._byClipCacheIndex = null;
  25765. const actionByRoot = actionsForClip.actionByRoot,
  25766. rootUuid = (action._localRoot || this._root).uuid;
  25767. delete actionByRoot[rootUuid];
  25768. if (knownActionsForClip.length === 0) {
  25769. delete actionsByClip[clipUuid];
  25770. }
  25771. this._removeInactiveBindingsForAction(action);
  25772. }
  25773. _removeInactiveBindingsForAction(action) {
  25774. const bindings = action._propertyBindings;
  25775. for (let i = 0, n = bindings.length; i !== n; ++i) {
  25776. const binding = bindings[i];
  25777. if (--binding.referenceCount === 0) {
  25778. this._removeInactiveBinding(binding);
  25779. }
  25780. }
  25781. }
  25782. _lendAction(action) {
  25783. // [ active actions | inactive actions ]
  25784. // [ active actions >| inactive actions ]
  25785. // s a
  25786. // <-swap->
  25787. // a s
  25788. const actions = this._actions,
  25789. prevIndex = action._cacheIndex,
  25790. lastActiveIndex = this._nActiveActions++,
  25791. firstInactiveAction = actions[lastActiveIndex];
  25792. action._cacheIndex = lastActiveIndex;
  25793. actions[lastActiveIndex] = action;
  25794. firstInactiveAction._cacheIndex = prevIndex;
  25795. actions[prevIndex] = firstInactiveAction;
  25796. }
  25797. _takeBackAction(action) {
  25798. // [ active actions | inactive actions ]
  25799. // [ active actions |< inactive actions ]
  25800. // a s
  25801. // <-swap->
  25802. // s a
  25803. const actions = this._actions,
  25804. prevIndex = action._cacheIndex,
  25805. firstInactiveIndex = --this._nActiveActions,
  25806. lastActiveAction = actions[firstInactiveIndex];
  25807. action._cacheIndex = firstInactiveIndex;
  25808. actions[firstInactiveIndex] = action;
  25809. lastActiveAction._cacheIndex = prevIndex;
  25810. actions[prevIndex] = lastActiveAction;
  25811. } // Memory management for PropertyMixer objects
  25812. _addInactiveBinding(binding, rootUuid, trackName) {
  25813. const bindingsByRoot = this._bindingsByRootAndName,
  25814. bindings = this._bindings;
  25815. let bindingByName = bindingsByRoot[rootUuid];
  25816. if (bindingByName === undefined) {
  25817. bindingByName = {};
  25818. bindingsByRoot[rootUuid] = bindingByName;
  25819. }
  25820. bindingByName[trackName] = binding;
  25821. binding._cacheIndex = bindings.length;
  25822. bindings.push(binding);
  25823. }
  25824. _removeInactiveBinding(binding) {
  25825. const bindings = this._bindings,
  25826. propBinding = binding.binding,
  25827. rootUuid = propBinding.rootNode.uuid,
  25828. trackName = propBinding.path,
  25829. bindingsByRoot = this._bindingsByRootAndName,
  25830. bindingByName = bindingsByRoot[rootUuid],
  25831. lastInactiveBinding = bindings[bindings.length - 1],
  25832. cacheIndex = binding._cacheIndex;
  25833. lastInactiveBinding._cacheIndex = cacheIndex;
  25834. bindings[cacheIndex] = lastInactiveBinding;
  25835. bindings.pop();
  25836. delete bindingByName[trackName];
  25837. if (Object.keys(bindingByName).length === 0) {
  25838. delete bindingsByRoot[rootUuid];
  25839. }
  25840. }
  25841. _lendBinding(binding) {
  25842. const bindings = this._bindings,
  25843. prevIndex = binding._cacheIndex,
  25844. lastActiveIndex = this._nActiveBindings++,
  25845. firstInactiveBinding = bindings[lastActiveIndex];
  25846. binding._cacheIndex = lastActiveIndex;
  25847. bindings[lastActiveIndex] = binding;
  25848. firstInactiveBinding._cacheIndex = prevIndex;
  25849. bindings[prevIndex] = firstInactiveBinding;
  25850. }
  25851. _takeBackBinding(binding) {
  25852. const bindings = this._bindings,
  25853. prevIndex = binding._cacheIndex,
  25854. firstInactiveIndex = --this._nActiveBindings,
  25855. lastActiveBinding = bindings[firstInactiveIndex];
  25856. binding._cacheIndex = firstInactiveIndex;
  25857. bindings[firstInactiveIndex] = binding;
  25858. lastActiveBinding._cacheIndex = prevIndex;
  25859. bindings[prevIndex] = lastActiveBinding;
  25860. } // Memory management of Interpolants for weight and time scale
  25861. _lendControlInterpolant() {
  25862. const interpolants = this._controlInterpolants,
  25863. lastActiveIndex = this._nActiveControlInterpolants++;
  25864. let interpolant = interpolants[lastActiveIndex];
  25865. if (interpolant === undefined) {
  25866. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  25867. interpolant.__cacheIndex = lastActiveIndex;
  25868. interpolants[lastActiveIndex] = interpolant;
  25869. }
  25870. return interpolant;
  25871. }
  25872. _takeBackControlInterpolant(interpolant) {
  25873. const interpolants = this._controlInterpolants,
  25874. prevIndex = interpolant.__cacheIndex,
  25875. firstInactiveIndex = --this._nActiveControlInterpolants,
  25876. lastActiveInterpolant = interpolants[firstInactiveIndex];
  25877. interpolant.__cacheIndex = firstInactiveIndex;
  25878. interpolants[firstInactiveIndex] = interpolant;
  25879. lastActiveInterpolant.__cacheIndex = prevIndex;
  25880. interpolants[prevIndex] = lastActiveInterpolant;
  25881. } // return an action for a clip optionally using a custom root target
  25882. // object (this method allocates a lot of dynamic memory in case a
  25883. // previously unknown clip/root combination is specified)
  25884. clipAction(clip, optionalRoot, blendMode) {
  25885. const root = optionalRoot || this._root,
  25886. rootUuid = root.uuid;
  25887. let clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
  25888. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  25889. const actionsForClip = this._actionsByClip[clipUuid];
  25890. let prototypeAction = null;
  25891. if (blendMode === undefined) {
  25892. if (clipObject !== null) {
  25893. blendMode = clipObject.blendMode;
  25894. } else {
  25895. blendMode = NormalAnimationBlendMode;
  25896. }
  25897. }
  25898. if (actionsForClip !== undefined) {
  25899. const existingAction = actionsForClip.actionByRoot[rootUuid];
  25900. if (existingAction !== undefined && existingAction.blendMode === blendMode) {
  25901. return existingAction;
  25902. } // we know the clip, so we don't have to parse all
  25903. // the bindings again but can just copy
  25904. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  25905. if (clipObject === null) clipObject = prototypeAction._clip;
  25906. } // clip must be known when specified via string
  25907. if (clipObject === null) return null; // allocate all resources required to run it
  25908. const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
  25909. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  25910. this._addInactiveAction(newAction, clipUuid, rootUuid);
  25911. return newAction;
  25912. } // get an existing action
  25913. existingAction(clip, optionalRoot) {
  25914. const root = optionalRoot || this._root,
  25915. rootUuid = root.uuid,
  25916. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  25917. clipUuid = clipObject ? clipObject.uuid : clip,
  25918. actionsForClip = this._actionsByClip[clipUuid];
  25919. if (actionsForClip !== undefined) {
  25920. return actionsForClip.actionByRoot[rootUuid] || null;
  25921. }
  25922. return null;
  25923. } // deactivates all previously scheduled actions
  25924. stopAllAction() {
  25925. const actions = this._actions,
  25926. nActions = this._nActiveActions;
  25927. for (let i = nActions - 1; i >= 0; --i) {
  25928. actions[i].stop();
  25929. }
  25930. return this;
  25931. } // advance the time and update apply the animation
  25932. update(deltaTime) {
  25933. deltaTime *= this.timeScale;
  25934. const actions = this._actions,
  25935. nActions = this._nActiveActions,
  25936. time = this.time += deltaTime,
  25937. timeDirection = Math.sign(deltaTime),
  25938. accuIndex = this._accuIndex ^= 1; // run active actions
  25939. for (let i = 0; i !== nActions; ++i) {
  25940. const action = actions[i];
  25941. action._update(time, deltaTime, timeDirection, accuIndex);
  25942. } // update scene graph
  25943. const bindings = this._bindings,
  25944. nBindings = this._nActiveBindings;
  25945. for (let i = 0; i !== nBindings; ++i) {
  25946. bindings[i].apply(accuIndex);
  25947. }
  25948. return this;
  25949. } // Allows you to seek to a specific time in an animation.
  25950. setTime(timeInSeconds) {
  25951. this.time = 0; // Zero out time attribute for AnimationMixer object;
  25952. for (let i = 0; i < this._actions.length; i++) {
  25953. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  25954. }
  25955. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  25956. } // return this mixer's root target object
  25957. getRoot() {
  25958. return this._root;
  25959. } // free all resources specific to a particular clip
  25960. uncacheClip(clip) {
  25961. const actions = this._actions,
  25962. clipUuid = clip.uuid,
  25963. actionsByClip = this._actionsByClip,
  25964. actionsForClip = actionsByClip[clipUuid];
  25965. if (actionsForClip !== undefined) {
  25966. // note: just calling _removeInactiveAction would mess up the
  25967. // iteration state and also require updating the state we can
  25968. // just throw away
  25969. const actionsToRemove = actionsForClip.knownActions;
  25970. for (let i = 0, n = actionsToRemove.length; i !== n; ++i) {
  25971. const action = actionsToRemove[i];
  25972. this._deactivateAction(action);
  25973. const cacheIndex = action._cacheIndex,
  25974. lastInactiveAction = actions[actions.length - 1];
  25975. action._cacheIndex = null;
  25976. action._byClipCacheIndex = null;
  25977. lastInactiveAction._cacheIndex = cacheIndex;
  25978. actions[cacheIndex] = lastInactiveAction;
  25979. actions.pop();
  25980. this._removeInactiveBindingsForAction(action);
  25981. }
  25982. delete actionsByClip[clipUuid];
  25983. }
  25984. } // free all resources specific to a particular root target object
  25985. uncacheRoot(root) {
  25986. const rootUuid = root.uuid,
  25987. actionsByClip = this._actionsByClip;
  25988. for (const clipUuid in actionsByClip) {
  25989. const actionByRoot = actionsByClip[clipUuid].actionByRoot,
  25990. action = actionByRoot[rootUuid];
  25991. if (action !== undefined) {
  25992. this._deactivateAction(action);
  25993. this._removeInactiveAction(action);
  25994. }
  25995. }
  25996. const bindingsByRoot = this._bindingsByRootAndName,
  25997. bindingByName = bindingsByRoot[rootUuid];
  25998. if (bindingByName !== undefined) {
  25999. for (const trackName in bindingByName) {
  26000. const binding = bindingByName[trackName];
  26001. binding.restoreOriginalState();
  26002. this._removeInactiveBinding(binding);
  26003. }
  26004. }
  26005. } // remove a targeted clip from the cache
  26006. uncacheAction(clip, optionalRoot) {
  26007. const action = this.existingAction(clip, optionalRoot);
  26008. if (action !== null) {
  26009. this._deactivateAction(action);
  26010. this._removeInactiveAction(action);
  26011. }
  26012. }
  26013. }
  26014. AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array(1);
  26015. class Uniform {
  26016. constructor(value) {
  26017. if (typeof value === 'string') {
  26018. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  26019. value = arguments[1];
  26020. }
  26021. this.value = value;
  26022. }
  26023. clone() {
  26024. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  26025. }
  26026. }
  26027. class InstancedInterleavedBuffer extends InterleavedBuffer {
  26028. constructor(array, stride, meshPerAttribute = 1) {
  26029. super(array, stride);
  26030. this.meshPerAttribute = meshPerAttribute;
  26031. }
  26032. copy(source) {
  26033. super.copy(source);
  26034. this.meshPerAttribute = source.meshPerAttribute;
  26035. return this;
  26036. }
  26037. clone(data) {
  26038. const ib = super.clone(data);
  26039. ib.meshPerAttribute = this.meshPerAttribute;
  26040. return ib;
  26041. }
  26042. toJSON(data) {
  26043. const json = super.toJSON(data);
  26044. json.isInstancedInterleavedBuffer = true;
  26045. json.meshPerAttribute = this.meshPerAttribute;
  26046. return json;
  26047. }
  26048. }
  26049. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  26050. class GLBufferAttribute {
  26051. constructor(buffer, type, itemSize, elementSize, count) {
  26052. this.buffer = buffer;
  26053. this.type = type;
  26054. this.itemSize = itemSize;
  26055. this.elementSize = elementSize;
  26056. this.count = count;
  26057. this.version = 0;
  26058. }
  26059. set needsUpdate(value) {
  26060. if (value === true) this.version++;
  26061. }
  26062. setBuffer(buffer) {
  26063. this.buffer = buffer;
  26064. return this;
  26065. }
  26066. setType(type, elementSize) {
  26067. this.type = type;
  26068. this.elementSize = elementSize;
  26069. return this;
  26070. }
  26071. setItemSize(itemSize) {
  26072. this.itemSize = itemSize;
  26073. return this;
  26074. }
  26075. setCount(count) {
  26076. this.count = count;
  26077. return this;
  26078. }
  26079. }
  26080. GLBufferAttribute.prototype.isGLBufferAttribute = true;
  26081. class Raycaster {
  26082. constructor(origin, direction, near = 0, far = Infinity) {
  26083. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  26084. this.near = near;
  26085. this.far = far;
  26086. this.camera = null;
  26087. this.layers = new Layers();
  26088. this.params = {
  26089. Mesh: {},
  26090. Line: {
  26091. threshold: 1
  26092. },
  26093. LOD: {},
  26094. Points: {
  26095. threshold: 1
  26096. },
  26097. Sprite: {}
  26098. };
  26099. }
  26100. set(origin, direction) {
  26101. // direction is assumed to be normalized (for accurate distance calculations)
  26102. this.ray.set(origin, direction);
  26103. }
  26104. setFromCamera(coords, camera) {
  26105. if (camera && camera.isPerspectiveCamera) {
  26106. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  26107. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  26108. this.camera = camera;
  26109. } else if (camera && camera.isOrthographicCamera) {
  26110. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  26111. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  26112. this.camera = camera;
  26113. } else {
  26114. console.error('THREE.Raycaster: Unsupported camera type: ' + camera.type);
  26115. }
  26116. }
  26117. intersectObject(object, recursive = false, intersects = []) {
  26118. intersectObject(object, this, intersects, recursive);
  26119. intersects.sort(ascSort);
  26120. return intersects;
  26121. }
  26122. intersectObjects(objects, recursive = false, intersects = []) {
  26123. for (let i = 0, l = objects.length; i < l; i++) {
  26124. intersectObject(objects[i], this, intersects, recursive);
  26125. }
  26126. intersects.sort(ascSort);
  26127. return intersects;
  26128. }
  26129. }
  26130. function ascSort(a, b) {
  26131. return a.distance - b.distance;
  26132. }
  26133. function intersectObject(object, raycaster, intersects, recursive) {
  26134. if (object.layers.test(raycaster.layers)) {
  26135. object.raycast(raycaster, intersects);
  26136. }
  26137. if (recursive === true) {
  26138. const children = object.children;
  26139. for (let i = 0, l = children.length; i < l; i++) {
  26140. intersectObject(children[i], raycaster, intersects, true);
  26141. }
  26142. }
  26143. }
  26144. /**
  26145. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  26146. *
  26147. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  26148. * The azimuthal angle (theta) is measured from the positive z-axis.
  26149. */
  26150. class Spherical {
  26151. constructor(radius = 1, phi = 0, theta = 0) {
  26152. this.radius = radius;
  26153. this.phi = phi; // polar angle
  26154. this.theta = theta; // azimuthal angle
  26155. return this;
  26156. }
  26157. set(radius, phi, theta) {
  26158. this.radius = radius;
  26159. this.phi = phi;
  26160. this.theta = theta;
  26161. return this;
  26162. }
  26163. copy(other) {
  26164. this.radius = other.radius;
  26165. this.phi = other.phi;
  26166. this.theta = other.theta;
  26167. return this;
  26168. } // restrict phi to be betwee EPS and PI-EPS
  26169. makeSafe() {
  26170. const EPS = 0.000001;
  26171. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  26172. return this;
  26173. }
  26174. setFromVector3(v) {
  26175. return this.setFromCartesianCoords(v.x, v.y, v.z);
  26176. }
  26177. setFromCartesianCoords(x, y, z) {
  26178. this.radius = Math.sqrt(x * x + y * y + z * z);
  26179. if (this.radius === 0) {
  26180. this.theta = 0;
  26181. this.phi = 0;
  26182. } else {
  26183. this.theta = Math.atan2(x, z);
  26184. this.phi = Math.acos(clamp(y / this.radius, -1, 1));
  26185. }
  26186. return this;
  26187. }
  26188. clone() {
  26189. return new this.constructor().copy(this);
  26190. }
  26191. }
  26192. /**
  26193. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  26194. */
  26195. class Cylindrical {
  26196. constructor(radius = 1, theta = 0, y = 0) {
  26197. this.radius = radius; // distance from the origin to a point in the x-z plane
  26198. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  26199. this.y = y; // height above the x-z plane
  26200. return this;
  26201. }
  26202. set(radius, theta, y) {
  26203. this.radius = radius;
  26204. this.theta = theta;
  26205. this.y = y;
  26206. return this;
  26207. }
  26208. copy(other) {
  26209. this.radius = other.radius;
  26210. this.theta = other.theta;
  26211. this.y = other.y;
  26212. return this;
  26213. }
  26214. setFromVector3(v) {
  26215. return this.setFromCartesianCoords(v.x, v.y, v.z);
  26216. }
  26217. setFromCartesianCoords(x, y, z) {
  26218. this.radius = Math.sqrt(x * x + z * z);
  26219. this.theta = Math.atan2(x, z);
  26220. this.y = y;
  26221. return this;
  26222. }
  26223. clone() {
  26224. return new this.constructor().copy(this);
  26225. }
  26226. }
  26227. const _vector$4 = /*@__PURE__*/new Vector2();
  26228. class Box2 {
  26229. constructor(min = new Vector2(+Infinity, +Infinity), max = new Vector2(-Infinity, -Infinity)) {
  26230. this.min = min;
  26231. this.max = max;
  26232. }
  26233. set(min, max) {
  26234. this.min.copy(min);
  26235. this.max.copy(max);
  26236. return this;
  26237. }
  26238. setFromPoints(points) {
  26239. this.makeEmpty();
  26240. for (let i = 0, il = points.length; i < il; i++) {
  26241. this.expandByPoint(points[i]);
  26242. }
  26243. return this;
  26244. }
  26245. setFromCenterAndSize(center, size) {
  26246. const halfSize = _vector$4.copy(size).multiplyScalar(0.5);
  26247. this.min.copy(center).sub(halfSize);
  26248. this.max.copy(center).add(halfSize);
  26249. return this;
  26250. }
  26251. clone() {
  26252. return new this.constructor().copy(this);
  26253. }
  26254. copy(box) {
  26255. this.min.copy(box.min);
  26256. this.max.copy(box.max);
  26257. return this;
  26258. }
  26259. makeEmpty() {
  26260. this.min.x = this.min.y = +Infinity;
  26261. this.max.x = this.max.y = -Infinity;
  26262. return this;
  26263. }
  26264. isEmpty() {
  26265. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  26266. return this.max.x < this.min.x || this.max.y < this.min.y;
  26267. }
  26268. getCenter(target) {
  26269. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  26270. }
  26271. getSize(target) {
  26272. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  26273. }
  26274. expandByPoint(point) {
  26275. this.min.min(point);
  26276. this.max.max(point);
  26277. return this;
  26278. }
  26279. expandByVector(vector) {
  26280. this.min.sub(vector);
  26281. this.max.add(vector);
  26282. return this;
  26283. }
  26284. expandByScalar(scalar) {
  26285. this.min.addScalar(-scalar);
  26286. this.max.addScalar(scalar);
  26287. return this;
  26288. }
  26289. containsPoint(point) {
  26290. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  26291. }
  26292. containsBox(box) {
  26293. 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;
  26294. }
  26295. getParameter(point, target) {
  26296. // This can potentially have a divide by zero if the box
  26297. // has a size dimension of 0.
  26298. 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));
  26299. }
  26300. intersectsBox(box) {
  26301. // using 4 splitting planes to rule out intersections
  26302. 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;
  26303. }
  26304. clampPoint(point, target) {
  26305. return target.copy(point).clamp(this.min, this.max);
  26306. }
  26307. distanceToPoint(point) {
  26308. const clampedPoint = _vector$4.copy(point).clamp(this.min, this.max);
  26309. return clampedPoint.sub(point).length();
  26310. }
  26311. intersect(box) {
  26312. this.min.max(box.min);
  26313. this.max.min(box.max);
  26314. return this;
  26315. }
  26316. union(box) {
  26317. this.min.min(box.min);
  26318. this.max.max(box.max);
  26319. return this;
  26320. }
  26321. translate(offset) {
  26322. this.min.add(offset);
  26323. this.max.add(offset);
  26324. return this;
  26325. }
  26326. equals(box) {
  26327. return box.min.equals(this.min) && box.max.equals(this.max);
  26328. }
  26329. }
  26330. Box2.prototype.isBox2 = true;
  26331. const _startP = /*@__PURE__*/new Vector3();
  26332. const _startEnd = /*@__PURE__*/new Vector3();
  26333. class Line3 {
  26334. constructor(start = new Vector3(), end = new Vector3()) {
  26335. this.start = start;
  26336. this.end = end;
  26337. }
  26338. set(start, end) {
  26339. this.start.copy(start);
  26340. this.end.copy(end);
  26341. return this;
  26342. }
  26343. copy(line) {
  26344. this.start.copy(line.start);
  26345. this.end.copy(line.end);
  26346. return this;
  26347. }
  26348. getCenter(target) {
  26349. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  26350. }
  26351. delta(target) {
  26352. return target.subVectors(this.end, this.start);
  26353. }
  26354. distanceSq() {
  26355. return this.start.distanceToSquared(this.end);
  26356. }
  26357. distance() {
  26358. return this.start.distanceTo(this.end);
  26359. }
  26360. at(t, target) {
  26361. return this.delta(target).multiplyScalar(t).add(this.start);
  26362. }
  26363. closestPointToPointParameter(point, clampToLine) {
  26364. _startP.subVectors(point, this.start);
  26365. _startEnd.subVectors(this.end, this.start);
  26366. const startEnd2 = _startEnd.dot(_startEnd);
  26367. const startEnd_startP = _startEnd.dot(_startP);
  26368. let t = startEnd_startP / startEnd2;
  26369. if (clampToLine) {
  26370. t = clamp(t, 0, 1);
  26371. }
  26372. return t;
  26373. }
  26374. closestPointToPoint(point, clampToLine, target) {
  26375. const t = this.closestPointToPointParameter(point, clampToLine);
  26376. return this.delta(target).multiplyScalar(t).add(this.start);
  26377. }
  26378. applyMatrix4(matrix) {
  26379. this.start.applyMatrix4(matrix);
  26380. this.end.applyMatrix4(matrix);
  26381. return this;
  26382. }
  26383. equals(line) {
  26384. return line.start.equals(this.start) && line.end.equals(this.end);
  26385. }
  26386. clone() {
  26387. return new this.constructor().copy(this);
  26388. }
  26389. }
  26390. class ImmediateRenderObject extends Object3D {
  26391. constructor(material) {
  26392. super();
  26393. this.material = material;
  26394. this.render = function ()
  26395. /* renderCallback */
  26396. {};
  26397. this.hasPositions = false;
  26398. this.hasNormals = false;
  26399. this.hasColors = false;
  26400. this.hasUvs = false;
  26401. this.positionArray = null;
  26402. this.normalArray = null;
  26403. this.colorArray = null;
  26404. this.uvArray = null;
  26405. this.count = 0;
  26406. }
  26407. }
  26408. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  26409. const _vector$3 = /*@__PURE__*/new Vector3();
  26410. class SpotLightHelper extends Object3D {
  26411. constructor(light, color) {
  26412. super();
  26413. this.light = light;
  26414. this.light.updateMatrixWorld();
  26415. this.matrix = light.matrixWorld;
  26416. this.matrixAutoUpdate = false;
  26417. this.color = color;
  26418. const geometry = new BufferGeometry();
  26419. 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];
  26420. for (let i = 0, j = 1, l = 32; i < l; i++, j++) {
  26421. const p1 = i / l * Math.PI * 2;
  26422. const p2 = j / l * Math.PI * 2;
  26423. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  26424. }
  26425. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  26426. const material = new LineBasicMaterial({
  26427. fog: false,
  26428. toneMapped: false
  26429. });
  26430. this.cone = new LineSegments(geometry, material);
  26431. this.add(this.cone);
  26432. this.update();
  26433. }
  26434. dispose() {
  26435. this.cone.geometry.dispose();
  26436. this.cone.material.dispose();
  26437. }
  26438. update() {
  26439. this.light.updateMatrixWorld();
  26440. const coneLength = this.light.distance ? this.light.distance : 1000;
  26441. const coneWidth = coneLength * Math.tan(this.light.angle);
  26442. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  26443. _vector$3.setFromMatrixPosition(this.light.target.matrixWorld);
  26444. this.cone.lookAt(_vector$3);
  26445. if (this.color !== undefined) {
  26446. this.cone.material.color.set(this.color);
  26447. } else {
  26448. this.cone.material.color.copy(this.light.color);
  26449. }
  26450. }
  26451. }
  26452. const _vector$2 = /*@__PURE__*/new Vector3();
  26453. const _boneMatrix = /*@__PURE__*/new Matrix4();
  26454. const _matrixWorldInv = /*@__PURE__*/new Matrix4();
  26455. class SkeletonHelper extends LineSegments {
  26456. constructor(object) {
  26457. const bones = getBoneList(object);
  26458. const geometry = new BufferGeometry();
  26459. const vertices = [];
  26460. const colors = [];
  26461. const color1 = new Color(0, 0, 1);
  26462. const color2 = new Color(0, 1, 0);
  26463. for (let i = 0; i < bones.length; i++) {
  26464. const bone = bones[i];
  26465. if (bone.parent && bone.parent.isBone) {
  26466. vertices.push(0, 0, 0);
  26467. vertices.push(0, 0, 0);
  26468. colors.push(color1.r, color1.g, color1.b);
  26469. colors.push(color2.r, color2.g, color2.b);
  26470. }
  26471. }
  26472. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26473. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26474. const material = new LineBasicMaterial({
  26475. vertexColors: true,
  26476. depthTest: false,
  26477. depthWrite: false,
  26478. toneMapped: false,
  26479. transparent: true
  26480. });
  26481. super(geometry, material);
  26482. this.type = 'SkeletonHelper';
  26483. this.isSkeletonHelper = true;
  26484. this.root = object;
  26485. this.bones = bones;
  26486. this.matrix = object.matrixWorld;
  26487. this.matrixAutoUpdate = false;
  26488. }
  26489. updateMatrixWorld(force) {
  26490. const bones = this.bones;
  26491. const geometry = this.geometry;
  26492. const position = geometry.getAttribute('position');
  26493. _matrixWorldInv.copy(this.root.matrixWorld).invert();
  26494. for (let i = 0, j = 0; i < bones.length; i++) {
  26495. const bone = bones[i];
  26496. if (bone.parent && bone.parent.isBone) {
  26497. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  26498. _vector$2.setFromMatrixPosition(_boneMatrix);
  26499. position.setXYZ(j, _vector$2.x, _vector$2.y, _vector$2.z);
  26500. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  26501. _vector$2.setFromMatrixPosition(_boneMatrix);
  26502. position.setXYZ(j + 1, _vector$2.x, _vector$2.y, _vector$2.z);
  26503. j += 2;
  26504. }
  26505. }
  26506. geometry.getAttribute('position').needsUpdate = true;
  26507. super.updateMatrixWorld(force);
  26508. }
  26509. }
  26510. function getBoneList(object) {
  26511. const boneList = [];
  26512. if (object && object.isBone) {
  26513. boneList.push(object);
  26514. }
  26515. for (let i = 0; i < object.children.length; i++) {
  26516. boneList.push.apply(boneList, getBoneList(object.children[i]));
  26517. }
  26518. return boneList;
  26519. }
  26520. class PointLightHelper extends Mesh {
  26521. constructor(light, sphereSize, color) {
  26522. const geometry = new SphereGeometry(sphereSize, 4, 2);
  26523. const material = new MeshBasicMaterial({
  26524. wireframe: true,
  26525. fog: false,
  26526. toneMapped: false
  26527. });
  26528. super(geometry, material);
  26529. this.light = light;
  26530. this.light.updateMatrixWorld();
  26531. this.color = color;
  26532. this.type = 'PointLightHelper';
  26533. this.matrix = this.light.matrixWorld;
  26534. this.matrixAutoUpdate = false;
  26535. this.update();
  26536. /*
  26537. // TODO: delete this comment?
  26538. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  26539. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  26540. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  26541. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  26542. const d = light.distance;
  26543. if ( d === 0.0 ) {
  26544. this.lightDistance.visible = false;
  26545. } else {
  26546. this.lightDistance.scale.set( d, d, d );
  26547. }
  26548. this.add( this.lightDistance );
  26549. */
  26550. }
  26551. dispose() {
  26552. this.geometry.dispose();
  26553. this.material.dispose();
  26554. }
  26555. update() {
  26556. if (this.color !== undefined) {
  26557. this.material.color.set(this.color);
  26558. } else {
  26559. this.material.color.copy(this.light.color);
  26560. }
  26561. /*
  26562. const d = this.light.distance;
  26563. if ( d === 0.0 ) {
  26564. this.lightDistance.visible = false;
  26565. } else {
  26566. this.lightDistance.visible = true;
  26567. this.lightDistance.scale.set( d, d, d );
  26568. }
  26569. */
  26570. }
  26571. }
  26572. const _vector$1 = /*@__PURE__*/new Vector3();
  26573. const _color1 = /*@__PURE__*/new Color();
  26574. const _color2 = /*@__PURE__*/new Color();
  26575. class HemisphereLightHelper extends Object3D {
  26576. constructor(light, size, color) {
  26577. super();
  26578. this.light = light;
  26579. this.light.updateMatrixWorld();
  26580. this.matrix = light.matrixWorld;
  26581. this.matrixAutoUpdate = false;
  26582. this.color = color;
  26583. const geometry = new OctahedronGeometry(size);
  26584. geometry.rotateY(Math.PI * 0.5);
  26585. this.material = new MeshBasicMaterial({
  26586. wireframe: true,
  26587. fog: false,
  26588. toneMapped: false
  26589. });
  26590. if (this.color === undefined) this.material.vertexColors = true;
  26591. const position = geometry.getAttribute('position');
  26592. const colors = new Float32Array(position.count * 3);
  26593. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  26594. this.add(new Mesh(geometry, this.material));
  26595. this.update();
  26596. }
  26597. dispose() {
  26598. this.children[0].geometry.dispose();
  26599. this.children[0].material.dispose();
  26600. }
  26601. update() {
  26602. const mesh = this.children[0];
  26603. if (this.color !== undefined) {
  26604. this.material.color.set(this.color);
  26605. } else {
  26606. const colors = mesh.geometry.getAttribute('color');
  26607. _color1.copy(this.light.color);
  26608. _color2.copy(this.light.groundColor);
  26609. for (let i = 0, l = colors.count; i < l; i++) {
  26610. const color = i < l / 2 ? _color1 : _color2;
  26611. colors.setXYZ(i, color.r, color.g, color.b);
  26612. }
  26613. colors.needsUpdate = true;
  26614. }
  26615. mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate());
  26616. }
  26617. }
  26618. class GridHelper extends LineSegments {
  26619. constructor(size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888) {
  26620. color1 = new Color(color1);
  26621. color2 = new Color(color2);
  26622. const center = divisions / 2;
  26623. const step = size / divisions;
  26624. const halfSize = size / 2;
  26625. const vertices = [],
  26626. colors = [];
  26627. for (let i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  26628. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  26629. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  26630. const color = i === center ? color1 : color2;
  26631. color.toArray(colors, j);
  26632. j += 3;
  26633. color.toArray(colors, j);
  26634. j += 3;
  26635. color.toArray(colors, j);
  26636. j += 3;
  26637. color.toArray(colors, j);
  26638. j += 3;
  26639. }
  26640. const geometry = new BufferGeometry();
  26641. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26642. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26643. const material = new LineBasicMaterial({
  26644. vertexColors: true,
  26645. toneMapped: false
  26646. });
  26647. super(geometry, material);
  26648. this.type = 'GridHelper';
  26649. }
  26650. }
  26651. class PolarGridHelper extends LineSegments {
  26652. constructor(radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888) {
  26653. color1 = new Color(color1);
  26654. color2 = new Color(color2);
  26655. const vertices = [];
  26656. const colors = []; // create the radials
  26657. for (let i = 0; i <= radials; i++) {
  26658. const v = i / radials * (Math.PI * 2);
  26659. const x = Math.sin(v) * radius;
  26660. const z = Math.cos(v) * radius;
  26661. vertices.push(0, 0, 0);
  26662. vertices.push(x, 0, z);
  26663. const color = i & 1 ? color1 : color2;
  26664. colors.push(color.r, color.g, color.b);
  26665. colors.push(color.r, color.g, color.b);
  26666. } // create the circles
  26667. for (let i = 0; i <= circles; i++) {
  26668. const color = i & 1 ? color1 : color2;
  26669. const r = radius - radius / circles * i;
  26670. for (let j = 0; j < divisions; j++) {
  26671. // first vertex
  26672. let v = j / divisions * (Math.PI * 2);
  26673. let x = Math.sin(v) * r;
  26674. let z = Math.cos(v) * r;
  26675. vertices.push(x, 0, z);
  26676. colors.push(color.r, color.g, color.b); // second vertex
  26677. v = (j + 1) / divisions * (Math.PI * 2);
  26678. x = Math.sin(v) * r;
  26679. z = Math.cos(v) * r;
  26680. vertices.push(x, 0, z);
  26681. colors.push(color.r, color.g, color.b);
  26682. }
  26683. }
  26684. const geometry = new BufferGeometry();
  26685. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26686. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26687. const material = new LineBasicMaterial({
  26688. vertexColors: true,
  26689. toneMapped: false
  26690. });
  26691. super(geometry, material);
  26692. this.type = 'PolarGridHelper';
  26693. }
  26694. }
  26695. const _v1 = /*@__PURE__*/new Vector3();
  26696. const _v2 = /*@__PURE__*/new Vector3();
  26697. const _v3 = /*@__PURE__*/new Vector3();
  26698. class DirectionalLightHelper extends Object3D {
  26699. constructor(light, size, color) {
  26700. super();
  26701. this.light = light;
  26702. this.light.updateMatrixWorld();
  26703. this.matrix = light.matrixWorld;
  26704. this.matrixAutoUpdate = false;
  26705. this.color = color;
  26706. if (size === undefined) size = 1;
  26707. let geometry = new BufferGeometry();
  26708. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  26709. const material = new LineBasicMaterial({
  26710. fog: false,
  26711. toneMapped: false
  26712. });
  26713. this.lightPlane = new Line(geometry, material);
  26714. this.add(this.lightPlane);
  26715. geometry = new BufferGeometry();
  26716. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  26717. this.targetLine = new Line(geometry, material);
  26718. this.add(this.targetLine);
  26719. this.update();
  26720. }
  26721. dispose() {
  26722. this.lightPlane.geometry.dispose();
  26723. this.lightPlane.material.dispose();
  26724. this.targetLine.geometry.dispose();
  26725. this.targetLine.material.dispose();
  26726. }
  26727. update() {
  26728. _v1.setFromMatrixPosition(this.light.matrixWorld);
  26729. _v2.setFromMatrixPosition(this.light.target.matrixWorld);
  26730. _v3.subVectors(_v2, _v1);
  26731. this.lightPlane.lookAt(_v2);
  26732. if (this.color !== undefined) {
  26733. this.lightPlane.material.color.set(this.color);
  26734. this.targetLine.material.color.set(this.color);
  26735. } else {
  26736. this.lightPlane.material.color.copy(this.light.color);
  26737. this.targetLine.material.color.copy(this.light.color);
  26738. }
  26739. this.targetLine.lookAt(_v2);
  26740. this.targetLine.scale.z = _v3.length();
  26741. }
  26742. }
  26743. const _vector = /*@__PURE__*/new Vector3();
  26744. const _camera = /*@__PURE__*/new Camera();
  26745. /**
  26746. * - shows frustum, line of sight and up of the camera
  26747. * - suitable for fast updates
  26748. * - based on frustum visualization in lightgl.js shadowmap example
  26749. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  26750. */
  26751. class CameraHelper extends LineSegments {
  26752. constructor(camera) {
  26753. const geometry = new BufferGeometry();
  26754. const material = new LineBasicMaterial({
  26755. color: 0xffffff,
  26756. vertexColors: true,
  26757. toneMapped: false
  26758. });
  26759. const vertices = [];
  26760. const colors = [];
  26761. const pointMap = {}; // colors
  26762. const colorFrustum = new Color(0xffaa00);
  26763. const colorCone = new Color(0xff0000);
  26764. const colorUp = new Color(0x00aaff);
  26765. const colorTarget = new Color(0xffffff);
  26766. const colorCross = new Color(0x333333); // near
  26767. addLine('n1', 'n2', colorFrustum);
  26768. addLine('n2', 'n4', colorFrustum);
  26769. addLine('n4', 'n3', colorFrustum);
  26770. addLine('n3', 'n1', colorFrustum); // far
  26771. addLine('f1', 'f2', colorFrustum);
  26772. addLine('f2', 'f4', colorFrustum);
  26773. addLine('f4', 'f3', colorFrustum);
  26774. addLine('f3', 'f1', colorFrustum); // sides
  26775. addLine('n1', 'f1', colorFrustum);
  26776. addLine('n2', 'f2', colorFrustum);
  26777. addLine('n3', 'f3', colorFrustum);
  26778. addLine('n4', 'f4', colorFrustum); // cone
  26779. addLine('p', 'n1', colorCone);
  26780. addLine('p', 'n2', colorCone);
  26781. addLine('p', 'n3', colorCone);
  26782. addLine('p', 'n4', colorCone); // up
  26783. addLine('u1', 'u2', colorUp);
  26784. addLine('u2', 'u3', colorUp);
  26785. addLine('u3', 'u1', colorUp); // target
  26786. addLine('c', 't', colorTarget);
  26787. addLine('p', 'c', colorCross); // cross
  26788. addLine('cn1', 'cn2', colorCross);
  26789. addLine('cn3', 'cn4', colorCross);
  26790. addLine('cf1', 'cf2', colorCross);
  26791. addLine('cf3', 'cf4', colorCross);
  26792. function addLine(a, b, color) {
  26793. addPoint(a, color);
  26794. addPoint(b, color);
  26795. }
  26796. function addPoint(id, color) {
  26797. vertices.push(0, 0, 0);
  26798. colors.push(color.r, color.g, color.b);
  26799. if (pointMap[id] === undefined) {
  26800. pointMap[id] = [];
  26801. }
  26802. pointMap[id].push(vertices.length / 3 - 1);
  26803. }
  26804. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26805. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26806. super(geometry, material);
  26807. this.type = 'CameraHelper';
  26808. this.camera = camera;
  26809. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  26810. this.matrix = camera.matrixWorld;
  26811. this.matrixAutoUpdate = false;
  26812. this.pointMap = pointMap;
  26813. this.update();
  26814. }
  26815. update() {
  26816. const geometry = this.geometry;
  26817. const pointMap = this.pointMap;
  26818. const w = 1,
  26819. h = 1; // we need just camera projection matrix inverse
  26820. // world matrix must be identity
  26821. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  26822. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  26823. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  26824. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  26825. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  26826. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  26827. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  26828. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  26829. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  26830. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  26831. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  26832. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  26833. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  26834. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  26835. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  26836. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  26837. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  26838. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  26839. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  26840. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  26841. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  26842. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  26843. geometry.getAttribute('position').needsUpdate = true;
  26844. }
  26845. dispose() {
  26846. this.geometry.dispose();
  26847. this.material.dispose();
  26848. }
  26849. }
  26850. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  26851. _vector.set(x, y, z).unproject(camera);
  26852. const points = pointMap[point];
  26853. if (points !== undefined) {
  26854. const position = geometry.getAttribute('position');
  26855. for (let i = 0, l = points.length; i < l; i++) {
  26856. position.setXYZ(points[i], _vector.x, _vector.y, _vector.z);
  26857. }
  26858. }
  26859. }
  26860. const _box = /*@__PURE__*/new Box3();
  26861. class BoxHelper extends LineSegments {
  26862. constructor(object, color = 0xffff00) {
  26863. 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]);
  26864. const positions = new Float32Array(8 * 3);
  26865. const geometry = new BufferGeometry();
  26866. geometry.setIndex(new BufferAttribute(indices, 1));
  26867. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  26868. super(geometry, new LineBasicMaterial({
  26869. color: color,
  26870. toneMapped: false
  26871. }));
  26872. this.object = object;
  26873. this.type = 'BoxHelper';
  26874. this.matrixAutoUpdate = false;
  26875. this.update();
  26876. }
  26877. update(object) {
  26878. if (object !== undefined) {
  26879. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  26880. }
  26881. if (this.object !== undefined) {
  26882. _box.setFromObject(this.object);
  26883. }
  26884. if (_box.isEmpty()) return;
  26885. const min = _box.min;
  26886. const max = _box.max;
  26887. /*
  26888. 5____4
  26889. 1/___0/|
  26890. | 6__|_7
  26891. 2/___3/
  26892. 0: max.x, max.y, max.z
  26893. 1: min.x, max.y, max.z
  26894. 2: min.x, min.y, max.z
  26895. 3: max.x, min.y, max.z
  26896. 4: max.x, max.y, min.z
  26897. 5: min.x, max.y, min.z
  26898. 6: min.x, min.y, min.z
  26899. 7: max.x, min.y, min.z
  26900. */
  26901. const position = this.geometry.attributes.position;
  26902. const array = position.array;
  26903. array[0] = max.x;
  26904. array[1] = max.y;
  26905. array[2] = max.z;
  26906. array[3] = min.x;
  26907. array[4] = max.y;
  26908. array[5] = max.z;
  26909. array[6] = min.x;
  26910. array[7] = min.y;
  26911. array[8] = max.z;
  26912. array[9] = max.x;
  26913. array[10] = min.y;
  26914. array[11] = max.z;
  26915. array[12] = max.x;
  26916. array[13] = max.y;
  26917. array[14] = min.z;
  26918. array[15] = min.x;
  26919. array[16] = max.y;
  26920. array[17] = min.z;
  26921. array[18] = min.x;
  26922. array[19] = min.y;
  26923. array[20] = min.z;
  26924. array[21] = max.x;
  26925. array[22] = min.y;
  26926. array[23] = min.z;
  26927. position.needsUpdate = true;
  26928. this.geometry.computeBoundingSphere();
  26929. }
  26930. setFromObject(object) {
  26931. this.object = object;
  26932. this.update();
  26933. return this;
  26934. }
  26935. copy(source) {
  26936. LineSegments.prototype.copy.call(this, source);
  26937. this.object = source.object;
  26938. return this;
  26939. }
  26940. }
  26941. class Box3Helper extends LineSegments {
  26942. constructor(box, color = 0xffff00) {
  26943. 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]);
  26944. 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];
  26945. const geometry = new BufferGeometry();
  26946. geometry.setIndex(new BufferAttribute(indices, 1));
  26947. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  26948. super(geometry, new LineBasicMaterial({
  26949. color: color,
  26950. toneMapped: false
  26951. }));
  26952. this.box = box;
  26953. this.type = 'Box3Helper';
  26954. this.geometry.computeBoundingSphere();
  26955. }
  26956. updateMatrixWorld(force) {
  26957. const box = this.box;
  26958. if (box.isEmpty()) return;
  26959. box.getCenter(this.position);
  26960. box.getSize(this.scale);
  26961. this.scale.multiplyScalar(0.5);
  26962. super.updateMatrixWorld(force);
  26963. }
  26964. }
  26965. class PlaneHelper extends Line {
  26966. constructor(plane, size = 1, hex = 0xffff00) {
  26967. const color = hex;
  26968. 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];
  26969. const geometry = new BufferGeometry();
  26970. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  26971. geometry.computeBoundingSphere();
  26972. super(geometry, new LineBasicMaterial({
  26973. color: color,
  26974. toneMapped: false
  26975. }));
  26976. this.type = 'PlaneHelper';
  26977. this.plane = plane;
  26978. this.size = size;
  26979. const positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  26980. const geometry2 = new BufferGeometry();
  26981. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  26982. geometry2.computeBoundingSphere();
  26983. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  26984. color: color,
  26985. opacity: 0.2,
  26986. transparent: true,
  26987. depthWrite: false,
  26988. toneMapped: false
  26989. })));
  26990. }
  26991. updateMatrixWorld(force) {
  26992. let scale = -this.plane.constant;
  26993. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  26994. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  26995. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  26996. this.lookAt(this.plane.normal);
  26997. super.updateMatrixWorld(force);
  26998. }
  26999. }
  27000. const _axis = /*@__PURE__*/new Vector3();
  27001. let _lineGeometry, _coneGeometry;
  27002. class ArrowHelper extends Object3D {
  27003. // dir is assumed to be normalized
  27004. 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) {
  27005. super();
  27006. this.type = 'ArrowHelper';
  27007. if (_lineGeometry === undefined) {
  27008. _lineGeometry = new BufferGeometry();
  27009. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  27010. _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1);
  27011. _coneGeometry.translate(0, -0.5, 0);
  27012. }
  27013. this.position.copy(origin);
  27014. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  27015. color: color,
  27016. toneMapped: false
  27017. }));
  27018. this.line.matrixAutoUpdate = false;
  27019. this.add(this.line);
  27020. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  27021. color: color,
  27022. toneMapped: false
  27023. }));
  27024. this.cone.matrixAutoUpdate = false;
  27025. this.add(this.cone);
  27026. this.setDirection(dir);
  27027. this.setLength(length, headLength, headWidth);
  27028. }
  27029. setDirection(dir) {
  27030. // dir is assumed to be normalized
  27031. if (dir.y > 0.99999) {
  27032. this.quaternion.set(0, 0, 0, 1);
  27033. } else if (dir.y < -0.99999) {
  27034. this.quaternion.set(1, 0, 0, 0);
  27035. } else {
  27036. _axis.set(dir.z, 0, -dir.x).normalize();
  27037. const radians = Math.acos(dir.y);
  27038. this.quaternion.setFromAxisAngle(_axis, radians);
  27039. }
  27040. }
  27041. setLength(length, headLength = length * 0.2, headWidth = headLength * 0.2) {
  27042. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  27043. this.line.updateMatrix();
  27044. this.cone.scale.set(headWidth, headLength, headWidth);
  27045. this.cone.position.y = length;
  27046. this.cone.updateMatrix();
  27047. }
  27048. setColor(color) {
  27049. this.line.material.color.set(color);
  27050. this.cone.material.color.set(color);
  27051. }
  27052. copy(source) {
  27053. super.copy(source, false);
  27054. this.line.copy(source.line);
  27055. this.cone.copy(source.cone);
  27056. return this;
  27057. }
  27058. }
  27059. class AxesHelper extends LineSegments {
  27060. constructor(size = 1) {
  27061. const vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  27062. const colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  27063. const geometry = new BufferGeometry();
  27064. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27065. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27066. const material = new LineBasicMaterial({
  27067. vertexColors: true,
  27068. toneMapped: false
  27069. });
  27070. super(geometry, material);
  27071. this.type = 'AxesHelper';
  27072. }
  27073. setColors(xAxisColor, yAxisColor, zAxisColor) {
  27074. const color = new Color();
  27075. const array = this.geometry.attributes.color.array;
  27076. color.set(xAxisColor);
  27077. color.toArray(array, 0);
  27078. color.toArray(array, 3);
  27079. color.set(yAxisColor);
  27080. color.toArray(array, 6);
  27081. color.toArray(array, 9);
  27082. color.set(zAxisColor);
  27083. color.toArray(array, 12);
  27084. color.toArray(array, 15);
  27085. this.geometry.attributes.color.needsUpdate = true;
  27086. return this;
  27087. }
  27088. dispose() {
  27089. this.geometry.dispose();
  27090. this.material.dispose();
  27091. }
  27092. }
  27093. const _floatView = new Float32Array(1);
  27094. const _int32View = new Int32Array(_floatView.buffer);
  27095. class DataUtils {
  27096. // Converts float32 to float16 (stored as uint16 value).
  27097. static toHalfFloat(val) {
  27098. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  27099. /* This method is faster than the OpenEXR implementation (very often
  27100. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  27101. * by James Tursa?s half-precision code. */
  27102. _floatView[0] = val;
  27103. const x = _int32View[0];
  27104. let bits = x >> 16 & 0x8000;
  27105. /* Get the sign */
  27106. let m = x >> 12 & 0x07ff;
  27107. /* Keep one extra bit for rounding */
  27108. const e = x >> 23 & 0xff;
  27109. /* Using int is faster here */
  27110. /* If zero, or denormal, or exponent underflows too much for a denormal
  27111. * half, return signed zero. */
  27112. if (e < 103) return bits;
  27113. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  27114. if (e > 142) {
  27115. bits |= 0x7c00;
  27116. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  27117. * not Inf, so make sure we set one mantissa bit too. */
  27118. bits |= (e == 255 ? 0 : 1) && x & 0x007fffff;
  27119. return bits;
  27120. }
  27121. /* If exponent underflows but not too much, return a denormal */
  27122. if (e < 113) {
  27123. m |= 0x0800;
  27124. /* Extra rounding may overflow and set mantissa to 0 and exponent
  27125. * to 1, which is OK. */
  27126. bits |= (m >> 114 - e) + (m >> 113 - e & 1);
  27127. return bits;
  27128. }
  27129. bits |= e - 112 << 10 | m >> 1;
  27130. /* Extra rounding. An overflow will set mantissa to 0 and increment
  27131. * the exponent, which is OK. */
  27132. bits += m & 1;
  27133. return bits;
  27134. }
  27135. }
  27136. const LOD_MIN = 4;
  27137. const LOD_MAX = 8;
  27138. const SIZE_MAX = Math.pow(2, LOD_MAX); // The standard deviations (radians) associated with the extra mips. These are
  27139. // chosen to approximate a Trowbridge-Reitz distribution function times the
  27140. // geometric shadowing function. These sigma values squared must match the
  27141. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  27142. const EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
  27143. 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
  27144. // samples and exit early, but not recompile the shader.
  27145. const MAX_SAMPLES = 20;
  27146. const ENCODINGS = {
  27147. [LinearEncoding]: 0,
  27148. [sRGBEncoding]: 1,
  27149. [RGBEEncoding]: 2,
  27150. [RGBM7Encoding]: 3,
  27151. [RGBM16Encoding]: 4,
  27152. [RGBDEncoding]: 5,
  27153. [GammaEncoding]: 6
  27154. };
  27155. const backgroundMaterial = new MeshBasicMaterial({
  27156. side: BackSide,
  27157. depthWrite: false,
  27158. depthTest: false
  27159. });
  27160. const backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial);
  27161. const _flatCamera = /*@__PURE__*/new OrthographicCamera();
  27162. const {
  27163. _lodPlanes,
  27164. _sizeLods,
  27165. _sigmas
  27166. } = /*@__PURE__*/_createPlanes();
  27167. const _clearColor = /*@__PURE__*/new Color();
  27168. let _oldTarget = null; // Golden Ratio
  27169. const PHI = (1 + Math.sqrt(5)) / 2;
  27170. const INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
  27171. // same axis), used as axis directions evenly spread on a sphere.
  27172. 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)];
  27173. /**
  27174. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  27175. * (PMREM) from a cubeMap environment texture. This allows different levels of
  27176. * blur to be quickly accessed based on material roughness. It is packed into a
  27177. * special CubeUV format that allows us to perform custom interpolation so that
  27178. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  27179. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  27180. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  27181. * higher roughness levels. In this way we maintain resolution to smoothly
  27182. * interpolate diffuse lighting while limiting sampling computation.
  27183. *
  27184. * Paper: Fast, Accurate Image-Based Lighting
  27185. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  27186. */
  27187. function convertLinearToRGBE(color) {
  27188. const maxComponent = Math.max(color.r, color.g, color.b);
  27189. const fExp = Math.min(Math.max(Math.ceil(Math.log2(maxComponent)), -128.0), 127.0);
  27190. color.multiplyScalar(Math.pow(2.0, -fExp));
  27191. const alpha = (fExp + 128.0) / 255.0;
  27192. return alpha;
  27193. }
  27194. class PMREMGenerator {
  27195. constructor(renderer) {
  27196. this._renderer = renderer;
  27197. this._pingPongRenderTarget = null;
  27198. this._blurMaterial = _getBlurShader(MAX_SAMPLES);
  27199. this._equirectShader = null;
  27200. this._cubemapShader = null;
  27201. this._compileMaterial(this._blurMaterial);
  27202. }
  27203. /**
  27204. * Generates a PMREM from a supplied Scene, which can be faster than using an
  27205. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  27206. * in radians to be applied to the scene before PMREM generation. Optional near
  27207. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  27208. * is placed at the origin).
  27209. */
  27210. fromScene(scene, sigma = 0, near = 0.1, far = 100) {
  27211. _oldTarget = this._renderer.getRenderTarget();
  27212. const cubeUVRenderTarget = this._allocateTargets();
  27213. this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  27214. if (sigma > 0) {
  27215. this._blur(cubeUVRenderTarget, 0, 0, sigma);
  27216. }
  27217. this._applyPMREM(cubeUVRenderTarget);
  27218. this._cleanup(cubeUVRenderTarget);
  27219. return cubeUVRenderTarget;
  27220. }
  27221. /**
  27222. * Generates a PMREM from an equirectangular texture, which can be either LDR
  27223. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  27224. * as this matches best with the 256 x 256 cubemap output.
  27225. */
  27226. fromEquirectangular(equirectangular) {
  27227. return this._fromTexture(equirectangular);
  27228. }
  27229. /**
  27230. * Generates a PMREM from an cubemap texture, which can be either LDR
  27231. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  27232. * as this matches best with the 256 x 256 cubemap output.
  27233. */
  27234. fromCubemap(cubemap) {
  27235. return this._fromTexture(cubemap);
  27236. }
  27237. /**
  27238. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  27239. * your texture's network fetch for increased concurrency.
  27240. */
  27241. compileCubemapShader() {
  27242. if (this._cubemapShader === null) {
  27243. this._cubemapShader = _getCubemapShader();
  27244. this._compileMaterial(this._cubemapShader);
  27245. }
  27246. }
  27247. /**
  27248. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  27249. * your texture's network fetch for increased concurrency.
  27250. */
  27251. compileEquirectangularShader() {
  27252. if (this._equirectShader === null) {
  27253. this._equirectShader = _getEquirectShader();
  27254. this._compileMaterial(this._equirectShader);
  27255. }
  27256. }
  27257. /**
  27258. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  27259. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  27260. * one of them will cause any others to also become unusable.
  27261. */
  27262. dispose() {
  27263. this._blurMaterial.dispose();
  27264. if (this._cubemapShader !== null) this._cubemapShader.dispose();
  27265. if (this._equirectShader !== null) this._equirectShader.dispose();
  27266. for (let i = 0; i < _lodPlanes.length; i++) {
  27267. _lodPlanes[i].dispose();
  27268. }
  27269. } // private interface
  27270. _cleanup(outputTarget) {
  27271. this._pingPongRenderTarget.dispose();
  27272. this._renderer.setRenderTarget(_oldTarget);
  27273. outputTarget.scissorTest = false;
  27274. _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
  27275. }
  27276. _fromTexture(texture) {
  27277. _oldTarget = this._renderer.getRenderTarget();
  27278. const cubeUVRenderTarget = this._allocateTargets(texture);
  27279. this._textureToCubeUV(texture, cubeUVRenderTarget);
  27280. this._applyPMREM(cubeUVRenderTarget);
  27281. this._cleanup(cubeUVRenderTarget);
  27282. return cubeUVRenderTarget;
  27283. }
  27284. _allocateTargets(texture) {
  27285. // warning: null texture is valid
  27286. const params = {
  27287. magFilter: NearestFilter,
  27288. minFilter: NearestFilter,
  27289. generateMipmaps: false,
  27290. type: UnsignedByteType,
  27291. format: RGBEFormat,
  27292. encoding: _isLDR(texture) ? texture.encoding : RGBEEncoding,
  27293. depthBuffer: false
  27294. };
  27295. const cubeUVRenderTarget = _createRenderTarget(params);
  27296. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  27297. this._pingPongRenderTarget = _createRenderTarget(params);
  27298. return cubeUVRenderTarget;
  27299. }
  27300. _compileMaterial(material) {
  27301. const tmpMesh = new Mesh(_lodPlanes[0], material);
  27302. this._renderer.compile(tmpMesh, _flatCamera);
  27303. }
  27304. _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  27305. const fov = 90;
  27306. const aspect = 1;
  27307. const cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  27308. const upSign = [1, -1, 1, 1, 1, 1];
  27309. const forwardSign = [1, 1, 1, -1, -1, -1];
  27310. const renderer = this._renderer;
  27311. const originalAutoClear = renderer.autoClear;
  27312. const outputEncoding = renderer.outputEncoding;
  27313. const toneMapping = renderer.toneMapping;
  27314. renderer.getClearColor(_clearColor);
  27315. renderer.toneMapping = NoToneMapping;
  27316. renderer.outputEncoding = LinearEncoding;
  27317. renderer.autoClear = false;
  27318. let useSolidColor = false;
  27319. const background = scene.background;
  27320. if (background) {
  27321. if (background.isColor) {
  27322. backgroundMaterial.color.copy(background).convertSRGBToLinear();
  27323. scene.background = null;
  27324. const alpha = convertLinearToRGBE(backgroundMaterial.color);
  27325. backgroundMaterial.opacity = alpha;
  27326. useSolidColor = true;
  27327. }
  27328. } else {
  27329. backgroundMaterial.color.copy(_clearColor).convertSRGBToLinear();
  27330. const alpha = convertLinearToRGBE(backgroundMaterial.color);
  27331. backgroundMaterial.opacity = alpha;
  27332. useSolidColor = true;
  27333. }
  27334. for (let i = 0; i < 6; i++) {
  27335. const col = i % 3;
  27336. if (col == 0) {
  27337. cubeCamera.up.set(0, upSign[i], 0);
  27338. cubeCamera.lookAt(forwardSign[i], 0, 0);
  27339. } else if (col == 1) {
  27340. cubeCamera.up.set(0, 0, upSign[i]);
  27341. cubeCamera.lookAt(0, forwardSign[i], 0);
  27342. } else {
  27343. cubeCamera.up.set(0, upSign[i], 0);
  27344. cubeCamera.lookAt(0, 0, forwardSign[i]);
  27345. }
  27346. _setViewport(cubeUVRenderTarget, col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX);
  27347. renderer.setRenderTarget(cubeUVRenderTarget);
  27348. if (useSolidColor) {
  27349. renderer.render(backgroundBox, cubeCamera);
  27350. }
  27351. renderer.render(scene, cubeCamera);
  27352. }
  27353. renderer.toneMapping = toneMapping;
  27354. renderer.outputEncoding = outputEncoding;
  27355. renderer.autoClear = originalAutoClear;
  27356. }
  27357. _textureToCubeUV(texture, cubeUVRenderTarget) {
  27358. const renderer = this._renderer;
  27359. if (texture.isCubeTexture) {
  27360. if (this._cubemapShader == null) {
  27361. this._cubemapShader = _getCubemapShader();
  27362. }
  27363. } else {
  27364. if (this._equirectShader == null) {
  27365. this._equirectShader = _getEquirectShader();
  27366. }
  27367. }
  27368. const material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  27369. const mesh = new Mesh(_lodPlanes[0], material);
  27370. const uniforms = material.uniforms;
  27371. uniforms['envMap'].value = texture;
  27372. if (!texture.isCubeTexture) {
  27373. uniforms['texelSize'].value.set(1.0 / texture.image.width, 1.0 / texture.image.height);
  27374. }
  27375. uniforms['inputEncoding'].value = ENCODINGS[texture.encoding];
  27376. uniforms['outputEncoding'].value = ENCODINGS[cubeUVRenderTarget.texture.encoding];
  27377. _setViewport(cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX);
  27378. renderer.setRenderTarget(cubeUVRenderTarget);
  27379. renderer.render(mesh, _flatCamera);
  27380. }
  27381. _applyPMREM(cubeUVRenderTarget) {
  27382. const renderer = this._renderer;
  27383. const autoClear = renderer.autoClear;
  27384. renderer.autoClear = false;
  27385. for (let i = 1; i < TOTAL_LODS; i++) {
  27386. const sigma = Math.sqrt(_sigmas[i] * _sigmas[i] - _sigmas[i - 1] * _sigmas[i - 1]);
  27387. const poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  27388. this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  27389. }
  27390. renderer.autoClear = autoClear;
  27391. }
  27392. /**
  27393. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  27394. * vertically and horizontally, but this breaks down on a cube. Here we apply
  27395. * the blur latitudinally (around the poles), and then longitudinally (towards
  27396. * the poles) to approximate the orthogonally-separable blur. It is least
  27397. * accurate at the poles, but still does a decent job.
  27398. */
  27399. _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  27400. const pingPongRenderTarget = this._pingPongRenderTarget;
  27401. this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  27402. this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  27403. }
  27404. _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  27405. const renderer = this._renderer;
  27406. const blurMaterial = this._blurMaterial;
  27407. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  27408. console.error('blur direction must be either latitudinal or longitudinal!');
  27409. } // Number of standard deviations at which to cut off the discrete approximation.
  27410. const STANDARD_DEVIATIONS = 3;
  27411. const blurMesh = new Mesh(_lodPlanes[lodOut], blurMaterial);
  27412. const blurUniforms = blurMaterial.uniforms;
  27413. const pixels = _sizeLods[lodIn] - 1;
  27414. const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  27415. const sigmaPixels = sigmaRadians / radiansPerPixel;
  27416. const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  27417. if (samples > MAX_SAMPLES) {
  27418. console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
  27419. }
  27420. const weights = [];
  27421. let sum = 0;
  27422. for (let i = 0; i < MAX_SAMPLES; ++i) {
  27423. const x = i / sigmaPixels;
  27424. const weight = Math.exp(-x * x / 2);
  27425. weights.push(weight);
  27426. if (i == 0) {
  27427. sum += weight;
  27428. } else if (i < samples) {
  27429. sum += 2 * weight;
  27430. }
  27431. }
  27432. for (let i = 0; i < weights.length; i++) {
  27433. weights[i] = weights[i] / sum;
  27434. }
  27435. blurUniforms['envMap'].value = targetIn.texture;
  27436. blurUniforms['samples'].value = samples;
  27437. blurUniforms['weights'].value = weights;
  27438. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  27439. if (poleAxis) {
  27440. blurUniforms['poleAxis'].value = poleAxis;
  27441. }
  27442. blurUniforms['dTheta'].value = radiansPerPixel;
  27443. blurUniforms['mipInt'].value = LOD_MAX - lodIn;
  27444. blurUniforms['inputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  27445. blurUniforms['outputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  27446. const outputSize = _sizeLods[lodOut];
  27447. const x = 3 * Math.max(0, SIZE_MAX - 2 * outputSize);
  27448. const y = (lodOut === 0 ? 0 : 2 * SIZE_MAX) + 2 * outputSize * (lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0);
  27449. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  27450. renderer.setRenderTarget(targetOut);
  27451. renderer.render(blurMesh, _flatCamera);
  27452. }
  27453. }
  27454. function _isLDR(texture) {
  27455. if (texture === undefined || texture.type !== UnsignedByteType) return false;
  27456. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  27457. }
  27458. function _createPlanes() {
  27459. const _lodPlanes = [];
  27460. const _sizeLods = [];
  27461. const _sigmas = [];
  27462. let lod = LOD_MAX;
  27463. for (let i = 0; i < TOTAL_LODS; i++) {
  27464. const sizeLod = Math.pow(2, lod);
  27465. _sizeLods.push(sizeLod);
  27466. let sigma = 1.0 / sizeLod;
  27467. if (i > LOD_MAX - LOD_MIN) {
  27468. sigma = EXTRA_LOD_SIGMA[i - LOD_MAX + LOD_MIN - 1];
  27469. } else if (i == 0) {
  27470. sigma = 0;
  27471. }
  27472. _sigmas.push(sigma);
  27473. const texelSize = 1.0 / (sizeLod - 1);
  27474. const min = -texelSize / 2;
  27475. const max = 1 + texelSize / 2;
  27476. const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  27477. const cubeFaces = 6;
  27478. const vertices = 6;
  27479. const positionSize = 3;
  27480. const uvSize = 2;
  27481. const faceIndexSize = 1;
  27482. const position = new Float32Array(positionSize * vertices * cubeFaces);
  27483. const uv = new Float32Array(uvSize * vertices * cubeFaces);
  27484. const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  27485. for (let face = 0; face < cubeFaces; face++) {
  27486. const x = face % 3 * 2 / 3 - 1;
  27487. const y = face > 2 ? 0 : -1;
  27488. 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];
  27489. position.set(coordinates, positionSize * vertices * face);
  27490. uv.set(uv1, uvSize * vertices * face);
  27491. const fill = [face, face, face, face, face, face];
  27492. faceIndex.set(fill, faceIndexSize * vertices * face);
  27493. }
  27494. const planes = new BufferGeometry();
  27495. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  27496. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  27497. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  27498. _lodPlanes.push(planes);
  27499. if (lod > LOD_MIN) {
  27500. lod--;
  27501. }
  27502. }
  27503. return {
  27504. _lodPlanes,
  27505. _sizeLods,
  27506. _sigmas
  27507. };
  27508. }
  27509. function _createRenderTarget(params) {
  27510. const cubeUVRenderTarget = new WebGLRenderTarget(3 * SIZE_MAX, 3 * SIZE_MAX, params);
  27511. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  27512. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  27513. cubeUVRenderTarget.scissorTest = true;
  27514. return cubeUVRenderTarget;
  27515. }
  27516. function _setViewport(target, x, y, width, height) {
  27517. target.viewport.set(x, y, width, height);
  27518. target.scissor.set(x, y, width, height);
  27519. }
  27520. function _getBlurShader(maxSamples) {
  27521. const weights = new Float32Array(maxSamples);
  27522. const poleAxis = new Vector3(0, 1, 0);
  27523. const shaderMaterial = new RawShaderMaterial({
  27524. name: 'SphericalGaussianBlur',
  27525. defines: {
  27526. 'n': maxSamples
  27527. },
  27528. uniforms: {
  27529. 'envMap': {
  27530. value: null
  27531. },
  27532. 'samples': {
  27533. value: 1
  27534. },
  27535. 'weights': {
  27536. value: weights
  27537. },
  27538. 'latitudinal': {
  27539. value: false
  27540. },
  27541. 'dTheta': {
  27542. value: 0
  27543. },
  27544. 'mipInt': {
  27545. value: 0
  27546. },
  27547. 'poleAxis': {
  27548. value: poleAxis
  27549. },
  27550. 'inputEncoding': {
  27551. value: ENCODINGS[LinearEncoding]
  27552. },
  27553. 'outputEncoding': {
  27554. value: ENCODINGS[LinearEncoding]
  27555. }
  27556. },
  27557. vertexShader: _getCommonVertexShader(),
  27558. fragmentShader:
  27559. /* glsl */
  27560. `
  27561. precision mediump float;
  27562. precision mediump int;
  27563. varying vec3 vOutputDirection;
  27564. uniform sampler2D envMap;
  27565. uniform int samples;
  27566. uniform float weights[ n ];
  27567. uniform bool latitudinal;
  27568. uniform float dTheta;
  27569. uniform float mipInt;
  27570. uniform vec3 poleAxis;
  27571. ${_getEncodings()}
  27572. #define ENVMAP_TYPE_CUBE_UV
  27573. #include <cube_uv_reflection_fragment>
  27574. vec3 getSample( float theta, vec3 axis ) {
  27575. float cosTheta = cos( theta );
  27576. // Rodrigues' axis-angle rotation
  27577. vec3 sampleDirection = vOutputDirection * cosTheta
  27578. + cross( axis, vOutputDirection ) * sin( theta )
  27579. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  27580. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  27581. }
  27582. void main() {
  27583. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  27584. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  27585. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  27586. }
  27587. axis = normalize( axis );
  27588. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  27589. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  27590. for ( int i = 1; i < n; i++ ) {
  27591. if ( i >= samples ) {
  27592. break;
  27593. }
  27594. float theta = dTheta * float( i );
  27595. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  27596. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  27597. }
  27598. gl_FragColor = linearToOutputTexel( gl_FragColor );
  27599. }
  27600. `,
  27601. blending: NoBlending,
  27602. depthTest: false,
  27603. depthWrite: false
  27604. });
  27605. return shaderMaterial;
  27606. }
  27607. function _getEquirectShader() {
  27608. const texelSize = new Vector2(1, 1);
  27609. const shaderMaterial = new RawShaderMaterial({
  27610. name: 'EquirectangularToCubeUV',
  27611. uniforms: {
  27612. 'envMap': {
  27613. value: null
  27614. },
  27615. 'texelSize': {
  27616. value: texelSize
  27617. },
  27618. 'inputEncoding': {
  27619. value: ENCODINGS[LinearEncoding]
  27620. },
  27621. 'outputEncoding': {
  27622. value: ENCODINGS[LinearEncoding]
  27623. }
  27624. },
  27625. vertexShader: _getCommonVertexShader(),
  27626. fragmentShader:
  27627. /* glsl */
  27628. `
  27629. precision mediump float;
  27630. precision mediump int;
  27631. varying vec3 vOutputDirection;
  27632. uniform sampler2D envMap;
  27633. uniform vec2 texelSize;
  27634. ${_getEncodings()}
  27635. #include <common>
  27636. void main() {
  27637. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  27638. vec3 outputDirection = normalize( vOutputDirection );
  27639. vec2 uv = equirectUv( outputDirection );
  27640. vec2 f = fract( uv / texelSize - 0.5 );
  27641. uv -= f * texelSize;
  27642. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27643. uv.x += texelSize.x;
  27644. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27645. uv.y += texelSize.y;
  27646. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27647. uv.x -= texelSize.x;
  27648. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27649. vec3 tm = mix( tl, tr, f.x );
  27650. vec3 bm = mix( bl, br, f.x );
  27651. gl_FragColor.rgb = mix( tm, bm, f.y );
  27652. gl_FragColor = linearToOutputTexel( gl_FragColor );
  27653. }
  27654. `,
  27655. blending: NoBlending,
  27656. depthTest: false,
  27657. depthWrite: false
  27658. });
  27659. return shaderMaterial;
  27660. }
  27661. function _getCubemapShader() {
  27662. const shaderMaterial = new RawShaderMaterial({
  27663. name: 'CubemapToCubeUV',
  27664. uniforms: {
  27665. 'envMap': {
  27666. value: null
  27667. },
  27668. 'inputEncoding': {
  27669. value: ENCODINGS[LinearEncoding]
  27670. },
  27671. 'outputEncoding': {
  27672. value: ENCODINGS[LinearEncoding]
  27673. }
  27674. },
  27675. vertexShader: _getCommonVertexShader(),
  27676. fragmentShader:
  27677. /* glsl */
  27678. `
  27679. precision mediump float;
  27680. precision mediump int;
  27681. varying vec3 vOutputDirection;
  27682. uniform samplerCube envMap;
  27683. ${_getEncodings()}
  27684. void main() {
  27685. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  27686. gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;
  27687. gl_FragColor = linearToOutputTexel( gl_FragColor );
  27688. }
  27689. `,
  27690. blending: NoBlending,
  27691. depthTest: false,
  27692. depthWrite: false
  27693. });
  27694. return shaderMaterial;
  27695. }
  27696. function _getCommonVertexShader() {
  27697. return (
  27698. /* glsl */
  27699. `
  27700. precision mediump float;
  27701. precision mediump int;
  27702. attribute vec3 position;
  27703. attribute vec2 uv;
  27704. attribute float faceIndex;
  27705. varying vec3 vOutputDirection;
  27706. // RH coordinate system; PMREM face-indexing convention
  27707. vec3 getDirection( vec2 uv, float face ) {
  27708. uv = 2.0 * uv - 1.0;
  27709. vec3 direction = vec3( uv, 1.0 );
  27710. if ( face == 0.0 ) {
  27711. direction = direction.zyx; // ( 1, v, u ) pos x
  27712. } else if ( face == 1.0 ) {
  27713. direction = direction.xzy;
  27714. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  27715. } else if ( face == 2.0 ) {
  27716. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  27717. } else if ( face == 3.0 ) {
  27718. direction = direction.zyx;
  27719. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  27720. } else if ( face == 4.0 ) {
  27721. direction = direction.xzy;
  27722. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  27723. } else if ( face == 5.0 ) {
  27724. direction.z *= -1.0; // ( u, v, -1 ) neg z
  27725. }
  27726. return direction;
  27727. }
  27728. void main() {
  27729. vOutputDirection = getDirection( uv, faceIndex );
  27730. gl_Position = vec4( position, 1.0 );
  27731. }
  27732. `
  27733. );
  27734. }
  27735. function _getEncodings() {
  27736. return (
  27737. /* glsl */
  27738. `
  27739. uniform int inputEncoding;
  27740. uniform int outputEncoding;
  27741. #include <encodings_pars_fragment>
  27742. vec4 inputTexelToLinear( vec4 value ) {
  27743. if ( inputEncoding == 0 ) {
  27744. return value;
  27745. } else if ( inputEncoding == 1 ) {
  27746. return sRGBToLinear( value );
  27747. } else if ( inputEncoding == 2 ) {
  27748. return RGBEToLinear( value );
  27749. } else if ( inputEncoding == 3 ) {
  27750. return RGBMToLinear( value, 7.0 );
  27751. } else if ( inputEncoding == 4 ) {
  27752. return RGBMToLinear( value, 16.0 );
  27753. } else if ( inputEncoding == 5 ) {
  27754. return RGBDToLinear( value, 256.0 );
  27755. } else {
  27756. return GammaToLinear( value, 2.2 );
  27757. }
  27758. }
  27759. vec4 linearToOutputTexel( vec4 value ) {
  27760. if ( outputEncoding == 0 ) {
  27761. return value;
  27762. } else if ( outputEncoding == 1 ) {
  27763. return LinearTosRGB( value );
  27764. } else if ( outputEncoding == 2 ) {
  27765. return LinearToRGBE( value );
  27766. } else if ( outputEncoding == 3 ) {
  27767. return LinearToRGBM( value, 7.0 );
  27768. } else if ( outputEncoding == 4 ) {
  27769. return LinearToRGBM( value, 16.0 );
  27770. } else if ( outputEncoding == 5 ) {
  27771. return LinearToRGBD( value, 256.0 );
  27772. } else {
  27773. return LinearToGamma( value, 2.2 );
  27774. }
  27775. }
  27776. vec4 envMapTexelToLinear( vec4 color ) {
  27777. return inputTexelToLinear( color );
  27778. }
  27779. `
  27780. );
  27781. }
  27782. const LineStrip = 0;
  27783. const LinePieces = 1;
  27784. const NoColors = 0;
  27785. const FaceColors = 1;
  27786. const VertexColors = 2;
  27787. function MeshFaceMaterial(materials) {
  27788. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  27789. return materials;
  27790. }
  27791. function MultiMaterial(materials = []) {
  27792. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  27793. materials.isMultiMaterial = true;
  27794. materials.materials = materials;
  27795. materials.clone = function () {
  27796. return materials.slice();
  27797. };
  27798. return materials;
  27799. }
  27800. function PointCloud(geometry, material) {
  27801. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  27802. return new Points(geometry, material);
  27803. }
  27804. function Particle(material) {
  27805. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  27806. return new Sprite(material);
  27807. }
  27808. function ParticleSystem(geometry, material) {
  27809. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  27810. return new Points(geometry, material);
  27811. }
  27812. function PointCloudMaterial(parameters) {
  27813. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  27814. return new PointsMaterial(parameters);
  27815. }
  27816. function ParticleBasicMaterial(parameters) {
  27817. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  27818. return new PointsMaterial(parameters);
  27819. }
  27820. function ParticleSystemMaterial(parameters) {
  27821. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  27822. return new PointsMaterial(parameters);
  27823. }
  27824. function Vertex(x, y, z) {
  27825. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  27826. return new Vector3(x, y, z);
  27827. } //
  27828. function DynamicBufferAttribute(array, itemSize) {
  27829. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.');
  27830. return new BufferAttribute(array, itemSize).setUsage(DynamicDrawUsage);
  27831. }
  27832. function Int8Attribute(array, itemSize) {
  27833. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  27834. return new Int8BufferAttribute(array, itemSize);
  27835. }
  27836. function Uint8Attribute(array, itemSize) {
  27837. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  27838. return new Uint8BufferAttribute(array, itemSize);
  27839. }
  27840. function Uint8ClampedAttribute(array, itemSize) {
  27841. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  27842. return new Uint8ClampedBufferAttribute(array, itemSize);
  27843. }
  27844. function Int16Attribute(array, itemSize) {
  27845. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  27846. return new Int16BufferAttribute(array, itemSize);
  27847. }
  27848. function Uint16Attribute(array, itemSize) {
  27849. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  27850. return new Uint16BufferAttribute(array, itemSize);
  27851. }
  27852. function Int32Attribute(array, itemSize) {
  27853. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  27854. return new Int32BufferAttribute(array, itemSize);
  27855. }
  27856. function Uint32Attribute(array, itemSize) {
  27857. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  27858. return new Uint32BufferAttribute(array, itemSize);
  27859. }
  27860. function Float32Attribute(array, itemSize) {
  27861. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  27862. return new Float32BufferAttribute(array, itemSize);
  27863. }
  27864. function Float64Attribute(array, itemSize) {
  27865. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  27866. return new Float64BufferAttribute(array, itemSize);
  27867. } //
  27868. Curve.create = function (construct, getPoint) {
  27869. console.log('THREE.Curve.create() has been deprecated');
  27870. construct.prototype = Object.create(Curve.prototype);
  27871. construct.prototype.constructor = construct;
  27872. construct.prototype.getPoint = getPoint;
  27873. return construct;
  27874. }; //
  27875. Path.prototype.fromPoints = function (points) {
  27876. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  27877. return this.setFromPoints(points);
  27878. }; //
  27879. function AxisHelper(size) {
  27880. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  27881. return new AxesHelper(size);
  27882. }
  27883. function BoundingBoxHelper(object, color) {
  27884. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  27885. return new BoxHelper(object, color);
  27886. }
  27887. function EdgesHelper(object, hex) {
  27888. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  27889. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  27890. color: hex !== undefined ? hex : 0xffffff
  27891. }));
  27892. }
  27893. GridHelper.prototype.setColors = function () {
  27894. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  27895. };
  27896. SkeletonHelper.prototype.update = function () {
  27897. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  27898. };
  27899. function WireframeHelper(object, hex) {
  27900. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  27901. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  27902. color: hex !== undefined ? hex : 0xffffff
  27903. }));
  27904. } //
  27905. Loader.prototype.extractUrlBase = function (url) {
  27906. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  27907. return LoaderUtils.extractUrlBase(url);
  27908. };
  27909. Loader.Handlers = {
  27910. add: function ()
  27911. /* regex, loader */
  27912. {
  27913. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  27914. },
  27915. get: function ()
  27916. /* file */
  27917. {
  27918. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  27919. }
  27920. };
  27921. function XHRLoader(manager) {
  27922. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  27923. return new FileLoader(manager);
  27924. }
  27925. function BinaryTextureLoader(manager) {
  27926. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  27927. return new DataTextureLoader(manager);
  27928. } //
  27929. Box2.prototype.center = function (optionalTarget) {
  27930. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  27931. return this.getCenter(optionalTarget);
  27932. };
  27933. Box2.prototype.empty = function () {
  27934. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  27935. return this.isEmpty();
  27936. };
  27937. Box2.prototype.isIntersectionBox = function (box) {
  27938. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  27939. return this.intersectsBox(box);
  27940. };
  27941. Box2.prototype.size = function (optionalTarget) {
  27942. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  27943. return this.getSize(optionalTarget);
  27944. }; //
  27945. Box3.prototype.center = function (optionalTarget) {
  27946. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  27947. return this.getCenter(optionalTarget);
  27948. };
  27949. Box3.prototype.empty = function () {
  27950. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  27951. return this.isEmpty();
  27952. };
  27953. Box3.prototype.isIntersectionBox = function (box) {
  27954. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  27955. return this.intersectsBox(box);
  27956. };
  27957. Box3.prototype.isIntersectionSphere = function (sphere) {
  27958. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  27959. return this.intersectsSphere(sphere);
  27960. };
  27961. Box3.prototype.size = function (optionalTarget) {
  27962. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  27963. return this.getSize(optionalTarget);
  27964. }; //
  27965. Sphere.prototype.empty = function () {
  27966. console.warn('THREE.Sphere: .empty() has been renamed to .isEmpty().');
  27967. return this.isEmpty();
  27968. }; //
  27969. Frustum.prototype.setFromMatrix = function (m) {
  27970. console.warn('THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().');
  27971. return this.setFromProjectionMatrix(m);
  27972. }; //
  27973. Line3.prototype.center = function (optionalTarget) {
  27974. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  27975. return this.getCenter(optionalTarget);
  27976. }; //
  27977. Matrix3.prototype.flattenToArrayOffset = function (array, offset) {
  27978. console.warn('THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  27979. return this.toArray(array, offset);
  27980. };
  27981. Matrix3.prototype.multiplyVector3 = function (vector) {
  27982. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  27983. return vector.applyMatrix3(this);
  27984. };
  27985. Matrix3.prototype.multiplyVector3Array = function ()
  27986. /* a */
  27987. {
  27988. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  27989. };
  27990. Matrix3.prototype.applyToBufferAttribute = function (attribute) {
  27991. console.warn('THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.');
  27992. return attribute.applyMatrix3(this);
  27993. };
  27994. Matrix3.prototype.applyToVector3Array = function ()
  27995. /* array, offset, length */
  27996. {
  27997. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  27998. };
  27999. Matrix3.prototype.getInverse = function (matrix) {
  28000. console.warn('THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  28001. return this.copy(matrix).invert();
  28002. }; //
  28003. Matrix4.prototype.extractPosition = function (m) {
  28004. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  28005. return this.copyPosition(m);
  28006. };
  28007. Matrix4.prototype.flattenToArrayOffset = function (array, offset) {
  28008. console.warn('THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  28009. return this.toArray(array, offset);
  28010. };
  28011. Matrix4.prototype.getPosition = function () {
  28012. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  28013. return new Vector3().setFromMatrixColumn(this, 3);
  28014. };
  28015. Matrix4.prototype.setRotationFromQuaternion = function (q) {
  28016. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  28017. return this.makeRotationFromQuaternion(q);
  28018. };
  28019. Matrix4.prototype.multiplyToArray = function () {
  28020. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  28021. };
  28022. Matrix4.prototype.multiplyVector3 = function (vector) {
  28023. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28024. return vector.applyMatrix4(this);
  28025. };
  28026. Matrix4.prototype.multiplyVector4 = function (vector) {
  28027. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28028. return vector.applyMatrix4(this);
  28029. };
  28030. Matrix4.prototype.multiplyVector3Array = function ()
  28031. /* a */
  28032. {
  28033. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  28034. };
  28035. Matrix4.prototype.rotateAxis = function (v) {
  28036. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  28037. v.transformDirection(this);
  28038. };
  28039. Matrix4.prototype.crossVector = function (vector) {
  28040. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28041. return vector.applyMatrix4(this);
  28042. };
  28043. Matrix4.prototype.translate = function () {
  28044. console.error('THREE.Matrix4: .translate() has been removed.');
  28045. };
  28046. Matrix4.prototype.rotateX = function () {
  28047. console.error('THREE.Matrix4: .rotateX() has been removed.');
  28048. };
  28049. Matrix4.prototype.rotateY = function () {
  28050. console.error('THREE.Matrix4: .rotateY() has been removed.');
  28051. };
  28052. Matrix4.prototype.rotateZ = function () {
  28053. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  28054. };
  28055. Matrix4.prototype.rotateByAxis = function () {
  28056. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  28057. };
  28058. Matrix4.prototype.applyToBufferAttribute = function (attribute) {
  28059. console.warn('THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.');
  28060. return attribute.applyMatrix4(this);
  28061. };
  28062. Matrix4.prototype.applyToVector3Array = function ()
  28063. /* array, offset, length */
  28064. {
  28065. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  28066. };
  28067. Matrix4.prototype.makeFrustum = function (left, right, bottom, top, near, far) {
  28068. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  28069. return this.makePerspective(left, right, top, bottom, near, far);
  28070. };
  28071. Matrix4.prototype.getInverse = function (matrix) {
  28072. console.warn('THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  28073. return this.copy(matrix).invert();
  28074. }; //
  28075. Plane.prototype.isIntersectionLine = function (line) {
  28076. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  28077. return this.intersectsLine(line);
  28078. }; //
  28079. Quaternion.prototype.multiplyVector3 = function (vector) {
  28080. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  28081. return vector.applyQuaternion(this);
  28082. };
  28083. Quaternion.prototype.inverse = function () {
  28084. console.warn('THREE.Quaternion: .inverse() has been renamed to invert().');
  28085. return this.invert();
  28086. }; //
  28087. Ray.prototype.isIntersectionBox = function (box) {
  28088. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  28089. return this.intersectsBox(box);
  28090. };
  28091. Ray.prototype.isIntersectionPlane = function (plane) {
  28092. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  28093. return this.intersectsPlane(plane);
  28094. };
  28095. Ray.prototype.isIntersectionSphere = function (sphere) {
  28096. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  28097. return this.intersectsSphere(sphere);
  28098. }; //
  28099. Triangle.prototype.area = function () {
  28100. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  28101. return this.getArea();
  28102. };
  28103. Triangle.prototype.barycoordFromPoint = function (point, target) {
  28104. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28105. return this.getBarycoord(point, target);
  28106. };
  28107. Triangle.prototype.midpoint = function (target) {
  28108. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  28109. return this.getMidpoint(target);
  28110. };
  28111. Triangle.prototypenormal = function (target) {
  28112. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28113. return this.getNormal(target);
  28114. };
  28115. Triangle.prototype.plane = function (target) {
  28116. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  28117. return this.getPlane(target);
  28118. };
  28119. Triangle.barycoordFromPoint = function (point, a, b, c, target) {
  28120. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28121. return Triangle.getBarycoord(point, a, b, c, target);
  28122. };
  28123. Triangle.normal = function (a, b, c, target) {
  28124. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28125. return Triangle.getNormal(a, b, c, target);
  28126. }; //
  28127. Shape.prototype.extractAllPoints = function (divisions) {
  28128. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  28129. return this.extractPoints(divisions);
  28130. };
  28131. Shape.prototype.extrude = function (options) {
  28132. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  28133. return new ExtrudeGeometry(this, options);
  28134. };
  28135. Shape.prototype.makeGeometry = function (options) {
  28136. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  28137. return new ShapeGeometry(this, options);
  28138. }; //
  28139. Vector2.prototype.fromAttribute = function (attribute, index, offset) {
  28140. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28141. return this.fromBufferAttribute(attribute, index, offset);
  28142. };
  28143. Vector2.prototype.distanceToManhattan = function (v) {
  28144. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28145. return this.manhattanDistanceTo(v);
  28146. };
  28147. Vector2.prototype.lengthManhattan = function () {
  28148. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  28149. return this.manhattanLength();
  28150. }; //
  28151. Vector3.prototype.setEulerFromRotationMatrix = function () {
  28152. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  28153. };
  28154. Vector3.prototype.setEulerFromQuaternion = function () {
  28155. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  28156. };
  28157. Vector3.prototype.getPositionFromMatrix = function (m) {
  28158. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  28159. return this.setFromMatrixPosition(m);
  28160. };
  28161. Vector3.prototype.getScaleFromMatrix = function (m) {
  28162. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  28163. return this.setFromMatrixScale(m);
  28164. };
  28165. Vector3.prototype.getColumnFromMatrix = function (index, matrix) {
  28166. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  28167. return this.setFromMatrixColumn(matrix, index);
  28168. };
  28169. Vector3.prototype.applyProjection = function (m) {
  28170. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  28171. return this.applyMatrix4(m);
  28172. };
  28173. Vector3.prototype.fromAttribute = function (attribute, index, offset) {
  28174. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28175. return this.fromBufferAttribute(attribute, index, offset);
  28176. };
  28177. Vector3.prototype.distanceToManhattan = function (v) {
  28178. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28179. return this.manhattanDistanceTo(v);
  28180. };
  28181. Vector3.prototype.lengthManhattan = function () {
  28182. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  28183. return this.manhattanLength();
  28184. }; //
  28185. Vector4.prototype.fromAttribute = function (attribute, index, offset) {
  28186. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28187. return this.fromBufferAttribute(attribute, index, offset);
  28188. };
  28189. Vector4.prototype.lengthManhattan = function () {
  28190. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  28191. return this.manhattanLength();
  28192. }; //
  28193. Object3D.prototype.getChildByName = function (name) {
  28194. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  28195. return this.getObjectByName(name);
  28196. };
  28197. Object3D.prototype.renderDepth = function () {
  28198. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  28199. };
  28200. Object3D.prototype.translate = function (distance, axis) {
  28201. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  28202. return this.translateOnAxis(axis, distance);
  28203. };
  28204. Object3D.prototype.getWorldRotation = function () {
  28205. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  28206. };
  28207. Object3D.prototype.applyMatrix = function (matrix) {
  28208. console.warn('THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().');
  28209. return this.applyMatrix4(matrix);
  28210. };
  28211. Object.defineProperties(Object3D.prototype, {
  28212. eulerOrder: {
  28213. get: function () {
  28214. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28215. return this.rotation.order;
  28216. },
  28217. set: function (value) {
  28218. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28219. this.rotation.order = value;
  28220. }
  28221. },
  28222. useQuaternion: {
  28223. get: function () {
  28224. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28225. },
  28226. set: function () {
  28227. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28228. }
  28229. }
  28230. });
  28231. Mesh.prototype.setDrawMode = function () {
  28232. console.error('THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28233. };
  28234. Object.defineProperties(Mesh.prototype, {
  28235. drawMode: {
  28236. get: function () {
  28237. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.');
  28238. return TrianglesDrawMode;
  28239. },
  28240. set: function () {
  28241. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28242. }
  28243. }
  28244. });
  28245. SkinnedMesh.prototype.initBones = function () {
  28246. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  28247. }; //
  28248. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  28249. console.warn('THREE.PerspectiveCamera.setLens is deprecated. ' + 'Use .setFocalLength and .filmGauge for a photographic setup.');
  28250. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  28251. this.setFocalLength(focalLength);
  28252. }; //
  28253. Object.defineProperties(Light.prototype, {
  28254. onlyShadow: {
  28255. set: function () {
  28256. console.warn('THREE.Light: .onlyShadow has been removed.');
  28257. }
  28258. },
  28259. shadowCameraFov: {
  28260. set: function (value) {
  28261. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  28262. this.shadow.camera.fov = value;
  28263. }
  28264. },
  28265. shadowCameraLeft: {
  28266. set: function (value) {
  28267. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  28268. this.shadow.camera.left = value;
  28269. }
  28270. },
  28271. shadowCameraRight: {
  28272. set: function (value) {
  28273. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  28274. this.shadow.camera.right = value;
  28275. }
  28276. },
  28277. shadowCameraTop: {
  28278. set: function (value) {
  28279. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  28280. this.shadow.camera.top = value;
  28281. }
  28282. },
  28283. shadowCameraBottom: {
  28284. set: function (value) {
  28285. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  28286. this.shadow.camera.bottom = value;
  28287. }
  28288. },
  28289. shadowCameraNear: {
  28290. set: function (value) {
  28291. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  28292. this.shadow.camera.near = value;
  28293. }
  28294. },
  28295. shadowCameraFar: {
  28296. set: function (value) {
  28297. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  28298. this.shadow.camera.far = value;
  28299. }
  28300. },
  28301. shadowCameraVisible: {
  28302. set: function () {
  28303. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  28304. }
  28305. },
  28306. shadowBias: {
  28307. set: function (value) {
  28308. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  28309. this.shadow.bias = value;
  28310. }
  28311. },
  28312. shadowDarkness: {
  28313. set: function () {
  28314. console.warn('THREE.Light: .shadowDarkness has been removed.');
  28315. }
  28316. },
  28317. shadowMapWidth: {
  28318. set: function (value) {
  28319. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  28320. this.shadow.mapSize.width = value;
  28321. }
  28322. },
  28323. shadowMapHeight: {
  28324. set: function (value) {
  28325. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  28326. this.shadow.mapSize.height = value;
  28327. }
  28328. }
  28329. }); //
  28330. Object.defineProperties(BufferAttribute.prototype, {
  28331. length: {
  28332. get: function () {
  28333. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  28334. return this.array.length;
  28335. }
  28336. },
  28337. dynamic: {
  28338. get: function () {
  28339. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28340. return this.usage === DynamicDrawUsage;
  28341. },
  28342. set: function ()
  28343. /* value */
  28344. {
  28345. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28346. this.setUsage(DynamicDrawUsage);
  28347. }
  28348. }
  28349. });
  28350. BufferAttribute.prototype.setDynamic = function (value) {
  28351. console.warn('THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28352. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28353. return this;
  28354. };
  28355. BufferAttribute.prototype.copyIndicesArray = function ()
  28356. /* indices */
  28357. {
  28358. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  28359. }, BufferAttribute.prototype.setArray = function ()
  28360. /* array */
  28361. {
  28362. console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28363. }; //
  28364. BufferGeometry.prototype.addIndex = function (index) {
  28365. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  28366. this.setIndex(index);
  28367. };
  28368. BufferGeometry.prototype.addAttribute = function (name, attribute) {
  28369. console.warn('THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().');
  28370. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  28371. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  28372. return this.setAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  28373. }
  28374. if (name === 'index') {
  28375. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  28376. this.setIndex(attribute);
  28377. return this;
  28378. }
  28379. return this.setAttribute(name, attribute);
  28380. };
  28381. BufferGeometry.prototype.addDrawCall = function (start, count, indexOffset) {
  28382. if (indexOffset !== undefined) {
  28383. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  28384. }
  28385. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  28386. this.addGroup(start, count);
  28387. };
  28388. BufferGeometry.prototype.clearDrawCalls = function () {
  28389. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  28390. this.clearGroups();
  28391. };
  28392. BufferGeometry.prototype.computeOffsets = function () {
  28393. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  28394. };
  28395. BufferGeometry.prototype.removeAttribute = function (name) {
  28396. console.warn('THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().');
  28397. return this.deleteAttribute(name);
  28398. };
  28399. BufferGeometry.prototype.applyMatrix = function (matrix) {
  28400. console.warn('THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().');
  28401. return this.applyMatrix4(matrix);
  28402. };
  28403. Object.defineProperties(BufferGeometry.prototype, {
  28404. drawcalls: {
  28405. get: function () {
  28406. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  28407. return this.groups;
  28408. }
  28409. },
  28410. offsets: {
  28411. get: function () {
  28412. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  28413. return this.groups;
  28414. }
  28415. }
  28416. });
  28417. InterleavedBuffer.prototype.setDynamic = function (value) {
  28418. console.warn('THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28419. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28420. return this;
  28421. };
  28422. InterleavedBuffer.prototype.setArray = function ()
  28423. /* array */
  28424. {
  28425. console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28426. }; //
  28427. ExtrudeGeometry.prototype.getArrays = function () {
  28428. console.error('THREE.ExtrudeGeometry: .getArrays() has been removed.');
  28429. };
  28430. ExtrudeGeometry.prototype.addShapeList = function () {
  28431. console.error('THREE.ExtrudeGeometry: .addShapeList() has been removed.');
  28432. };
  28433. ExtrudeGeometry.prototype.addShape = function () {
  28434. console.error('THREE.ExtrudeGeometry: .addShape() has been removed.');
  28435. }; //
  28436. Scene.prototype.dispose = function () {
  28437. console.error('THREE.Scene: .dispose() has been removed.');
  28438. }; //
  28439. Uniform.prototype.onUpdate = function () {
  28440. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  28441. return this;
  28442. }; //
  28443. Object.defineProperties(Material.prototype, {
  28444. wrapAround: {
  28445. get: function () {
  28446. console.warn('THREE.Material: .wrapAround has been removed.');
  28447. },
  28448. set: function () {
  28449. console.warn('THREE.Material: .wrapAround has been removed.');
  28450. }
  28451. },
  28452. overdraw: {
  28453. get: function () {
  28454. console.warn('THREE.Material: .overdraw has been removed.');
  28455. },
  28456. set: function () {
  28457. console.warn('THREE.Material: .overdraw has been removed.');
  28458. }
  28459. },
  28460. wrapRGB: {
  28461. get: function () {
  28462. console.warn('THREE.Material: .wrapRGB has been removed.');
  28463. return new Color();
  28464. }
  28465. },
  28466. shading: {
  28467. get: function () {
  28468. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28469. },
  28470. set: function (value) {
  28471. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28472. this.flatShading = value === FlatShading;
  28473. }
  28474. },
  28475. stencilMask: {
  28476. get: function () {
  28477. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28478. return this.stencilFuncMask;
  28479. },
  28480. set: function (value) {
  28481. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28482. this.stencilFuncMask = value;
  28483. }
  28484. }
  28485. });
  28486. Object.defineProperties(ShaderMaterial.prototype, {
  28487. derivatives: {
  28488. get: function () {
  28489. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28490. return this.extensions.derivatives;
  28491. },
  28492. set: function (value) {
  28493. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28494. this.extensions.derivatives = value;
  28495. }
  28496. }
  28497. }); //
  28498. WebGLRenderer.prototype.clearTarget = function (renderTarget, color, depth, stencil) {
  28499. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  28500. this.setRenderTarget(renderTarget);
  28501. this.clear(color, depth, stencil);
  28502. };
  28503. WebGLRenderer.prototype.animate = function (callback) {
  28504. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  28505. this.setAnimationLoop(callback);
  28506. };
  28507. WebGLRenderer.prototype.getCurrentRenderTarget = function () {
  28508. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  28509. return this.getRenderTarget();
  28510. };
  28511. WebGLRenderer.prototype.getMaxAnisotropy = function () {
  28512. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  28513. return this.capabilities.getMaxAnisotropy();
  28514. };
  28515. WebGLRenderer.prototype.getPrecision = function () {
  28516. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  28517. return this.capabilities.precision;
  28518. };
  28519. WebGLRenderer.prototype.resetGLState = function () {
  28520. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  28521. return this.state.reset();
  28522. };
  28523. WebGLRenderer.prototype.supportsFloatTextures = function () {
  28524. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  28525. return this.extensions.get('OES_texture_float');
  28526. };
  28527. WebGLRenderer.prototype.supportsHalfFloatTextures = function () {
  28528. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  28529. return this.extensions.get('OES_texture_half_float');
  28530. };
  28531. WebGLRenderer.prototype.supportsStandardDerivatives = function () {
  28532. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  28533. return this.extensions.get('OES_standard_derivatives');
  28534. };
  28535. WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () {
  28536. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  28537. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  28538. };
  28539. WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () {
  28540. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  28541. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  28542. };
  28543. WebGLRenderer.prototype.supportsBlendMinMax = function () {
  28544. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  28545. return this.extensions.get('EXT_blend_minmax');
  28546. };
  28547. WebGLRenderer.prototype.supportsVertexTextures = function () {
  28548. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  28549. return this.capabilities.vertexTextures;
  28550. };
  28551. WebGLRenderer.prototype.supportsInstancedArrays = function () {
  28552. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  28553. return this.extensions.get('ANGLE_instanced_arrays');
  28554. };
  28555. WebGLRenderer.prototype.enableScissorTest = function (boolean) {
  28556. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  28557. this.setScissorTest(boolean);
  28558. };
  28559. WebGLRenderer.prototype.initMaterial = function () {
  28560. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  28561. };
  28562. WebGLRenderer.prototype.addPrePlugin = function () {
  28563. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  28564. };
  28565. WebGLRenderer.prototype.addPostPlugin = function () {
  28566. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  28567. };
  28568. WebGLRenderer.prototype.updateShadowMap = function () {
  28569. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  28570. };
  28571. WebGLRenderer.prototype.setFaceCulling = function () {
  28572. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  28573. };
  28574. WebGLRenderer.prototype.allocTextureUnit = function () {
  28575. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  28576. };
  28577. WebGLRenderer.prototype.setTexture = function () {
  28578. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  28579. };
  28580. WebGLRenderer.prototype.setTexture2D = function () {
  28581. console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
  28582. };
  28583. WebGLRenderer.prototype.setTextureCube = function () {
  28584. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  28585. };
  28586. WebGLRenderer.prototype.getActiveMipMapLevel = function () {
  28587. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  28588. return this.getActiveMipmapLevel();
  28589. };
  28590. Object.defineProperties(WebGLRenderer.prototype, {
  28591. shadowMapEnabled: {
  28592. get: function () {
  28593. return this.shadowMap.enabled;
  28594. },
  28595. set: function (value) {
  28596. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  28597. this.shadowMap.enabled = value;
  28598. }
  28599. },
  28600. shadowMapType: {
  28601. get: function () {
  28602. return this.shadowMap.type;
  28603. },
  28604. set: function (value) {
  28605. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  28606. this.shadowMap.type = value;
  28607. }
  28608. },
  28609. shadowMapCullFace: {
  28610. get: function () {
  28611. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  28612. return undefined;
  28613. },
  28614. set: function ()
  28615. /* value */
  28616. {
  28617. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  28618. }
  28619. },
  28620. context: {
  28621. get: function () {
  28622. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  28623. return this.getContext();
  28624. }
  28625. },
  28626. vr: {
  28627. get: function () {
  28628. console.warn('THREE.WebGLRenderer: .vr has been renamed to .xr');
  28629. return this.xr;
  28630. }
  28631. },
  28632. gammaInput: {
  28633. get: function () {
  28634. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  28635. return false;
  28636. },
  28637. set: function () {
  28638. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  28639. }
  28640. },
  28641. gammaOutput: {
  28642. get: function () {
  28643. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  28644. return false;
  28645. },
  28646. set: function (value) {
  28647. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  28648. this.outputEncoding = value === true ? sRGBEncoding : LinearEncoding;
  28649. }
  28650. },
  28651. toneMappingWhitePoint: {
  28652. get: function () {
  28653. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  28654. return 1.0;
  28655. },
  28656. set: function () {
  28657. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  28658. }
  28659. }
  28660. });
  28661. Object.defineProperties(WebGLShadowMap.prototype, {
  28662. cullFace: {
  28663. get: function () {
  28664. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  28665. return undefined;
  28666. },
  28667. set: function ()
  28668. /* cullFace */
  28669. {
  28670. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  28671. }
  28672. },
  28673. renderReverseSided: {
  28674. get: function () {
  28675. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  28676. return undefined;
  28677. },
  28678. set: function () {
  28679. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  28680. }
  28681. },
  28682. renderSingleSided: {
  28683. get: function () {
  28684. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  28685. return undefined;
  28686. },
  28687. set: function () {
  28688. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  28689. }
  28690. }
  28691. });
  28692. function WebGLRenderTargetCube(width, height, options) {
  28693. console.warn('THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).');
  28694. return new WebGLCubeRenderTarget(width, options);
  28695. } //
  28696. Object.defineProperties(WebGLRenderTarget.prototype, {
  28697. wrapS: {
  28698. get: function () {
  28699. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  28700. return this.texture.wrapS;
  28701. },
  28702. set: function (value) {
  28703. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  28704. this.texture.wrapS = value;
  28705. }
  28706. },
  28707. wrapT: {
  28708. get: function () {
  28709. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  28710. return this.texture.wrapT;
  28711. },
  28712. set: function (value) {
  28713. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  28714. this.texture.wrapT = value;
  28715. }
  28716. },
  28717. magFilter: {
  28718. get: function () {
  28719. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  28720. return this.texture.magFilter;
  28721. },
  28722. set: function (value) {
  28723. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  28724. this.texture.magFilter = value;
  28725. }
  28726. },
  28727. minFilter: {
  28728. get: function () {
  28729. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  28730. return this.texture.minFilter;
  28731. },
  28732. set: function (value) {
  28733. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  28734. this.texture.minFilter = value;
  28735. }
  28736. },
  28737. anisotropy: {
  28738. get: function () {
  28739. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  28740. return this.texture.anisotropy;
  28741. },
  28742. set: function (value) {
  28743. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  28744. this.texture.anisotropy = value;
  28745. }
  28746. },
  28747. offset: {
  28748. get: function () {
  28749. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  28750. return this.texture.offset;
  28751. },
  28752. set: function (value) {
  28753. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  28754. this.texture.offset = value;
  28755. }
  28756. },
  28757. repeat: {
  28758. get: function () {
  28759. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  28760. return this.texture.repeat;
  28761. },
  28762. set: function (value) {
  28763. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  28764. this.texture.repeat = value;
  28765. }
  28766. },
  28767. format: {
  28768. get: function () {
  28769. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  28770. return this.texture.format;
  28771. },
  28772. set: function (value) {
  28773. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  28774. this.texture.format = value;
  28775. }
  28776. },
  28777. type: {
  28778. get: function () {
  28779. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  28780. return this.texture.type;
  28781. },
  28782. set: function (value) {
  28783. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  28784. this.texture.type = value;
  28785. }
  28786. },
  28787. generateMipmaps: {
  28788. get: function () {
  28789. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  28790. return this.texture.generateMipmaps;
  28791. },
  28792. set: function (value) {
  28793. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  28794. this.texture.generateMipmaps = value;
  28795. }
  28796. }
  28797. }); //
  28798. Audio.prototype.load = function (file) {
  28799. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  28800. const scope = this;
  28801. const audioLoader = new AudioLoader();
  28802. audioLoader.load(file, function (buffer) {
  28803. scope.setBuffer(buffer);
  28804. });
  28805. return this;
  28806. };
  28807. AudioAnalyser.prototype.getData = function () {
  28808. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  28809. return this.getFrequencyData();
  28810. }; //
  28811. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  28812. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  28813. return this.update(renderer, scene);
  28814. };
  28815. CubeCamera.prototype.clear = function (renderer, color, depth, stencil) {
  28816. console.warn('THREE.CubeCamera: .clear() is now .renderTarget.clear().');
  28817. return this.renderTarget.clear(renderer, color, depth, stencil);
  28818. };
  28819. ImageUtils.crossOrigin = undefined;
  28820. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  28821. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  28822. const loader = new TextureLoader();
  28823. loader.setCrossOrigin(this.crossOrigin);
  28824. const texture = loader.load(url, onLoad, undefined, onError);
  28825. if (mapping) texture.mapping = mapping;
  28826. return texture;
  28827. };
  28828. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  28829. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  28830. const loader = new CubeTextureLoader();
  28831. loader.setCrossOrigin(this.crossOrigin);
  28832. const texture = loader.load(urls, onLoad, undefined, onError);
  28833. if (mapping) texture.mapping = mapping;
  28834. return texture;
  28835. };
  28836. ImageUtils.loadCompressedTexture = function () {
  28837. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  28838. };
  28839. ImageUtils.loadCompressedTextureCube = function () {
  28840. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  28841. }; //
  28842. function CanvasRenderer() {
  28843. console.error('THREE.CanvasRenderer has been removed');
  28844. } //
  28845. function JSONLoader() {
  28846. console.error('THREE.JSONLoader has been removed.');
  28847. } //
  28848. const SceneUtils = {
  28849. createMultiMaterialObject: function ()
  28850. /* geometry, materials */
  28851. {
  28852. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28853. },
  28854. detach: function ()
  28855. /* child, parent, scene */
  28856. {
  28857. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28858. },
  28859. attach: function ()
  28860. /* child, scene, parent */
  28861. {
  28862. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28863. }
  28864. }; //
  28865. function LensFlare() {
  28866. console.error('THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js');
  28867. }
  28868. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  28869. /* eslint-disable no-undef */
  28870. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  28871. detail: {
  28872. revision: REVISION
  28873. }
  28874. }));
  28875. /* eslint-enable no-undef */
  28876. }
  28877. if (typeof window !== 'undefined') {
  28878. if (window.__THREE__) {
  28879. console.warn('WARNING: Multiple instances of Three.js being imported.');
  28880. } else {
  28881. window.__THREE__ = REVISION;
  28882. }
  28883. }
  28884. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  28885. exports.AddEquation = AddEquation;
  28886. exports.AddOperation = AddOperation;
  28887. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  28888. exports.AdditiveBlending = AdditiveBlending;
  28889. exports.AlphaFormat = AlphaFormat;
  28890. exports.AlwaysDepth = AlwaysDepth;
  28891. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  28892. exports.AmbientLight = AmbientLight;
  28893. exports.AmbientLightProbe = AmbientLightProbe;
  28894. exports.AnimationClip = AnimationClip;
  28895. exports.AnimationLoader = AnimationLoader;
  28896. exports.AnimationMixer = AnimationMixer;
  28897. exports.AnimationObjectGroup = AnimationObjectGroup;
  28898. exports.AnimationUtils = AnimationUtils;
  28899. exports.ArcCurve = ArcCurve;
  28900. exports.ArrayCamera = ArrayCamera;
  28901. exports.ArrowHelper = ArrowHelper;
  28902. exports.Audio = Audio;
  28903. exports.AudioAnalyser = AudioAnalyser;
  28904. exports.AudioContext = AudioContext;
  28905. exports.AudioListener = AudioListener;
  28906. exports.AudioLoader = AudioLoader;
  28907. exports.AxesHelper = AxesHelper;
  28908. exports.AxisHelper = AxisHelper;
  28909. exports.BackSide = BackSide;
  28910. exports.BasicDepthPacking = BasicDepthPacking;
  28911. exports.BasicShadowMap = BasicShadowMap;
  28912. exports.BinaryTextureLoader = BinaryTextureLoader;
  28913. exports.Bone = Bone;
  28914. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  28915. exports.BoundingBoxHelper = BoundingBoxHelper;
  28916. exports.Box2 = Box2;
  28917. exports.Box3 = Box3;
  28918. exports.Box3Helper = Box3Helper;
  28919. exports.BoxBufferGeometry = BoxGeometry;
  28920. exports.BoxGeometry = BoxGeometry;
  28921. exports.BoxHelper = BoxHelper;
  28922. exports.BufferAttribute = BufferAttribute;
  28923. exports.BufferGeometry = BufferGeometry;
  28924. exports.BufferGeometryLoader = BufferGeometryLoader;
  28925. exports.ByteType = ByteType;
  28926. exports.Cache = Cache;
  28927. exports.Camera = Camera;
  28928. exports.CameraHelper = CameraHelper;
  28929. exports.CanvasRenderer = CanvasRenderer;
  28930. exports.CanvasTexture = CanvasTexture;
  28931. exports.CatmullRomCurve3 = CatmullRomCurve3;
  28932. exports.CineonToneMapping = CineonToneMapping;
  28933. exports.CircleBufferGeometry = CircleGeometry;
  28934. exports.CircleGeometry = CircleGeometry;
  28935. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  28936. exports.Clock = Clock;
  28937. exports.Color = Color;
  28938. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  28939. exports.CompressedTexture = CompressedTexture;
  28940. exports.CompressedTextureLoader = CompressedTextureLoader;
  28941. exports.ConeBufferGeometry = ConeGeometry;
  28942. exports.ConeGeometry = ConeGeometry;
  28943. exports.CubeCamera = CubeCamera;
  28944. exports.CubeReflectionMapping = CubeReflectionMapping;
  28945. exports.CubeRefractionMapping = CubeRefractionMapping;
  28946. exports.CubeTexture = CubeTexture;
  28947. exports.CubeTextureLoader = CubeTextureLoader;
  28948. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  28949. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  28950. exports.CubicBezierCurve = CubicBezierCurve;
  28951. exports.CubicBezierCurve3 = CubicBezierCurve3;
  28952. exports.CubicInterpolant = CubicInterpolant;
  28953. exports.CullFaceBack = CullFaceBack;
  28954. exports.CullFaceFront = CullFaceFront;
  28955. exports.CullFaceFrontBack = CullFaceFrontBack;
  28956. exports.CullFaceNone = CullFaceNone;
  28957. exports.Curve = Curve;
  28958. exports.CurvePath = CurvePath;
  28959. exports.CustomBlending = CustomBlending;
  28960. exports.CustomToneMapping = CustomToneMapping;
  28961. exports.CylinderBufferGeometry = CylinderGeometry;
  28962. exports.CylinderGeometry = CylinderGeometry;
  28963. exports.Cylindrical = Cylindrical;
  28964. exports.DataTexture = DataTexture;
  28965. exports.DataTexture2DArray = DataTexture2DArray;
  28966. exports.DataTexture3D = DataTexture3D;
  28967. exports.DataTextureLoader = DataTextureLoader;
  28968. exports.DataUtils = DataUtils;
  28969. exports.DecrementStencilOp = DecrementStencilOp;
  28970. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  28971. exports.DefaultLoadingManager = DefaultLoadingManager;
  28972. exports.DepthFormat = DepthFormat;
  28973. exports.DepthStencilFormat = DepthStencilFormat;
  28974. exports.DepthTexture = DepthTexture;
  28975. exports.DirectionalLight = DirectionalLight;
  28976. exports.DirectionalLightHelper = DirectionalLightHelper;
  28977. exports.DiscreteInterpolant = DiscreteInterpolant;
  28978. exports.DodecahedronBufferGeometry = DodecahedronGeometry;
  28979. exports.DodecahedronGeometry = DodecahedronGeometry;
  28980. exports.DoubleSide = DoubleSide;
  28981. exports.DstAlphaFactor = DstAlphaFactor;
  28982. exports.DstColorFactor = DstColorFactor;
  28983. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  28984. exports.DynamicCopyUsage = DynamicCopyUsage;
  28985. exports.DynamicDrawUsage = DynamicDrawUsage;
  28986. exports.DynamicReadUsage = DynamicReadUsage;
  28987. exports.EdgesGeometry = EdgesGeometry;
  28988. exports.EdgesHelper = EdgesHelper;
  28989. exports.EllipseCurve = EllipseCurve;
  28990. exports.EqualDepth = EqualDepth;
  28991. exports.EqualStencilFunc = EqualStencilFunc;
  28992. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  28993. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  28994. exports.Euler = Euler;
  28995. exports.EventDispatcher = EventDispatcher;
  28996. exports.ExtrudeBufferGeometry = ExtrudeGeometry;
  28997. exports.ExtrudeGeometry = ExtrudeGeometry;
  28998. exports.FaceColors = FaceColors;
  28999. exports.FileLoader = FileLoader;
  29000. exports.FlatShading = FlatShading;
  29001. exports.Float16BufferAttribute = Float16BufferAttribute;
  29002. exports.Float32Attribute = Float32Attribute;
  29003. exports.Float32BufferAttribute = Float32BufferAttribute;
  29004. exports.Float64Attribute = Float64Attribute;
  29005. exports.Float64BufferAttribute = Float64BufferAttribute;
  29006. exports.FloatType = FloatType;
  29007. exports.Fog = Fog;
  29008. exports.FogExp2 = FogExp2;
  29009. exports.Font = Font;
  29010. exports.FontLoader = FontLoader;
  29011. exports.FrontSide = FrontSide;
  29012. exports.Frustum = Frustum;
  29013. exports.GLBufferAttribute = GLBufferAttribute;
  29014. exports.GLSL1 = GLSL1;
  29015. exports.GLSL3 = GLSL3;
  29016. exports.GammaEncoding = GammaEncoding;
  29017. exports.GreaterDepth = GreaterDepth;
  29018. exports.GreaterEqualDepth = GreaterEqualDepth;
  29019. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  29020. exports.GreaterStencilFunc = GreaterStencilFunc;
  29021. exports.GridHelper = GridHelper;
  29022. exports.Group = Group;
  29023. exports.HalfFloatType = HalfFloatType;
  29024. exports.HemisphereLight = HemisphereLight;
  29025. exports.HemisphereLightHelper = HemisphereLightHelper;
  29026. exports.HemisphereLightProbe = HemisphereLightProbe;
  29027. exports.IcosahedronBufferGeometry = IcosahedronGeometry;
  29028. exports.IcosahedronGeometry = IcosahedronGeometry;
  29029. exports.ImageBitmapLoader = ImageBitmapLoader;
  29030. exports.ImageLoader = ImageLoader;
  29031. exports.ImageUtils = ImageUtils;
  29032. exports.ImmediateRenderObject = ImmediateRenderObject;
  29033. exports.IncrementStencilOp = IncrementStencilOp;
  29034. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  29035. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  29036. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  29037. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  29038. exports.InstancedMesh = InstancedMesh;
  29039. exports.Int16Attribute = Int16Attribute;
  29040. exports.Int16BufferAttribute = Int16BufferAttribute;
  29041. exports.Int32Attribute = Int32Attribute;
  29042. exports.Int32BufferAttribute = Int32BufferAttribute;
  29043. exports.Int8Attribute = Int8Attribute;
  29044. exports.Int8BufferAttribute = Int8BufferAttribute;
  29045. exports.IntType = IntType;
  29046. exports.InterleavedBuffer = InterleavedBuffer;
  29047. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  29048. exports.Interpolant = Interpolant;
  29049. exports.InterpolateDiscrete = InterpolateDiscrete;
  29050. exports.InterpolateLinear = InterpolateLinear;
  29051. exports.InterpolateSmooth = InterpolateSmooth;
  29052. exports.InvertStencilOp = InvertStencilOp;
  29053. exports.JSONLoader = JSONLoader;
  29054. exports.KeepStencilOp = KeepStencilOp;
  29055. exports.KeyframeTrack = KeyframeTrack;
  29056. exports.LOD = LOD;
  29057. exports.LatheBufferGeometry = LatheGeometry;
  29058. exports.LatheGeometry = LatheGeometry;
  29059. exports.Layers = Layers;
  29060. exports.LensFlare = LensFlare;
  29061. exports.LessDepth = LessDepth;
  29062. exports.LessEqualDepth = LessEqualDepth;
  29063. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  29064. exports.LessStencilFunc = LessStencilFunc;
  29065. exports.Light = Light;
  29066. exports.LightProbe = LightProbe;
  29067. exports.Line = Line;
  29068. exports.Line3 = Line3;
  29069. exports.LineBasicMaterial = LineBasicMaterial;
  29070. exports.LineCurve = LineCurve;
  29071. exports.LineCurve3 = LineCurve3;
  29072. exports.LineDashedMaterial = LineDashedMaterial;
  29073. exports.LineLoop = LineLoop;
  29074. exports.LinePieces = LinePieces;
  29075. exports.LineSegments = LineSegments;
  29076. exports.LineStrip = LineStrip;
  29077. exports.LinearEncoding = LinearEncoding;
  29078. exports.LinearFilter = LinearFilter;
  29079. exports.LinearInterpolant = LinearInterpolant;
  29080. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  29081. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  29082. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  29083. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  29084. exports.LinearToneMapping = LinearToneMapping;
  29085. exports.Loader = Loader;
  29086. exports.LoaderUtils = LoaderUtils;
  29087. exports.LoadingManager = LoadingManager;
  29088. exports.LogLuvEncoding = LogLuvEncoding;
  29089. exports.LoopOnce = LoopOnce;
  29090. exports.LoopPingPong = LoopPingPong;
  29091. exports.LoopRepeat = LoopRepeat;
  29092. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  29093. exports.LuminanceFormat = LuminanceFormat;
  29094. exports.MOUSE = MOUSE;
  29095. exports.Material = Material;
  29096. exports.MaterialLoader = MaterialLoader;
  29097. exports.Math = MathUtils;
  29098. exports.MathUtils = MathUtils;
  29099. exports.Matrix3 = Matrix3;
  29100. exports.Matrix4 = Matrix4;
  29101. exports.MaxEquation = MaxEquation;
  29102. exports.Mesh = Mesh;
  29103. exports.MeshBasicMaterial = MeshBasicMaterial;
  29104. exports.MeshDepthMaterial = MeshDepthMaterial;
  29105. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  29106. exports.MeshFaceMaterial = MeshFaceMaterial;
  29107. exports.MeshLambertMaterial = MeshLambertMaterial;
  29108. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  29109. exports.MeshNormalMaterial = MeshNormalMaterial;
  29110. exports.MeshPhongMaterial = MeshPhongMaterial;
  29111. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  29112. exports.MeshStandardMaterial = MeshStandardMaterial;
  29113. exports.MeshToonMaterial = MeshToonMaterial;
  29114. exports.MinEquation = MinEquation;
  29115. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  29116. exports.MixOperation = MixOperation;
  29117. exports.MultiMaterial = MultiMaterial;
  29118. exports.MultiplyBlending = MultiplyBlending;
  29119. exports.MultiplyOperation = MultiplyOperation;
  29120. exports.NearestFilter = NearestFilter;
  29121. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  29122. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  29123. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  29124. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  29125. exports.NeverDepth = NeverDepth;
  29126. exports.NeverStencilFunc = NeverStencilFunc;
  29127. exports.NoBlending = NoBlending;
  29128. exports.NoColors = NoColors;
  29129. exports.NoToneMapping = NoToneMapping;
  29130. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  29131. exports.NormalBlending = NormalBlending;
  29132. exports.NotEqualDepth = NotEqualDepth;
  29133. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  29134. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  29135. exports.Object3D = Object3D;
  29136. exports.ObjectLoader = ObjectLoader;
  29137. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  29138. exports.OctahedronBufferGeometry = OctahedronGeometry;
  29139. exports.OctahedronGeometry = OctahedronGeometry;
  29140. exports.OneFactor = OneFactor;
  29141. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  29142. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  29143. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  29144. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  29145. exports.OrthographicCamera = OrthographicCamera;
  29146. exports.PCFShadowMap = PCFShadowMap;
  29147. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  29148. exports.PMREMGenerator = PMREMGenerator;
  29149. exports.ParametricBufferGeometry = ParametricGeometry;
  29150. exports.ParametricGeometry = ParametricGeometry;
  29151. exports.Particle = Particle;
  29152. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  29153. exports.ParticleSystem = ParticleSystem;
  29154. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  29155. exports.Path = Path;
  29156. exports.PerspectiveCamera = PerspectiveCamera;
  29157. exports.Plane = Plane;
  29158. exports.PlaneBufferGeometry = PlaneGeometry;
  29159. exports.PlaneGeometry = PlaneGeometry;
  29160. exports.PlaneHelper = PlaneHelper;
  29161. exports.PointCloud = PointCloud;
  29162. exports.PointCloudMaterial = PointCloudMaterial;
  29163. exports.PointLight = PointLight;
  29164. exports.PointLightHelper = PointLightHelper;
  29165. exports.Points = Points;
  29166. exports.PointsMaterial = PointsMaterial;
  29167. exports.PolarGridHelper = PolarGridHelper;
  29168. exports.PolyhedronBufferGeometry = PolyhedronGeometry;
  29169. exports.PolyhedronGeometry = PolyhedronGeometry;
  29170. exports.PositionalAudio = PositionalAudio;
  29171. exports.PropertyBinding = PropertyBinding;
  29172. exports.PropertyMixer = PropertyMixer;
  29173. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  29174. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  29175. exports.Quaternion = Quaternion;
  29176. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  29177. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  29178. exports.REVISION = REVISION;
  29179. exports.RGBADepthPacking = RGBADepthPacking;
  29180. exports.RGBAFormat = RGBAFormat;
  29181. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  29182. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  29183. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  29184. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  29185. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  29186. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  29187. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  29188. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  29189. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  29190. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  29191. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  29192. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  29193. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  29194. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  29195. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  29196. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  29197. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  29198. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  29199. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  29200. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  29201. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  29202. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  29203. exports.RGBDEncoding = RGBDEncoding;
  29204. exports.RGBEEncoding = RGBEEncoding;
  29205. exports.RGBEFormat = RGBEFormat;
  29206. exports.RGBFormat = RGBFormat;
  29207. exports.RGBIntegerFormat = RGBIntegerFormat;
  29208. exports.RGBM16Encoding = RGBM16Encoding;
  29209. exports.RGBM7Encoding = RGBM7Encoding;
  29210. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  29211. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  29212. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  29213. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  29214. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  29215. exports.RGFormat = RGFormat;
  29216. exports.RGIntegerFormat = RGIntegerFormat;
  29217. exports.RawShaderMaterial = RawShaderMaterial;
  29218. exports.Ray = Ray;
  29219. exports.Raycaster = Raycaster;
  29220. exports.RectAreaLight = RectAreaLight;
  29221. exports.RedFormat = RedFormat;
  29222. exports.RedIntegerFormat = RedIntegerFormat;
  29223. exports.ReinhardToneMapping = ReinhardToneMapping;
  29224. exports.RepeatWrapping = RepeatWrapping;
  29225. exports.ReplaceStencilOp = ReplaceStencilOp;
  29226. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  29227. exports.RingBufferGeometry = RingGeometry;
  29228. exports.RingGeometry = RingGeometry;
  29229. exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
  29230. exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
  29231. exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
  29232. exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
  29233. exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
  29234. exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
  29235. exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
  29236. exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
  29237. exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
  29238. exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
  29239. exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
  29240. exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
  29241. exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
  29242. exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
  29243. exports.Scene = Scene;
  29244. exports.SceneUtils = SceneUtils;
  29245. exports.ShaderChunk = ShaderChunk;
  29246. exports.ShaderLib = ShaderLib;
  29247. exports.ShaderMaterial = ShaderMaterial;
  29248. exports.ShadowMaterial = ShadowMaterial;
  29249. exports.Shape = Shape;
  29250. exports.ShapeBufferGeometry = ShapeGeometry;
  29251. exports.ShapeGeometry = ShapeGeometry;
  29252. exports.ShapePath = ShapePath;
  29253. exports.ShapeUtils = ShapeUtils;
  29254. exports.ShortType = ShortType;
  29255. exports.Skeleton = Skeleton;
  29256. exports.SkeletonHelper = SkeletonHelper;
  29257. exports.SkinnedMesh = SkinnedMesh;
  29258. exports.SmoothShading = SmoothShading;
  29259. exports.Sphere = Sphere;
  29260. exports.SphereBufferGeometry = SphereGeometry;
  29261. exports.SphereGeometry = SphereGeometry;
  29262. exports.Spherical = Spherical;
  29263. exports.SphericalHarmonics3 = SphericalHarmonics3;
  29264. exports.SplineCurve = SplineCurve;
  29265. exports.SpotLight = SpotLight;
  29266. exports.SpotLightHelper = SpotLightHelper;
  29267. exports.Sprite = Sprite;
  29268. exports.SpriteMaterial = SpriteMaterial;
  29269. exports.SrcAlphaFactor = SrcAlphaFactor;
  29270. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  29271. exports.SrcColorFactor = SrcColorFactor;
  29272. exports.StaticCopyUsage = StaticCopyUsage;
  29273. exports.StaticDrawUsage = StaticDrawUsage;
  29274. exports.StaticReadUsage = StaticReadUsage;
  29275. exports.StereoCamera = StereoCamera;
  29276. exports.StreamCopyUsage = StreamCopyUsage;
  29277. exports.StreamDrawUsage = StreamDrawUsage;
  29278. exports.StreamReadUsage = StreamReadUsage;
  29279. exports.StringKeyframeTrack = StringKeyframeTrack;
  29280. exports.SubtractEquation = SubtractEquation;
  29281. exports.SubtractiveBlending = SubtractiveBlending;
  29282. exports.TOUCH = TOUCH;
  29283. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  29284. exports.TetrahedronBufferGeometry = TetrahedronGeometry;
  29285. exports.TetrahedronGeometry = TetrahedronGeometry;
  29286. exports.TextBufferGeometry = TextGeometry;
  29287. exports.TextGeometry = TextGeometry;
  29288. exports.Texture = Texture;
  29289. exports.TextureLoader = TextureLoader;
  29290. exports.TorusBufferGeometry = TorusGeometry;
  29291. exports.TorusGeometry = TorusGeometry;
  29292. exports.TorusKnotBufferGeometry = TorusKnotGeometry;
  29293. exports.TorusKnotGeometry = TorusKnotGeometry;
  29294. exports.Triangle = Triangle;
  29295. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  29296. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  29297. exports.TrianglesDrawMode = TrianglesDrawMode;
  29298. exports.TubeBufferGeometry = TubeGeometry;
  29299. exports.TubeGeometry = TubeGeometry;
  29300. exports.UVMapping = UVMapping;
  29301. exports.Uint16Attribute = Uint16Attribute;
  29302. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  29303. exports.Uint32Attribute = Uint32Attribute;
  29304. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  29305. exports.Uint8Attribute = Uint8Attribute;
  29306. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  29307. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  29308. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  29309. exports.Uniform = Uniform;
  29310. exports.UniformsLib = UniformsLib;
  29311. exports.UniformsUtils = UniformsUtils;
  29312. exports.UnsignedByteType = UnsignedByteType;
  29313. exports.UnsignedInt248Type = UnsignedInt248Type;
  29314. exports.UnsignedIntType = UnsignedIntType;
  29315. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  29316. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  29317. exports.UnsignedShort565Type = UnsignedShort565Type;
  29318. exports.UnsignedShortType = UnsignedShortType;
  29319. exports.VSMShadowMap = VSMShadowMap;
  29320. exports.Vector2 = Vector2;
  29321. exports.Vector3 = Vector3;
  29322. exports.Vector4 = Vector4;
  29323. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  29324. exports.Vertex = Vertex;
  29325. exports.VertexColors = VertexColors;
  29326. exports.VideoTexture = VideoTexture;
  29327. exports.WebGL1Renderer = WebGL1Renderer;
  29328. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  29329. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  29330. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  29331. exports.WebGLRenderTarget = WebGLRenderTarget;
  29332. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  29333. exports.WebGLRenderer = WebGLRenderer;
  29334. exports.WebGLUtils = WebGLUtils;
  29335. exports.WireframeGeometry = WireframeGeometry;
  29336. exports.WireframeHelper = WireframeHelper;
  29337. exports.WrapAroundEnding = WrapAroundEnding;
  29338. exports.XHRLoader = XHRLoader;
  29339. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  29340. exports.ZeroFactor = ZeroFactor;
  29341. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  29342. exports.ZeroStencilOp = ZeroStencilOp;
  29343. exports.sRGBEncoding = sRGBEncoding;
  29344. Object.defineProperty(exports, '__esModule', { value: true });
  29345. })));