three.js 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254
  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 = '129';
  12. const MOUSE = {
  13. LEFT: 0,
  14. MIDDLE: 1,
  15. RIGHT: 2,
  16. ROTATE: 0,
  17. DOLLY: 1,
  18. PAN: 2
  19. };
  20. const TOUCH = {
  21. ROTATE: 0,
  22. PAN: 1,
  23. DOLLY_PAN: 2,
  24. DOLLY_ROTATE: 3
  25. };
  26. const CullFaceNone = 0;
  27. const CullFaceBack = 1;
  28. const CullFaceFront = 2;
  29. const CullFaceFrontBack = 3;
  30. const BasicShadowMap = 0;
  31. const PCFShadowMap = 1;
  32. const PCFSoftShadowMap = 2;
  33. const VSMShadowMap = 3;
  34. const FrontSide = 0;
  35. const BackSide = 1;
  36. const DoubleSide = 2;
  37. const FlatShading = 1;
  38. const SmoothShading = 2;
  39. const NoBlending = 0;
  40. const NormalBlending = 1;
  41. const AdditiveBlending = 2;
  42. const SubtractiveBlending = 3;
  43. const MultiplyBlending = 4;
  44. const CustomBlending = 5;
  45. const AddEquation = 100;
  46. const SubtractEquation = 101;
  47. const ReverseSubtractEquation = 102;
  48. const MinEquation = 103;
  49. const MaxEquation = 104;
  50. const ZeroFactor = 200;
  51. const OneFactor = 201;
  52. const SrcColorFactor = 202;
  53. const OneMinusSrcColorFactor = 203;
  54. const SrcAlphaFactor = 204;
  55. const OneMinusSrcAlphaFactor = 205;
  56. const DstAlphaFactor = 206;
  57. const OneMinusDstAlphaFactor = 207;
  58. const DstColorFactor = 208;
  59. const OneMinusDstColorFactor = 209;
  60. const SrcAlphaSaturateFactor = 210;
  61. const NeverDepth = 0;
  62. const AlwaysDepth = 1;
  63. const LessDepth = 2;
  64. const LessEqualDepth = 3;
  65. const EqualDepth = 4;
  66. const GreaterEqualDepth = 5;
  67. const GreaterDepth = 6;
  68. const NotEqualDepth = 7;
  69. const MultiplyOperation = 0;
  70. const MixOperation = 1;
  71. const AddOperation = 2;
  72. const NoToneMapping = 0;
  73. const LinearToneMapping = 1;
  74. const ReinhardToneMapping = 2;
  75. const CineonToneMapping = 3;
  76. const ACESFilmicToneMapping = 4;
  77. const CustomToneMapping = 5;
  78. const UVMapping = 300;
  79. const CubeReflectionMapping = 301;
  80. const CubeRefractionMapping = 302;
  81. const EquirectangularReflectionMapping = 303;
  82. const EquirectangularRefractionMapping = 304;
  83. const CubeUVReflectionMapping = 306;
  84. const CubeUVRefractionMapping = 307;
  85. const RepeatWrapping = 1000;
  86. const ClampToEdgeWrapping = 1001;
  87. const MirroredRepeatWrapping = 1002;
  88. const NearestFilter = 1003;
  89. const NearestMipmapNearestFilter = 1004;
  90. const NearestMipMapNearestFilter = 1004;
  91. const NearestMipmapLinearFilter = 1005;
  92. const NearestMipMapLinearFilter = 1005;
  93. const LinearFilter = 1006;
  94. const LinearMipmapNearestFilter = 1007;
  95. const LinearMipMapNearestFilter = 1007;
  96. const LinearMipmapLinearFilter = 1008;
  97. const LinearMipMapLinearFilter = 1008;
  98. const UnsignedByteType = 1009;
  99. const ByteType = 1010;
  100. const ShortType = 1011;
  101. const UnsignedShortType = 1012;
  102. const IntType = 1013;
  103. const UnsignedIntType = 1014;
  104. const FloatType = 1015;
  105. const HalfFloatType = 1016;
  106. const UnsignedShort4444Type = 1017;
  107. const UnsignedShort5551Type = 1018;
  108. const UnsignedShort565Type = 1019;
  109. const UnsignedInt248Type = 1020;
  110. const AlphaFormat = 1021;
  111. const RGBFormat = 1022;
  112. const RGBAFormat = 1023;
  113. const LuminanceFormat = 1024;
  114. const LuminanceAlphaFormat = 1025;
  115. const RGBEFormat = RGBAFormat;
  116. const DepthFormat = 1026;
  117. const DepthStencilFormat = 1027;
  118. const RedFormat = 1028;
  119. const RedIntegerFormat = 1029;
  120. const RGFormat = 1030;
  121. const RGIntegerFormat = 1031;
  122. const RGBIntegerFormat = 1032;
  123. const RGBAIntegerFormat = 1033;
  124. const RGB_S3TC_DXT1_Format = 33776;
  125. const RGBA_S3TC_DXT1_Format = 33777;
  126. const RGBA_S3TC_DXT3_Format = 33778;
  127. const RGBA_S3TC_DXT5_Format = 33779;
  128. const RGB_PVRTC_4BPPV1_Format = 35840;
  129. const RGB_PVRTC_2BPPV1_Format = 35841;
  130. const RGBA_PVRTC_4BPPV1_Format = 35842;
  131. const RGBA_PVRTC_2BPPV1_Format = 35843;
  132. const RGB_ETC1_Format = 36196;
  133. const RGB_ETC2_Format = 37492;
  134. const RGBA_ETC2_EAC_Format = 37496;
  135. const RGBA_ASTC_4x4_Format = 37808;
  136. const RGBA_ASTC_5x4_Format = 37809;
  137. const RGBA_ASTC_5x5_Format = 37810;
  138. const RGBA_ASTC_6x5_Format = 37811;
  139. const RGBA_ASTC_6x6_Format = 37812;
  140. const RGBA_ASTC_8x5_Format = 37813;
  141. const RGBA_ASTC_8x6_Format = 37814;
  142. const RGBA_ASTC_8x8_Format = 37815;
  143. const RGBA_ASTC_10x5_Format = 37816;
  144. const RGBA_ASTC_10x6_Format = 37817;
  145. const RGBA_ASTC_10x8_Format = 37818;
  146. const RGBA_ASTC_10x10_Format = 37819;
  147. const RGBA_ASTC_12x10_Format = 37820;
  148. const RGBA_ASTC_12x12_Format = 37821;
  149. const RGBA_BPTC_Format = 36492;
  150. const SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  151. const SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  152. const SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  153. const SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  154. const SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  155. const SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  156. const SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  157. const SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  158. const SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  159. const SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  160. const SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  161. const SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  162. const SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  163. const SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  164. const LoopOnce = 2200;
  165. const LoopRepeat = 2201;
  166. const LoopPingPong = 2202;
  167. const InterpolateDiscrete = 2300;
  168. const InterpolateLinear = 2301;
  169. const InterpolateSmooth = 2302;
  170. const ZeroCurvatureEnding = 2400;
  171. const ZeroSlopeEnding = 2401;
  172. const WrapAroundEnding = 2402;
  173. const NormalAnimationBlendMode = 2500;
  174. const AdditiveAnimationBlendMode = 2501;
  175. const TrianglesDrawMode = 0;
  176. const TriangleStripDrawMode = 1;
  177. const TriangleFanDrawMode = 2;
  178. const LinearEncoding = 3000;
  179. const sRGBEncoding = 3001;
  180. const GammaEncoding = 3007;
  181. const RGBEEncoding = 3002;
  182. const LogLuvEncoding = 3003;
  183. const RGBM7Encoding = 3004;
  184. const RGBM16Encoding = 3005;
  185. const RGBDEncoding = 3006;
  186. const BasicDepthPacking = 3200;
  187. const RGBADepthPacking = 3201;
  188. const TangentSpaceNormalMap = 0;
  189. const ObjectSpaceNormalMap = 1;
  190. const ZeroStencilOp = 0;
  191. const KeepStencilOp = 7680;
  192. const ReplaceStencilOp = 7681;
  193. const IncrementStencilOp = 7682;
  194. const DecrementStencilOp = 7683;
  195. const IncrementWrapStencilOp = 34055;
  196. const DecrementWrapStencilOp = 34056;
  197. const InvertStencilOp = 5386;
  198. const NeverStencilFunc = 512;
  199. const LessStencilFunc = 513;
  200. const EqualStencilFunc = 514;
  201. const LessEqualStencilFunc = 515;
  202. const GreaterStencilFunc = 516;
  203. const NotEqualStencilFunc = 517;
  204. const GreaterEqualStencilFunc = 518;
  205. const AlwaysStencilFunc = 519;
  206. const StaticDrawUsage = 35044;
  207. const DynamicDrawUsage = 35048;
  208. const StreamDrawUsage = 35040;
  209. const StaticReadUsage = 35045;
  210. const DynamicReadUsage = 35049;
  211. const StreamReadUsage = 35041;
  212. const StaticCopyUsage = 35046;
  213. const DynamicCopyUsage = 35050;
  214. const StreamCopyUsage = 35042;
  215. const GLSL1 = '100';
  216. const GLSL3 = '300 es';
  217. /**
  218. * https://github.com/mrdoob/eventdispatcher.js/
  219. */
  220. class EventDispatcher {
  221. addEventListener(type, listener) {
  222. if (this._listeners === undefined) this._listeners = {};
  223. const listeners = this._listeners;
  224. if (listeners[type] === undefined) {
  225. listeners[type] = [];
  226. }
  227. if (listeners[type].indexOf(listener) === -1) {
  228. listeners[type].push(listener);
  229. }
  230. }
  231. hasEventListener(type, listener) {
  232. if (this._listeners === undefined) return false;
  233. const listeners = this._listeners;
  234. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  235. }
  236. removeEventListener(type, listener) {
  237. if (this._listeners === undefined) return;
  238. const listeners = this._listeners;
  239. const listenerArray = listeners[type];
  240. if (listenerArray !== undefined) {
  241. const index = listenerArray.indexOf(listener);
  242. if (index !== -1) {
  243. listenerArray.splice(index, 1);
  244. }
  245. }
  246. }
  247. dispatchEvent(event) {
  248. if (this._listeners === undefined) return;
  249. const listeners = this._listeners;
  250. const listenerArray = listeners[event.type];
  251. if (listenerArray !== undefined) {
  252. event.target = this; // Make a copy, in case listeners are removed while iterating.
  253. const array = listenerArray.slice(0);
  254. for (let i = 0, l = array.length; i < l; i++) {
  255. array[i].call(this, event);
  256. }
  257. event.target = null;
  258. }
  259. }
  260. }
  261. const _lut = [];
  262. for (let i = 0; i < 256; i++) {
  263. _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
  264. }
  265. let _seed = 1234567;
  266. const DEG2RAD = Math.PI / 180;
  267. const RAD2DEG = 180 / Math.PI; // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  268. function generateUUID() {
  269. const d0 = Math.random() * 0xffffffff | 0;
  270. const d1 = Math.random() * 0xffffffff | 0;
  271. const d2 = Math.random() * 0xffffffff | 0;
  272. const d3 = Math.random() * 0xffffffff | 0;
  273. const uuid = _lut[d0 & 0xff] + _lut[d0 >> 8 & 0xff] + _lut[d0 >> 16 & 0xff] + _lut[d0 >> 24 & 0xff] + '-' + _lut[d1 & 0xff] + _lut[d1 >> 8 & 0xff] + '-' + _lut[d1 >> 16 & 0x0f | 0x40] + _lut[d1 >> 24 & 0xff] + '-' + _lut[d2 & 0x3f | 0x80] + _lut[d2 >> 8 & 0xff] + '-' + _lut[d2 >> 16 & 0xff] + _lut[d2 >> 24 & 0xff] + _lut[d3 & 0xff] + _lut[d3 >> 8 & 0xff] + _lut[d3 >> 16 & 0xff] + _lut[d3 >> 24 & 0xff]; // .toUpperCase() here flattens concatenated strings to save heap memory space.
  274. return uuid.toUpperCase();
  275. }
  276. function clamp(value, min, max) {
  277. return Math.max(min, Math.min(max, value));
  278. } // compute euclidian modulo of m % n
  279. // https://en.wikipedia.org/wiki/Modulo_operation
  280. function euclideanModulo(n, m) {
  281. return (n % m + m) % m;
  282. } // Linear mapping from range <a1, a2> to range <b1, b2>
  283. function mapLinear(x, a1, a2, b1, b2) {
  284. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  285. } // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  286. function inverseLerp(x, y, value) {
  287. if (x !== y) {
  288. return (value - x) / (y - x);
  289. } else {
  290. return 0;
  291. }
  292. } // https://en.wikipedia.org/wiki/Linear_interpolation
  293. function lerp(x, y, t) {
  294. return (1 - t) * x + t * y;
  295. } // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  296. function damp(x, y, lambda, dt) {
  297. return lerp(x, y, 1 - Math.exp(-lambda * dt));
  298. } // https://www.desmos.com/calculator/vcsjnyz7x4
  299. function pingpong(x, length = 1) {
  300. return length - Math.abs(euclideanModulo(x, length * 2) - length);
  301. } // http://en.wikipedia.org/wiki/Smoothstep
  302. function smoothstep(x, min, max) {
  303. if (x <= min) return 0;
  304. if (x >= max) return 1;
  305. x = (x - min) / (max - min);
  306. return x * x * (3 - 2 * x);
  307. }
  308. function smootherstep(x, min, max) {
  309. if (x <= min) return 0;
  310. if (x >= max) return 1;
  311. x = (x - min) / (max - min);
  312. return x * x * x * (x * (x * 6 - 15) + 10);
  313. } // Random integer from <low, high> interval
  314. function randInt(low, high) {
  315. return low + Math.floor(Math.random() * (high - low + 1));
  316. } // Random float from <low, high> interval
  317. function randFloat(low, high) {
  318. return low + Math.random() * (high - low);
  319. } // Random float from <-range/2, range/2> interval
  320. function randFloatSpread(range) {
  321. return range * (0.5 - Math.random());
  322. } // Deterministic pseudo-random float in the interval [ 0, 1 ]
  323. function seededRandom(s) {
  324. if (s !== undefined) _seed = s % 2147483647; // Park-Miller algorithm
  325. _seed = _seed * 16807 % 2147483647;
  326. return (_seed - 1) / 2147483646;
  327. }
  328. function degToRad(degrees) {
  329. return degrees * DEG2RAD;
  330. }
  331. function radToDeg(radians) {
  332. return radians * RAD2DEG;
  333. }
  334. function isPowerOfTwo(value) {
  335. return (value & value - 1) === 0 && value !== 0;
  336. }
  337. function ceilPowerOfTwo(value) {
  338. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  339. }
  340. function floorPowerOfTwo(value) {
  341. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  342. }
  343. function setQuaternionFromProperEuler(q, a, b, c, order) {
  344. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  345. // rotations are applied to the axes in the order specified by 'order'
  346. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  347. // angles are in radians
  348. const cos = Math.cos;
  349. const sin = Math.sin;
  350. const c2 = cos(b / 2);
  351. const s2 = sin(b / 2);
  352. const c13 = cos((a + c) / 2);
  353. const s13 = sin((a + c) / 2);
  354. const c1_3 = cos((a - c) / 2);
  355. const s1_3 = sin((a - c) / 2);
  356. const c3_1 = cos((c - a) / 2);
  357. const s3_1 = sin((c - a) / 2);
  358. switch (order) {
  359. case 'XYX':
  360. q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
  361. break;
  362. case 'YZY':
  363. q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
  364. break;
  365. case 'ZXZ':
  366. q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
  367. break;
  368. case 'XZX':
  369. q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
  370. break;
  371. case 'YXY':
  372. q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
  373. break;
  374. case 'ZYZ':
  375. q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
  376. break;
  377. default:
  378. console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order);
  379. }
  380. }
  381. var MathUtils = /*#__PURE__*/Object.freeze({
  382. __proto__: null,
  383. DEG2RAD: DEG2RAD,
  384. RAD2DEG: RAD2DEG,
  385. generateUUID: generateUUID,
  386. clamp: clamp,
  387. euclideanModulo: euclideanModulo,
  388. mapLinear: mapLinear,
  389. inverseLerp: inverseLerp,
  390. lerp: lerp,
  391. damp: damp,
  392. pingpong: pingpong,
  393. smoothstep: smoothstep,
  394. smootherstep: smootherstep,
  395. randInt: randInt,
  396. randFloat: randFloat,
  397. randFloatSpread: randFloatSpread,
  398. seededRandom: seededRandom,
  399. degToRad: degToRad,
  400. radToDeg: radToDeg,
  401. isPowerOfTwo: isPowerOfTwo,
  402. ceilPowerOfTwo: ceilPowerOfTwo,
  403. floorPowerOfTwo: floorPowerOfTwo,
  404. setQuaternionFromProperEuler: setQuaternionFromProperEuler
  405. });
  406. class Vector2 {
  407. constructor(x = 0, y = 0) {
  408. this.x = x;
  409. this.y = y;
  410. }
  411. get width() {
  412. return this.x;
  413. }
  414. set width(value) {
  415. this.x = value;
  416. }
  417. get height() {
  418. return this.y;
  419. }
  420. set height(value) {
  421. this.y = value;
  422. }
  423. set(x, y) {
  424. this.x = x;
  425. this.y = y;
  426. return this;
  427. }
  428. setScalar(scalar) {
  429. this.x = scalar;
  430. this.y = scalar;
  431. return this;
  432. }
  433. setX(x) {
  434. this.x = x;
  435. return this;
  436. }
  437. setY(y) {
  438. this.y = y;
  439. return this;
  440. }
  441. setComponent(index, value) {
  442. switch (index) {
  443. case 0:
  444. this.x = value;
  445. break;
  446. case 1:
  447. this.y = value;
  448. break;
  449. default:
  450. throw new Error('index is out of range: ' + index);
  451. }
  452. return this;
  453. }
  454. getComponent(index) {
  455. switch (index) {
  456. case 0:
  457. return this.x;
  458. case 1:
  459. return this.y;
  460. default:
  461. throw new Error('index is out of range: ' + index);
  462. }
  463. }
  464. clone() {
  465. return new this.constructor(this.x, this.y);
  466. }
  467. copy(v) {
  468. this.x = v.x;
  469. this.y = v.y;
  470. return this;
  471. }
  472. add(v, w) {
  473. if (w !== undefined) {
  474. console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  475. return this.addVectors(v, w);
  476. }
  477. this.x += v.x;
  478. this.y += v.y;
  479. return this;
  480. }
  481. addScalar(s) {
  482. this.x += s;
  483. this.y += s;
  484. return this;
  485. }
  486. addVectors(a, b) {
  487. this.x = a.x + b.x;
  488. this.y = a.y + b.y;
  489. return this;
  490. }
  491. addScaledVector(v, s) {
  492. this.x += v.x * s;
  493. this.y += v.y * s;
  494. return this;
  495. }
  496. sub(v, w) {
  497. if (w !== undefined) {
  498. console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  499. return this.subVectors(v, w);
  500. }
  501. this.x -= v.x;
  502. this.y -= v.y;
  503. return this;
  504. }
  505. subScalar(s) {
  506. this.x -= s;
  507. this.y -= s;
  508. return this;
  509. }
  510. subVectors(a, b) {
  511. this.x = a.x - b.x;
  512. this.y = a.y - b.y;
  513. return this;
  514. }
  515. multiply(v) {
  516. this.x *= v.x;
  517. this.y *= v.y;
  518. return this;
  519. }
  520. multiplyScalar(scalar) {
  521. this.x *= scalar;
  522. this.y *= scalar;
  523. return this;
  524. }
  525. divide(v) {
  526. this.x /= v.x;
  527. this.y /= v.y;
  528. return this;
  529. }
  530. divideScalar(scalar) {
  531. return this.multiplyScalar(1 / scalar);
  532. }
  533. applyMatrix3(m) {
  534. const x = this.x,
  535. y = this.y;
  536. const e = m.elements;
  537. this.x = e[0] * x + e[3] * y + e[6];
  538. this.y = e[1] * x + e[4] * y + e[7];
  539. return this;
  540. }
  541. min(v) {
  542. this.x = Math.min(this.x, v.x);
  543. this.y = Math.min(this.y, v.y);
  544. return this;
  545. }
  546. max(v) {
  547. this.x = Math.max(this.x, v.x);
  548. this.y = Math.max(this.y, v.y);
  549. return this;
  550. }
  551. clamp(min, max) {
  552. // assumes min < max, componentwise
  553. this.x = Math.max(min.x, Math.min(max.x, this.x));
  554. this.y = Math.max(min.y, Math.min(max.y, this.y));
  555. return this;
  556. }
  557. clampScalar(minVal, maxVal) {
  558. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  559. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  560. return this;
  561. }
  562. clampLength(min, max) {
  563. const length = this.length();
  564. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  565. }
  566. floor() {
  567. this.x = Math.floor(this.x);
  568. this.y = Math.floor(this.y);
  569. return this;
  570. }
  571. ceil() {
  572. this.x = Math.ceil(this.x);
  573. this.y = Math.ceil(this.y);
  574. return this;
  575. }
  576. round() {
  577. this.x = Math.round(this.x);
  578. this.y = Math.round(this.y);
  579. return this;
  580. }
  581. roundToZero() {
  582. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  583. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  584. return this;
  585. }
  586. negate() {
  587. this.x = -this.x;
  588. this.y = -this.y;
  589. return this;
  590. }
  591. dot(v) {
  592. return this.x * v.x + this.y * v.y;
  593. }
  594. cross(v) {
  595. return this.x * v.y - this.y * v.x;
  596. }
  597. lengthSq() {
  598. return this.x * this.x + this.y * this.y;
  599. }
  600. length() {
  601. return Math.sqrt(this.x * this.x + this.y * this.y);
  602. }
  603. manhattanLength() {
  604. return Math.abs(this.x) + Math.abs(this.y);
  605. }
  606. normalize() {
  607. return this.divideScalar(this.length() || 1);
  608. }
  609. angle() {
  610. // computes the angle in radians with respect to the positive x-axis
  611. const angle = Math.atan2(-this.y, -this.x) + Math.PI;
  612. return angle;
  613. }
  614. distanceTo(v) {
  615. return Math.sqrt(this.distanceToSquared(v));
  616. }
  617. distanceToSquared(v) {
  618. const dx = this.x - v.x,
  619. dy = this.y - v.y;
  620. return dx * dx + dy * dy;
  621. }
  622. manhattanDistanceTo(v) {
  623. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  624. }
  625. setLength(length) {
  626. return this.normalize().multiplyScalar(length);
  627. }
  628. lerp(v, alpha) {
  629. this.x += (v.x - this.x) * alpha;
  630. this.y += (v.y - this.y) * alpha;
  631. return this;
  632. }
  633. lerpVectors(v1, v2, alpha) {
  634. this.x = v1.x + (v2.x - v1.x) * alpha;
  635. this.y = v1.y + (v2.y - v1.y) * alpha;
  636. return this;
  637. }
  638. equals(v) {
  639. return v.x === this.x && v.y === this.y;
  640. }
  641. fromArray(array, offset = 0) {
  642. this.x = array[offset];
  643. this.y = array[offset + 1];
  644. return this;
  645. }
  646. toArray(array = [], offset = 0) {
  647. array[offset] = this.x;
  648. array[offset + 1] = this.y;
  649. return array;
  650. }
  651. fromBufferAttribute(attribute, index, offset) {
  652. if (offset !== undefined) {
  653. console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
  654. }
  655. this.x = attribute.getX(index);
  656. this.y = attribute.getY(index);
  657. return this;
  658. }
  659. rotateAround(center, angle) {
  660. const c = Math.cos(angle),
  661. s = Math.sin(angle);
  662. const x = this.x - center.x;
  663. const y = this.y - center.y;
  664. this.x = x * c - y * s + center.x;
  665. this.y = x * s + y * c + center.y;
  666. return this;
  667. }
  668. random() {
  669. this.x = Math.random();
  670. this.y = Math.random();
  671. return this;
  672. }
  673. }
  674. Vector2.prototype.isVector2 = true;
  675. class Matrix3 {
  676. constructor() {
  677. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  678. if (arguments.length > 0) {
  679. console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
  680. }
  681. }
  682. set(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  683. const te = this.elements;
  684. te[0] = n11;
  685. te[1] = n21;
  686. te[2] = n31;
  687. te[3] = n12;
  688. te[4] = n22;
  689. te[5] = n32;
  690. te[6] = n13;
  691. te[7] = n23;
  692. te[8] = n33;
  693. return this;
  694. }
  695. identity() {
  696. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  697. return this;
  698. }
  699. copy(m) {
  700. const te = this.elements;
  701. const me = m.elements;
  702. te[0] = me[0];
  703. te[1] = me[1];
  704. te[2] = me[2];
  705. te[3] = me[3];
  706. te[4] = me[4];
  707. te[5] = me[5];
  708. te[6] = me[6];
  709. te[7] = me[7];
  710. te[8] = me[8];
  711. return this;
  712. }
  713. extractBasis(xAxis, yAxis, zAxis) {
  714. xAxis.setFromMatrix3Column(this, 0);
  715. yAxis.setFromMatrix3Column(this, 1);
  716. zAxis.setFromMatrix3Column(this, 2);
  717. return this;
  718. }
  719. setFromMatrix4(m) {
  720. const me = m.elements;
  721. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  722. return this;
  723. }
  724. multiply(m) {
  725. return this.multiplyMatrices(this, m);
  726. }
  727. premultiply(m) {
  728. return this.multiplyMatrices(m, this);
  729. }
  730. multiplyMatrices(a, b) {
  731. const ae = a.elements;
  732. const be = b.elements;
  733. const te = this.elements;
  734. const a11 = ae[0],
  735. a12 = ae[3],
  736. a13 = ae[6];
  737. const a21 = ae[1],
  738. a22 = ae[4],
  739. a23 = ae[7];
  740. const a31 = ae[2],
  741. a32 = ae[5],
  742. a33 = ae[8];
  743. const b11 = be[0],
  744. b12 = be[3],
  745. b13 = be[6];
  746. const b21 = be[1],
  747. b22 = be[4],
  748. b23 = be[7];
  749. const b31 = be[2],
  750. b32 = be[5],
  751. b33 = be[8];
  752. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  753. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  754. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  755. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  756. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  757. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  758. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  759. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  760. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  761. return this;
  762. }
  763. multiplyScalar(s) {
  764. const te = this.elements;
  765. te[0] *= s;
  766. te[3] *= s;
  767. te[6] *= s;
  768. te[1] *= s;
  769. te[4] *= s;
  770. te[7] *= s;
  771. te[2] *= s;
  772. te[5] *= s;
  773. te[8] *= s;
  774. return this;
  775. }
  776. determinant() {
  777. const te = this.elements;
  778. const a = te[0],
  779. b = te[1],
  780. c = te[2],
  781. d = te[3],
  782. e = te[4],
  783. f = te[5],
  784. g = te[6],
  785. h = te[7],
  786. i = te[8];
  787. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  788. }
  789. invert() {
  790. const te = this.elements,
  791. n11 = te[0],
  792. n21 = te[1],
  793. n31 = te[2],
  794. n12 = te[3],
  795. n22 = te[4],
  796. n32 = te[5],
  797. n13 = te[6],
  798. n23 = te[7],
  799. n33 = te[8],
  800. t11 = n33 * n22 - n32 * n23,
  801. t12 = n32 * n13 - n33 * n12,
  802. t13 = n23 * n12 - n22 * n13,
  803. det = n11 * t11 + n21 * t12 + n31 * t13;
  804. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  805. const detInv = 1 / det;
  806. te[0] = t11 * detInv;
  807. te[1] = (n31 * n23 - n33 * n21) * detInv;
  808. te[2] = (n32 * n21 - n31 * n22) * detInv;
  809. te[3] = t12 * detInv;
  810. te[4] = (n33 * n11 - n31 * n13) * detInv;
  811. te[5] = (n31 * n12 - n32 * n11) * detInv;
  812. te[6] = t13 * detInv;
  813. te[7] = (n21 * n13 - n23 * n11) * detInv;
  814. te[8] = (n22 * n11 - n21 * n12) * detInv;
  815. return this;
  816. }
  817. transpose() {
  818. let tmp;
  819. const m = this.elements;
  820. tmp = m[1];
  821. m[1] = m[3];
  822. m[3] = tmp;
  823. tmp = m[2];
  824. m[2] = m[6];
  825. m[6] = tmp;
  826. tmp = m[5];
  827. m[5] = m[7];
  828. m[7] = tmp;
  829. return this;
  830. }
  831. getNormalMatrix(matrix4) {
  832. return this.setFromMatrix4(matrix4).invert().transpose();
  833. }
  834. transposeIntoArray(r) {
  835. const m = this.elements;
  836. r[0] = m[0];
  837. r[1] = m[3];
  838. r[2] = m[6];
  839. r[3] = m[1];
  840. r[4] = m[4];
  841. r[5] = m[7];
  842. r[6] = m[2];
  843. r[7] = m[5];
  844. r[8] = m[8];
  845. return this;
  846. }
  847. setUvTransform(tx, ty, sx, sy, rotation, cx, cy) {
  848. const c = Math.cos(rotation);
  849. const s = Math.sin(rotation);
  850. this.set(sx * c, sx * s, -sx * (c * cx + s * cy) + cx + tx, -sy * s, sy * c, -sy * (-s * cx + c * cy) + cy + ty, 0, 0, 1);
  851. return this;
  852. }
  853. scale(sx, sy) {
  854. const te = this.elements;
  855. te[0] *= sx;
  856. te[3] *= sx;
  857. te[6] *= sx;
  858. te[1] *= sy;
  859. te[4] *= sy;
  860. te[7] *= sy;
  861. return this;
  862. }
  863. rotate(theta) {
  864. const c = Math.cos(theta);
  865. const s = Math.sin(theta);
  866. const te = this.elements;
  867. const a11 = te[0],
  868. a12 = te[3],
  869. a13 = te[6];
  870. const a21 = te[1],
  871. a22 = te[4],
  872. a23 = te[7];
  873. te[0] = c * a11 + s * a21;
  874. te[3] = c * a12 + s * a22;
  875. te[6] = c * a13 + s * a23;
  876. te[1] = -s * a11 + c * a21;
  877. te[4] = -s * a12 + c * a22;
  878. te[7] = -s * a13 + c * a23;
  879. return this;
  880. }
  881. translate(tx, ty) {
  882. const te = this.elements;
  883. te[0] += tx * te[2];
  884. te[3] += tx * te[5];
  885. te[6] += tx * te[8];
  886. te[1] += ty * te[2];
  887. te[4] += ty * te[5];
  888. te[7] += ty * te[8];
  889. return this;
  890. }
  891. equals(matrix) {
  892. const te = this.elements;
  893. const me = matrix.elements;
  894. for (let i = 0; i < 9; i++) {
  895. if (te[i] !== me[i]) return false;
  896. }
  897. return true;
  898. }
  899. fromArray(array, offset = 0) {
  900. for (let i = 0; i < 9; i++) {
  901. this.elements[i] = array[i + offset];
  902. }
  903. return this;
  904. }
  905. toArray(array = [], offset = 0) {
  906. const te = this.elements;
  907. array[offset] = te[0];
  908. array[offset + 1] = te[1];
  909. array[offset + 2] = te[2];
  910. array[offset + 3] = te[3];
  911. array[offset + 4] = te[4];
  912. array[offset + 5] = te[5];
  913. array[offset + 6] = te[6];
  914. array[offset + 7] = te[7];
  915. array[offset + 8] = te[8];
  916. return array;
  917. }
  918. clone() {
  919. return new this.constructor().fromArray(this.elements);
  920. }
  921. }
  922. Matrix3.prototype.isMatrix3 = true;
  923. let _canvas;
  924. class ImageUtils {
  925. static getDataURL(image) {
  926. if (/^data:/i.test(image.src)) {
  927. return image.src;
  928. }
  929. if (typeof HTMLCanvasElement == 'undefined') {
  930. return image.src;
  931. }
  932. let canvas;
  933. if (image instanceof HTMLCanvasElement) {
  934. canvas = image;
  935. } else {
  936. if (_canvas === undefined) _canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  937. _canvas.width = image.width;
  938. _canvas.height = image.height;
  939. const context = _canvas.getContext('2d');
  940. if (image instanceof ImageData) {
  941. context.putImageData(image, 0, 0);
  942. } else {
  943. context.drawImage(image, 0, 0, image.width, image.height);
  944. }
  945. canvas = _canvas;
  946. }
  947. if (canvas.width > 2048 || canvas.height > 2048) {
  948. console.warn('THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image);
  949. return canvas.toDataURL('image/jpeg', 0.6);
  950. } else {
  951. return canvas.toDataURL('image/png');
  952. }
  953. }
  954. }
  955. let textureId = 0;
  956. class Texture extends EventDispatcher {
  957. constructor(image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = 1, encoding = LinearEncoding) {
  958. super();
  959. Object.defineProperty(this, 'id', {
  960. value: textureId++
  961. });
  962. this.uuid = generateUUID();
  963. this.name = '';
  964. this.image = image;
  965. this.mipmaps = [];
  966. this.mapping = mapping;
  967. this.wrapS = wrapS;
  968. this.wrapT = wrapT;
  969. this.magFilter = magFilter;
  970. this.minFilter = minFilter;
  971. this.anisotropy = anisotropy;
  972. this.format = format;
  973. this.internalFormat = null;
  974. this.type = type;
  975. this.offset = new Vector2(0, 0);
  976. this.repeat = new Vector2(1, 1);
  977. this.center = new Vector2(0, 0);
  978. this.rotation = 0;
  979. this.matrixAutoUpdate = true;
  980. this.matrix = new Matrix3();
  981. this.generateMipmaps = true;
  982. this.premultiplyAlpha = false;
  983. this.flipY = true;
  984. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  985. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  986. //
  987. // Also changing the encoding after already used by a Material will not automatically make the Material
  988. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  989. this.encoding = encoding;
  990. this.version = 0;
  991. this.onUpdate = null;
  992. }
  993. updateMatrix() {
  994. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  995. }
  996. clone() {
  997. return new this.constructor().copy(this);
  998. }
  999. copy(source) {
  1000. this.name = source.name;
  1001. this.image = source.image;
  1002. this.mipmaps = source.mipmaps.slice(0);
  1003. this.mapping = source.mapping;
  1004. this.wrapS = source.wrapS;
  1005. this.wrapT = source.wrapT;
  1006. this.magFilter = source.magFilter;
  1007. this.minFilter = source.minFilter;
  1008. this.anisotropy = source.anisotropy;
  1009. this.format = source.format;
  1010. this.internalFormat = source.internalFormat;
  1011. this.type = source.type;
  1012. this.offset.copy(source.offset);
  1013. this.repeat.copy(source.repeat);
  1014. this.center.copy(source.center);
  1015. this.rotation = source.rotation;
  1016. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1017. this.matrix.copy(source.matrix);
  1018. this.generateMipmaps = source.generateMipmaps;
  1019. this.premultiplyAlpha = source.premultiplyAlpha;
  1020. this.flipY = source.flipY;
  1021. this.unpackAlignment = source.unpackAlignment;
  1022. this.encoding = source.encoding;
  1023. return this;
  1024. }
  1025. toJSON(meta) {
  1026. const isRootObject = meta === undefined || typeof meta === 'string';
  1027. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  1028. return meta.textures[this.uuid];
  1029. }
  1030. const output = {
  1031. metadata: {
  1032. version: 4.5,
  1033. type: 'Texture',
  1034. generator: 'Texture.toJSON'
  1035. },
  1036. uuid: this.uuid,
  1037. name: this.name,
  1038. mapping: this.mapping,
  1039. repeat: [this.repeat.x, this.repeat.y],
  1040. offset: [this.offset.x, this.offset.y],
  1041. center: [this.center.x, this.center.y],
  1042. rotation: this.rotation,
  1043. wrap: [this.wrapS, this.wrapT],
  1044. format: this.format,
  1045. type: this.type,
  1046. encoding: this.encoding,
  1047. minFilter: this.minFilter,
  1048. magFilter: this.magFilter,
  1049. anisotropy: this.anisotropy,
  1050. flipY: this.flipY,
  1051. premultiplyAlpha: this.premultiplyAlpha,
  1052. unpackAlignment: this.unpackAlignment
  1053. };
  1054. if (this.image !== undefined) {
  1055. // TODO: Move to THREE.Image
  1056. const image = this.image;
  1057. if (image.uuid === undefined) {
  1058. image.uuid = generateUUID(); // UGH
  1059. }
  1060. if (!isRootObject && meta.images[image.uuid] === undefined) {
  1061. let url;
  1062. if (Array.isArray(image)) {
  1063. // process array of images e.g. CubeTexture
  1064. url = [];
  1065. for (let i = 0, l = image.length; i < l; i++) {
  1066. // check cube texture with data textures
  1067. if (image[i].isDataTexture) {
  1068. url.push(serializeImage(image[i].image));
  1069. } else {
  1070. url.push(serializeImage(image[i]));
  1071. }
  1072. }
  1073. } else {
  1074. // process single image
  1075. url = serializeImage(image);
  1076. }
  1077. meta.images[image.uuid] = {
  1078. uuid: image.uuid,
  1079. url: url
  1080. };
  1081. }
  1082. output.image = image.uuid;
  1083. }
  1084. if (!isRootObject) {
  1085. meta.textures[this.uuid] = output;
  1086. }
  1087. return output;
  1088. }
  1089. dispose() {
  1090. this.dispatchEvent({
  1091. type: 'dispose'
  1092. });
  1093. }
  1094. transformUv(uv) {
  1095. if (this.mapping !== UVMapping) return uv;
  1096. uv.applyMatrix3(this.matrix);
  1097. if (uv.x < 0 || uv.x > 1) {
  1098. switch (this.wrapS) {
  1099. case RepeatWrapping:
  1100. uv.x = uv.x - Math.floor(uv.x);
  1101. break;
  1102. case ClampToEdgeWrapping:
  1103. uv.x = uv.x < 0 ? 0 : 1;
  1104. break;
  1105. case MirroredRepeatWrapping:
  1106. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  1107. uv.x = Math.ceil(uv.x) - uv.x;
  1108. } else {
  1109. uv.x = uv.x - Math.floor(uv.x);
  1110. }
  1111. break;
  1112. }
  1113. }
  1114. if (uv.y < 0 || uv.y > 1) {
  1115. switch (this.wrapT) {
  1116. case RepeatWrapping:
  1117. uv.y = uv.y - Math.floor(uv.y);
  1118. break;
  1119. case ClampToEdgeWrapping:
  1120. uv.y = uv.y < 0 ? 0 : 1;
  1121. break;
  1122. case MirroredRepeatWrapping:
  1123. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  1124. uv.y = Math.ceil(uv.y) - uv.y;
  1125. } else {
  1126. uv.y = uv.y - Math.floor(uv.y);
  1127. }
  1128. break;
  1129. }
  1130. }
  1131. if (this.flipY) {
  1132. uv.y = 1 - uv.y;
  1133. }
  1134. return uv;
  1135. }
  1136. set needsUpdate(value) {
  1137. if (value === true) this.version++;
  1138. }
  1139. }
  1140. Texture.DEFAULT_IMAGE = undefined;
  1141. Texture.DEFAULT_MAPPING = UVMapping;
  1142. Texture.prototype.isTexture = true;
  1143. function serializeImage(image) {
  1144. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  1145. // default images
  1146. return ImageUtils.getDataURL(image);
  1147. } else {
  1148. if (image.data) {
  1149. // images of DataTexture
  1150. return {
  1151. data: Array.prototype.slice.call(image.data),
  1152. width: image.width,
  1153. height: image.height,
  1154. type: image.data.constructor.name
  1155. };
  1156. } else {
  1157. console.warn('THREE.Texture: Unable to serialize Texture.');
  1158. return {};
  1159. }
  1160. }
  1161. }
  1162. class Vector4 {
  1163. constructor(x = 0, y = 0, z = 0, w = 1) {
  1164. this.x = x;
  1165. this.y = y;
  1166. this.z = z;
  1167. this.w = w;
  1168. }
  1169. get width() {
  1170. return this.z;
  1171. }
  1172. set width(value) {
  1173. this.z = value;
  1174. }
  1175. get height() {
  1176. return this.w;
  1177. }
  1178. set height(value) {
  1179. this.w = value;
  1180. }
  1181. set(x, y, z, w) {
  1182. this.x = x;
  1183. this.y = y;
  1184. this.z = z;
  1185. this.w = w;
  1186. return this;
  1187. }
  1188. setScalar(scalar) {
  1189. this.x = scalar;
  1190. this.y = scalar;
  1191. this.z = scalar;
  1192. this.w = scalar;
  1193. return this;
  1194. }
  1195. setX(x) {
  1196. this.x = x;
  1197. return this;
  1198. }
  1199. setY(y) {
  1200. this.y = y;
  1201. return this;
  1202. }
  1203. setZ(z) {
  1204. this.z = z;
  1205. return this;
  1206. }
  1207. setW(w) {
  1208. this.w = w;
  1209. return this;
  1210. }
  1211. setComponent(index, value) {
  1212. switch (index) {
  1213. case 0:
  1214. this.x = value;
  1215. break;
  1216. case 1:
  1217. this.y = value;
  1218. break;
  1219. case 2:
  1220. this.z = value;
  1221. break;
  1222. case 3:
  1223. this.w = value;
  1224. break;
  1225. default:
  1226. throw new Error('index is out of range: ' + index);
  1227. }
  1228. return this;
  1229. }
  1230. getComponent(index) {
  1231. switch (index) {
  1232. case 0:
  1233. return this.x;
  1234. case 1:
  1235. return this.y;
  1236. case 2:
  1237. return this.z;
  1238. case 3:
  1239. return this.w;
  1240. default:
  1241. throw new Error('index is out of range: ' + index);
  1242. }
  1243. }
  1244. clone() {
  1245. return new this.constructor(this.x, this.y, this.z, this.w);
  1246. }
  1247. copy(v) {
  1248. this.x = v.x;
  1249. this.y = v.y;
  1250. this.z = v.z;
  1251. this.w = v.w !== undefined ? v.w : 1;
  1252. return this;
  1253. }
  1254. add(v, w) {
  1255. if (w !== undefined) {
  1256. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  1257. return this.addVectors(v, w);
  1258. }
  1259. this.x += v.x;
  1260. this.y += v.y;
  1261. this.z += v.z;
  1262. this.w += v.w;
  1263. return this;
  1264. }
  1265. addScalar(s) {
  1266. this.x += s;
  1267. this.y += s;
  1268. this.z += s;
  1269. this.w += s;
  1270. return this;
  1271. }
  1272. addVectors(a, b) {
  1273. this.x = a.x + b.x;
  1274. this.y = a.y + b.y;
  1275. this.z = a.z + b.z;
  1276. this.w = a.w + b.w;
  1277. return this;
  1278. }
  1279. addScaledVector(v, s) {
  1280. this.x += v.x * s;
  1281. this.y += v.y * s;
  1282. this.z += v.z * s;
  1283. this.w += v.w * s;
  1284. return this;
  1285. }
  1286. sub(v, w) {
  1287. if (w !== undefined) {
  1288. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  1289. return this.subVectors(v, w);
  1290. }
  1291. this.x -= v.x;
  1292. this.y -= v.y;
  1293. this.z -= v.z;
  1294. this.w -= v.w;
  1295. return this;
  1296. }
  1297. subScalar(s) {
  1298. this.x -= s;
  1299. this.y -= s;
  1300. this.z -= s;
  1301. this.w -= s;
  1302. return this;
  1303. }
  1304. subVectors(a, b) {
  1305. this.x = a.x - b.x;
  1306. this.y = a.y - b.y;
  1307. this.z = a.z - b.z;
  1308. this.w = a.w - b.w;
  1309. return this;
  1310. }
  1311. multiply(v) {
  1312. this.x *= v.x;
  1313. this.y *= v.y;
  1314. this.z *= v.z;
  1315. this.w *= v.w;
  1316. return this;
  1317. }
  1318. multiplyScalar(scalar) {
  1319. this.x *= scalar;
  1320. this.y *= scalar;
  1321. this.z *= scalar;
  1322. this.w *= scalar;
  1323. return this;
  1324. }
  1325. applyMatrix4(m) {
  1326. const x = this.x,
  1327. y = this.y,
  1328. z = this.z,
  1329. w = this.w;
  1330. const e = m.elements;
  1331. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1332. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1333. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1334. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1335. return this;
  1336. }
  1337. divideScalar(scalar) {
  1338. return this.multiplyScalar(1 / scalar);
  1339. }
  1340. setAxisAngleFromQuaternion(q) {
  1341. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1342. // q is assumed to be normalized
  1343. this.w = 2 * Math.acos(q.w);
  1344. const s = Math.sqrt(1 - q.w * q.w);
  1345. if (s < 0.0001) {
  1346. this.x = 1;
  1347. this.y = 0;
  1348. this.z = 0;
  1349. } else {
  1350. this.x = q.x / s;
  1351. this.y = q.y / s;
  1352. this.z = q.z / s;
  1353. }
  1354. return this;
  1355. }
  1356. setAxisAngleFromRotationMatrix(m) {
  1357. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1358. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1359. let angle, x, y, z; // variables for result
  1360. const epsilon = 0.01,
  1361. // margin to allow for rounding errors
  1362. epsilon2 = 0.1,
  1363. // margin to distinguish between 0 and 180 degrees
  1364. te = m.elements,
  1365. m11 = te[0],
  1366. m12 = te[4],
  1367. m13 = te[8],
  1368. m21 = te[1],
  1369. m22 = te[5],
  1370. m23 = te[9],
  1371. m31 = te[2],
  1372. m32 = te[6],
  1373. m33 = te[10];
  1374. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  1375. // singularity found
  1376. // first check for identity matrix which must have +1 for all terms
  1377. // in leading diagonal and zero in other terms
  1378. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  1379. // this singularity is identity matrix so angle = 0
  1380. this.set(1, 0, 0, 0);
  1381. return this; // zero angle, arbitrary axis
  1382. } // otherwise this singularity is angle = 180
  1383. angle = Math.PI;
  1384. const xx = (m11 + 1) / 2;
  1385. const yy = (m22 + 1) / 2;
  1386. const zz = (m33 + 1) / 2;
  1387. const xy = (m12 + m21) / 4;
  1388. const xz = (m13 + m31) / 4;
  1389. const yz = (m23 + m32) / 4;
  1390. if (xx > yy && xx > zz) {
  1391. // m11 is the largest diagonal term
  1392. if (xx < epsilon) {
  1393. x = 0;
  1394. y = 0.707106781;
  1395. z = 0.707106781;
  1396. } else {
  1397. x = Math.sqrt(xx);
  1398. y = xy / x;
  1399. z = xz / x;
  1400. }
  1401. } else if (yy > zz) {
  1402. // m22 is the largest diagonal term
  1403. if (yy < epsilon) {
  1404. x = 0.707106781;
  1405. y = 0;
  1406. z = 0.707106781;
  1407. } else {
  1408. y = Math.sqrt(yy);
  1409. x = xy / y;
  1410. z = yz / y;
  1411. }
  1412. } else {
  1413. // m33 is the largest diagonal term so base result on this
  1414. if (zz < epsilon) {
  1415. x = 0.707106781;
  1416. y = 0.707106781;
  1417. z = 0;
  1418. } else {
  1419. z = Math.sqrt(zz);
  1420. x = xz / z;
  1421. y = yz / z;
  1422. }
  1423. }
  1424. this.set(x, y, z, angle);
  1425. return this; // return 180 deg rotation
  1426. } // as we have reached here there are no singularities so we can handle normally
  1427. let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  1428. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1429. // caught by singularity test above, but I've left it in just in case
  1430. this.x = (m32 - m23) / s;
  1431. this.y = (m13 - m31) / s;
  1432. this.z = (m21 - m12) / s;
  1433. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  1434. return this;
  1435. }
  1436. min(v) {
  1437. this.x = Math.min(this.x, v.x);
  1438. this.y = Math.min(this.y, v.y);
  1439. this.z = Math.min(this.z, v.z);
  1440. this.w = Math.min(this.w, v.w);
  1441. return this;
  1442. }
  1443. max(v) {
  1444. this.x = Math.max(this.x, v.x);
  1445. this.y = Math.max(this.y, v.y);
  1446. this.z = Math.max(this.z, v.z);
  1447. this.w = Math.max(this.w, v.w);
  1448. return this;
  1449. }
  1450. clamp(min, max) {
  1451. // assumes min < max, componentwise
  1452. this.x = Math.max(min.x, Math.min(max.x, this.x));
  1453. this.y = Math.max(min.y, Math.min(max.y, this.y));
  1454. this.z = Math.max(min.z, Math.min(max.z, this.z));
  1455. this.w = Math.max(min.w, Math.min(max.w, this.w));
  1456. return this;
  1457. }
  1458. clampScalar(minVal, maxVal) {
  1459. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  1460. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  1461. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  1462. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  1463. return this;
  1464. }
  1465. clampLength(min, max) {
  1466. const length = this.length();
  1467. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  1468. }
  1469. floor() {
  1470. this.x = Math.floor(this.x);
  1471. this.y = Math.floor(this.y);
  1472. this.z = Math.floor(this.z);
  1473. this.w = Math.floor(this.w);
  1474. return this;
  1475. }
  1476. ceil() {
  1477. this.x = Math.ceil(this.x);
  1478. this.y = Math.ceil(this.y);
  1479. this.z = Math.ceil(this.z);
  1480. this.w = Math.ceil(this.w);
  1481. return this;
  1482. }
  1483. round() {
  1484. this.x = Math.round(this.x);
  1485. this.y = Math.round(this.y);
  1486. this.z = Math.round(this.z);
  1487. this.w = Math.round(this.w);
  1488. return this;
  1489. }
  1490. roundToZero() {
  1491. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  1492. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  1493. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  1494. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  1495. return this;
  1496. }
  1497. negate() {
  1498. this.x = -this.x;
  1499. this.y = -this.y;
  1500. this.z = -this.z;
  1501. this.w = -this.w;
  1502. return this;
  1503. }
  1504. dot(v) {
  1505. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1506. }
  1507. lengthSq() {
  1508. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1509. }
  1510. length() {
  1511. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1512. }
  1513. manhattanLength() {
  1514. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  1515. }
  1516. normalize() {
  1517. return this.divideScalar(this.length() || 1);
  1518. }
  1519. setLength(length) {
  1520. return this.normalize().multiplyScalar(length);
  1521. }
  1522. lerp(v, alpha) {
  1523. this.x += (v.x - this.x) * alpha;
  1524. this.y += (v.y - this.y) * alpha;
  1525. this.z += (v.z - this.z) * alpha;
  1526. this.w += (v.w - this.w) * alpha;
  1527. return this;
  1528. }
  1529. lerpVectors(v1, v2, alpha) {
  1530. this.x = v1.x + (v2.x - v1.x) * alpha;
  1531. this.y = v1.y + (v2.y - v1.y) * alpha;
  1532. this.z = v1.z + (v2.z - v1.z) * alpha;
  1533. this.w = v1.w + (v2.w - v1.w) * alpha;
  1534. return this;
  1535. }
  1536. equals(v) {
  1537. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  1538. }
  1539. fromArray(array, offset = 0) {
  1540. this.x = array[offset];
  1541. this.y = array[offset + 1];
  1542. this.z = array[offset + 2];
  1543. this.w = array[offset + 3];
  1544. return this;
  1545. }
  1546. toArray(array = [], offset = 0) {
  1547. array[offset] = this.x;
  1548. array[offset + 1] = this.y;
  1549. array[offset + 2] = this.z;
  1550. array[offset + 3] = this.w;
  1551. return array;
  1552. }
  1553. fromBufferAttribute(attribute, index, offset) {
  1554. if (offset !== undefined) {
  1555. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  1556. }
  1557. this.x = attribute.getX(index);
  1558. this.y = attribute.getY(index);
  1559. this.z = attribute.getZ(index);
  1560. this.w = attribute.getW(index);
  1561. return this;
  1562. }
  1563. random() {
  1564. this.x = Math.random();
  1565. this.y = Math.random();
  1566. this.z = Math.random();
  1567. this.w = Math.random();
  1568. return this;
  1569. }
  1570. }
  1571. Vector4.prototype.isVector4 = true;
  1572. /*
  1573. In options, we can specify:
  1574. * Texture parameters for an auto-generated target texture
  1575. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1576. */
  1577. class WebGLRenderTarget extends EventDispatcher {
  1578. constructor(width, height, options) {
  1579. super();
  1580. this.width = width;
  1581. this.height = height;
  1582. this.depth = 1;
  1583. this.scissor = new Vector4(0, 0, width, height);
  1584. this.scissorTest = false;
  1585. this.viewport = new Vector4(0, 0, width, height);
  1586. options = options || {};
  1587. this.texture = new Texture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  1588. this.texture.image = {};
  1589. this.texture.image.width = width;
  1590. this.texture.image.height = height;
  1591. this.texture.image.depth = 1;
  1592. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  1593. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  1594. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1595. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  1596. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1597. }
  1598. setTexture(texture) {
  1599. texture.image = {
  1600. width: this.width,
  1601. height: this.height,
  1602. depth: this.depth
  1603. };
  1604. this.texture = texture;
  1605. }
  1606. setSize(width, height, depth = 1) {
  1607. if (this.width !== width || this.height !== height || this.depth !== depth) {
  1608. this.width = width;
  1609. this.height = height;
  1610. this.depth = depth;
  1611. this.texture.image.width = width;
  1612. this.texture.image.height = height;
  1613. this.texture.image.depth = depth;
  1614. this.dispose();
  1615. }
  1616. this.viewport.set(0, 0, width, height);
  1617. this.scissor.set(0, 0, width, height);
  1618. }
  1619. clone() {
  1620. return new this.constructor().copy(this);
  1621. }
  1622. copy(source) {
  1623. this.width = source.width;
  1624. this.height = source.height;
  1625. this.depth = source.depth;
  1626. this.viewport.copy(source.viewport);
  1627. this.texture = source.texture.clone();
  1628. this.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. if (target === undefined) {
  2645. console.warn('THREE.Box3: .getCenter() target is now required');
  2646. target = new Vector3();
  2647. }
  2648. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  2649. }
  2650. getSize(target) {
  2651. if (target === undefined) {
  2652. console.warn('THREE.Box3: .getSize() target is now required');
  2653. target = new Vector3();
  2654. }
  2655. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  2656. }
  2657. expandByPoint(point) {
  2658. this.min.min(point);
  2659. this.max.max(point);
  2660. return this;
  2661. }
  2662. expandByVector(vector) {
  2663. this.min.sub(vector);
  2664. this.max.add(vector);
  2665. return this;
  2666. }
  2667. expandByScalar(scalar) {
  2668. this.min.addScalar(-scalar);
  2669. this.max.addScalar(scalar);
  2670. return this;
  2671. }
  2672. expandByObject(object) {
  2673. // Computes the world-axis-aligned bounding box of an object (including its children),
  2674. // accounting for both the object's, and children's, world transforms
  2675. object.updateWorldMatrix(false, false);
  2676. const geometry = object.geometry;
  2677. if (geometry !== undefined) {
  2678. if (geometry.boundingBox === null) {
  2679. geometry.computeBoundingBox();
  2680. }
  2681. _box$3.copy(geometry.boundingBox);
  2682. _box$3.applyMatrix4(object.matrixWorld);
  2683. this.union(_box$3);
  2684. }
  2685. const children = object.children;
  2686. for (let i = 0, l = children.length; i < l; i++) {
  2687. this.expandByObject(children[i]);
  2688. }
  2689. return this;
  2690. }
  2691. containsPoint(point) {
  2692. 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;
  2693. }
  2694. containsBox(box) {
  2695. 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;
  2696. }
  2697. getParameter(point, target) {
  2698. // This can potentially have a divide by zero if the box
  2699. // has a size dimension of 0.
  2700. if (target === undefined) {
  2701. console.warn('THREE.Box3: .getParameter() target is now required');
  2702. target = new Vector3();
  2703. }
  2704. 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));
  2705. }
  2706. intersectsBox(box) {
  2707. // using 6 splitting planes to rule out intersections.
  2708. 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;
  2709. }
  2710. intersectsSphere(sphere) {
  2711. // Find the point on the AABB closest to the sphere center.
  2712. this.clampPoint(sphere.center, _vector$b); // If that point is inside the sphere, the AABB and sphere intersect.
  2713. return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  2714. }
  2715. intersectsPlane(plane) {
  2716. // We compute the minimum and maximum dot product values. If those values
  2717. // are on the same side (back or front) of the plane, then there is no intersection.
  2718. let min, max;
  2719. if (plane.normal.x > 0) {
  2720. min = plane.normal.x * this.min.x;
  2721. max = plane.normal.x * this.max.x;
  2722. } else {
  2723. min = plane.normal.x * this.max.x;
  2724. max = plane.normal.x * this.min.x;
  2725. }
  2726. if (plane.normal.y > 0) {
  2727. min += plane.normal.y * this.min.y;
  2728. max += plane.normal.y * this.max.y;
  2729. } else {
  2730. min += plane.normal.y * this.max.y;
  2731. max += plane.normal.y * this.min.y;
  2732. }
  2733. if (plane.normal.z > 0) {
  2734. min += plane.normal.z * this.min.z;
  2735. max += plane.normal.z * this.max.z;
  2736. } else {
  2737. min += plane.normal.z * this.max.z;
  2738. max += plane.normal.z * this.min.z;
  2739. }
  2740. return min <= -plane.constant && max >= -plane.constant;
  2741. }
  2742. intersectsTriangle(triangle) {
  2743. if (this.isEmpty()) {
  2744. return false;
  2745. } // compute box center and extents
  2746. this.getCenter(_center);
  2747. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  2748. _v0$2.subVectors(triangle.a, _center);
  2749. _v1$7.subVectors(triangle.b, _center);
  2750. _v2$3.subVectors(triangle.c, _center); // compute edge vectors for triangle
  2751. _f0.subVectors(_v1$7, _v0$2);
  2752. _f1.subVectors(_v2$3, _v1$7);
  2753. _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
  2754. // 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
  2755. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2756. 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];
  2757. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  2758. return false;
  2759. } // test 3 face normals from the aabb
  2760. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  2761. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  2762. return false;
  2763. } // finally testing the face normal of the triangle
  2764. // use already existing triangle edge vectors here
  2765. _triangleNormal.crossVectors(_f0, _f1);
  2766. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  2767. return satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents);
  2768. }
  2769. clampPoint(point, target) {
  2770. if (target === undefined) {
  2771. console.warn('THREE.Box3: .clampPoint() target is now required');
  2772. target = new Vector3();
  2773. }
  2774. return target.copy(point).clamp(this.min, this.max);
  2775. }
  2776. distanceToPoint(point) {
  2777. const clampedPoint = _vector$b.copy(point).clamp(this.min, this.max);
  2778. return clampedPoint.sub(point).length();
  2779. }
  2780. getBoundingSphere(target) {
  2781. if (target === undefined) {
  2782. console.error('THREE.Box3: .getBoundingSphere() target is now required'); //target = new Sphere(); // removed to avoid cyclic dependency
  2783. }
  2784. this.getCenter(target.center);
  2785. target.radius = this.getSize(_vector$b).length() * 0.5;
  2786. return target;
  2787. }
  2788. intersect(box) {
  2789. this.min.max(box.min);
  2790. 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.
  2791. if (this.isEmpty()) this.makeEmpty();
  2792. return this;
  2793. }
  2794. union(box) {
  2795. this.min.min(box.min);
  2796. this.max.max(box.max);
  2797. return this;
  2798. }
  2799. applyMatrix4(matrix) {
  2800. // transform of empty box is an empty box.
  2801. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2802. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  2803. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  2804. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  2805. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  2806. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  2807. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  2808. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  2809. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  2810. this.setFromPoints(_points);
  2811. return this;
  2812. }
  2813. translate(offset) {
  2814. this.min.add(offset);
  2815. this.max.add(offset);
  2816. return this;
  2817. }
  2818. equals(box) {
  2819. return box.min.equals(this.min) && box.max.equals(this.max);
  2820. }
  2821. }
  2822. Box3.prototype.isBox3 = true;
  2823. 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()];
  2824. const _vector$b = /*@__PURE__*/new Vector3();
  2825. const _box$3 = /*@__PURE__*/new Box3(); // triangle centered vertices
  2826. const _v0$2 = /*@__PURE__*/new Vector3();
  2827. const _v1$7 = /*@__PURE__*/new Vector3();
  2828. const _v2$3 = /*@__PURE__*/new Vector3(); // triangle edge vectors
  2829. const _f0 = /*@__PURE__*/new Vector3();
  2830. const _f1 = /*@__PURE__*/new Vector3();
  2831. const _f2 = /*@__PURE__*/new Vector3();
  2832. const _center = /*@__PURE__*/new Vector3();
  2833. const _extents = /*@__PURE__*/new Vector3();
  2834. const _triangleNormal = /*@__PURE__*/new Vector3();
  2835. const _testAxis = /*@__PURE__*/new Vector3();
  2836. function satForAxes(axes, v0, v1, v2, extents) {
  2837. for (let i = 0, j = axes.length - 3; i <= j; i += 3) {
  2838. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  2839. 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
  2840. const p0 = v0.dot(_testAxis);
  2841. const p1 = v1.dot(_testAxis);
  2842. const p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  2843. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  2844. // points of the projected triangle are outside the projected half-length of the aabb
  2845. // the axis is seperating and we can exit
  2846. return false;
  2847. }
  2848. }
  2849. return true;
  2850. }
  2851. const _box$2 = /*@__PURE__*/new Box3();
  2852. const _v1$6 = /*@__PURE__*/new Vector3();
  2853. const _toFarthestPoint = /*@__PURE__*/new Vector3();
  2854. const _toPoint = /*@__PURE__*/new Vector3();
  2855. class Sphere {
  2856. constructor(center = new Vector3(), radius = -1) {
  2857. this.center = center;
  2858. this.radius = radius;
  2859. }
  2860. set(center, radius) {
  2861. this.center.copy(center);
  2862. this.radius = radius;
  2863. return this;
  2864. }
  2865. setFromPoints(points, optionalCenter) {
  2866. const center = this.center;
  2867. if (optionalCenter !== undefined) {
  2868. center.copy(optionalCenter);
  2869. } else {
  2870. _box$2.setFromPoints(points).getCenter(center);
  2871. }
  2872. let maxRadiusSq = 0;
  2873. for (let i = 0, il = points.length; i < il; i++) {
  2874. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  2875. }
  2876. this.radius = Math.sqrt(maxRadiusSq);
  2877. return this;
  2878. }
  2879. copy(sphere) {
  2880. this.center.copy(sphere.center);
  2881. this.radius = sphere.radius;
  2882. return this;
  2883. }
  2884. isEmpty() {
  2885. return this.radius < 0;
  2886. }
  2887. makeEmpty() {
  2888. this.center.set(0, 0, 0);
  2889. this.radius = -1;
  2890. return this;
  2891. }
  2892. containsPoint(point) {
  2893. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  2894. }
  2895. distanceToPoint(point) {
  2896. return point.distanceTo(this.center) - this.radius;
  2897. }
  2898. intersectsSphere(sphere) {
  2899. const radiusSum = this.radius + sphere.radius;
  2900. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  2901. }
  2902. intersectsBox(box) {
  2903. return box.intersectsSphere(this);
  2904. }
  2905. intersectsPlane(plane) {
  2906. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  2907. }
  2908. clampPoint(point, target) {
  2909. const deltaLengthSq = this.center.distanceToSquared(point);
  2910. if (target === undefined) {
  2911. console.warn('THREE.Sphere: .clampPoint() target is now required');
  2912. target = new Vector3();
  2913. }
  2914. target.copy(point);
  2915. if (deltaLengthSq > this.radius * this.radius) {
  2916. target.sub(this.center).normalize();
  2917. target.multiplyScalar(this.radius).add(this.center);
  2918. }
  2919. return target;
  2920. }
  2921. getBoundingBox(target) {
  2922. if (target === undefined) {
  2923. console.warn('THREE.Sphere: .getBoundingBox() target is now required');
  2924. target = new Box3();
  2925. }
  2926. if (this.isEmpty()) {
  2927. // Empty sphere produces empty bounding box
  2928. target.makeEmpty();
  2929. return target;
  2930. }
  2931. target.set(this.center, this.center);
  2932. target.expandByScalar(this.radius);
  2933. return target;
  2934. }
  2935. applyMatrix4(matrix) {
  2936. this.center.applyMatrix4(matrix);
  2937. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2938. return this;
  2939. }
  2940. translate(offset) {
  2941. this.center.add(offset);
  2942. return this;
  2943. }
  2944. expandByPoint(point) {
  2945. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  2946. _toPoint.subVectors(point, this.center);
  2947. const lengthSq = _toPoint.lengthSq();
  2948. if (lengthSq > this.radius * this.radius) {
  2949. const length = Math.sqrt(lengthSq);
  2950. const missingRadiusHalf = (length - this.radius) * 0.5; // Nudge this sphere towards the target point. Add half the missing distance to radius,
  2951. // and the other half to position. This gives a tighter enclosure, instead of if
  2952. // the whole missing distance were just added to radius.
  2953. this.center.add(_toPoint.multiplyScalar(missingRadiusHalf / length));
  2954. this.radius += missingRadiusHalf;
  2955. }
  2956. return this;
  2957. }
  2958. union(sphere) {
  2959. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  2960. // To enclose another sphere into this sphere, we only need to enclose two points:
  2961. // 1) Enclose the farthest point on the other sphere into this sphere.
  2962. // 2) Enclose the opposite point of the farthest point into this sphere.
  2963. _toFarthestPoint.subVectors(sphere.center, this.center).normalize().multiplyScalar(sphere.radius);
  2964. this.expandByPoint(_v1$6.copy(sphere.center).add(_toFarthestPoint));
  2965. this.expandByPoint(_v1$6.copy(sphere.center).sub(_toFarthestPoint));
  2966. return this;
  2967. }
  2968. equals(sphere) {
  2969. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  2970. }
  2971. clone() {
  2972. return new this.constructor().copy(this);
  2973. }
  2974. }
  2975. const _vector$a = /*@__PURE__*/new Vector3();
  2976. const _segCenter = /*@__PURE__*/new Vector3();
  2977. const _segDir = /*@__PURE__*/new Vector3();
  2978. const _diff = /*@__PURE__*/new Vector3();
  2979. const _edge1 = /*@__PURE__*/new Vector3();
  2980. const _edge2 = /*@__PURE__*/new Vector3();
  2981. const _normal$1 = /*@__PURE__*/new Vector3();
  2982. class Ray {
  2983. constructor(origin = new Vector3(), direction = new Vector3(0, 0, -1)) {
  2984. this.origin = origin;
  2985. this.direction = direction;
  2986. }
  2987. set(origin, direction) {
  2988. this.origin.copy(origin);
  2989. this.direction.copy(direction);
  2990. return this;
  2991. }
  2992. copy(ray) {
  2993. this.origin.copy(ray.origin);
  2994. this.direction.copy(ray.direction);
  2995. return this;
  2996. }
  2997. at(t, target) {
  2998. if (target === undefined) {
  2999. console.warn('THREE.Ray: .at() target is now required');
  3000. target = new Vector3();
  3001. }
  3002. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  3003. }
  3004. lookAt(v) {
  3005. this.direction.copy(v).sub(this.origin).normalize();
  3006. return this;
  3007. }
  3008. recast(t) {
  3009. this.origin.copy(this.at(t, _vector$a));
  3010. return this;
  3011. }
  3012. closestPointToPoint(point, target) {
  3013. if (target === undefined) {
  3014. console.warn('THREE.Ray: .closestPointToPoint() target is now required');
  3015. target = new Vector3();
  3016. }
  3017. target.subVectors(point, this.origin);
  3018. const directionDistance = target.dot(this.direction);
  3019. if (directionDistance < 0) {
  3020. return target.copy(this.origin);
  3021. }
  3022. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3023. }
  3024. distanceToPoint(point) {
  3025. return Math.sqrt(this.distanceSqToPoint(point));
  3026. }
  3027. distanceSqToPoint(point) {
  3028. const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  3029. if (directionDistance < 0) {
  3030. return this.origin.distanceToSquared(point);
  3031. }
  3032. _vector$a.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3033. return _vector$a.distanceToSquared(point);
  3034. }
  3035. distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  3036. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3037. // It returns the min distance between the ray and the segment
  3038. // defined by v0 and v1
  3039. // It can also set two optional targets :
  3040. // - The closest point on the ray
  3041. // - The closest point on the segment
  3042. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  3043. _segDir.copy(v1).sub(v0).normalize();
  3044. _diff.copy(this.origin).sub(_segCenter);
  3045. const segExtent = v0.distanceTo(v1) * 0.5;
  3046. const a01 = -this.direction.dot(_segDir);
  3047. const b0 = _diff.dot(this.direction);
  3048. const b1 = -_diff.dot(_segDir);
  3049. const c = _diff.lengthSq();
  3050. const det = Math.abs(1 - a01 * a01);
  3051. let s0, s1, sqrDist, extDet;
  3052. if (det > 0) {
  3053. // The ray and segment are not parallel.
  3054. s0 = a01 * b1 - b0;
  3055. s1 = a01 * b0 - b1;
  3056. extDet = segExtent * det;
  3057. if (s0 >= 0) {
  3058. if (s1 >= -extDet) {
  3059. if (s1 <= extDet) {
  3060. // region 0
  3061. // Minimum at interior points of ray and segment.
  3062. const invDet = 1 / det;
  3063. s0 *= invDet;
  3064. s1 *= invDet;
  3065. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  3066. } else {
  3067. // region 1
  3068. s1 = segExtent;
  3069. s0 = Math.max(0, -(a01 * s1 + b0));
  3070. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3071. }
  3072. } else {
  3073. // region 5
  3074. s1 = -segExtent;
  3075. s0 = Math.max(0, -(a01 * s1 + b0));
  3076. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3077. }
  3078. } else {
  3079. if (s1 <= -extDet) {
  3080. // region 4
  3081. s0 = Math.max(0, -(-a01 * segExtent + b0));
  3082. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3083. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3084. } else if (s1 <= extDet) {
  3085. // region 3
  3086. s0 = 0;
  3087. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  3088. sqrDist = s1 * (s1 + 2 * b1) + c;
  3089. } else {
  3090. // region 2
  3091. s0 = Math.max(0, -(a01 * segExtent + b0));
  3092. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3093. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3094. }
  3095. }
  3096. } else {
  3097. // Ray and segment are parallel.
  3098. s1 = a01 > 0 ? -segExtent : segExtent;
  3099. s0 = Math.max(0, -(a01 * s1 + b0));
  3100. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3101. }
  3102. if (optionalPointOnRay) {
  3103. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  3104. }
  3105. if (optionalPointOnSegment) {
  3106. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  3107. }
  3108. return sqrDist;
  3109. }
  3110. intersectSphere(sphere, target) {
  3111. _vector$a.subVectors(sphere.center, this.origin);
  3112. const tca = _vector$a.dot(this.direction);
  3113. const d2 = _vector$a.dot(_vector$a) - tca * tca;
  3114. const radius2 = sphere.radius * sphere.radius;
  3115. if (d2 > radius2) return null;
  3116. const thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  3117. const t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  3118. const t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  3119. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  3120. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3121. // in order to always return an intersect point that is in front of the ray.
  3122. 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
  3123. return this.at(t0, target);
  3124. }
  3125. intersectsSphere(sphere) {
  3126. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  3127. }
  3128. distanceToPlane(plane) {
  3129. const denominator = plane.normal.dot(this.direction);
  3130. if (denominator === 0) {
  3131. // line is coplanar, return origin
  3132. if (plane.distanceToPoint(this.origin) === 0) {
  3133. return 0;
  3134. } // Null is preferable to undefined since undefined means.... it is undefined
  3135. return null;
  3136. }
  3137. const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  3138. return t >= 0 ? t : null;
  3139. }
  3140. intersectPlane(plane, target) {
  3141. const t = this.distanceToPlane(plane);
  3142. if (t === null) {
  3143. return null;
  3144. }
  3145. return this.at(t, target);
  3146. }
  3147. intersectsPlane(plane) {
  3148. // check if the ray lies on the plane first
  3149. const distToPoint = plane.distanceToPoint(this.origin);
  3150. if (distToPoint === 0) {
  3151. return true;
  3152. }
  3153. const denominator = plane.normal.dot(this.direction);
  3154. if (denominator * distToPoint < 0) {
  3155. return true;
  3156. } // ray origin is behind the plane (and is pointing behind it)
  3157. return false;
  3158. }
  3159. intersectBox(box, target) {
  3160. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3161. const invdirx = 1 / this.direction.x,
  3162. invdiry = 1 / this.direction.y,
  3163. invdirz = 1 / this.direction.z;
  3164. const origin = this.origin;
  3165. if (invdirx >= 0) {
  3166. tmin = (box.min.x - origin.x) * invdirx;
  3167. tmax = (box.max.x - origin.x) * invdirx;
  3168. } else {
  3169. tmin = (box.max.x - origin.x) * invdirx;
  3170. tmax = (box.min.x - origin.x) * invdirx;
  3171. }
  3172. if (invdiry >= 0) {
  3173. tymin = (box.min.y - origin.y) * invdiry;
  3174. tymax = (box.max.y - origin.y) * invdiry;
  3175. } else {
  3176. tymin = (box.max.y - origin.y) * invdiry;
  3177. tymax = (box.min.y - origin.y) * invdiry;
  3178. }
  3179. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  3180. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3181. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  3182. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  3183. if (invdirz >= 0) {
  3184. tzmin = (box.min.z - origin.z) * invdirz;
  3185. tzmax = (box.max.z - origin.z) * invdirz;
  3186. } else {
  3187. tzmin = (box.max.z - origin.z) * invdirz;
  3188. tzmax = (box.min.z - origin.z) * invdirz;
  3189. }
  3190. if (tmin > tzmax || tzmin > tmax) return null;
  3191. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  3192. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  3193. if (tmax < 0) return null;
  3194. return this.at(tmin >= 0 ? tmin : tmax, target);
  3195. }
  3196. intersectsBox(box) {
  3197. return this.intersectBox(box, _vector$a) !== null;
  3198. }
  3199. intersectTriangle(a, b, c, backfaceCulling, target) {
  3200. // Compute the offset origin, edges, and normal.
  3201. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3202. _edge1.subVectors(b, a);
  3203. _edge2.subVectors(c, a);
  3204. _normal$1.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3205. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3206. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3207. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3208. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3209. let DdN = this.direction.dot(_normal$1);
  3210. let sign;
  3211. if (DdN > 0) {
  3212. if (backfaceCulling) return null;
  3213. sign = 1;
  3214. } else if (DdN < 0) {
  3215. sign = -1;
  3216. DdN = -DdN;
  3217. } else {
  3218. return null;
  3219. }
  3220. _diff.subVectors(this.origin, a);
  3221. const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  3222. if (DdQxE2 < 0) {
  3223. return null;
  3224. }
  3225. const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  3226. if (DdE1xQ < 0) {
  3227. return null;
  3228. } // b1+b2 > 1, no intersection
  3229. if (DdQxE2 + DdE1xQ > DdN) {
  3230. return null;
  3231. } // Line intersects triangle, check if ray does.
  3232. const QdN = -sign * _diff.dot(_normal$1); // t < 0, no intersection
  3233. if (QdN < 0) {
  3234. return null;
  3235. } // Ray intersects triangle.
  3236. return this.at(QdN / DdN, target);
  3237. }
  3238. applyMatrix4(matrix4) {
  3239. this.origin.applyMatrix4(matrix4);
  3240. this.direction.transformDirection(matrix4);
  3241. return this;
  3242. }
  3243. equals(ray) {
  3244. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  3245. }
  3246. clone() {
  3247. return new this.constructor().copy(this);
  3248. }
  3249. }
  3250. class Matrix4 {
  3251. constructor() {
  3252. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  3253. if (arguments.length > 0) {
  3254. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  3255. }
  3256. }
  3257. set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  3258. const te = this.elements;
  3259. te[0] = n11;
  3260. te[4] = n12;
  3261. te[8] = n13;
  3262. te[12] = n14;
  3263. te[1] = n21;
  3264. te[5] = n22;
  3265. te[9] = n23;
  3266. te[13] = n24;
  3267. te[2] = n31;
  3268. te[6] = n32;
  3269. te[10] = n33;
  3270. te[14] = n34;
  3271. te[3] = n41;
  3272. te[7] = n42;
  3273. te[11] = n43;
  3274. te[15] = n44;
  3275. return this;
  3276. }
  3277. identity() {
  3278. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3279. return this;
  3280. }
  3281. clone() {
  3282. return new Matrix4().fromArray(this.elements);
  3283. }
  3284. copy(m) {
  3285. const te = this.elements;
  3286. const me = m.elements;
  3287. te[0] = me[0];
  3288. te[1] = me[1];
  3289. te[2] = me[2];
  3290. te[3] = me[3];
  3291. te[4] = me[4];
  3292. te[5] = me[5];
  3293. te[6] = me[6];
  3294. te[7] = me[7];
  3295. te[8] = me[8];
  3296. te[9] = me[9];
  3297. te[10] = me[10];
  3298. te[11] = me[11];
  3299. te[12] = me[12];
  3300. te[13] = me[13];
  3301. te[14] = me[14];
  3302. te[15] = me[15];
  3303. return this;
  3304. }
  3305. copyPosition(m) {
  3306. const te = this.elements,
  3307. me = m.elements;
  3308. te[12] = me[12];
  3309. te[13] = me[13];
  3310. te[14] = me[14];
  3311. return this;
  3312. }
  3313. setFromMatrix3(m) {
  3314. const me = m.elements;
  3315. 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);
  3316. return this;
  3317. }
  3318. extractBasis(xAxis, yAxis, zAxis) {
  3319. xAxis.setFromMatrixColumn(this, 0);
  3320. yAxis.setFromMatrixColumn(this, 1);
  3321. zAxis.setFromMatrixColumn(this, 2);
  3322. return this;
  3323. }
  3324. makeBasis(xAxis, yAxis, zAxis) {
  3325. 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);
  3326. return this;
  3327. }
  3328. extractRotation(m) {
  3329. // this method does not support reflection matrices
  3330. const te = this.elements;
  3331. const me = m.elements;
  3332. const scaleX = 1 / _v1$5.setFromMatrixColumn(m, 0).length();
  3333. const scaleY = 1 / _v1$5.setFromMatrixColumn(m, 1).length();
  3334. const scaleZ = 1 / _v1$5.setFromMatrixColumn(m, 2).length();
  3335. te[0] = me[0] * scaleX;
  3336. te[1] = me[1] * scaleX;
  3337. te[2] = me[2] * scaleX;
  3338. te[3] = 0;
  3339. te[4] = me[4] * scaleY;
  3340. te[5] = me[5] * scaleY;
  3341. te[6] = me[6] * scaleY;
  3342. te[7] = 0;
  3343. te[8] = me[8] * scaleZ;
  3344. te[9] = me[9] * scaleZ;
  3345. te[10] = me[10] * scaleZ;
  3346. te[11] = 0;
  3347. te[12] = 0;
  3348. te[13] = 0;
  3349. te[14] = 0;
  3350. te[15] = 1;
  3351. return this;
  3352. }
  3353. makeRotationFromEuler(euler) {
  3354. if (!(euler && euler.isEuler)) {
  3355. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  3356. }
  3357. const te = this.elements;
  3358. const x = euler.x,
  3359. y = euler.y,
  3360. z = euler.z;
  3361. const a = Math.cos(x),
  3362. b = Math.sin(x);
  3363. const c = Math.cos(y),
  3364. d = Math.sin(y);
  3365. const e = Math.cos(z),
  3366. f = Math.sin(z);
  3367. if (euler.order === 'XYZ') {
  3368. const ae = a * e,
  3369. af = a * f,
  3370. be = b * e,
  3371. bf = b * f;
  3372. te[0] = c * e;
  3373. te[4] = -c * f;
  3374. te[8] = d;
  3375. te[1] = af + be * d;
  3376. te[5] = ae - bf * d;
  3377. te[9] = -b * c;
  3378. te[2] = bf - ae * d;
  3379. te[6] = be + af * d;
  3380. te[10] = a * c;
  3381. } else if (euler.order === 'YXZ') {
  3382. const ce = c * e,
  3383. cf = c * f,
  3384. de = d * e,
  3385. df = d * f;
  3386. te[0] = ce + df * b;
  3387. te[4] = de * b - cf;
  3388. te[8] = a * d;
  3389. te[1] = a * f;
  3390. te[5] = a * e;
  3391. te[9] = -b;
  3392. te[2] = cf * b - de;
  3393. te[6] = df + ce * b;
  3394. te[10] = a * c;
  3395. } else if (euler.order === 'ZXY') {
  3396. const ce = c * e,
  3397. cf = c * f,
  3398. de = d * e,
  3399. df = d * f;
  3400. te[0] = ce - df * b;
  3401. te[4] = -a * f;
  3402. te[8] = de + cf * b;
  3403. te[1] = cf + de * b;
  3404. te[5] = a * e;
  3405. te[9] = df - ce * b;
  3406. te[2] = -a * d;
  3407. te[6] = b;
  3408. te[10] = a * c;
  3409. } else if (euler.order === 'ZYX') {
  3410. const ae = a * e,
  3411. af = a * f,
  3412. be = b * e,
  3413. bf = b * f;
  3414. te[0] = c * e;
  3415. te[4] = be * d - af;
  3416. te[8] = ae * d + bf;
  3417. te[1] = c * f;
  3418. te[5] = bf * d + ae;
  3419. te[9] = af * d - be;
  3420. te[2] = -d;
  3421. te[6] = b * c;
  3422. te[10] = a * c;
  3423. } else if (euler.order === 'YZX') {
  3424. const ac = a * c,
  3425. ad = a * d,
  3426. bc = b * c,
  3427. bd = b * d;
  3428. te[0] = c * e;
  3429. te[4] = bd - ac * f;
  3430. te[8] = bc * f + ad;
  3431. te[1] = f;
  3432. te[5] = a * e;
  3433. te[9] = -b * e;
  3434. te[2] = -d * e;
  3435. te[6] = ad * f + bc;
  3436. te[10] = ac - bd * f;
  3437. } else if (euler.order === 'XZY') {
  3438. const ac = a * c,
  3439. ad = a * d,
  3440. bc = b * c,
  3441. bd = b * d;
  3442. te[0] = c * e;
  3443. te[4] = -f;
  3444. te[8] = d * e;
  3445. te[1] = ac * f + bd;
  3446. te[5] = a * e;
  3447. te[9] = ad * f - bc;
  3448. te[2] = bc * f - ad;
  3449. te[6] = b * e;
  3450. te[10] = bd * f + ac;
  3451. } // bottom row
  3452. te[3] = 0;
  3453. te[7] = 0;
  3454. te[11] = 0; // last column
  3455. te[12] = 0;
  3456. te[13] = 0;
  3457. te[14] = 0;
  3458. te[15] = 1;
  3459. return this;
  3460. }
  3461. makeRotationFromQuaternion(q) {
  3462. return this.compose(_zero, q, _one);
  3463. }
  3464. lookAt(eye, target, up) {
  3465. const te = this.elements;
  3466. _z.subVectors(eye, target);
  3467. if (_z.lengthSq() === 0) {
  3468. // eye and target are in the same position
  3469. _z.z = 1;
  3470. }
  3471. _z.normalize();
  3472. _x.crossVectors(up, _z);
  3473. if (_x.lengthSq() === 0) {
  3474. // up and z are parallel
  3475. if (Math.abs(up.z) === 1) {
  3476. _z.x += 0.0001;
  3477. } else {
  3478. _z.z += 0.0001;
  3479. }
  3480. _z.normalize();
  3481. _x.crossVectors(up, _z);
  3482. }
  3483. _x.normalize();
  3484. _y.crossVectors(_z, _x);
  3485. te[0] = _x.x;
  3486. te[4] = _y.x;
  3487. te[8] = _z.x;
  3488. te[1] = _x.y;
  3489. te[5] = _y.y;
  3490. te[9] = _z.y;
  3491. te[2] = _x.z;
  3492. te[6] = _y.z;
  3493. te[10] = _z.z;
  3494. return this;
  3495. }
  3496. multiply(m, n) {
  3497. if (n !== undefined) {
  3498. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  3499. return this.multiplyMatrices(m, n);
  3500. }
  3501. return this.multiplyMatrices(this, m);
  3502. }
  3503. premultiply(m) {
  3504. return this.multiplyMatrices(m, this);
  3505. }
  3506. multiplyMatrices(a, b) {
  3507. const ae = a.elements;
  3508. const be = b.elements;
  3509. const te = this.elements;
  3510. const a11 = ae[0],
  3511. a12 = ae[4],
  3512. a13 = ae[8],
  3513. a14 = ae[12];
  3514. const a21 = ae[1],
  3515. a22 = ae[5],
  3516. a23 = ae[9],
  3517. a24 = ae[13];
  3518. const a31 = ae[2],
  3519. a32 = ae[6],
  3520. a33 = ae[10],
  3521. a34 = ae[14];
  3522. const a41 = ae[3],
  3523. a42 = ae[7],
  3524. a43 = ae[11],
  3525. a44 = ae[15];
  3526. const b11 = be[0],
  3527. b12 = be[4],
  3528. b13 = be[8],
  3529. b14 = be[12];
  3530. const b21 = be[1],
  3531. b22 = be[5],
  3532. b23 = be[9],
  3533. b24 = be[13];
  3534. const b31 = be[2],
  3535. b32 = be[6],
  3536. b33 = be[10],
  3537. b34 = be[14];
  3538. const b41 = be[3],
  3539. b42 = be[7],
  3540. b43 = be[11],
  3541. b44 = be[15];
  3542. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3543. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3544. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3545. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3546. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3547. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3548. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3549. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3550. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3551. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3552. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3553. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3554. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3555. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3556. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3557. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3558. return this;
  3559. }
  3560. multiplyScalar(s) {
  3561. const te = this.elements;
  3562. te[0] *= s;
  3563. te[4] *= s;
  3564. te[8] *= s;
  3565. te[12] *= s;
  3566. te[1] *= s;
  3567. te[5] *= s;
  3568. te[9] *= s;
  3569. te[13] *= s;
  3570. te[2] *= s;
  3571. te[6] *= s;
  3572. te[10] *= s;
  3573. te[14] *= s;
  3574. te[3] *= s;
  3575. te[7] *= s;
  3576. te[11] *= s;
  3577. te[15] *= s;
  3578. return this;
  3579. }
  3580. determinant() {
  3581. const te = this.elements;
  3582. const n11 = te[0],
  3583. n12 = te[4],
  3584. n13 = te[8],
  3585. n14 = te[12];
  3586. const n21 = te[1],
  3587. n22 = te[5],
  3588. n23 = te[9],
  3589. n24 = te[13];
  3590. const n31 = te[2],
  3591. n32 = te[6],
  3592. n33 = te[10],
  3593. n34 = te[14];
  3594. const n41 = te[3],
  3595. n42 = te[7],
  3596. n43 = te[11],
  3597. n44 = te[15]; //TODO: make this more efficient
  3598. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3599. 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);
  3600. }
  3601. transpose() {
  3602. const te = this.elements;
  3603. let tmp;
  3604. tmp = te[1];
  3605. te[1] = te[4];
  3606. te[4] = tmp;
  3607. tmp = te[2];
  3608. te[2] = te[8];
  3609. te[8] = tmp;
  3610. tmp = te[6];
  3611. te[6] = te[9];
  3612. te[9] = tmp;
  3613. tmp = te[3];
  3614. te[3] = te[12];
  3615. te[12] = tmp;
  3616. tmp = te[7];
  3617. te[7] = te[13];
  3618. te[13] = tmp;
  3619. tmp = te[11];
  3620. te[11] = te[14];
  3621. te[14] = tmp;
  3622. return this;
  3623. }
  3624. setPosition(x, y, z) {
  3625. const te = this.elements;
  3626. if (x.isVector3) {
  3627. te[12] = x.x;
  3628. te[13] = x.y;
  3629. te[14] = x.z;
  3630. } else {
  3631. te[12] = x;
  3632. te[13] = y;
  3633. te[14] = z;
  3634. }
  3635. return this;
  3636. }
  3637. invert() {
  3638. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3639. const te = this.elements,
  3640. n11 = te[0],
  3641. n21 = te[1],
  3642. n31 = te[2],
  3643. n41 = te[3],
  3644. n12 = te[4],
  3645. n22 = te[5],
  3646. n32 = te[6],
  3647. n42 = te[7],
  3648. n13 = te[8],
  3649. n23 = te[9],
  3650. n33 = te[10],
  3651. n43 = te[11],
  3652. n14 = te[12],
  3653. n24 = te[13],
  3654. n34 = te[14],
  3655. n44 = te[15],
  3656. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3657. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3658. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3659. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3660. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3661. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  3662. const detInv = 1 / det;
  3663. te[0] = t11 * detInv;
  3664. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  3665. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  3666. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  3667. te[4] = t12 * detInv;
  3668. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  3669. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  3670. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  3671. te[8] = t13 * detInv;
  3672. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  3673. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  3674. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  3675. te[12] = t14 * detInv;
  3676. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  3677. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  3678. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  3679. return this;
  3680. }
  3681. scale(v) {
  3682. const te = this.elements;
  3683. const x = v.x,
  3684. y = v.y,
  3685. z = v.z;
  3686. te[0] *= x;
  3687. te[4] *= y;
  3688. te[8] *= z;
  3689. te[1] *= x;
  3690. te[5] *= y;
  3691. te[9] *= z;
  3692. te[2] *= x;
  3693. te[6] *= y;
  3694. te[10] *= z;
  3695. te[3] *= x;
  3696. te[7] *= y;
  3697. te[11] *= z;
  3698. return this;
  3699. }
  3700. getMaxScaleOnAxis() {
  3701. const te = this.elements;
  3702. const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  3703. const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  3704. const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  3705. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  3706. }
  3707. makeTranslation(x, y, z) {
  3708. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  3709. return this;
  3710. }
  3711. makeRotationX(theta) {
  3712. const c = Math.cos(theta),
  3713. s = Math.sin(theta);
  3714. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  3715. return this;
  3716. }
  3717. makeRotationY(theta) {
  3718. const c = Math.cos(theta),
  3719. s = Math.sin(theta);
  3720. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  3721. return this;
  3722. }
  3723. makeRotationZ(theta) {
  3724. const c = Math.cos(theta),
  3725. s = Math.sin(theta);
  3726. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3727. return this;
  3728. }
  3729. makeRotationAxis(axis, angle) {
  3730. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3731. const c = Math.cos(angle);
  3732. const s = Math.sin(angle);
  3733. const t = 1 - c;
  3734. const x = axis.x,
  3735. y = axis.y,
  3736. z = axis.z;
  3737. const tx = t * x,
  3738. ty = t * y;
  3739. 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);
  3740. return this;
  3741. }
  3742. makeScale(x, y, z) {
  3743. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  3744. return this;
  3745. }
  3746. makeShear(xy, xz, yx, yz, zx, zy) {
  3747. this.set(1, yx, zx, 0, xy, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1);
  3748. return this;
  3749. }
  3750. compose(position, quaternion, scale) {
  3751. const te = this.elements;
  3752. const x = quaternion._x,
  3753. y = quaternion._y,
  3754. z = quaternion._z,
  3755. w = quaternion._w;
  3756. const x2 = x + x,
  3757. y2 = y + y,
  3758. z2 = z + z;
  3759. const xx = x * x2,
  3760. xy = x * y2,
  3761. xz = x * z2;
  3762. const yy = y * y2,
  3763. yz = y * z2,
  3764. zz = z * z2;
  3765. const wx = w * x2,
  3766. wy = w * y2,
  3767. wz = w * z2;
  3768. const sx = scale.x,
  3769. sy = scale.y,
  3770. sz = scale.z;
  3771. te[0] = (1 - (yy + zz)) * sx;
  3772. te[1] = (xy + wz) * sx;
  3773. te[2] = (xz - wy) * sx;
  3774. te[3] = 0;
  3775. te[4] = (xy - wz) * sy;
  3776. te[5] = (1 - (xx + zz)) * sy;
  3777. te[6] = (yz + wx) * sy;
  3778. te[7] = 0;
  3779. te[8] = (xz + wy) * sz;
  3780. te[9] = (yz - wx) * sz;
  3781. te[10] = (1 - (xx + yy)) * sz;
  3782. te[11] = 0;
  3783. te[12] = position.x;
  3784. te[13] = position.y;
  3785. te[14] = position.z;
  3786. te[15] = 1;
  3787. return this;
  3788. }
  3789. decompose(position, quaternion, scale) {
  3790. const te = this.elements;
  3791. let sx = _v1$5.set(te[0], te[1], te[2]).length();
  3792. const sy = _v1$5.set(te[4], te[5], te[6]).length();
  3793. const sz = _v1$5.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  3794. const det = this.determinant();
  3795. if (det < 0) sx = -sx;
  3796. position.x = te[12];
  3797. position.y = te[13];
  3798. position.z = te[14]; // scale the rotation part
  3799. _m1$2.copy(this);
  3800. const invSX = 1 / sx;
  3801. const invSY = 1 / sy;
  3802. const invSZ = 1 / sz;
  3803. _m1$2.elements[0] *= invSX;
  3804. _m1$2.elements[1] *= invSX;
  3805. _m1$2.elements[2] *= invSX;
  3806. _m1$2.elements[4] *= invSY;
  3807. _m1$2.elements[5] *= invSY;
  3808. _m1$2.elements[6] *= invSY;
  3809. _m1$2.elements[8] *= invSZ;
  3810. _m1$2.elements[9] *= invSZ;
  3811. _m1$2.elements[10] *= invSZ;
  3812. quaternion.setFromRotationMatrix(_m1$2);
  3813. scale.x = sx;
  3814. scale.y = sy;
  3815. scale.z = sz;
  3816. return this;
  3817. }
  3818. makePerspective(left, right, top, bottom, near, far) {
  3819. if (far === undefined) {
  3820. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  3821. }
  3822. const te = this.elements;
  3823. const x = 2 * near / (right - left);
  3824. const y = 2 * near / (top - bottom);
  3825. const a = (right + left) / (right - left);
  3826. const b = (top + bottom) / (top - bottom);
  3827. const c = -(far + near) / (far - near);
  3828. const d = -2 * far * near / (far - near);
  3829. te[0] = x;
  3830. te[4] = 0;
  3831. te[8] = a;
  3832. te[12] = 0;
  3833. te[1] = 0;
  3834. te[5] = y;
  3835. te[9] = b;
  3836. te[13] = 0;
  3837. te[2] = 0;
  3838. te[6] = 0;
  3839. te[10] = c;
  3840. te[14] = d;
  3841. te[3] = 0;
  3842. te[7] = 0;
  3843. te[11] = -1;
  3844. te[15] = 0;
  3845. return this;
  3846. }
  3847. makeOrthographic(left, right, top, bottom, near, far) {
  3848. const te = this.elements;
  3849. const w = 1.0 / (right - left);
  3850. const h = 1.0 / (top - bottom);
  3851. const p = 1.0 / (far - near);
  3852. const x = (right + left) * w;
  3853. const y = (top + bottom) * h;
  3854. const z = (far + near) * p;
  3855. te[0] = 2 * w;
  3856. te[4] = 0;
  3857. te[8] = 0;
  3858. te[12] = -x;
  3859. te[1] = 0;
  3860. te[5] = 2 * h;
  3861. te[9] = 0;
  3862. te[13] = -y;
  3863. te[2] = 0;
  3864. te[6] = 0;
  3865. te[10] = -2 * p;
  3866. te[14] = -z;
  3867. te[3] = 0;
  3868. te[7] = 0;
  3869. te[11] = 0;
  3870. te[15] = 1;
  3871. return this;
  3872. }
  3873. equals(matrix) {
  3874. const te = this.elements;
  3875. const me = matrix.elements;
  3876. for (let i = 0; i < 16; i++) {
  3877. if (te[i] !== me[i]) return false;
  3878. }
  3879. return true;
  3880. }
  3881. fromArray(array, offset = 0) {
  3882. for (let i = 0; i < 16; i++) {
  3883. this.elements[i] = array[i + offset];
  3884. }
  3885. return this;
  3886. }
  3887. toArray(array = [], offset = 0) {
  3888. const te = this.elements;
  3889. array[offset] = te[0];
  3890. array[offset + 1] = te[1];
  3891. array[offset + 2] = te[2];
  3892. array[offset + 3] = te[3];
  3893. array[offset + 4] = te[4];
  3894. array[offset + 5] = te[5];
  3895. array[offset + 6] = te[6];
  3896. array[offset + 7] = te[7];
  3897. array[offset + 8] = te[8];
  3898. array[offset + 9] = te[9];
  3899. array[offset + 10] = te[10];
  3900. array[offset + 11] = te[11];
  3901. array[offset + 12] = te[12];
  3902. array[offset + 13] = te[13];
  3903. array[offset + 14] = te[14];
  3904. array[offset + 15] = te[15];
  3905. return array;
  3906. }
  3907. }
  3908. Matrix4.prototype.isMatrix4 = true;
  3909. const _v1$5 = /*@__PURE__*/new Vector3();
  3910. const _m1$2 = /*@__PURE__*/new Matrix4();
  3911. const _zero = /*@__PURE__*/new Vector3(0, 0, 0);
  3912. const _one = /*@__PURE__*/new Vector3(1, 1, 1);
  3913. const _x = /*@__PURE__*/new Vector3();
  3914. const _y = /*@__PURE__*/new Vector3();
  3915. const _z = /*@__PURE__*/new Vector3();
  3916. const _matrix$1 = /*@__PURE__*/new Matrix4();
  3917. const _quaternion$3 = /*@__PURE__*/new Quaternion();
  3918. class Euler {
  3919. constructor(x = 0, y = 0, z = 0, order = Euler.DefaultOrder) {
  3920. this._x = x;
  3921. this._y = y;
  3922. this._z = z;
  3923. this._order = order;
  3924. }
  3925. get x() {
  3926. return this._x;
  3927. }
  3928. set x(value) {
  3929. this._x = value;
  3930. this._onChangeCallback();
  3931. }
  3932. get y() {
  3933. return this._y;
  3934. }
  3935. set y(value) {
  3936. this._y = value;
  3937. this._onChangeCallback();
  3938. }
  3939. get z() {
  3940. return this._z;
  3941. }
  3942. set z(value) {
  3943. this._z = value;
  3944. this._onChangeCallback();
  3945. }
  3946. get order() {
  3947. return this._order;
  3948. }
  3949. set order(value) {
  3950. this._order = value;
  3951. this._onChangeCallback();
  3952. }
  3953. set(x, y, z, order) {
  3954. this._x = x;
  3955. this._y = y;
  3956. this._z = z;
  3957. this._order = order || this._order;
  3958. this._onChangeCallback();
  3959. return this;
  3960. }
  3961. clone() {
  3962. return new this.constructor(this._x, this._y, this._z, this._order);
  3963. }
  3964. copy(euler) {
  3965. this._x = euler._x;
  3966. this._y = euler._y;
  3967. this._z = euler._z;
  3968. this._order = euler._order;
  3969. this._onChangeCallback();
  3970. return this;
  3971. }
  3972. setFromRotationMatrix(m, order, update) {
  3973. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3974. const te = m.elements;
  3975. const m11 = te[0],
  3976. m12 = te[4],
  3977. m13 = te[8];
  3978. const m21 = te[1],
  3979. m22 = te[5],
  3980. m23 = te[9];
  3981. const m31 = te[2],
  3982. m32 = te[6],
  3983. m33 = te[10];
  3984. order = order || this._order;
  3985. switch (order) {
  3986. case 'XYZ':
  3987. this._y = Math.asin(clamp(m13, -1, 1));
  3988. if (Math.abs(m13) < 0.9999999) {
  3989. this._x = Math.atan2(-m23, m33);
  3990. this._z = Math.atan2(-m12, m11);
  3991. } else {
  3992. this._x = Math.atan2(m32, m22);
  3993. this._z = 0;
  3994. }
  3995. break;
  3996. case 'YXZ':
  3997. this._x = Math.asin(-clamp(m23, -1, 1));
  3998. if (Math.abs(m23) < 0.9999999) {
  3999. this._y = Math.atan2(m13, m33);
  4000. this._z = Math.atan2(m21, m22);
  4001. } else {
  4002. this._y = Math.atan2(-m31, m11);
  4003. this._z = 0;
  4004. }
  4005. break;
  4006. case 'ZXY':
  4007. this._x = Math.asin(clamp(m32, -1, 1));
  4008. if (Math.abs(m32) < 0.9999999) {
  4009. this._y = Math.atan2(-m31, m33);
  4010. this._z = Math.atan2(-m12, m22);
  4011. } else {
  4012. this._y = 0;
  4013. this._z = Math.atan2(m21, m11);
  4014. }
  4015. break;
  4016. case 'ZYX':
  4017. this._y = Math.asin(-clamp(m31, -1, 1));
  4018. if (Math.abs(m31) < 0.9999999) {
  4019. this._x = Math.atan2(m32, m33);
  4020. this._z = Math.atan2(m21, m11);
  4021. } else {
  4022. this._x = 0;
  4023. this._z = Math.atan2(-m12, m22);
  4024. }
  4025. break;
  4026. case 'YZX':
  4027. this._z = Math.asin(clamp(m21, -1, 1));
  4028. if (Math.abs(m21) < 0.9999999) {
  4029. this._x = Math.atan2(-m23, m22);
  4030. this._y = Math.atan2(-m31, m11);
  4031. } else {
  4032. this._x = 0;
  4033. this._y = Math.atan2(m13, m33);
  4034. }
  4035. break;
  4036. case 'XZY':
  4037. this._z = Math.asin(-clamp(m12, -1, 1));
  4038. if (Math.abs(m12) < 0.9999999) {
  4039. this._x = Math.atan2(m32, m22);
  4040. this._y = Math.atan2(m13, m11);
  4041. } else {
  4042. this._x = Math.atan2(-m23, m33);
  4043. this._y = 0;
  4044. }
  4045. break;
  4046. default:
  4047. console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
  4048. }
  4049. this._order = order;
  4050. if (update !== false) this._onChangeCallback();
  4051. return this;
  4052. }
  4053. setFromQuaternion(q, order, update) {
  4054. _matrix$1.makeRotationFromQuaternion(q);
  4055. return this.setFromRotationMatrix(_matrix$1, order, update);
  4056. }
  4057. setFromVector3(v, order) {
  4058. return this.set(v.x, v.y, v.z, order || this._order);
  4059. }
  4060. reorder(newOrder) {
  4061. // WARNING: this discards revolution information -bhouston
  4062. _quaternion$3.setFromEuler(this);
  4063. return this.setFromQuaternion(_quaternion$3, newOrder);
  4064. }
  4065. equals(euler) {
  4066. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4067. }
  4068. fromArray(array) {
  4069. this._x = array[0];
  4070. this._y = array[1];
  4071. this._z = array[2];
  4072. if (array[3] !== undefined) this._order = array[3];
  4073. this._onChangeCallback();
  4074. return this;
  4075. }
  4076. toArray(array = [], offset = 0) {
  4077. array[offset] = this._x;
  4078. array[offset + 1] = this._y;
  4079. array[offset + 2] = this._z;
  4080. array[offset + 3] = this._order;
  4081. return array;
  4082. }
  4083. toVector3(optionalResult) {
  4084. if (optionalResult) {
  4085. return optionalResult.set(this._x, this._y, this._z);
  4086. } else {
  4087. return new Vector3(this._x, this._y, this._z);
  4088. }
  4089. }
  4090. _onChange(callback) {
  4091. this._onChangeCallback = callback;
  4092. return this;
  4093. }
  4094. _onChangeCallback() {}
  4095. }
  4096. Euler.prototype.isEuler = true;
  4097. Euler.DefaultOrder = 'XYZ';
  4098. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4099. class Layers {
  4100. constructor() {
  4101. this.mask = 1 | 0;
  4102. }
  4103. set(channel) {
  4104. this.mask = 1 << channel | 0;
  4105. }
  4106. enable(channel) {
  4107. this.mask |= 1 << channel | 0;
  4108. }
  4109. enableAll() {
  4110. this.mask = 0xffffffff | 0;
  4111. }
  4112. toggle(channel) {
  4113. this.mask ^= 1 << channel | 0;
  4114. }
  4115. disable(channel) {
  4116. this.mask &= ~(1 << channel | 0);
  4117. }
  4118. disableAll() {
  4119. this.mask = 0;
  4120. }
  4121. test(layers) {
  4122. return (this.mask & layers.mask) !== 0;
  4123. }
  4124. }
  4125. let _object3DId = 0;
  4126. const _v1$4 = /*@__PURE__*/new Vector3();
  4127. const _q1 = /*@__PURE__*/new Quaternion();
  4128. const _m1$1 = /*@__PURE__*/new Matrix4();
  4129. const _target = /*@__PURE__*/new Vector3();
  4130. const _position$3 = /*@__PURE__*/new Vector3();
  4131. const _scale$2 = /*@__PURE__*/new Vector3();
  4132. const _quaternion$2 = /*@__PURE__*/new Quaternion();
  4133. const _xAxis = /*@__PURE__*/new Vector3(1, 0, 0);
  4134. const _yAxis = /*@__PURE__*/new Vector3(0, 1, 0);
  4135. const _zAxis = /*@__PURE__*/new Vector3(0, 0, 1);
  4136. const _addedEvent = {
  4137. type: 'added'
  4138. };
  4139. const _removedEvent = {
  4140. type: 'removed'
  4141. };
  4142. class Object3D extends EventDispatcher {
  4143. constructor() {
  4144. super();
  4145. Object.defineProperty(this, 'id', {
  4146. value: _object3DId++
  4147. });
  4148. this.uuid = generateUUID();
  4149. this.name = '';
  4150. this.type = 'Object3D';
  4151. this.parent = null;
  4152. this.children = [];
  4153. this.up = Object3D.DefaultUp.clone();
  4154. const position = new Vector3();
  4155. const rotation = new Euler();
  4156. const quaternion = new Quaternion();
  4157. const scale = new Vector3(1, 1, 1);
  4158. function onRotationChange() {
  4159. quaternion.setFromEuler(rotation, false);
  4160. }
  4161. function onQuaternionChange() {
  4162. rotation.setFromQuaternion(quaternion, undefined, false);
  4163. }
  4164. rotation._onChange(onRotationChange);
  4165. quaternion._onChange(onQuaternionChange);
  4166. Object.defineProperties(this, {
  4167. position: {
  4168. configurable: true,
  4169. enumerable: true,
  4170. value: position
  4171. },
  4172. rotation: {
  4173. configurable: true,
  4174. enumerable: true,
  4175. value: rotation
  4176. },
  4177. quaternion: {
  4178. configurable: true,
  4179. enumerable: true,
  4180. value: quaternion
  4181. },
  4182. scale: {
  4183. configurable: true,
  4184. enumerable: true,
  4185. value: scale
  4186. },
  4187. modelViewMatrix: {
  4188. value: new Matrix4()
  4189. },
  4190. normalMatrix: {
  4191. value: new Matrix3()
  4192. }
  4193. });
  4194. this.matrix = new Matrix4();
  4195. this.matrixWorld = new Matrix4();
  4196. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4197. this.matrixWorldNeedsUpdate = false;
  4198. this.layers = new Layers();
  4199. this.visible = true;
  4200. this.castShadow = false;
  4201. this.receiveShadow = false;
  4202. this.frustumCulled = true;
  4203. this.renderOrder = 0;
  4204. this.animations = [];
  4205. this.userData = {};
  4206. }
  4207. onBeforeRender() {}
  4208. onAfterRender() {}
  4209. applyMatrix4(matrix) {
  4210. if (this.matrixAutoUpdate) this.updateMatrix();
  4211. this.matrix.premultiply(matrix);
  4212. this.matrix.decompose(this.position, this.quaternion, this.scale);
  4213. }
  4214. applyQuaternion(q) {
  4215. this.quaternion.premultiply(q);
  4216. return this;
  4217. }
  4218. setRotationFromAxisAngle(axis, angle) {
  4219. // assumes axis is normalized
  4220. this.quaternion.setFromAxisAngle(axis, angle);
  4221. }
  4222. setRotationFromEuler(euler) {
  4223. this.quaternion.setFromEuler(euler, true);
  4224. }
  4225. setRotationFromMatrix(m) {
  4226. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4227. this.quaternion.setFromRotationMatrix(m);
  4228. }
  4229. setRotationFromQuaternion(q) {
  4230. // assumes q is normalized
  4231. this.quaternion.copy(q);
  4232. }
  4233. rotateOnAxis(axis, angle) {
  4234. // rotate object on axis in object space
  4235. // axis is assumed to be normalized
  4236. _q1.setFromAxisAngle(axis, angle);
  4237. this.quaternion.multiply(_q1);
  4238. return this;
  4239. }
  4240. rotateOnWorldAxis(axis, angle) {
  4241. // rotate object on axis in world space
  4242. // axis is assumed to be normalized
  4243. // method assumes no rotated parent
  4244. _q1.setFromAxisAngle(axis, angle);
  4245. this.quaternion.premultiply(_q1);
  4246. return this;
  4247. }
  4248. rotateX(angle) {
  4249. return this.rotateOnAxis(_xAxis, angle);
  4250. }
  4251. rotateY(angle) {
  4252. return this.rotateOnAxis(_yAxis, angle);
  4253. }
  4254. rotateZ(angle) {
  4255. return this.rotateOnAxis(_zAxis, angle);
  4256. }
  4257. translateOnAxis(axis, distance) {
  4258. // translate object by distance along axis in object space
  4259. // axis is assumed to be normalized
  4260. _v1$4.copy(axis).applyQuaternion(this.quaternion);
  4261. this.position.add(_v1$4.multiplyScalar(distance));
  4262. return this;
  4263. }
  4264. translateX(distance) {
  4265. return this.translateOnAxis(_xAxis, distance);
  4266. }
  4267. translateY(distance) {
  4268. return this.translateOnAxis(_yAxis, distance);
  4269. }
  4270. translateZ(distance) {
  4271. return this.translateOnAxis(_zAxis, distance);
  4272. }
  4273. localToWorld(vector) {
  4274. return vector.applyMatrix4(this.matrixWorld);
  4275. }
  4276. worldToLocal(vector) {
  4277. return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
  4278. }
  4279. lookAt(x, y, z) {
  4280. // This method does not support objects having non-uniformly-scaled parent(s)
  4281. if (x.isVector3) {
  4282. _target.copy(x);
  4283. } else {
  4284. _target.set(x, y, z);
  4285. }
  4286. const parent = this.parent;
  4287. this.updateWorldMatrix(true, false);
  4288. _position$3.setFromMatrixPosition(this.matrixWorld);
  4289. if (this.isCamera || this.isLight) {
  4290. _m1$1.lookAt(_position$3, _target, this.up);
  4291. } else {
  4292. _m1$1.lookAt(_target, _position$3, this.up);
  4293. }
  4294. this.quaternion.setFromRotationMatrix(_m1$1);
  4295. if (parent) {
  4296. _m1$1.extractRotation(parent.matrixWorld);
  4297. _q1.setFromRotationMatrix(_m1$1);
  4298. this.quaternion.premultiply(_q1.invert());
  4299. }
  4300. }
  4301. add(object) {
  4302. if (arguments.length > 1) {
  4303. for (let i = 0; i < arguments.length; i++) {
  4304. this.add(arguments[i]);
  4305. }
  4306. return this;
  4307. }
  4308. if (object === this) {
  4309. console.error('THREE.Object3D.add: object can\'t be added as a child of itself.', object);
  4310. return this;
  4311. }
  4312. if (object && object.isObject3D) {
  4313. if (object.parent !== null) {
  4314. object.parent.remove(object);
  4315. }
  4316. object.parent = this;
  4317. this.children.push(object);
  4318. object.dispatchEvent(_addedEvent);
  4319. } else {
  4320. console.error('THREE.Object3D.add: object not an instance of THREE.Object3D.', object);
  4321. }
  4322. return this;
  4323. }
  4324. remove(object) {
  4325. if (arguments.length > 1) {
  4326. for (let i = 0; i < arguments.length; i++) {
  4327. this.remove(arguments[i]);
  4328. }
  4329. return this;
  4330. }
  4331. const index = this.children.indexOf(object);
  4332. if (index !== -1) {
  4333. object.parent = null;
  4334. this.children.splice(index, 1);
  4335. object.dispatchEvent(_removedEvent);
  4336. }
  4337. return this;
  4338. }
  4339. removeFromParent() {
  4340. const parent = this.parent;
  4341. if (parent !== null) {
  4342. parent.remove(this);
  4343. }
  4344. return this;
  4345. }
  4346. clear() {
  4347. for (let i = 0; i < this.children.length; i++) {
  4348. const object = this.children[i];
  4349. object.parent = null;
  4350. object.dispatchEvent(_removedEvent);
  4351. }
  4352. this.children.length = 0;
  4353. return this;
  4354. }
  4355. attach(object) {
  4356. // adds object as a child of this, while maintaining the object's world transform
  4357. this.updateWorldMatrix(true, false);
  4358. _m1$1.copy(this.matrixWorld).invert();
  4359. if (object.parent !== null) {
  4360. object.parent.updateWorldMatrix(true, false);
  4361. _m1$1.multiply(object.parent.matrixWorld);
  4362. }
  4363. object.applyMatrix4(_m1$1);
  4364. this.add(object);
  4365. object.updateWorldMatrix(false, true);
  4366. return this;
  4367. }
  4368. getObjectById(id) {
  4369. return this.getObjectByProperty('id', id);
  4370. }
  4371. getObjectByName(name) {
  4372. return this.getObjectByProperty('name', name);
  4373. }
  4374. getObjectByProperty(name, value) {
  4375. if (this[name] === value) return this;
  4376. for (let i = 0, l = this.children.length; i < l; i++) {
  4377. const child = this.children[i];
  4378. const object = child.getObjectByProperty(name, value);
  4379. if (object !== undefined) {
  4380. return object;
  4381. }
  4382. }
  4383. return undefined;
  4384. }
  4385. getWorldPosition(target) {
  4386. if (target === undefined) {
  4387. console.warn('THREE.Object3D: .getWorldPosition() target is now required');
  4388. target = new Vector3();
  4389. }
  4390. this.updateWorldMatrix(true, false);
  4391. return target.setFromMatrixPosition(this.matrixWorld);
  4392. }
  4393. getWorldQuaternion(target) {
  4394. if (target === undefined) {
  4395. console.warn('THREE.Object3D: .getWorldQuaternion() target is now required');
  4396. target = new Quaternion();
  4397. }
  4398. this.updateWorldMatrix(true, false);
  4399. this.matrixWorld.decompose(_position$3, target, _scale$2);
  4400. return target;
  4401. }
  4402. getWorldScale(target) {
  4403. if (target === undefined) {
  4404. console.warn('THREE.Object3D: .getWorldScale() target is now required');
  4405. target = new Vector3();
  4406. }
  4407. this.updateWorldMatrix(true, false);
  4408. this.matrixWorld.decompose(_position$3, _quaternion$2, target);
  4409. return target;
  4410. }
  4411. getWorldDirection(target) {
  4412. if (target === undefined) {
  4413. console.warn('THREE.Object3D: .getWorldDirection() target is now required');
  4414. target = new Vector3();
  4415. }
  4416. this.updateWorldMatrix(true, false);
  4417. const e = this.matrixWorld.elements;
  4418. return target.set(e[8], e[9], e[10]).normalize();
  4419. }
  4420. raycast() {}
  4421. traverse(callback) {
  4422. callback(this);
  4423. const children = this.children;
  4424. for (let i = 0, l = children.length; i < l; i++) {
  4425. children[i].traverse(callback);
  4426. }
  4427. }
  4428. traverseVisible(callback) {
  4429. if (this.visible === false) return;
  4430. callback(this);
  4431. const children = this.children;
  4432. for (let i = 0, l = children.length; i < l; i++) {
  4433. children[i].traverseVisible(callback);
  4434. }
  4435. }
  4436. traverseAncestors(callback) {
  4437. const parent = this.parent;
  4438. if (parent !== null) {
  4439. callback(parent);
  4440. parent.traverseAncestors(callback);
  4441. }
  4442. }
  4443. updateMatrix() {
  4444. this.matrix.compose(this.position, this.quaternion, this.scale);
  4445. this.matrixWorldNeedsUpdate = true;
  4446. }
  4447. updateMatrixWorld(force) {
  4448. if (this.matrixAutoUpdate) this.updateMatrix();
  4449. if (this.matrixWorldNeedsUpdate || force) {
  4450. if (this.parent === null) {
  4451. this.matrixWorld.copy(this.matrix);
  4452. } else {
  4453. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4454. }
  4455. this.matrixWorldNeedsUpdate = false;
  4456. force = true;
  4457. } // update children
  4458. const children = this.children;
  4459. for (let i = 0, l = children.length; i < l; i++) {
  4460. children[i].updateMatrixWorld(force);
  4461. }
  4462. }
  4463. updateWorldMatrix(updateParents, updateChildren) {
  4464. const parent = this.parent;
  4465. if (updateParents === true && parent !== null) {
  4466. parent.updateWorldMatrix(true, false);
  4467. }
  4468. if (this.matrixAutoUpdate) this.updateMatrix();
  4469. if (this.parent === null) {
  4470. this.matrixWorld.copy(this.matrix);
  4471. } else {
  4472. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4473. } // update children
  4474. if (updateChildren === true) {
  4475. const children = this.children;
  4476. for (let i = 0, l = children.length; i < l; i++) {
  4477. children[i].updateWorldMatrix(false, true);
  4478. }
  4479. }
  4480. }
  4481. toJSON(meta) {
  4482. // meta is a string when called from JSON.stringify
  4483. const isRootObject = meta === undefined || typeof meta === 'string';
  4484. const output = {}; // meta is a hash used to collect geometries, materials.
  4485. // not providing it implies that this is the root object
  4486. // being serialized.
  4487. if (isRootObject) {
  4488. // initialize meta obj
  4489. meta = {
  4490. geometries: {},
  4491. materials: {},
  4492. textures: {},
  4493. images: {},
  4494. shapes: {},
  4495. skeletons: {},
  4496. animations: {}
  4497. };
  4498. output.metadata = {
  4499. version: 4.5,
  4500. type: 'Object',
  4501. generator: 'Object3D.toJSON'
  4502. };
  4503. } // standard Object3D serialization
  4504. const object = {};
  4505. object.uuid = this.uuid;
  4506. object.type = this.type;
  4507. if (this.name !== '') object.name = this.name;
  4508. if (this.castShadow === true) object.castShadow = true;
  4509. if (this.receiveShadow === true) object.receiveShadow = true;
  4510. if (this.visible === false) object.visible = false;
  4511. if (this.frustumCulled === false) object.frustumCulled = false;
  4512. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  4513. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  4514. object.layers = this.layers.mask;
  4515. object.matrix = this.matrix.toArray();
  4516. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  4517. if (this.isInstancedMesh) {
  4518. object.type = 'InstancedMesh';
  4519. object.count = this.count;
  4520. object.instanceMatrix = this.instanceMatrix.toJSON();
  4521. if (this.instanceColor !== null) object.instanceColor = this.instanceColor.toJSON();
  4522. } //
  4523. function serialize(library, element) {
  4524. if (library[element.uuid] === undefined) {
  4525. library[element.uuid] = element.toJSON(meta);
  4526. }
  4527. return element.uuid;
  4528. }
  4529. if (this.isMesh || this.isLine || this.isPoints) {
  4530. object.geometry = serialize(meta.geometries, this.geometry);
  4531. const parameters = this.geometry.parameters;
  4532. if (parameters !== undefined && parameters.shapes !== undefined) {
  4533. const shapes = parameters.shapes;
  4534. if (Array.isArray(shapes)) {
  4535. for (let i = 0, l = shapes.length; i < l; i++) {
  4536. const shape = shapes[i];
  4537. serialize(meta.shapes, shape);
  4538. }
  4539. } else {
  4540. serialize(meta.shapes, shapes);
  4541. }
  4542. }
  4543. }
  4544. if (this.isSkinnedMesh) {
  4545. object.bindMode = this.bindMode;
  4546. object.bindMatrix = this.bindMatrix.toArray();
  4547. if (this.skeleton !== undefined) {
  4548. serialize(meta.skeletons, this.skeleton);
  4549. object.skeleton = this.skeleton.uuid;
  4550. }
  4551. }
  4552. if (this.material !== undefined) {
  4553. if (Array.isArray(this.material)) {
  4554. const uuids = [];
  4555. for (let i = 0, l = this.material.length; i < l; i++) {
  4556. uuids.push(serialize(meta.materials, this.material[i]));
  4557. }
  4558. object.material = uuids;
  4559. } else {
  4560. object.material = serialize(meta.materials, this.material);
  4561. }
  4562. } //
  4563. if (this.children.length > 0) {
  4564. object.children = [];
  4565. for (let i = 0; i < this.children.length; i++) {
  4566. object.children.push(this.children[i].toJSON(meta).object);
  4567. }
  4568. } //
  4569. if (this.animations.length > 0) {
  4570. object.animations = [];
  4571. for (let i = 0; i < this.animations.length; i++) {
  4572. const animation = this.animations[i];
  4573. object.animations.push(serialize(meta.animations, animation));
  4574. }
  4575. }
  4576. if (isRootObject) {
  4577. const geometries = extractFromCache(meta.geometries);
  4578. const materials = extractFromCache(meta.materials);
  4579. const textures = extractFromCache(meta.textures);
  4580. const images = extractFromCache(meta.images);
  4581. const shapes = extractFromCache(meta.shapes);
  4582. const skeletons = extractFromCache(meta.skeletons);
  4583. const animations = extractFromCache(meta.animations);
  4584. if (geometries.length > 0) output.geometries = geometries;
  4585. if (materials.length > 0) output.materials = materials;
  4586. if (textures.length > 0) output.textures = textures;
  4587. if (images.length > 0) output.images = images;
  4588. if (shapes.length > 0) output.shapes = shapes;
  4589. if (skeletons.length > 0) output.skeletons = skeletons;
  4590. if (animations.length > 0) output.animations = animations;
  4591. }
  4592. output.object = object;
  4593. return output; // extract data from the cache hash
  4594. // remove metadata on each item
  4595. // and return as array
  4596. function extractFromCache(cache) {
  4597. const values = [];
  4598. for (const key in cache) {
  4599. const data = cache[key];
  4600. delete data.metadata;
  4601. values.push(data);
  4602. }
  4603. return values;
  4604. }
  4605. }
  4606. clone(recursive) {
  4607. return new this.constructor().copy(this, recursive);
  4608. }
  4609. copy(source, recursive = true) {
  4610. this.name = source.name;
  4611. this.up.copy(source.up);
  4612. this.position.copy(source.position);
  4613. this.rotation.order = source.rotation.order;
  4614. this.quaternion.copy(source.quaternion);
  4615. this.scale.copy(source.scale);
  4616. this.matrix.copy(source.matrix);
  4617. this.matrixWorld.copy(source.matrixWorld);
  4618. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4619. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4620. this.layers.mask = source.layers.mask;
  4621. this.visible = source.visible;
  4622. this.castShadow = source.castShadow;
  4623. this.receiveShadow = source.receiveShadow;
  4624. this.frustumCulled = source.frustumCulled;
  4625. this.renderOrder = source.renderOrder;
  4626. this.userData = JSON.parse(JSON.stringify(source.userData));
  4627. if (recursive === true) {
  4628. for (let i = 0; i < source.children.length; i++) {
  4629. const child = source.children[i];
  4630. this.add(child.clone());
  4631. }
  4632. }
  4633. return this;
  4634. }
  4635. }
  4636. Object3D.DefaultUp = new Vector3(0, 1, 0);
  4637. Object3D.DefaultMatrixAutoUpdate = true;
  4638. Object3D.prototype.isObject3D = true;
  4639. const _vector1 = /*@__PURE__*/new Vector3();
  4640. const _vector2$1 = /*@__PURE__*/new Vector3();
  4641. const _normalMatrix = /*@__PURE__*/new Matrix3();
  4642. class Plane {
  4643. constructor(normal = new Vector3(1, 0, 0), constant = 0) {
  4644. // normal is assumed to be normalized
  4645. this.normal = normal;
  4646. this.constant = constant;
  4647. }
  4648. set(normal, constant) {
  4649. this.normal.copy(normal);
  4650. this.constant = constant;
  4651. return this;
  4652. }
  4653. setComponents(x, y, z, w) {
  4654. this.normal.set(x, y, z);
  4655. this.constant = w;
  4656. return this;
  4657. }
  4658. setFromNormalAndCoplanarPoint(normal, point) {
  4659. this.normal.copy(normal);
  4660. this.constant = -point.dot(this.normal);
  4661. return this;
  4662. }
  4663. setFromCoplanarPoints(a, b, c) {
  4664. const normal = _vector1.subVectors(c, b).cross(_vector2$1.subVectors(a, b)).normalize(); // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  4665. this.setFromNormalAndCoplanarPoint(normal, a);
  4666. return this;
  4667. }
  4668. copy(plane) {
  4669. this.normal.copy(plane.normal);
  4670. this.constant = plane.constant;
  4671. return this;
  4672. }
  4673. normalize() {
  4674. // Note: will lead to a divide by zero if the plane is invalid.
  4675. const inverseNormalLength = 1.0 / this.normal.length();
  4676. this.normal.multiplyScalar(inverseNormalLength);
  4677. this.constant *= inverseNormalLength;
  4678. return this;
  4679. }
  4680. negate() {
  4681. this.constant *= -1;
  4682. this.normal.negate();
  4683. return this;
  4684. }
  4685. distanceToPoint(point) {
  4686. return this.normal.dot(point) + this.constant;
  4687. }
  4688. distanceToSphere(sphere) {
  4689. return this.distanceToPoint(sphere.center) - sphere.radius;
  4690. }
  4691. projectPoint(point, target) {
  4692. if (target === undefined) {
  4693. console.warn('THREE.Plane: .projectPoint() target is now required');
  4694. target = new Vector3();
  4695. }
  4696. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  4697. }
  4698. intersectLine(line, target) {
  4699. if (target === undefined) {
  4700. console.warn('THREE.Plane: .intersectLine() target is now required');
  4701. target = new Vector3();
  4702. }
  4703. const direction = line.delta(_vector1);
  4704. const denominator = this.normal.dot(direction);
  4705. if (denominator === 0) {
  4706. // line is coplanar, return origin
  4707. if (this.distanceToPoint(line.start) === 0) {
  4708. return target.copy(line.start);
  4709. } // Unsure if this is the correct method to handle this case.
  4710. return null;
  4711. }
  4712. const t = -(line.start.dot(this.normal) + this.constant) / denominator;
  4713. if (t < 0 || t > 1) {
  4714. return null;
  4715. }
  4716. return target.copy(direction).multiplyScalar(t).add(line.start);
  4717. }
  4718. intersectsLine(line) {
  4719. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  4720. const startSign = this.distanceToPoint(line.start);
  4721. const endSign = this.distanceToPoint(line.end);
  4722. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  4723. }
  4724. intersectsBox(box) {
  4725. return box.intersectsPlane(this);
  4726. }
  4727. intersectsSphere(sphere) {
  4728. return sphere.intersectsPlane(this);
  4729. }
  4730. coplanarPoint(target) {
  4731. if (target === undefined) {
  4732. console.warn('THREE.Plane: .coplanarPoint() target is now required');
  4733. target = new Vector3();
  4734. }
  4735. return target.copy(this.normal).multiplyScalar(-this.constant);
  4736. }
  4737. applyMatrix4(matrix, optionalNormalMatrix) {
  4738. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  4739. const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  4740. const normal = this.normal.applyMatrix3(normalMatrix).normalize();
  4741. this.constant = -referencePoint.dot(normal);
  4742. return this;
  4743. }
  4744. translate(offset) {
  4745. this.constant -= offset.dot(this.normal);
  4746. return this;
  4747. }
  4748. equals(plane) {
  4749. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  4750. }
  4751. clone() {
  4752. return new this.constructor().copy(this);
  4753. }
  4754. }
  4755. Plane.prototype.isPlane = true;
  4756. const _v0$1 = /*@__PURE__*/new Vector3();
  4757. const _v1$3 = /*@__PURE__*/new Vector3();
  4758. const _v2$2 = /*@__PURE__*/new Vector3();
  4759. const _v3$1 = /*@__PURE__*/new Vector3();
  4760. const _vab = /*@__PURE__*/new Vector3();
  4761. const _vac = /*@__PURE__*/new Vector3();
  4762. const _vbc = /*@__PURE__*/new Vector3();
  4763. const _vap = /*@__PURE__*/new Vector3();
  4764. const _vbp = /*@__PURE__*/new Vector3();
  4765. const _vcp = /*@__PURE__*/new Vector3();
  4766. class Triangle {
  4767. constructor(a = new Vector3(), b = new Vector3(), c = new Vector3()) {
  4768. this.a = a;
  4769. this.b = b;
  4770. this.c = c;
  4771. }
  4772. static getNormal(a, b, c, target) {
  4773. if (target === undefined) {
  4774. console.warn('THREE.Triangle: .getNormal() target is now required');
  4775. target = new Vector3();
  4776. }
  4777. target.subVectors(c, b);
  4778. _v0$1.subVectors(a, b);
  4779. target.cross(_v0$1);
  4780. const targetLengthSq = target.lengthSq();
  4781. if (targetLengthSq > 0) {
  4782. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  4783. }
  4784. return target.set(0, 0, 0);
  4785. } // static/instance method to calculate barycentric coordinates
  4786. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4787. static getBarycoord(point, a, b, c, target) {
  4788. _v0$1.subVectors(c, a);
  4789. _v1$3.subVectors(b, a);
  4790. _v2$2.subVectors(point, a);
  4791. const dot00 = _v0$1.dot(_v0$1);
  4792. const dot01 = _v0$1.dot(_v1$3);
  4793. const dot02 = _v0$1.dot(_v2$2);
  4794. const dot11 = _v1$3.dot(_v1$3);
  4795. const dot12 = _v1$3.dot(_v2$2);
  4796. const denom = dot00 * dot11 - dot01 * dot01;
  4797. if (target === undefined) {
  4798. console.warn('THREE.Triangle: .getBarycoord() target is now required');
  4799. target = new Vector3();
  4800. } // collinear or singular triangle
  4801. if (denom === 0) {
  4802. // arbitrary location outside of triangle?
  4803. // not sure if this is the best idea, maybe should be returning undefined
  4804. return target.set(-2, -1, -1);
  4805. }
  4806. const invDenom = 1 / denom;
  4807. const u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  4808. const v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  4809. return target.set(1 - u - v, v, u);
  4810. }
  4811. static containsPoint(point, a, b, c) {
  4812. this.getBarycoord(point, a, b, c, _v3$1);
  4813. return _v3$1.x >= 0 && _v3$1.y >= 0 && _v3$1.x + _v3$1.y <= 1;
  4814. }
  4815. static getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
  4816. this.getBarycoord(point, p1, p2, p3, _v3$1);
  4817. target.set(0, 0);
  4818. target.addScaledVector(uv1, _v3$1.x);
  4819. target.addScaledVector(uv2, _v3$1.y);
  4820. target.addScaledVector(uv3, _v3$1.z);
  4821. return target;
  4822. }
  4823. static isFrontFacing(a, b, c, direction) {
  4824. _v0$1.subVectors(c, b);
  4825. _v1$3.subVectors(a, b); // strictly front facing
  4826. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  4827. }
  4828. set(a, b, c) {
  4829. this.a.copy(a);
  4830. this.b.copy(b);
  4831. this.c.copy(c);
  4832. return this;
  4833. }
  4834. setFromPointsAndIndices(points, i0, i1, i2) {
  4835. this.a.copy(points[i0]);
  4836. this.b.copy(points[i1]);
  4837. this.c.copy(points[i2]);
  4838. return this;
  4839. }
  4840. clone() {
  4841. return new this.constructor().copy(this);
  4842. }
  4843. copy(triangle) {
  4844. this.a.copy(triangle.a);
  4845. this.b.copy(triangle.b);
  4846. this.c.copy(triangle.c);
  4847. return this;
  4848. }
  4849. getArea() {
  4850. _v0$1.subVectors(this.c, this.b);
  4851. _v1$3.subVectors(this.a, this.b);
  4852. return _v0$1.cross(_v1$3).length() * 0.5;
  4853. }
  4854. getMidpoint(target) {
  4855. if (target === undefined) {
  4856. console.warn('THREE.Triangle: .getMidpoint() target is now required');
  4857. target = new Vector3();
  4858. }
  4859. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  4860. }
  4861. getNormal(target) {
  4862. return Triangle.getNormal(this.a, this.b, this.c, target);
  4863. }
  4864. getPlane(target) {
  4865. if (target === undefined) {
  4866. console.warn('THREE.Triangle: .getPlane() target is now required');
  4867. target = new Plane();
  4868. }
  4869. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  4870. }
  4871. getBarycoord(point, target) {
  4872. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  4873. }
  4874. getUV(point, uv1, uv2, uv3, target) {
  4875. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  4876. }
  4877. containsPoint(point) {
  4878. return Triangle.containsPoint(point, this.a, this.b, this.c);
  4879. }
  4880. isFrontFacing(direction) {
  4881. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  4882. }
  4883. intersectsBox(box) {
  4884. return box.intersectsTriangle(this);
  4885. }
  4886. closestPointToPoint(p, target) {
  4887. if (target === undefined) {
  4888. console.warn('THREE.Triangle: .closestPointToPoint() target is now required');
  4889. target = new Vector3();
  4890. }
  4891. const a = this.a,
  4892. b = this.b,
  4893. c = this.c;
  4894. let v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4895. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4896. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4897. // basically, we're distinguishing which of the voronoi regions of the triangle
  4898. // the point lies in with the minimum amount of redundant computation.
  4899. _vab.subVectors(b, a);
  4900. _vac.subVectors(c, a);
  4901. _vap.subVectors(p, a);
  4902. const d1 = _vab.dot(_vap);
  4903. const d2 = _vac.dot(_vap);
  4904. if (d1 <= 0 && d2 <= 0) {
  4905. // vertex region of A; barycentric coords (1, 0, 0)
  4906. return target.copy(a);
  4907. }
  4908. _vbp.subVectors(p, b);
  4909. const d3 = _vab.dot(_vbp);
  4910. const d4 = _vac.dot(_vbp);
  4911. if (d3 >= 0 && d4 <= d3) {
  4912. // vertex region of B; barycentric coords (0, 1, 0)
  4913. return target.copy(b);
  4914. }
  4915. const vc = d1 * d4 - d3 * d2;
  4916. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  4917. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  4918. return target.copy(a).addScaledVector(_vab, v);
  4919. }
  4920. _vcp.subVectors(p, c);
  4921. const d5 = _vab.dot(_vcp);
  4922. const d6 = _vac.dot(_vcp);
  4923. if (d6 >= 0 && d5 <= d6) {
  4924. // vertex region of C; barycentric coords (0, 0, 1)
  4925. return target.copy(c);
  4926. }
  4927. const vb = d5 * d2 - d1 * d6;
  4928. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  4929. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  4930. return target.copy(a).addScaledVector(_vac, w);
  4931. }
  4932. const va = d3 * d6 - d5 * d4;
  4933. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  4934. _vbc.subVectors(c, b);
  4935. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  4936. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  4937. } // face region
  4938. const denom = 1 / (va + vb + vc); // u = va * denom
  4939. v = vb * denom;
  4940. w = vc * denom;
  4941. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  4942. }
  4943. equals(triangle) {
  4944. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  4945. }
  4946. }
  4947. let materialId = 0;
  4948. class Material extends EventDispatcher {
  4949. constructor() {
  4950. super();
  4951. Object.defineProperty(this, 'id', {
  4952. value: materialId++
  4953. });
  4954. this.uuid = generateUUID();
  4955. this.name = '';
  4956. this.type = 'Material';
  4957. this.fog = true;
  4958. this.blending = NormalBlending;
  4959. this.side = FrontSide;
  4960. this.vertexColors = false;
  4961. this.opacity = 1;
  4962. this.transparent = false;
  4963. this.blendSrc = SrcAlphaFactor;
  4964. this.blendDst = OneMinusSrcAlphaFactor;
  4965. this.blendEquation = AddEquation;
  4966. this.blendSrcAlpha = null;
  4967. this.blendDstAlpha = null;
  4968. this.blendEquationAlpha = null;
  4969. this.depthFunc = LessEqualDepth;
  4970. this.depthTest = true;
  4971. this.depthWrite = true;
  4972. this.stencilWriteMask = 0xff;
  4973. this.stencilFunc = AlwaysStencilFunc;
  4974. this.stencilRef = 0;
  4975. this.stencilFuncMask = 0xff;
  4976. this.stencilFail = KeepStencilOp;
  4977. this.stencilZFail = KeepStencilOp;
  4978. this.stencilZPass = KeepStencilOp;
  4979. this.stencilWrite = false;
  4980. this.clippingPlanes = null;
  4981. this.clipIntersection = false;
  4982. this.clipShadows = false;
  4983. this.shadowSide = null;
  4984. this.colorWrite = true;
  4985. this.precision = null; // override the renderer's default precision for this material
  4986. this.polygonOffset = false;
  4987. this.polygonOffsetFactor = 0;
  4988. this.polygonOffsetUnits = 0;
  4989. this.dithering = false;
  4990. this.alphaTest = 0;
  4991. this.alphaToCoverage = false;
  4992. this.premultipliedAlpha = false;
  4993. this.visible = true;
  4994. this.toneMapped = true;
  4995. this.userData = {};
  4996. this.version = 0;
  4997. }
  4998. onBuild()
  4999. /* shaderobject, renderer */
  5000. {}
  5001. onBeforeCompile()
  5002. /* shaderobject, renderer */
  5003. {}
  5004. customProgramCacheKey() {
  5005. return this.onBeforeCompile.toString();
  5006. }
  5007. setValues(values) {
  5008. if (values === undefined) return;
  5009. for (const key in values) {
  5010. const newValue = values[key];
  5011. if (newValue === undefined) {
  5012. console.warn('THREE.Material: \'' + key + '\' parameter is undefined.');
  5013. continue;
  5014. } // for backward compatability if shading is set in the constructor
  5015. if (key === 'shading') {
  5016. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  5017. this.flatShading = newValue === FlatShading ? true : false;
  5018. continue;
  5019. }
  5020. const currentValue = this[key];
  5021. if (currentValue === undefined) {
  5022. console.warn('THREE.' + this.type + ': \'' + key + '\' is not a property of this material.');
  5023. continue;
  5024. }
  5025. if (currentValue && currentValue.isColor) {
  5026. currentValue.set(newValue);
  5027. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  5028. currentValue.copy(newValue);
  5029. } else {
  5030. this[key] = newValue;
  5031. }
  5032. }
  5033. }
  5034. toJSON(meta) {
  5035. const isRoot = meta === undefined || typeof meta === 'string';
  5036. if (isRoot) {
  5037. meta = {
  5038. textures: {},
  5039. images: {}
  5040. };
  5041. }
  5042. const data = {
  5043. metadata: {
  5044. version: 4.5,
  5045. type: 'Material',
  5046. generator: 'Material.toJSON'
  5047. }
  5048. }; // standard Material serialization
  5049. data.uuid = this.uuid;
  5050. data.type = this.type;
  5051. if (this.name !== '') data.name = this.name;
  5052. if (this.color && this.color.isColor) data.color = this.color.getHex();
  5053. if (this.roughness !== undefined) data.roughness = this.roughness;
  5054. if (this.metalness !== undefined) data.metalness = this.metalness;
  5055. if (this.sheen && this.sheen.isColor) data.sheen = this.sheen.getHex();
  5056. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  5057. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  5058. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  5059. if (this.shininess !== undefined) data.shininess = this.shininess;
  5060. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  5061. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  5062. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  5063. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  5064. }
  5065. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  5066. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  5067. }
  5068. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  5069. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  5070. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5071. }
  5072. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  5073. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  5074. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  5075. if (this.lightMap && this.lightMap.isTexture) {
  5076. data.lightMap = this.lightMap.toJSON(meta).uuid;
  5077. data.lightMapIntensity = this.lightMapIntensity;
  5078. }
  5079. if (this.aoMap && this.aoMap.isTexture) {
  5080. data.aoMap = this.aoMap.toJSON(meta).uuid;
  5081. data.aoMapIntensity = this.aoMapIntensity;
  5082. }
  5083. if (this.bumpMap && this.bumpMap.isTexture) {
  5084. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  5085. data.bumpScale = this.bumpScale;
  5086. }
  5087. if (this.normalMap && this.normalMap.isTexture) {
  5088. data.normalMap = this.normalMap.toJSON(meta).uuid;
  5089. data.normalMapType = this.normalMapType;
  5090. data.normalScale = this.normalScale.toArray();
  5091. }
  5092. if (this.displacementMap && this.displacementMap.isTexture) {
  5093. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  5094. data.displacementScale = this.displacementScale;
  5095. data.displacementBias = this.displacementBias;
  5096. }
  5097. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  5098. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  5099. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  5100. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  5101. if (this.envMap && this.envMap.isTexture) {
  5102. data.envMap = this.envMap.toJSON(meta).uuid;
  5103. if (this.combine !== undefined) data.combine = this.combine;
  5104. }
  5105. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  5106. if (this.reflectivity !== undefined) data.reflectivity = this.reflectivity;
  5107. if (this.refractionRatio !== undefined) data.refractionRatio = this.refractionRatio;
  5108. if (this.gradientMap && this.gradientMap.isTexture) {
  5109. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  5110. }
  5111. if (this.transmission !== undefined) data.transmission = this.transmission;
  5112. if (this.transmissionMap && this.transmissionMap.isTexture) data.transmissionMap = this.transmissionMap.toJSON(meta).uuid;
  5113. if (this.thickness !== undefined) data.thickness = this.thickness;
  5114. if (this.thicknessMap && this.thicknessMap.isTexture) data.thicknessMap = this.thicknessMap.toJSON(meta).uuid;
  5115. if (this.attenuationDistance !== undefined) data.attenuationDistance = this.attenuationDistance;
  5116. if (this.attenuationColor !== undefined) data.attenuationColor = this.attenuationColor.getHex();
  5117. if (this.size !== undefined) data.size = this.size;
  5118. if (this.shadowSide !== null) data.shadowSide = this.shadowSide;
  5119. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  5120. if (this.blending !== NormalBlending) data.blending = this.blending;
  5121. if (this.side !== FrontSide) data.side = this.side;
  5122. if (this.vertexColors) data.vertexColors = true;
  5123. if (this.opacity < 1) data.opacity = this.opacity;
  5124. if (this.transparent === true) data.transparent = this.transparent;
  5125. data.depthFunc = this.depthFunc;
  5126. data.depthTest = this.depthTest;
  5127. data.depthWrite = this.depthWrite;
  5128. data.colorWrite = this.colorWrite;
  5129. data.stencilWrite = this.stencilWrite;
  5130. data.stencilWriteMask = this.stencilWriteMask;
  5131. data.stencilFunc = this.stencilFunc;
  5132. data.stencilRef = this.stencilRef;
  5133. data.stencilFuncMask = this.stencilFuncMask;
  5134. data.stencilFail = this.stencilFail;
  5135. data.stencilZFail = this.stencilZFail;
  5136. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  5137. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  5138. if (this.polygonOffset === true) data.polygonOffset = true;
  5139. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5140. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5141. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  5142. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  5143. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  5144. if (this.scale !== undefined) data.scale = this.scale;
  5145. if (this.dithering === true) data.dithering = true;
  5146. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  5147. if (this.alphaToCoverage === true) data.alphaToCoverage = this.alphaToCoverage;
  5148. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  5149. if (this.wireframe === true) data.wireframe = this.wireframe;
  5150. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  5151. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  5152. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  5153. if (this.morphTargets === true) data.morphTargets = true;
  5154. if (this.morphNormals === true) data.morphNormals = true;
  5155. if (this.flatShading === true) data.flatShading = this.flatShading;
  5156. if (this.visible === false) data.visible = false;
  5157. if (this.toneMapped === false) data.toneMapped = false;
  5158. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  5159. function extractFromCache(cache) {
  5160. const values = [];
  5161. for (const key in cache) {
  5162. const data = cache[key];
  5163. delete data.metadata;
  5164. values.push(data);
  5165. }
  5166. return values;
  5167. }
  5168. if (isRoot) {
  5169. const textures = extractFromCache(meta.textures);
  5170. const images = extractFromCache(meta.images);
  5171. if (textures.length > 0) data.textures = textures;
  5172. if (images.length > 0) data.images = images;
  5173. }
  5174. return data;
  5175. }
  5176. clone() {
  5177. return new this.constructor().copy(this);
  5178. }
  5179. copy(source) {
  5180. this.name = source.name;
  5181. this.fog = source.fog;
  5182. this.blending = source.blending;
  5183. this.side = source.side;
  5184. this.vertexColors = source.vertexColors;
  5185. this.opacity = source.opacity;
  5186. this.transparent = source.transparent;
  5187. this.blendSrc = source.blendSrc;
  5188. this.blendDst = source.blendDst;
  5189. this.blendEquation = source.blendEquation;
  5190. this.blendSrcAlpha = source.blendSrcAlpha;
  5191. this.blendDstAlpha = source.blendDstAlpha;
  5192. this.blendEquationAlpha = source.blendEquationAlpha;
  5193. this.depthFunc = source.depthFunc;
  5194. this.depthTest = source.depthTest;
  5195. this.depthWrite = source.depthWrite;
  5196. this.stencilWriteMask = source.stencilWriteMask;
  5197. this.stencilFunc = source.stencilFunc;
  5198. this.stencilRef = source.stencilRef;
  5199. this.stencilFuncMask = source.stencilFuncMask;
  5200. this.stencilFail = source.stencilFail;
  5201. this.stencilZFail = source.stencilZFail;
  5202. this.stencilZPass = source.stencilZPass;
  5203. this.stencilWrite = source.stencilWrite;
  5204. const srcPlanes = source.clippingPlanes;
  5205. let dstPlanes = null;
  5206. if (srcPlanes !== null) {
  5207. const n = srcPlanes.length;
  5208. dstPlanes = new Array(n);
  5209. for (let i = 0; i !== n; ++i) {
  5210. dstPlanes[i] = srcPlanes[i].clone();
  5211. }
  5212. }
  5213. this.clippingPlanes = dstPlanes;
  5214. this.clipIntersection = source.clipIntersection;
  5215. this.clipShadows = source.clipShadows;
  5216. this.shadowSide = source.shadowSide;
  5217. this.colorWrite = source.colorWrite;
  5218. this.precision = source.precision;
  5219. this.polygonOffset = source.polygonOffset;
  5220. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5221. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5222. this.dithering = source.dithering;
  5223. this.alphaTest = source.alphaTest;
  5224. this.alphaToCoverage = source.alphaToCoverage;
  5225. this.premultipliedAlpha = source.premultipliedAlpha;
  5226. this.visible = source.visible;
  5227. this.toneMapped = source.toneMapped;
  5228. this.userData = JSON.parse(JSON.stringify(source.userData));
  5229. return this;
  5230. }
  5231. dispose() {
  5232. this.dispatchEvent({
  5233. type: 'dispose'
  5234. });
  5235. }
  5236. set needsUpdate(value) {
  5237. if (value === true) this.version++;
  5238. }
  5239. }
  5240. Material.prototype.isMaterial = true;
  5241. const _colorKeywords = {
  5242. 'aliceblue': 0xF0F8FF,
  5243. 'antiquewhite': 0xFAEBD7,
  5244. 'aqua': 0x00FFFF,
  5245. 'aquamarine': 0x7FFFD4,
  5246. 'azure': 0xF0FFFF,
  5247. 'beige': 0xF5F5DC,
  5248. 'bisque': 0xFFE4C4,
  5249. 'black': 0x000000,
  5250. 'blanchedalmond': 0xFFEBCD,
  5251. 'blue': 0x0000FF,
  5252. 'blueviolet': 0x8A2BE2,
  5253. 'brown': 0xA52A2A,
  5254. 'burlywood': 0xDEB887,
  5255. 'cadetblue': 0x5F9EA0,
  5256. 'chartreuse': 0x7FFF00,
  5257. 'chocolate': 0xD2691E,
  5258. 'coral': 0xFF7F50,
  5259. 'cornflowerblue': 0x6495ED,
  5260. 'cornsilk': 0xFFF8DC,
  5261. 'crimson': 0xDC143C,
  5262. 'cyan': 0x00FFFF,
  5263. 'darkblue': 0x00008B,
  5264. 'darkcyan': 0x008B8B,
  5265. 'darkgoldenrod': 0xB8860B,
  5266. 'darkgray': 0xA9A9A9,
  5267. 'darkgreen': 0x006400,
  5268. 'darkgrey': 0xA9A9A9,
  5269. 'darkkhaki': 0xBDB76B,
  5270. 'darkmagenta': 0x8B008B,
  5271. 'darkolivegreen': 0x556B2F,
  5272. 'darkorange': 0xFF8C00,
  5273. 'darkorchid': 0x9932CC,
  5274. 'darkred': 0x8B0000,
  5275. 'darksalmon': 0xE9967A,
  5276. 'darkseagreen': 0x8FBC8F,
  5277. 'darkslateblue': 0x483D8B,
  5278. 'darkslategray': 0x2F4F4F,
  5279. 'darkslategrey': 0x2F4F4F,
  5280. 'darkturquoise': 0x00CED1,
  5281. 'darkviolet': 0x9400D3,
  5282. 'deeppink': 0xFF1493,
  5283. 'deepskyblue': 0x00BFFF,
  5284. 'dimgray': 0x696969,
  5285. 'dimgrey': 0x696969,
  5286. 'dodgerblue': 0x1E90FF,
  5287. 'firebrick': 0xB22222,
  5288. 'floralwhite': 0xFFFAF0,
  5289. 'forestgreen': 0x228B22,
  5290. 'fuchsia': 0xFF00FF,
  5291. 'gainsboro': 0xDCDCDC,
  5292. 'ghostwhite': 0xF8F8FF,
  5293. 'gold': 0xFFD700,
  5294. 'goldenrod': 0xDAA520,
  5295. 'gray': 0x808080,
  5296. 'green': 0x008000,
  5297. 'greenyellow': 0xADFF2F,
  5298. 'grey': 0x808080,
  5299. 'honeydew': 0xF0FFF0,
  5300. 'hotpink': 0xFF69B4,
  5301. 'indianred': 0xCD5C5C,
  5302. 'indigo': 0x4B0082,
  5303. 'ivory': 0xFFFFF0,
  5304. 'khaki': 0xF0E68C,
  5305. 'lavender': 0xE6E6FA,
  5306. 'lavenderblush': 0xFFF0F5,
  5307. 'lawngreen': 0x7CFC00,
  5308. 'lemonchiffon': 0xFFFACD,
  5309. 'lightblue': 0xADD8E6,
  5310. 'lightcoral': 0xF08080,
  5311. 'lightcyan': 0xE0FFFF,
  5312. 'lightgoldenrodyellow': 0xFAFAD2,
  5313. 'lightgray': 0xD3D3D3,
  5314. 'lightgreen': 0x90EE90,
  5315. 'lightgrey': 0xD3D3D3,
  5316. 'lightpink': 0xFFB6C1,
  5317. 'lightsalmon': 0xFFA07A,
  5318. 'lightseagreen': 0x20B2AA,
  5319. 'lightskyblue': 0x87CEFA,
  5320. 'lightslategray': 0x778899,
  5321. 'lightslategrey': 0x778899,
  5322. 'lightsteelblue': 0xB0C4DE,
  5323. 'lightyellow': 0xFFFFE0,
  5324. 'lime': 0x00FF00,
  5325. 'limegreen': 0x32CD32,
  5326. 'linen': 0xFAF0E6,
  5327. 'magenta': 0xFF00FF,
  5328. 'maroon': 0x800000,
  5329. 'mediumaquamarine': 0x66CDAA,
  5330. 'mediumblue': 0x0000CD,
  5331. 'mediumorchid': 0xBA55D3,
  5332. 'mediumpurple': 0x9370DB,
  5333. 'mediumseagreen': 0x3CB371,
  5334. 'mediumslateblue': 0x7B68EE,
  5335. 'mediumspringgreen': 0x00FA9A,
  5336. 'mediumturquoise': 0x48D1CC,
  5337. 'mediumvioletred': 0xC71585,
  5338. 'midnightblue': 0x191970,
  5339. 'mintcream': 0xF5FFFA,
  5340. 'mistyrose': 0xFFE4E1,
  5341. 'moccasin': 0xFFE4B5,
  5342. 'navajowhite': 0xFFDEAD,
  5343. 'navy': 0x000080,
  5344. 'oldlace': 0xFDF5E6,
  5345. 'olive': 0x808000,
  5346. 'olivedrab': 0x6B8E23,
  5347. 'orange': 0xFFA500,
  5348. 'orangered': 0xFF4500,
  5349. 'orchid': 0xDA70D6,
  5350. 'palegoldenrod': 0xEEE8AA,
  5351. 'palegreen': 0x98FB98,
  5352. 'paleturquoise': 0xAFEEEE,
  5353. 'palevioletred': 0xDB7093,
  5354. 'papayawhip': 0xFFEFD5,
  5355. 'peachpuff': 0xFFDAB9,
  5356. 'peru': 0xCD853F,
  5357. 'pink': 0xFFC0CB,
  5358. 'plum': 0xDDA0DD,
  5359. 'powderblue': 0xB0E0E6,
  5360. 'purple': 0x800080,
  5361. 'rebeccapurple': 0x663399,
  5362. 'red': 0xFF0000,
  5363. 'rosybrown': 0xBC8F8F,
  5364. 'royalblue': 0x4169E1,
  5365. 'saddlebrown': 0x8B4513,
  5366. 'salmon': 0xFA8072,
  5367. 'sandybrown': 0xF4A460,
  5368. 'seagreen': 0x2E8B57,
  5369. 'seashell': 0xFFF5EE,
  5370. 'sienna': 0xA0522D,
  5371. 'silver': 0xC0C0C0,
  5372. 'skyblue': 0x87CEEB,
  5373. 'slateblue': 0x6A5ACD,
  5374. 'slategray': 0x708090,
  5375. 'slategrey': 0x708090,
  5376. 'snow': 0xFFFAFA,
  5377. 'springgreen': 0x00FF7F,
  5378. 'steelblue': 0x4682B4,
  5379. 'tan': 0xD2B48C,
  5380. 'teal': 0x008080,
  5381. 'thistle': 0xD8BFD8,
  5382. 'tomato': 0xFF6347,
  5383. 'turquoise': 0x40E0D0,
  5384. 'violet': 0xEE82EE,
  5385. 'wheat': 0xF5DEB3,
  5386. 'white': 0xFFFFFF,
  5387. 'whitesmoke': 0xF5F5F5,
  5388. 'yellow': 0xFFFF00,
  5389. 'yellowgreen': 0x9ACD32
  5390. };
  5391. const _hslA = {
  5392. h: 0,
  5393. s: 0,
  5394. l: 0
  5395. };
  5396. const _hslB = {
  5397. h: 0,
  5398. s: 0,
  5399. l: 0
  5400. };
  5401. function hue2rgb(p, q, t) {
  5402. if (t < 0) t += 1;
  5403. if (t > 1) t -= 1;
  5404. if (t < 1 / 6) return p + (q - p) * 6 * t;
  5405. if (t < 1 / 2) return q;
  5406. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  5407. return p;
  5408. }
  5409. function SRGBToLinear(c) {
  5410. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  5411. }
  5412. function LinearToSRGB(c) {
  5413. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  5414. }
  5415. class Color {
  5416. constructor(r, g, b) {
  5417. if (g === undefined && b === undefined) {
  5418. // r is THREE.Color, hex or string
  5419. return this.set(r);
  5420. }
  5421. return this.setRGB(r, g, b);
  5422. }
  5423. set(value) {
  5424. if (value && value.isColor) {
  5425. this.copy(value);
  5426. } else if (typeof value === 'number') {
  5427. this.setHex(value);
  5428. } else if (typeof value === 'string') {
  5429. this.setStyle(value);
  5430. }
  5431. return this;
  5432. }
  5433. setScalar(scalar) {
  5434. this.r = scalar;
  5435. this.g = scalar;
  5436. this.b = scalar;
  5437. return this;
  5438. }
  5439. setHex(hex) {
  5440. hex = Math.floor(hex);
  5441. this.r = (hex >> 16 & 255) / 255;
  5442. this.g = (hex >> 8 & 255) / 255;
  5443. this.b = (hex & 255) / 255;
  5444. return this;
  5445. }
  5446. setRGB(r, g, b) {
  5447. this.r = r;
  5448. this.g = g;
  5449. this.b = b;
  5450. return this;
  5451. }
  5452. setHSL(h, s, l) {
  5453. // h,s,l ranges are in 0.0 - 1.0
  5454. h = euclideanModulo(h, 1);
  5455. s = clamp(s, 0, 1);
  5456. l = clamp(l, 0, 1);
  5457. if (s === 0) {
  5458. this.r = this.g = this.b = l;
  5459. } else {
  5460. const p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  5461. const q = 2 * l - p;
  5462. this.r = hue2rgb(q, p, h + 1 / 3);
  5463. this.g = hue2rgb(q, p, h);
  5464. this.b = hue2rgb(q, p, h - 1 / 3);
  5465. }
  5466. return this;
  5467. }
  5468. setStyle(style) {
  5469. function handleAlpha(string) {
  5470. if (string === undefined) return;
  5471. if (parseFloat(string) < 1) {
  5472. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  5473. }
  5474. }
  5475. let m;
  5476. if (m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style)) {
  5477. // rgb / hsl
  5478. let color;
  5479. const name = m[1];
  5480. const components = m[2];
  5481. switch (name) {
  5482. case 'rgb':
  5483. case 'rgba':
  5484. if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5485. // rgb(255,0,0) rgba(255,0,0,0.5)
  5486. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  5487. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  5488. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  5489. handleAlpha(color[4]);
  5490. return this;
  5491. }
  5492. if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5493. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5494. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  5495. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  5496. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  5497. handleAlpha(color[4]);
  5498. return this;
  5499. }
  5500. break;
  5501. case 'hsl':
  5502. case 'hsla':
  5503. if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  5504. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5505. const h = parseFloat(color[1]) / 360;
  5506. const s = parseInt(color[2], 10) / 100;
  5507. const l = parseInt(color[3], 10) / 100;
  5508. handleAlpha(color[4]);
  5509. return this.setHSL(h, s, l);
  5510. }
  5511. break;
  5512. }
  5513. } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) {
  5514. // hex color
  5515. const hex = m[1];
  5516. const size = hex.length;
  5517. if (size === 3) {
  5518. // #ff0
  5519. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  5520. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  5521. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  5522. return this;
  5523. } else if (size === 6) {
  5524. // #ff0000
  5525. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  5526. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  5527. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  5528. return this;
  5529. }
  5530. }
  5531. if (style && style.length > 0) {
  5532. return this.setColorName(style);
  5533. }
  5534. return this;
  5535. }
  5536. setColorName(style) {
  5537. // color keywords
  5538. const hex = _colorKeywords[style.toLowerCase()];
  5539. if (hex !== undefined) {
  5540. // red
  5541. this.setHex(hex);
  5542. } else {
  5543. // unknown color
  5544. console.warn('THREE.Color: Unknown color ' + style);
  5545. }
  5546. return this;
  5547. }
  5548. clone() {
  5549. return new this.constructor(this.r, this.g, this.b);
  5550. }
  5551. copy(color) {
  5552. this.r = color.r;
  5553. this.g = color.g;
  5554. this.b = color.b;
  5555. return this;
  5556. }
  5557. copyGammaToLinear(color, gammaFactor = 2.0) {
  5558. this.r = Math.pow(color.r, gammaFactor);
  5559. this.g = Math.pow(color.g, gammaFactor);
  5560. this.b = Math.pow(color.b, gammaFactor);
  5561. return this;
  5562. }
  5563. copyLinearToGamma(color, gammaFactor = 2.0) {
  5564. const safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  5565. this.r = Math.pow(color.r, safeInverse);
  5566. this.g = Math.pow(color.g, safeInverse);
  5567. this.b = Math.pow(color.b, safeInverse);
  5568. return this;
  5569. }
  5570. convertGammaToLinear(gammaFactor) {
  5571. this.copyGammaToLinear(this, gammaFactor);
  5572. return this;
  5573. }
  5574. convertLinearToGamma(gammaFactor) {
  5575. this.copyLinearToGamma(this, gammaFactor);
  5576. return this;
  5577. }
  5578. copySRGBToLinear(color) {
  5579. this.r = SRGBToLinear(color.r);
  5580. this.g = SRGBToLinear(color.g);
  5581. this.b = SRGBToLinear(color.b);
  5582. return this;
  5583. }
  5584. copyLinearToSRGB(color) {
  5585. this.r = LinearToSRGB(color.r);
  5586. this.g = LinearToSRGB(color.g);
  5587. this.b = LinearToSRGB(color.b);
  5588. return this;
  5589. }
  5590. convertSRGBToLinear() {
  5591. this.copySRGBToLinear(this);
  5592. return this;
  5593. }
  5594. convertLinearToSRGB() {
  5595. this.copyLinearToSRGB(this);
  5596. return this;
  5597. }
  5598. getHex() {
  5599. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  5600. }
  5601. getHexString() {
  5602. return ('000000' + this.getHex().toString(16)).slice(-6);
  5603. }
  5604. getHSL(target) {
  5605. // h,s,l ranges are in 0.0 - 1.0
  5606. if (target === undefined) {
  5607. console.warn('THREE.Color: .getHSL() target is now required');
  5608. target = {
  5609. h: 0,
  5610. s: 0,
  5611. l: 0
  5612. };
  5613. }
  5614. const r = this.r,
  5615. g = this.g,
  5616. b = this.b;
  5617. const max = Math.max(r, g, b);
  5618. const min = Math.min(r, g, b);
  5619. let hue, saturation;
  5620. const lightness = (min + max) / 2.0;
  5621. if (min === max) {
  5622. hue = 0;
  5623. saturation = 0;
  5624. } else {
  5625. const delta = max - min;
  5626. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  5627. switch (max) {
  5628. case r:
  5629. hue = (g - b) / delta + (g < b ? 6 : 0);
  5630. break;
  5631. case g:
  5632. hue = (b - r) / delta + 2;
  5633. break;
  5634. case b:
  5635. hue = (r - g) / delta + 4;
  5636. break;
  5637. }
  5638. hue /= 6;
  5639. }
  5640. target.h = hue;
  5641. target.s = saturation;
  5642. target.l = lightness;
  5643. return target;
  5644. }
  5645. getStyle() {
  5646. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  5647. }
  5648. offsetHSL(h, s, l) {
  5649. this.getHSL(_hslA);
  5650. _hslA.h += h;
  5651. _hslA.s += s;
  5652. _hslA.l += l;
  5653. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  5654. return this;
  5655. }
  5656. add(color) {
  5657. this.r += color.r;
  5658. this.g += color.g;
  5659. this.b += color.b;
  5660. return this;
  5661. }
  5662. addColors(color1, color2) {
  5663. this.r = color1.r + color2.r;
  5664. this.g = color1.g + color2.g;
  5665. this.b = color1.b + color2.b;
  5666. return this;
  5667. }
  5668. addScalar(s) {
  5669. this.r += s;
  5670. this.g += s;
  5671. this.b += s;
  5672. return this;
  5673. }
  5674. sub(color) {
  5675. this.r = Math.max(0, this.r - color.r);
  5676. this.g = Math.max(0, this.g - color.g);
  5677. this.b = Math.max(0, this.b - color.b);
  5678. return this;
  5679. }
  5680. multiply(color) {
  5681. this.r *= color.r;
  5682. this.g *= color.g;
  5683. this.b *= color.b;
  5684. return this;
  5685. }
  5686. multiplyScalar(s) {
  5687. this.r *= s;
  5688. this.g *= s;
  5689. this.b *= s;
  5690. return this;
  5691. }
  5692. lerp(color, alpha) {
  5693. this.r += (color.r - this.r) * alpha;
  5694. this.g += (color.g - this.g) * alpha;
  5695. this.b += (color.b - this.b) * alpha;
  5696. return this;
  5697. }
  5698. lerpColors(color1, color2, alpha) {
  5699. this.r = color1.r + (color2.r - color1.r) * alpha;
  5700. this.g = color1.g + (color2.g - color1.g) * alpha;
  5701. this.b = color1.b + (color2.b - color1.b) * alpha;
  5702. return this;
  5703. }
  5704. lerpHSL(color, alpha) {
  5705. this.getHSL(_hslA);
  5706. color.getHSL(_hslB);
  5707. const h = lerp(_hslA.h, _hslB.h, alpha);
  5708. const s = lerp(_hslA.s, _hslB.s, alpha);
  5709. const l = lerp(_hslA.l, _hslB.l, alpha);
  5710. this.setHSL(h, s, l);
  5711. return this;
  5712. }
  5713. equals(c) {
  5714. return c.r === this.r && c.g === this.g && c.b === this.b;
  5715. }
  5716. fromArray(array, offset = 0) {
  5717. this.r = array[offset];
  5718. this.g = array[offset + 1];
  5719. this.b = array[offset + 2];
  5720. return this;
  5721. }
  5722. toArray(array = [], offset = 0) {
  5723. array[offset] = this.r;
  5724. array[offset + 1] = this.g;
  5725. array[offset + 2] = this.b;
  5726. return array;
  5727. }
  5728. fromBufferAttribute(attribute, index) {
  5729. this.r = attribute.getX(index);
  5730. this.g = attribute.getY(index);
  5731. this.b = attribute.getZ(index);
  5732. if (attribute.normalized === true) {
  5733. // assuming Uint8Array
  5734. this.r /= 255;
  5735. this.g /= 255;
  5736. this.b /= 255;
  5737. }
  5738. return this;
  5739. }
  5740. toJSON() {
  5741. return this.getHex();
  5742. }
  5743. }
  5744. Color.NAMES = _colorKeywords;
  5745. Color.prototype.isColor = true;
  5746. Color.prototype.r = 1;
  5747. Color.prototype.g = 1;
  5748. Color.prototype.b = 1;
  5749. /**
  5750. * parameters = {
  5751. * color: <hex>,
  5752. * opacity: <float>,
  5753. * map: new THREE.Texture( <Image> ),
  5754. *
  5755. * lightMap: new THREE.Texture( <Image> ),
  5756. * lightMapIntensity: <float>
  5757. *
  5758. * aoMap: new THREE.Texture( <Image> ),
  5759. * aoMapIntensity: <float>
  5760. *
  5761. * specularMap: new THREE.Texture( <Image> ),
  5762. *
  5763. * alphaMap: new THREE.Texture( <Image> ),
  5764. *
  5765. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  5766. * combine: THREE.Multiply,
  5767. * reflectivity: <float>,
  5768. * refractionRatio: <float>,
  5769. *
  5770. * depthTest: <bool>,
  5771. * depthWrite: <bool>,
  5772. *
  5773. * wireframe: <boolean>,
  5774. * wireframeLinewidth: <float>,
  5775. *
  5776. * morphTargets: <bool>
  5777. * }
  5778. */
  5779. class MeshBasicMaterial extends Material {
  5780. constructor(parameters) {
  5781. super();
  5782. this.type = 'MeshBasicMaterial';
  5783. this.color = new Color(0xffffff); // emissive
  5784. this.map = null;
  5785. this.lightMap = null;
  5786. this.lightMapIntensity = 1.0;
  5787. this.aoMap = null;
  5788. this.aoMapIntensity = 1.0;
  5789. this.specularMap = null;
  5790. this.alphaMap = null;
  5791. this.envMap = null;
  5792. this.combine = MultiplyOperation;
  5793. this.reflectivity = 1;
  5794. this.refractionRatio = 0.98;
  5795. this.wireframe = false;
  5796. this.wireframeLinewidth = 1;
  5797. this.wireframeLinecap = 'round';
  5798. this.wireframeLinejoin = 'round';
  5799. this.morphTargets = false;
  5800. this.setValues(parameters);
  5801. }
  5802. copy(source) {
  5803. super.copy(source);
  5804. this.color.copy(source.color);
  5805. this.map = source.map;
  5806. this.lightMap = source.lightMap;
  5807. this.lightMapIntensity = source.lightMapIntensity;
  5808. this.aoMap = source.aoMap;
  5809. this.aoMapIntensity = source.aoMapIntensity;
  5810. this.specularMap = source.specularMap;
  5811. this.alphaMap = source.alphaMap;
  5812. this.envMap = source.envMap;
  5813. this.combine = source.combine;
  5814. this.reflectivity = source.reflectivity;
  5815. this.refractionRatio = source.refractionRatio;
  5816. this.wireframe = source.wireframe;
  5817. this.wireframeLinewidth = source.wireframeLinewidth;
  5818. this.wireframeLinecap = source.wireframeLinecap;
  5819. this.wireframeLinejoin = source.wireframeLinejoin;
  5820. this.morphTargets = source.morphTargets;
  5821. return this;
  5822. }
  5823. }
  5824. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  5825. const _vector$9 = /*@__PURE__*/new Vector3();
  5826. const _vector2 = /*@__PURE__*/new Vector2();
  5827. class BufferAttribute {
  5828. constructor(array, itemSize, normalized) {
  5829. if (Array.isArray(array)) {
  5830. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  5831. }
  5832. this.name = '';
  5833. this.array = array;
  5834. this.itemSize = itemSize;
  5835. this.count = array !== undefined ? array.length / itemSize : 0;
  5836. this.normalized = normalized === true;
  5837. this.usage = StaticDrawUsage;
  5838. this.updateRange = {
  5839. offset: 0,
  5840. count: -1
  5841. };
  5842. this.version = 0;
  5843. }
  5844. onUploadCallback() {}
  5845. set needsUpdate(value) {
  5846. if (value === true) this.version++;
  5847. }
  5848. setUsage(value) {
  5849. this.usage = value;
  5850. return this;
  5851. }
  5852. copy(source) {
  5853. this.name = source.name;
  5854. this.array = new source.array.constructor(source.array);
  5855. this.itemSize = source.itemSize;
  5856. this.count = source.count;
  5857. this.normalized = source.normalized;
  5858. this.usage = source.usage;
  5859. return this;
  5860. }
  5861. copyAt(index1, attribute, index2) {
  5862. index1 *= this.itemSize;
  5863. index2 *= attribute.itemSize;
  5864. for (let i = 0, l = this.itemSize; i < l; i++) {
  5865. this.array[index1 + i] = attribute.array[index2 + i];
  5866. }
  5867. return this;
  5868. }
  5869. copyArray(array) {
  5870. this.array.set(array);
  5871. return this;
  5872. }
  5873. copyColorsArray(colors) {
  5874. const array = this.array;
  5875. let offset = 0;
  5876. for (let i = 0, l = colors.length; i < l; i++) {
  5877. let color = colors[i];
  5878. if (color === undefined) {
  5879. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  5880. color = new Color();
  5881. }
  5882. array[offset++] = color.r;
  5883. array[offset++] = color.g;
  5884. array[offset++] = color.b;
  5885. }
  5886. return this;
  5887. }
  5888. copyVector2sArray(vectors) {
  5889. const array = this.array;
  5890. let offset = 0;
  5891. for (let i = 0, l = vectors.length; i < l; i++) {
  5892. let vector = vectors[i];
  5893. if (vector === undefined) {
  5894. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  5895. vector = new Vector2();
  5896. }
  5897. array[offset++] = vector.x;
  5898. array[offset++] = vector.y;
  5899. }
  5900. return this;
  5901. }
  5902. copyVector3sArray(vectors) {
  5903. const array = this.array;
  5904. let offset = 0;
  5905. for (let i = 0, l = vectors.length; i < l; i++) {
  5906. let vector = vectors[i];
  5907. if (vector === undefined) {
  5908. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  5909. vector = new Vector3();
  5910. }
  5911. array[offset++] = vector.x;
  5912. array[offset++] = vector.y;
  5913. array[offset++] = vector.z;
  5914. }
  5915. return this;
  5916. }
  5917. copyVector4sArray(vectors) {
  5918. const array = this.array;
  5919. let offset = 0;
  5920. for (let i = 0, l = vectors.length; i < l; i++) {
  5921. let vector = vectors[i];
  5922. if (vector === undefined) {
  5923. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  5924. vector = new Vector4();
  5925. }
  5926. array[offset++] = vector.x;
  5927. array[offset++] = vector.y;
  5928. array[offset++] = vector.z;
  5929. array[offset++] = vector.w;
  5930. }
  5931. return this;
  5932. }
  5933. applyMatrix3(m) {
  5934. if (this.itemSize === 2) {
  5935. for (let i = 0, l = this.count; i < l; i++) {
  5936. _vector2.fromBufferAttribute(this, i);
  5937. _vector2.applyMatrix3(m);
  5938. this.setXY(i, _vector2.x, _vector2.y);
  5939. }
  5940. } else if (this.itemSize === 3) {
  5941. for (let i = 0, l = this.count; i < l; i++) {
  5942. _vector$9.fromBufferAttribute(this, i);
  5943. _vector$9.applyMatrix3(m);
  5944. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5945. }
  5946. }
  5947. return this;
  5948. }
  5949. applyMatrix4(m) {
  5950. for (let i = 0, l = this.count; i < l; i++) {
  5951. _vector$9.x = this.getX(i);
  5952. _vector$9.y = this.getY(i);
  5953. _vector$9.z = this.getZ(i);
  5954. _vector$9.applyMatrix4(m);
  5955. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5956. }
  5957. return this;
  5958. }
  5959. applyNormalMatrix(m) {
  5960. for (let i = 0, l = this.count; i < l; i++) {
  5961. _vector$9.x = this.getX(i);
  5962. _vector$9.y = this.getY(i);
  5963. _vector$9.z = this.getZ(i);
  5964. _vector$9.applyNormalMatrix(m);
  5965. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5966. }
  5967. return this;
  5968. }
  5969. transformDirection(m) {
  5970. for (let i = 0, l = this.count; i < l; i++) {
  5971. _vector$9.x = this.getX(i);
  5972. _vector$9.y = this.getY(i);
  5973. _vector$9.z = this.getZ(i);
  5974. _vector$9.transformDirection(m);
  5975. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  5976. }
  5977. return this;
  5978. }
  5979. set(value, offset = 0) {
  5980. this.array.set(value, offset);
  5981. return this;
  5982. }
  5983. getX(index) {
  5984. return this.array[index * this.itemSize];
  5985. }
  5986. setX(index, x) {
  5987. this.array[index * this.itemSize] = x;
  5988. return this;
  5989. }
  5990. getY(index) {
  5991. return this.array[index * this.itemSize + 1];
  5992. }
  5993. setY(index, y) {
  5994. this.array[index * this.itemSize + 1] = y;
  5995. return this;
  5996. }
  5997. getZ(index) {
  5998. return this.array[index * this.itemSize + 2];
  5999. }
  6000. setZ(index, z) {
  6001. this.array[index * this.itemSize + 2] = z;
  6002. return this;
  6003. }
  6004. getW(index) {
  6005. return this.array[index * this.itemSize + 3];
  6006. }
  6007. setW(index, w) {
  6008. this.array[index * this.itemSize + 3] = w;
  6009. return this;
  6010. }
  6011. setXY(index, x, y) {
  6012. index *= this.itemSize;
  6013. this.array[index + 0] = x;
  6014. this.array[index + 1] = y;
  6015. return this;
  6016. }
  6017. setXYZ(index, x, y, z) {
  6018. index *= this.itemSize;
  6019. this.array[index + 0] = x;
  6020. this.array[index + 1] = y;
  6021. this.array[index + 2] = z;
  6022. return this;
  6023. }
  6024. setXYZW(index, x, y, z, w) {
  6025. index *= this.itemSize;
  6026. this.array[index + 0] = x;
  6027. this.array[index + 1] = y;
  6028. this.array[index + 2] = z;
  6029. this.array[index + 3] = w;
  6030. return this;
  6031. }
  6032. onUpload(callback) {
  6033. this.onUploadCallback = callback;
  6034. return this;
  6035. }
  6036. clone() {
  6037. return new this.constructor(this.array, this.itemSize).copy(this);
  6038. }
  6039. toJSON() {
  6040. const data = {
  6041. itemSize: this.itemSize,
  6042. type: this.array.constructor.name,
  6043. array: Array.prototype.slice.call(this.array),
  6044. normalized: this.normalized
  6045. };
  6046. if (this.name !== '') data.name = this.name;
  6047. if (this.usage !== StaticDrawUsage) data.usage = this.usage;
  6048. if (this.updateRange.offset !== 0 || this.updateRange.count !== -1) data.updateRange = this.updateRange;
  6049. return data;
  6050. }
  6051. }
  6052. BufferAttribute.prototype.isBufferAttribute = true; //
  6053. class Int8BufferAttribute extends BufferAttribute {
  6054. constructor(array, itemSize, normalized) {
  6055. super(new Int8Array(array), itemSize, normalized);
  6056. }
  6057. }
  6058. class Uint8BufferAttribute extends BufferAttribute {
  6059. constructor(array, itemSize, normalized) {
  6060. super(new Uint8Array(array), itemSize, normalized);
  6061. }
  6062. }
  6063. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6064. constructor(array, itemSize, normalized) {
  6065. super(new Uint8ClampedArray(array), itemSize, normalized);
  6066. }
  6067. }
  6068. class Int16BufferAttribute extends BufferAttribute {
  6069. constructor(array, itemSize, normalized) {
  6070. super(new Int16Array(array), itemSize, normalized);
  6071. }
  6072. }
  6073. class Uint16BufferAttribute extends BufferAttribute {
  6074. constructor(array, itemSize, normalized) {
  6075. super(new Uint16Array(array), itemSize, normalized);
  6076. }
  6077. }
  6078. class Int32BufferAttribute extends BufferAttribute {
  6079. constructor(array, itemSize, normalized) {
  6080. super(new Int32Array(array), itemSize, normalized);
  6081. }
  6082. }
  6083. class Uint32BufferAttribute extends BufferAttribute {
  6084. constructor(array, itemSize, normalized) {
  6085. super(new Uint32Array(array), itemSize, normalized);
  6086. }
  6087. }
  6088. class Float16BufferAttribute extends BufferAttribute {
  6089. constructor(array, itemSize, normalized) {
  6090. super(new Uint16Array(array), itemSize, normalized);
  6091. }
  6092. }
  6093. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  6094. class Float32BufferAttribute extends BufferAttribute {
  6095. constructor(array, itemSize, normalized) {
  6096. super(new Float32Array(array), itemSize, normalized);
  6097. }
  6098. }
  6099. class Float64BufferAttribute extends BufferAttribute {
  6100. constructor(array, itemSize, normalized) {
  6101. super(new Float64Array(array), itemSize, normalized);
  6102. }
  6103. } //
  6104. function arrayMax(array) {
  6105. if (array.length === 0) return -Infinity;
  6106. let max = array[0];
  6107. for (let i = 1, l = array.length; i < l; ++i) {
  6108. if (array[i] > max) max = array[i];
  6109. }
  6110. return max;
  6111. }
  6112. const TYPED_ARRAYS = {
  6113. Int8Array: Int8Array,
  6114. Uint8Array: Uint8Array,
  6115. Uint8ClampedArray: Uint8ClampedArray,
  6116. Int16Array: Int16Array,
  6117. Uint16Array: Uint16Array,
  6118. Int32Array: Int32Array,
  6119. Uint32Array: Uint32Array,
  6120. Float32Array: Float32Array,
  6121. Float64Array: Float64Array
  6122. };
  6123. function getTypedArray(type, buffer) {
  6124. return new TYPED_ARRAYS[type](buffer);
  6125. }
  6126. let _id = 0;
  6127. const _m1 = /*@__PURE__*/new Matrix4();
  6128. const _obj = /*@__PURE__*/new Object3D();
  6129. const _offset = /*@__PURE__*/new Vector3();
  6130. const _box$1 = /*@__PURE__*/new Box3();
  6131. const _boxMorphTargets = /*@__PURE__*/new Box3();
  6132. const _vector$8 = /*@__PURE__*/new Vector3();
  6133. class BufferGeometry extends EventDispatcher {
  6134. constructor() {
  6135. super();
  6136. Object.defineProperty(this, 'id', {
  6137. value: _id++
  6138. });
  6139. this.uuid = generateUUID();
  6140. this.name = '';
  6141. this.type = 'BufferGeometry';
  6142. this.index = null;
  6143. this.attributes = {};
  6144. this.morphAttributes = {};
  6145. this.morphTargetsRelative = false;
  6146. this.groups = [];
  6147. this.boundingBox = null;
  6148. this.boundingSphere = null;
  6149. this.drawRange = {
  6150. start: 0,
  6151. count: Infinity
  6152. };
  6153. this.userData = {};
  6154. }
  6155. getIndex() {
  6156. return this.index;
  6157. }
  6158. setIndex(index) {
  6159. if (Array.isArray(index)) {
  6160. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  6161. } else {
  6162. this.index = index;
  6163. }
  6164. return this;
  6165. }
  6166. getAttribute(name) {
  6167. return this.attributes[name];
  6168. }
  6169. setAttribute(name, attribute) {
  6170. this.attributes[name] = attribute;
  6171. return this;
  6172. }
  6173. deleteAttribute(name) {
  6174. delete this.attributes[name];
  6175. return this;
  6176. }
  6177. hasAttribute(name) {
  6178. return this.attributes[name] !== undefined;
  6179. }
  6180. addGroup(start, count, materialIndex = 0) {
  6181. this.groups.push({
  6182. start: start,
  6183. count: count,
  6184. materialIndex: materialIndex
  6185. });
  6186. }
  6187. clearGroups() {
  6188. this.groups = [];
  6189. }
  6190. setDrawRange(start, count) {
  6191. this.drawRange.start = start;
  6192. this.drawRange.count = count;
  6193. }
  6194. applyMatrix4(matrix) {
  6195. const position = this.attributes.position;
  6196. if (position !== undefined) {
  6197. position.applyMatrix4(matrix);
  6198. position.needsUpdate = true;
  6199. }
  6200. const normal = this.attributes.normal;
  6201. if (normal !== undefined) {
  6202. const normalMatrix = new Matrix3().getNormalMatrix(matrix);
  6203. normal.applyNormalMatrix(normalMatrix);
  6204. normal.needsUpdate = true;
  6205. }
  6206. const tangent = this.attributes.tangent;
  6207. if (tangent !== undefined) {
  6208. tangent.transformDirection(matrix);
  6209. tangent.needsUpdate = true;
  6210. }
  6211. if (this.boundingBox !== null) {
  6212. this.computeBoundingBox();
  6213. }
  6214. if (this.boundingSphere !== null) {
  6215. this.computeBoundingSphere();
  6216. }
  6217. return this;
  6218. }
  6219. applyQuaternion(q) {
  6220. _m1.makeRotationFromQuaternion(q);
  6221. this.applyMatrix4(_m1);
  6222. return this;
  6223. }
  6224. rotateX(angle) {
  6225. // rotate geometry around world x-axis
  6226. _m1.makeRotationX(angle);
  6227. this.applyMatrix4(_m1);
  6228. return this;
  6229. }
  6230. rotateY(angle) {
  6231. // rotate geometry around world y-axis
  6232. _m1.makeRotationY(angle);
  6233. this.applyMatrix4(_m1);
  6234. return this;
  6235. }
  6236. rotateZ(angle) {
  6237. // rotate geometry around world z-axis
  6238. _m1.makeRotationZ(angle);
  6239. this.applyMatrix4(_m1);
  6240. return this;
  6241. }
  6242. translate(x, y, z) {
  6243. // translate geometry
  6244. _m1.makeTranslation(x, y, z);
  6245. this.applyMatrix4(_m1);
  6246. return this;
  6247. }
  6248. scale(x, y, z) {
  6249. // scale geometry
  6250. _m1.makeScale(x, y, z);
  6251. this.applyMatrix4(_m1);
  6252. return this;
  6253. }
  6254. lookAt(vector) {
  6255. _obj.lookAt(vector);
  6256. _obj.updateMatrix();
  6257. this.applyMatrix4(_obj.matrix);
  6258. return this;
  6259. }
  6260. center() {
  6261. this.computeBoundingBox();
  6262. this.boundingBox.getCenter(_offset).negate();
  6263. this.translate(_offset.x, _offset.y, _offset.z);
  6264. return this;
  6265. }
  6266. setFromPoints(points) {
  6267. const position = [];
  6268. for (let i = 0, l = points.length; i < l; i++) {
  6269. const point = points[i];
  6270. position.push(point.x, point.y, point.z || 0);
  6271. }
  6272. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  6273. return this;
  6274. }
  6275. computeBoundingBox() {
  6276. if (this.boundingBox === null) {
  6277. this.boundingBox = new Box3();
  6278. }
  6279. const position = this.attributes.position;
  6280. const morphAttributesPosition = this.morphAttributes.position;
  6281. if (position && position.isGLBufferAttribute) {
  6282. console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
  6283. this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
  6284. return;
  6285. }
  6286. if (position !== undefined) {
  6287. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  6288. if (morphAttributesPosition) {
  6289. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6290. const morphAttribute = morphAttributesPosition[i];
  6291. _box$1.setFromBufferAttribute(morphAttribute);
  6292. if (this.morphTargetsRelative) {
  6293. _vector$8.addVectors(this.boundingBox.min, _box$1.min);
  6294. this.boundingBox.expandByPoint(_vector$8);
  6295. _vector$8.addVectors(this.boundingBox.max, _box$1.max);
  6296. this.boundingBox.expandByPoint(_vector$8);
  6297. } else {
  6298. this.boundingBox.expandByPoint(_box$1.min);
  6299. this.boundingBox.expandByPoint(_box$1.max);
  6300. }
  6301. }
  6302. }
  6303. } else {
  6304. this.boundingBox.makeEmpty();
  6305. }
  6306. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  6307. console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  6308. }
  6309. }
  6310. computeBoundingSphere() {
  6311. if (this.boundingSphere === null) {
  6312. this.boundingSphere = new Sphere();
  6313. }
  6314. const position = this.attributes.position;
  6315. const morphAttributesPosition = this.morphAttributes.position;
  6316. if (position && position.isGLBufferAttribute) {
  6317. console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
  6318. this.boundingSphere.set(new Vector3(), Infinity);
  6319. return;
  6320. }
  6321. if (position) {
  6322. // first, find the center of the bounding sphere
  6323. const center = this.boundingSphere.center;
  6324. _box$1.setFromBufferAttribute(position); // process morph attributes if present
  6325. if (morphAttributesPosition) {
  6326. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6327. const morphAttribute = morphAttributesPosition[i];
  6328. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  6329. if (this.morphTargetsRelative) {
  6330. _vector$8.addVectors(_box$1.min, _boxMorphTargets.min);
  6331. _box$1.expandByPoint(_vector$8);
  6332. _vector$8.addVectors(_box$1.max, _boxMorphTargets.max);
  6333. _box$1.expandByPoint(_vector$8);
  6334. } else {
  6335. _box$1.expandByPoint(_boxMorphTargets.min);
  6336. _box$1.expandByPoint(_boxMorphTargets.max);
  6337. }
  6338. }
  6339. }
  6340. _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  6341. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6342. let maxRadiusSq = 0;
  6343. for (let i = 0, il = position.count; i < il; i++) {
  6344. _vector$8.fromBufferAttribute(position, i);
  6345. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6346. } // process morph attributes if present
  6347. if (morphAttributesPosition) {
  6348. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6349. const morphAttribute = morphAttributesPosition[i];
  6350. const morphTargetsRelative = this.morphTargetsRelative;
  6351. for (let j = 0, jl = morphAttribute.count; j < jl; j++) {
  6352. _vector$8.fromBufferAttribute(morphAttribute, j);
  6353. if (morphTargetsRelative) {
  6354. _offset.fromBufferAttribute(position, j);
  6355. _vector$8.add(_offset);
  6356. }
  6357. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6358. }
  6359. }
  6360. }
  6361. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  6362. if (isNaN(this.boundingSphere.radius)) {
  6363. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  6364. }
  6365. }
  6366. }
  6367. computeFaceNormals() {// backwards compatibility
  6368. }
  6369. computeTangents() {
  6370. const index = this.index;
  6371. const attributes = this.attributes; // based on http://www.terathon.com/code/tangent.html
  6372. // (per vertex tangents)
  6373. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  6374. console.error('THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)');
  6375. return;
  6376. }
  6377. const indices = index.array;
  6378. const positions = attributes.position.array;
  6379. const normals = attributes.normal.array;
  6380. const uvs = attributes.uv.array;
  6381. const nVertices = positions.length / 3;
  6382. if (attributes.tangent === undefined) {
  6383. this.setAttribute('tangent', new BufferAttribute(new Float32Array(4 * nVertices), 4));
  6384. }
  6385. const tangents = attributes.tangent.array;
  6386. const tan1 = [],
  6387. tan2 = [];
  6388. for (let i = 0; i < nVertices; i++) {
  6389. tan1[i] = new Vector3();
  6390. tan2[i] = new Vector3();
  6391. }
  6392. const vA = new Vector3(),
  6393. vB = new Vector3(),
  6394. vC = new Vector3(),
  6395. uvA = new Vector2(),
  6396. uvB = new Vector2(),
  6397. uvC = new Vector2(),
  6398. sdir = new Vector3(),
  6399. tdir = new Vector3();
  6400. function handleTriangle(a, b, c) {
  6401. vA.fromArray(positions, a * 3);
  6402. vB.fromArray(positions, b * 3);
  6403. vC.fromArray(positions, c * 3);
  6404. uvA.fromArray(uvs, a * 2);
  6405. uvB.fromArray(uvs, b * 2);
  6406. uvC.fromArray(uvs, c * 2);
  6407. vB.sub(vA);
  6408. vC.sub(vA);
  6409. uvB.sub(uvA);
  6410. uvC.sub(uvA);
  6411. const r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y); // silently ignore degenerate uv triangles having coincident or colinear vertices
  6412. if (!isFinite(r)) return;
  6413. sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
  6414. tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
  6415. tan1[a].add(sdir);
  6416. tan1[b].add(sdir);
  6417. tan1[c].add(sdir);
  6418. tan2[a].add(tdir);
  6419. tan2[b].add(tdir);
  6420. tan2[c].add(tdir);
  6421. }
  6422. let groups = this.groups;
  6423. if (groups.length === 0) {
  6424. groups = [{
  6425. start: 0,
  6426. count: indices.length
  6427. }];
  6428. }
  6429. for (let i = 0, il = groups.length; i < il; ++i) {
  6430. const group = groups[i];
  6431. const start = group.start;
  6432. const count = group.count;
  6433. for (let j = start, jl = start + count; j < jl; j += 3) {
  6434. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  6435. }
  6436. }
  6437. const tmp = new Vector3(),
  6438. tmp2 = new Vector3();
  6439. const n = new Vector3(),
  6440. n2 = new Vector3();
  6441. function handleVertex(v) {
  6442. n.fromArray(normals, v * 3);
  6443. n2.copy(n);
  6444. const t = tan1[v]; // Gram-Schmidt orthogonalize
  6445. tmp.copy(t);
  6446. tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
  6447. tmp2.crossVectors(n2, t);
  6448. const test = tmp2.dot(tan2[v]);
  6449. const w = test < 0.0 ? -1.0 : 1.0;
  6450. tangents[v * 4] = tmp.x;
  6451. tangents[v * 4 + 1] = tmp.y;
  6452. tangents[v * 4 + 2] = tmp.z;
  6453. tangents[v * 4 + 3] = w;
  6454. }
  6455. for (let i = 0, il = groups.length; i < il; ++i) {
  6456. const group = groups[i];
  6457. const start = group.start;
  6458. const count = group.count;
  6459. for (let j = start, jl = start + count; j < jl; j += 3) {
  6460. handleVertex(indices[j + 0]);
  6461. handleVertex(indices[j + 1]);
  6462. handleVertex(indices[j + 2]);
  6463. }
  6464. }
  6465. }
  6466. computeVertexNormals() {
  6467. const index = this.index;
  6468. const positionAttribute = this.getAttribute('position');
  6469. if (positionAttribute !== undefined) {
  6470. let normalAttribute = this.getAttribute('normal');
  6471. if (normalAttribute === undefined) {
  6472. normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
  6473. this.setAttribute('normal', normalAttribute);
  6474. } else {
  6475. // reset existing normals to zero
  6476. for (let i = 0, il = normalAttribute.count; i < il; i++) {
  6477. normalAttribute.setXYZ(i, 0, 0, 0);
  6478. }
  6479. }
  6480. const pA = new Vector3(),
  6481. pB = new Vector3(),
  6482. pC = new Vector3();
  6483. const nA = new Vector3(),
  6484. nB = new Vector3(),
  6485. nC = new Vector3();
  6486. const cb = new Vector3(),
  6487. ab = new Vector3(); // indexed elements
  6488. if (index) {
  6489. for (let i = 0, il = index.count; i < il; i += 3) {
  6490. const vA = index.getX(i + 0);
  6491. const vB = index.getX(i + 1);
  6492. const vC = index.getX(i + 2);
  6493. pA.fromBufferAttribute(positionAttribute, vA);
  6494. pB.fromBufferAttribute(positionAttribute, vB);
  6495. pC.fromBufferAttribute(positionAttribute, vC);
  6496. cb.subVectors(pC, pB);
  6497. ab.subVectors(pA, pB);
  6498. cb.cross(ab);
  6499. nA.fromBufferAttribute(normalAttribute, vA);
  6500. nB.fromBufferAttribute(normalAttribute, vB);
  6501. nC.fromBufferAttribute(normalAttribute, vC);
  6502. nA.add(cb);
  6503. nB.add(cb);
  6504. nC.add(cb);
  6505. normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
  6506. normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
  6507. normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
  6508. }
  6509. } else {
  6510. // non-indexed elements (unconnected triangle soup)
  6511. for (let i = 0, il = positionAttribute.count; i < il; i += 3) {
  6512. pA.fromBufferAttribute(positionAttribute, i + 0);
  6513. pB.fromBufferAttribute(positionAttribute, i + 1);
  6514. pC.fromBufferAttribute(positionAttribute, i + 2);
  6515. cb.subVectors(pC, pB);
  6516. ab.subVectors(pA, pB);
  6517. cb.cross(ab);
  6518. normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z);
  6519. normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z);
  6520. normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z);
  6521. }
  6522. }
  6523. this.normalizeNormals();
  6524. normalAttribute.needsUpdate = true;
  6525. }
  6526. }
  6527. merge(geometry, offset) {
  6528. if (!(geometry && geometry.isBufferGeometry)) {
  6529. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  6530. return;
  6531. }
  6532. if (offset === undefined) {
  6533. offset = 0;
  6534. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  6535. }
  6536. const attributes = this.attributes;
  6537. for (const key in attributes) {
  6538. if (geometry.attributes[key] === undefined) continue;
  6539. const attribute1 = attributes[key];
  6540. const attributeArray1 = attribute1.array;
  6541. const attribute2 = geometry.attributes[key];
  6542. const attributeArray2 = attribute2.array;
  6543. const attributeOffset = attribute2.itemSize * offset;
  6544. const length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  6545. for (let i = 0, j = attributeOffset; i < length; i++, j++) {
  6546. attributeArray1[j] = attributeArray2[i];
  6547. }
  6548. }
  6549. return this;
  6550. }
  6551. normalizeNormals() {
  6552. const normals = this.attributes.normal;
  6553. for (let i = 0, il = normals.count; i < il; i++) {
  6554. _vector$8.fromBufferAttribute(normals, i);
  6555. _vector$8.normalize();
  6556. normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z);
  6557. }
  6558. }
  6559. toNonIndexed() {
  6560. function convertBufferAttribute(attribute, indices) {
  6561. const array = attribute.array;
  6562. const itemSize = attribute.itemSize;
  6563. const normalized = attribute.normalized;
  6564. const array2 = new array.constructor(indices.length * itemSize);
  6565. let index = 0,
  6566. index2 = 0;
  6567. for (let i = 0, l = indices.length; i < l; i++) {
  6568. index = indices[i] * itemSize;
  6569. for (let j = 0; j < itemSize; j++) {
  6570. array2[index2++] = array[index++];
  6571. }
  6572. }
  6573. return new BufferAttribute(array2, itemSize, normalized);
  6574. } //
  6575. if (this.index === null) {
  6576. console.warn('THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.');
  6577. return this;
  6578. }
  6579. const geometry2 = new BufferGeometry();
  6580. const indices = this.index.array;
  6581. const attributes = this.attributes; // attributes
  6582. for (const name in attributes) {
  6583. const attribute = attributes[name];
  6584. const newAttribute = convertBufferAttribute(attribute, indices);
  6585. geometry2.setAttribute(name, newAttribute);
  6586. } // morph attributes
  6587. const morphAttributes = this.morphAttributes;
  6588. for (const name in morphAttributes) {
  6589. const morphArray = [];
  6590. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6591. for (let i = 0, il = morphAttribute.length; i < il; i++) {
  6592. const attribute = morphAttribute[i];
  6593. const newAttribute = convertBufferAttribute(attribute, indices);
  6594. morphArray.push(newAttribute);
  6595. }
  6596. geometry2.morphAttributes[name] = morphArray;
  6597. }
  6598. geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
  6599. const groups = this.groups;
  6600. for (let i = 0, l = groups.length; i < l; i++) {
  6601. const group = groups[i];
  6602. geometry2.addGroup(group.start, group.count, group.materialIndex);
  6603. }
  6604. return geometry2;
  6605. }
  6606. toJSON() {
  6607. const data = {
  6608. metadata: {
  6609. version: 4.5,
  6610. type: 'BufferGeometry',
  6611. generator: 'BufferGeometry.toJSON'
  6612. }
  6613. }; // standard BufferGeometry serialization
  6614. data.uuid = this.uuid;
  6615. data.type = this.type;
  6616. if (this.name !== '') data.name = this.name;
  6617. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  6618. if (this.parameters !== undefined) {
  6619. const parameters = this.parameters;
  6620. for (const key in parameters) {
  6621. if (parameters[key] !== undefined) data[key] = parameters[key];
  6622. }
  6623. return data;
  6624. } // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6625. data.data = {
  6626. attributes: {}
  6627. };
  6628. const index = this.index;
  6629. if (index !== null) {
  6630. data.data.index = {
  6631. type: index.array.constructor.name,
  6632. array: Array.prototype.slice.call(index.array)
  6633. };
  6634. }
  6635. const attributes = this.attributes;
  6636. for (const key in attributes) {
  6637. const attribute = attributes[key];
  6638. data.data.attributes[key] = attribute.toJSON(data.data);
  6639. }
  6640. const morphAttributes = {};
  6641. let hasMorphAttributes = false;
  6642. for (const key in this.morphAttributes) {
  6643. const attributeArray = this.morphAttributes[key];
  6644. const array = [];
  6645. for (let i = 0, il = attributeArray.length; i < il; i++) {
  6646. const attribute = attributeArray[i];
  6647. array.push(attribute.toJSON(data.data));
  6648. }
  6649. if (array.length > 0) {
  6650. morphAttributes[key] = array;
  6651. hasMorphAttributes = true;
  6652. }
  6653. }
  6654. if (hasMorphAttributes) {
  6655. data.data.morphAttributes = morphAttributes;
  6656. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6657. }
  6658. const groups = this.groups;
  6659. if (groups.length > 0) {
  6660. data.data.groups = JSON.parse(JSON.stringify(groups));
  6661. }
  6662. const boundingSphere = this.boundingSphere;
  6663. if (boundingSphere !== null) {
  6664. data.data.boundingSphere = {
  6665. center: boundingSphere.center.toArray(),
  6666. radius: boundingSphere.radius
  6667. };
  6668. }
  6669. return data;
  6670. }
  6671. clone() {
  6672. /*
  6673. // Handle primitives
  6674. const parameters = this.parameters;
  6675. if ( parameters !== undefined ) {
  6676. const values = [];
  6677. for ( const key in parameters ) {
  6678. values.push( parameters[ key ] );
  6679. }
  6680. const geometry = Object.create( this.constructor.prototype );
  6681. this.constructor.apply( geometry, values );
  6682. return geometry;
  6683. }
  6684. return new this.constructor().copy( this );
  6685. */
  6686. return new BufferGeometry().copy(this);
  6687. }
  6688. copy(source) {
  6689. // reset
  6690. this.index = null;
  6691. this.attributes = {};
  6692. this.morphAttributes = {};
  6693. this.groups = [];
  6694. this.boundingBox = null;
  6695. this.boundingSphere = null; // used for storing cloned, shared data
  6696. const data = {}; // name
  6697. this.name = source.name; // index
  6698. const index = source.index;
  6699. if (index !== null) {
  6700. this.setIndex(index.clone(data));
  6701. } // attributes
  6702. const attributes = source.attributes;
  6703. for (const name in attributes) {
  6704. const attribute = attributes[name];
  6705. this.setAttribute(name, attribute.clone(data));
  6706. } // morph attributes
  6707. const morphAttributes = source.morphAttributes;
  6708. for (const name in morphAttributes) {
  6709. const array = [];
  6710. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6711. for (let i = 0, l = morphAttribute.length; i < l; i++) {
  6712. array.push(morphAttribute[i].clone(data));
  6713. }
  6714. this.morphAttributes[name] = array;
  6715. }
  6716. this.morphTargetsRelative = source.morphTargetsRelative; // groups
  6717. const groups = source.groups;
  6718. for (let i = 0, l = groups.length; i < l; i++) {
  6719. const group = groups[i];
  6720. this.addGroup(group.start, group.count, group.materialIndex);
  6721. } // bounding box
  6722. const boundingBox = source.boundingBox;
  6723. if (boundingBox !== null) {
  6724. this.boundingBox = boundingBox.clone();
  6725. } // bounding sphere
  6726. const boundingSphere = source.boundingSphere;
  6727. if (boundingSphere !== null) {
  6728. this.boundingSphere = boundingSphere.clone();
  6729. } // draw range
  6730. this.drawRange.start = source.drawRange.start;
  6731. this.drawRange.count = source.drawRange.count; // user data
  6732. this.userData = source.userData;
  6733. return this;
  6734. }
  6735. dispose() {
  6736. this.dispatchEvent({
  6737. type: 'dispose'
  6738. });
  6739. }
  6740. }
  6741. BufferGeometry.prototype.isBufferGeometry = true;
  6742. const _inverseMatrix$2 = /*@__PURE__*/new Matrix4();
  6743. const _ray$2 = /*@__PURE__*/new Ray();
  6744. const _sphere$3 = /*@__PURE__*/new Sphere();
  6745. const _vA$1 = /*@__PURE__*/new Vector3();
  6746. const _vB$1 = /*@__PURE__*/new Vector3();
  6747. const _vC$1 = /*@__PURE__*/new Vector3();
  6748. const _tempA = /*@__PURE__*/new Vector3();
  6749. const _tempB = /*@__PURE__*/new Vector3();
  6750. const _tempC = /*@__PURE__*/new Vector3();
  6751. const _morphA = /*@__PURE__*/new Vector3();
  6752. const _morphB = /*@__PURE__*/new Vector3();
  6753. const _morphC = /*@__PURE__*/new Vector3();
  6754. const _uvA$1 = /*@__PURE__*/new Vector2();
  6755. const _uvB$1 = /*@__PURE__*/new Vector2();
  6756. const _uvC$1 = /*@__PURE__*/new Vector2();
  6757. const _intersectionPoint = /*@__PURE__*/new Vector3();
  6758. const _intersectionPointWorld = /*@__PURE__*/new Vector3();
  6759. class Mesh extends Object3D {
  6760. constructor(geometry = new BufferGeometry(), material = new MeshBasicMaterial()) {
  6761. super();
  6762. this.type = 'Mesh';
  6763. this.geometry = geometry;
  6764. this.material = material;
  6765. this.updateMorphTargets();
  6766. }
  6767. copy(source) {
  6768. super.copy(source);
  6769. if (source.morphTargetInfluences !== undefined) {
  6770. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6771. }
  6772. if (source.morphTargetDictionary !== undefined) {
  6773. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  6774. }
  6775. this.material = source.material;
  6776. this.geometry = source.geometry;
  6777. return this;
  6778. }
  6779. updateMorphTargets() {
  6780. const geometry = this.geometry;
  6781. if (geometry.isBufferGeometry) {
  6782. const morphAttributes = geometry.morphAttributes;
  6783. const keys = Object.keys(morphAttributes);
  6784. if (keys.length > 0) {
  6785. const morphAttribute = morphAttributes[keys[0]];
  6786. if (morphAttribute !== undefined) {
  6787. this.morphTargetInfluences = [];
  6788. this.morphTargetDictionary = {};
  6789. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  6790. const name = morphAttribute[m].name || String(m);
  6791. this.morphTargetInfluences.push(0);
  6792. this.morphTargetDictionary[name] = m;
  6793. }
  6794. }
  6795. }
  6796. } else {
  6797. const morphTargets = geometry.morphTargets;
  6798. if (morphTargets !== undefined && morphTargets.length > 0) {
  6799. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6800. }
  6801. }
  6802. }
  6803. raycast(raycaster, intersects) {
  6804. const geometry = this.geometry;
  6805. const material = this.material;
  6806. const matrixWorld = this.matrixWorld;
  6807. if (material === undefined) return; // Checking boundingSphere distance to ray
  6808. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  6809. _sphere$3.copy(geometry.boundingSphere);
  6810. _sphere$3.applyMatrix4(matrixWorld);
  6811. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  6812. _inverseMatrix$2.copy(matrixWorld).invert();
  6813. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2); // Check boundingBox before continuing
  6814. if (geometry.boundingBox !== null) {
  6815. if (_ray$2.intersectsBox(geometry.boundingBox) === false) return;
  6816. }
  6817. let intersection;
  6818. if (geometry.isBufferGeometry) {
  6819. const index = geometry.index;
  6820. const position = geometry.attributes.position;
  6821. const morphPosition = geometry.morphAttributes.position;
  6822. const morphTargetsRelative = geometry.morphTargetsRelative;
  6823. const uv = geometry.attributes.uv;
  6824. const uv2 = geometry.attributes.uv2;
  6825. const groups = geometry.groups;
  6826. const drawRange = geometry.drawRange;
  6827. if (index !== null) {
  6828. // indexed buffer geometry
  6829. if (Array.isArray(material)) {
  6830. for (let i = 0, il = groups.length; i < il; i++) {
  6831. const group = groups[i];
  6832. const groupMaterial = material[group.materialIndex];
  6833. const start = Math.max(group.start, drawRange.start);
  6834. const end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  6835. for (let j = start, jl = end; j < jl; j += 3) {
  6836. const a = index.getX(j);
  6837. const b = index.getX(j + 1);
  6838. const c = index.getX(j + 2);
  6839. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6840. if (intersection) {
  6841. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  6842. intersection.face.materialIndex = group.materialIndex;
  6843. intersects.push(intersection);
  6844. }
  6845. }
  6846. }
  6847. } else {
  6848. const start = Math.max(0, drawRange.start);
  6849. const end = Math.min(index.count, drawRange.start + drawRange.count);
  6850. for (let i = start, il = end; i < il; i += 3) {
  6851. const a = index.getX(i);
  6852. const b = index.getX(i + 1);
  6853. const c = index.getX(i + 2);
  6854. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6855. if (intersection) {
  6856. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  6857. intersects.push(intersection);
  6858. }
  6859. }
  6860. }
  6861. } else if (position !== undefined) {
  6862. // non-indexed buffer geometry
  6863. if (Array.isArray(material)) {
  6864. for (let i = 0, il = groups.length; i < il; i++) {
  6865. const group = groups[i];
  6866. const groupMaterial = material[group.materialIndex];
  6867. const start = Math.max(group.start, drawRange.start);
  6868. const end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  6869. for (let j = start, jl = end; j < jl; j += 3) {
  6870. const a = j;
  6871. const b = j + 1;
  6872. const c = j + 2;
  6873. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6874. if (intersection) {
  6875. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  6876. intersection.face.materialIndex = group.materialIndex;
  6877. intersects.push(intersection);
  6878. }
  6879. }
  6880. }
  6881. } else {
  6882. const start = Math.max(0, drawRange.start);
  6883. const end = Math.min(position.count, drawRange.start + drawRange.count);
  6884. for (let i = start, il = end; i < il; i += 3) {
  6885. const a = i;
  6886. const b = i + 1;
  6887. const c = i + 2;
  6888. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6889. if (intersection) {
  6890. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  6891. intersects.push(intersection);
  6892. }
  6893. }
  6894. }
  6895. }
  6896. } else if (geometry.isGeometry) {
  6897. console.error('THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6898. }
  6899. }
  6900. }
  6901. Mesh.prototype.isMesh = true;
  6902. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  6903. let intersect;
  6904. if (material.side === BackSide) {
  6905. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  6906. } else {
  6907. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  6908. }
  6909. if (intersect === null) return null;
  6910. _intersectionPointWorld.copy(point);
  6911. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  6912. const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  6913. if (distance < raycaster.near || distance > raycaster.far) return null;
  6914. return {
  6915. distance: distance,
  6916. point: _intersectionPointWorld.clone(),
  6917. object: object
  6918. };
  6919. }
  6920. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  6921. _vA$1.fromBufferAttribute(position, a);
  6922. _vB$1.fromBufferAttribute(position, b);
  6923. _vC$1.fromBufferAttribute(position, c);
  6924. const morphInfluences = object.morphTargetInfluences;
  6925. if (material.morphTargets && morphPosition && morphInfluences) {
  6926. _morphA.set(0, 0, 0);
  6927. _morphB.set(0, 0, 0);
  6928. _morphC.set(0, 0, 0);
  6929. for (let i = 0, il = morphPosition.length; i < il; i++) {
  6930. const influence = morphInfluences[i];
  6931. const morphAttribute = morphPosition[i];
  6932. if (influence === 0) continue;
  6933. _tempA.fromBufferAttribute(morphAttribute, a);
  6934. _tempB.fromBufferAttribute(morphAttribute, b);
  6935. _tempC.fromBufferAttribute(morphAttribute, c);
  6936. if (morphTargetsRelative) {
  6937. _morphA.addScaledVector(_tempA, influence);
  6938. _morphB.addScaledVector(_tempB, influence);
  6939. _morphC.addScaledVector(_tempC, influence);
  6940. } else {
  6941. _morphA.addScaledVector(_tempA.sub(_vA$1), influence);
  6942. _morphB.addScaledVector(_tempB.sub(_vB$1), influence);
  6943. _morphC.addScaledVector(_tempC.sub(_vC$1), influence);
  6944. }
  6945. }
  6946. _vA$1.add(_morphA);
  6947. _vB$1.add(_morphB);
  6948. _vC$1.add(_morphC);
  6949. }
  6950. if (object.isSkinnedMesh) {
  6951. object.boneTransform(a, _vA$1);
  6952. object.boneTransform(b, _vB$1);
  6953. object.boneTransform(c, _vC$1);
  6954. }
  6955. const intersection = checkIntersection(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint);
  6956. if (intersection) {
  6957. if (uv) {
  6958. _uvA$1.fromBufferAttribute(uv, a);
  6959. _uvB$1.fromBufferAttribute(uv, b);
  6960. _uvC$1.fromBufferAttribute(uv, c);
  6961. intersection.uv = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6962. }
  6963. if (uv2) {
  6964. _uvA$1.fromBufferAttribute(uv2, a);
  6965. _uvB$1.fromBufferAttribute(uv2, b);
  6966. _uvC$1.fromBufferAttribute(uv2, c);
  6967. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  6968. }
  6969. const face = {
  6970. a: a,
  6971. b: b,
  6972. c: c,
  6973. normal: new Vector3(),
  6974. materialIndex: 0
  6975. };
  6976. Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal);
  6977. intersection.face = face;
  6978. }
  6979. return intersection;
  6980. }
  6981. class BoxGeometry extends BufferGeometry {
  6982. constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
  6983. super();
  6984. this.type = 'BoxGeometry';
  6985. this.parameters = {
  6986. width: width,
  6987. height: height,
  6988. depth: depth,
  6989. widthSegments: widthSegments,
  6990. heightSegments: heightSegments,
  6991. depthSegments: depthSegments
  6992. };
  6993. const scope = this; // segments
  6994. widthSegments = Math.floor(widthSegments);
  6995. heightSegments = Math.floor(heightSegments);
  6996. depthSegments = Math.floor(depthSegments); // buffers
  6997. const indices = [];
  6998. const vertices = [];
  6999. const normals = [];
  7000. const uvs = []; // helper variables
  7001. let numberOfVertices = 0;
  7002. let groupStart = 0; // build each side of the box geometry
  7003. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  7004. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  7005. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  7006. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  7007. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  7008. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  7009. // build geometry
  7010. this.setIndex(indices);
  7011. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  7012. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  7013. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  7014. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  7015. const segmentWidth = width / gridX;
  7016. const segmentHeight = height / gridY;
  7017. const widthHalf = width / 2;
  7018. const heightHalf = height / 2;
  7019. const depthHalf = depth / 2;
  7020. const gridX1 = gridX + 1;
  7021. const gridY1 = gridY + 1;
  7022. let vertexCounter = 0;
  7023. let groupCount = 0;
  7024. const vector = new Vector3(); // generate vertices, normals and uvs
  7025. for (let iy = 0; iy < gridY1; iy++) {
  7026. const y = iy * segmentHeight - heightHalf;
  7027. for (let ix = 0; ix < gridX1; ix++) {
  7028. const x = ix * segmentWidth - widthHalf; // set values to correct vector component
  7029. vector[u] = x * udir;
  7030. vector[v] = y * vdir;
  7031. vector[w] = depthHalf; // now apply vector to vertex buffer
  7032. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  7033. vector[u] = 0;
  7034. vector[v] = 0;
  7035. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  7036. normals.push(vector.x, vector.y, vector.z); // uvs
  7037. uvs.push(ix / gridX);
  7038. uvs.push(1 - iy / gridY); // counters
  7039. vertexCounter += 1;
  7040. }
  7041. } // indices
  7042. // 1. you need three indices to draw a single face
  7043. // 2. a single segment consists of two faces
  7044. // 3. so we need to generate six (2*3) indices per segment
  7045. for (let iy = 0; iy < gridY; iy++) {
  7046. for (let ix = 0; ix < gridX; ix++) {
  7047. const a = numberOfVertices + ix + gridX1 * iy;
  7048. const b = numberOfVertices + ix + gridX1 * (iy + 1);
  7049. const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  7050. const d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  7051. indices.push(a, b, d);
  7052. indices.push(b, c, d); // increase counter
  7053. groupCount += 6;
  7054. }
  7055. } // add a group to the geometry. this will ensure multi material support
  7056. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  7057. groupStart += groupCount; // update total number of vertices
  7058. numberOfVertices += vertexCounter;
  7059. }
  7060. }
  7061. }
  7062. /**
  7063. * Uniform Utilities
  7064. */
  7065. function cloneUniforms(src) {
  7066. const dst = {};
  7067. for (const u in src) {
  7068. dst[u] = {};
  7069. for (const p in src[u]) {
  7070. const property = src[u][p];
  7071. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion)) {
  7072. dst[u][p] = property.clone();
  7073. } else if (Array.isArray(property)) {
  7074. dst[u][p] = property.slice();
  7075. } else {
  7076. dst[u][p] = property;
  7077. }
  7078. }
  7079. }
  7080. return dst;
  7081. }
  7082. function mergeUniforms(uniforms) {
  7083. const merged = {};
  7084. for (let u = 0; u < uniforms.length; u++) {
  7085. const tmp = cloneUniforms(uniforms[u]);
  7086. for (const p in tmp) {
  7087. merged[p] = tmp[p];
  7088. }
  7089. }
  7090. return merged;
  7091. } // Legacy
  7092. const UniformsUtils = {
  7093. clone: cloneUniforms,
  7094. merge: mergeUniforms
  7095. };
  7096. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7097. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7098. /**
  7099. * parameters = {
  7100. * defines: { "label" : "value" },
  7101. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  7102. *
  7103. * fragmentShader: <string>,
  7104. * vertexShader: <string>,
  7105. *
  7106. * wireframe: <boolean>,
  7107. * wireframeLinewidth: <float>,
  7108. *
  7109. * lights: <bool>,
  7110. *
  7111. * morphTargets: <bool>,
  7112. * morphNormals: <bool>
  7113. * }
  7114. */
  7115. class ShaderMaterial extends Material {
  7116. constructor(parameters) {
  7117. super();
  7118. this.type = 'ShaderMaterial';
  7119. this.defines = {};
  7120. this.uniforms = {};
  7121. this.vertexShader = default_vertex;
  7122. this.fragmentShader = default_fragment;
  7123. this.linewidth = 1;
  7124. this.wireframe = false;
  7125. this.wireframeLinewidth = 1;
  7126. this.fog = false; // set to use scene fog
  7127. this.lights = false; // set to use scene lights
  7128. this.clipping = false; // set to use user-defined clipping planes
  7129. this.morphTargets = false; // set to use morph targets
  7130. this.morphNormals = false; // set to use morph normals
  7131. this.extensions = {
  7132. derivatives: false,
  7133. // set to use derivatives
  7134. fragDepth: false,
  7135. // set to use fragment depth values
  7136. drawBuffers: false,
  7137. // set to use draw buffers
  7138. shaderTextureLOD: false // set to use shader texture LOD
  7139. }; // When rendered geometry doesn't include these attributes but the material does,
  7140. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7141. this.defaultAttributeValues = {
  7142. 'color': [1, 1, 1],
  7143. 'uv': [0, 0],
  7144. 'uv2': [0, 0]
  7145. };
  7146. this.index0AttributeName = undefined;
  7147. this.uniformsNeedUpdate = false;
  7148. this.glslVersion = null;
  7149. if (parameters !== undefined) {
  7150. if (parameters.attributes !== undefined) {
  7151. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  7152. }
  7153. this.setValues(parameters);
  7154. }
  7155. }
  7156. copy(source) {
  7157. super.copy(source);
  7158. this.fragmentShader = source.fragmentShader;
  7159. this.vertexShader = source.vertexShader;
  7160. this.uniforms = cloneUniforms(source.uniforms);
  7161. this.defines = Object.assign({}, source.defines);
  7162. this.wireframe = source.wireframe;
  7163. this.wireframeLinewidth = source.wireframeLinewidth;
  7164. this.lights = source.lights;
  7165. this.clipping = source.clipping;
  7166. this.morphTargets = source.morphTargets;
  7167. this.morphNormals = source.morphNormals;
  7168. this.extensions = Object.assign({}, source.extensions);
  7169. this.glslVersion = source.glslVersion;
  7170. return this;
  7171. }
  7172. toJSON(meta) {
  7173. const data = super.toJSON(meta);
  7174. data.glslVersion = this.glslVersion;
  7175. data.uniforms = {};
  7176. for (const name in this.uniforms) {
  7177. const uniform = this.uniforms[name];
  7178. const value = uniform.value;
  7179. if (value && value.isTexture) {
  7180. data.uniforms[name] = {
  7181. type: 't',
  7182. value: value.toJSON(meta).uuid
  7183. };
  7184. } else if (value && value.isColor) {
  7185. data.uniforms[name] = {
  7186. type: 'c',
  7187. value: value.getHex()
  7188. };
  7189. } else if (value && value.isVector2) {
  7190. data.uniforms[name] = {
  7191. type: 'v2',
  7192. value: value.toArray()
  7193. };
  7194. } else if (value && value.isVector3) {
  7195. data.uniforms[name] = {
  7196. type: 'v3',
  7197. value: value.toArray()
  7198. };
  7199. } else if (value && value.isVector4) {
  7200. data.uniforms[name] = {
  7201. type: 'v4',
  7202. value: value.toArray()
  7203. };
  7204. } else if (value && value.isMatrix3) {
  7205. data.uniforms[name] = {
  7206. type: 'm3',
  7207. value: value.toArray()
  7208. };
  7209. } else if (value && value.isMatrix4) {
  7210. data.uniforms[name] = {
  7211. type: 'm4',
  7212. value: value.toArray()
  7213. };
  7214. } else {
  7215. data.uniforms[name] = {
  7216. value: value
  7217. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7218. }
  7219. }
  7220. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  7221. data.vertexShader = this.vertexShader;
  7222. data.fragmentShader = this.fragmentShader;
  7223. const extensions = {};
  7224. for (const key in this.extensions) {
  7225. if (this.extensions[key] === true) extensions[key] = true;
  7226. }
  7227. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  7228. return data;
  7229. }
  7230. }
  7231. ShaderMaterial.prototype.isShaderMaterial = true;
  7232. class Camera extends Object3D {
  7233. constructor() {
  7234. super();
  7235. this.type = 'Camera';
  7236. this.matrixWorldInverse = new Matrix4();
  7237. this.projectionMatrix = new Matrix4();
  7238. this.projectionMatrixInverse = new Matrix4();
  7239. }
  7240. copy(source, recursive) {
  7241. super.copy(source, recursive);
  7242. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  7243. this.projectionMatrix.copy(source.projectionMatrix);
  7244. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  7245. return this;
  7246. }
  7247. getWorldDirection(target) {
  7248. if (target === undefined) {
  7249. console.warn('THREE.Camera: .getWorldDirection() target is now required');
  7250. target = new Vector3();
  7251. }
  7252. this.updateWorldMatrix(true, false);
  7253. const e = this.matrixWorld.elements;
  7254. return target.set(-e[8], -e[9], -e[10]).normalize();
  7255. }
  7256. updateMatrixWorld(force) {
  7257. super.updateMatrixWorld(force);
  7258. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7259. }
  7260. updateWorldMatrix(updateParents, updateChildren) {
  7261. super.updateWorldMatrix(updateParents, updateChildren);
  7262. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7263. }
  7264. clone() {
  7265. return new this.constructor().copy(this);
  7266. }
  7267. }
  7268. Camera.prototype.isCamera = true;
  7269. class PerspectiveCamera extends Camera {
  7270. constructor(fov = 50, aspect = 1, near = 0.1, far = 2000) {
  7271. super();
  7272. this.type = 'PerspectiveCamera';
  7273. this.fov = fov;
  7274. this.zoom = 1;
  7275. this.near = near;
  7276. this.far = far;
  7277. this.focus = 10;
  7278. this.aspect = aspect;
  7279. this.view = null;
  7280. this.filmGauge = 35; // width of the film (default in millimeters)
  7281. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7282. this.updateProjectionMatrix();
  7283. }
  7284. copy(source, recursive) {
  7285. super.copy(source, recursive);
  7286. this.fov = source.fov;
  7287. this.zoom = source.zoom;
  7288. this.near = source.near;
  7289. this.far = source.far;
  7290. this.focus = source.focus;
  7291. this.aspect = source.aspect;
  7292. this.view = source.view === null ? null : Object.assign({}, source.view);
  7293. this.filmGauge = source.filmGauge;
  7294. this.filmOffset = source.filmOffset;
  7295. return this;
  7296. }
  7297. /**
  7298. * Sets the FOV by focal length in respect to the current .filmGauge.
  7299. *
  7300. * The default film gauge is 35, so that the focal length can be specified for
  7301. * a 35mm (full frame) camera.
  7302. *
  7303. * Values for focal length and film gauge must have the same unit.
  7304. */
  7305. setFocalLength(focalLength) {
  7306. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7307. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7308. this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope);
  7309. this.updateProjectionMatrix();
  7310. }
  7311. /**
  7312. * Calculates the focal length from the current .fov and .filmGauge.
  7313. */
  7314. getFocalLength() {
  7315. const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov);
  7316. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7317. }
  7318. getEffectiveFOV() {
  7319. return RAD2DEG * 2 * Math.atan(Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom);
  7320. }
  7321. getFilmWidth() {
  7322. // film not completely covered in portrait format (aspect < 1)
  7323. return this.filmGauge * Math.min(this.aspect, 1);
  7324. }
  7325. getFilmHeight() {
  7326. // film not completely covered in landscape format (aspect > 1)
  7327. return this.filmGauge / Math.max(this.aspect, 1);
  7328. }
  7329. /**
  7330. * Sets an offset in a larger frustum. This is useful for multi-window or
  7331. * multi-monitor/multi-machine setups.
  7332. *
  7333. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7334. * the monitors are in grid like this
  7335. *
  7336. * +---+---+---+
  7337. * | A | B | C |
  7338. * +---+---+---+
  7339. * | D | E | F |
  7340. * +---+---+---+
  7341. *
  7342. * then for each monitor you would call it like this
  7343. *
  7344. * const w = 1920;
  7345. * const h = 1080;
  7346. * const fullWidth = w * 3;
  7347. * const fullHeight = h * 2;
  7348. *
  7349. * --A--
  7350. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7351. * --B--
  7352. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7353. * --C--
  7354. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7355. * --D--
  7356. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7357. * --E--
  7358. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7359. * --F--
  7360. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7361. *
  7362. * Note there is no reason monitors have to be the same size or in a grid.
  7363. */
  7364. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  7365. this.aspect = fullWidth / fullHeight;
  7366. if (this.view === null) {
  7367. this.view = {
  7368. enabled: true,
  7369. fullWidth: 1,
  7370. fullHeight: 1,
  7371. offsetX: 0,
  7372. offsetY: 0,
  7373. width: 1,
  7374. height: 1
  7375. };
  7376. }
  7377. this.view.enabled = true;
  7378. this.view.fullWidth = fullWidth;
  7379. this.view.fullHeight = fullHeight;
  7380. this.view.offsetX = x;
  7381. this.view.offsetY = y;
  7382. this.view.width = width;
  7383. this.view.height = height;
  7384. this.updateProjectionMatrix();
  7385. }
  7386. clearViewOffset() {
  7387. if (this.view !== null) {
  7388. this.view.enabled = false;
  7389. }
  7390. this.updateProjectionMatrix();
  7391. }
  7392. updateProjectionMatrix() {
  7393. const near = this.near;
  7394. let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom;
  7395. let height = 2 * top;
  7396. let width = this.aspect * height;
  7397. let left = -0.5 * width;
  7398. const view = this.view;
  7399. if (this.view !== null && this.view.enabled) {
  7400. const fullWidth = view.fullWidth,
  7401. fullHeight = view.fullHeight;
  7402. left += view.offsetX * width / fullWidth;
  7403. top -= view.offsetY * height / fullHeight;
  7404. width *= view.width / fullWidth;
  7405. height *= view.height / fullHeight;
  7406. }
  7407. const skew = this.filmOffset;
  7408. if (skew !== 0) left += near * skew / this.getFilmWidth();
  7409. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  7410. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  7411. }
  7412. toJSON(meta) {
  7413. const data = super.toJSON(meta);
  7414. data.object.fov = this.fov;
  7415. data.object.zoom = this.zoom;
  7416. data.object.near = this.near;
  7417. data.object.far = this.far;
  7418. data.object.focus = this.focus;
  7419. data.object.aspect = this.aspect;
  7420. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  7421. data.object.filmGauge = this.filmGauge;
  7422. data.object.filmOffset = this.filmOffset;
  7423. return data;
  7424. }
  7425. }
  7426. PerspectiveCamera.prototype.isPerspectiveCamera = true;
  7427. const fov = 90,
  7428. aspect = 1;
  7429. class CubeCamera extends Object3D {
  7430. constructor(near, far, renderTarget) {
  7431. super();
  7432. this.type = 'CubeCamera';
  7433. if (renderTarget.isWebGLCubeRenderTarget !== true) {
  7434. console.error('THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.');
  7435. return;
  7436. }
  7437. this.renderTarget = renderTarget;
  7438. const cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  7439. cameraPX.layers = this.layers;
  7440. cameraPX.up.set(0, -1, 0);
  7441. cameraPX.lookAt(new Vector3(1, 0, 0));
  7442. this.add(cameraPX);
  7443. const cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  7444. cameraNX.layers = this.layers;
  7445. cameraNX.up.set(0, -1, 0);
  7446. cameraNX.lookAt(new Vector3(-1, 0, 0));
  7447. this.add(cameraNX);
  7448. const cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  7449. cameraPY.layers = this.layers;
  7450. cameraPY.up.set(0, 0, 1);
  7451. cameraPY.lookAt(new Vector3(0, 1, 0));
  7452. this.add(cameraPY);
  7453. const cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  7454. cameraNY.layers = this.layers;
  7455. cameraNY.up.set(0, 0, -1);
  7456. cameraNY.lookAt(new Vector3(0, -1, 0));
  7457. this.add(cameraNY);
  7458. const cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  7459. cameraPZ.layers = this.layers;
  7460. cameraPZ.up.set(0, -1, 0);
  7461. cameraPZ.lookAt(new Vector3(0, 0, 1));
  7462. this.add(cameraPZ);
  7463. const cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  7464. cameraNZ.layers = this.layers;
  7465. cameraNZ.up.set(0, -1, 0);
  7466. cameraNZ.lookAt(new Vector3(0, 0, -1));
  7467. this.add(cameraNZ);
  7468. }
  7469. update(renderer, scene) {
  7470. if (this.parent === null) this.updateMatrixWorld();
  7471. const renderTarget = this.renderTarget;
  7472. const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children;
  7473. const currentXrEnabled = renderer.xr.enabled;
  7474. const currentRenderTarget = renderer.getRenderTarget();
  7475. renderer.xr.enabled = false;
  7476. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7477. renderTarget.texture.generateMipmaps = false;
  7478. renderer.setRenderTarget(renderTarget, 0);
  7479. renderer.render(scene, cameraPX);
  7480. renderer.setRenderTarget(renderTarget, 1);
  7481. renderer.render(scene, cameraNX);
  7482. renderer.setRenderTarget(renderTarget, 2);
  7483. renderer.render(scene, cameraPY);
  7484. renderer.setRenderTarget(renderTarget, 3);
  7485. renderer.render(scene, cameraNY);
  7486. renderer.setRenderTarget(renderTarget, 4);
  7487. renderer.render(scene, cameraPZ);
  7488. renderTarget.texture.generateMipmaps = generateMipmaps;
  7489. renderer.setRenderTarget(renderTarget, 5);
  7490. renderer.render(scene, cameraNZ);
  7491. renderer.setRenderTarget(currentRenderTarget);
  7492. renderer.xr.enabled = currentXrEnabled;
  7493. }
  7494. }
  7495. class CubeTexture extends Texture {
  7496. constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  7497. images = images !== undefined ? images : [];
  7498. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7499. format = format !== undefined ? format : RGBFormat;
  7500. super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding); // Why CubeTexture._needsFlipEnvMap is necessary:
  7501. //
  7502. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7503. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7504. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7505. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7506. // and the flag _needsFlipEnvMap controls this conversion. The flip is not required (and thus _needsFlipEnvMap is set to false)
  7507. // when using WebGLCubeRenderTarget.texture as a cube texture.
  7508. this._needsFlipEnvMap = true;
  7509. this.flipY = false;
  7510. }
  7511. get images() {
  7512. return this.image;
  7513. }
  7514. set images(value) {
  7515. this.image = value;
  7516. }
  7517. }
  7518. CubeTexture.prototype.isCubeTexture = true;
  7519. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7520. constructor(size, options, dummy) {
  7521. if (Number.isInteger(options)) {
  7522. console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');
  7523. options = dummy;
  7524. }
  7525. super(size, size, options);
  7526. options = options || {};
  7527. this.texture = new CubeTexture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  7528. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7529. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7530. this.texture._needsFlipEnvMap = false;
  7531. }
  7532. fromEquirectangularTexture(renderer, texture) {
  7533. this.texture.type = texture.type;
  7534. this.texture.format = RGBAFormat; // see #18859
  7535. this.texture.encoding = texture.encoding;
  7536. this.texture.generateMipmaps = texture.generateMipmaps;
  7537. this.texture.minFilter = texture.minFilter;
  7538. this.texture.magFilter = texture.magFilter;
  7539. const shader = {
  7540. uniforms: {
  7541. tEquirect: {
  7542. value: null
  7543. }
  7544. },
  7545. vertexShader:
  7546. /* glsl */
  7547. `
  7548. varying vec3 vWorldDirection;
  7549. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7550. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7551. }
  7552. void main() {
  7553. vWorldDirection = transformDirection( position, modelMatrix );
  7554. #include <begin_vertex>
  7555. #include <project_vertex>
  7556. }
  7557. `,
  7558. fragmentShader:
  7559. /* glsl */
  7560. `
  7561. uniform sampler2D tEquirect;
  7562. varying vec3 vWorldDirection;
  7563. #include <common>
  7564. void main() {
  7565. vec3 direction = normalize( vWorldDirection );
  7566. vec2 sampleUV = equirectUv( direction );
  7567. gl_FragColor = texture2D( tEquirect, sampleUV );
  7568. }
  7569. `
  7570. };
  7571. const geometry = new BoxGeometry(5, 5, 5);
  7572. const material = new ShaderMaterial({
  7573. name: 'CubemapFromEquirect',
  7574. uniforms: cloneUniforms(shader.uniforms),
  7575. vertexShader: shader.vertexShader,
  7576. fragmentShader: shader.fragmentShader,
  7577. side: BackSide,
  7578. blending: NoBlending
  7579. });
  7580. material.uniforms.tEquirect.value = texture;
  7581. const mesh = new Mesh(geometry, material);
  7582. const currentMinFilter = texture.minFilter; // Avoid blurred poles
  7583. if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
  7584. const camera = new CubeCamera(1, 10, this);
  7585. camera.update(renderer, mesh);
  7586. texture.minFilter = currentMinFilter;
  7587. mesh.geometry.dispose();
  7588. mesh.material.dispose();
  7589. return this;
  7590. }
  7591. clear(renderer, color, depth, stencil) {
  7592. const currentRenderTarget = renderer.getRenderTarget();
  7593. for (let i = 0; i < 6; i++) {
  7594. renderer.setRenderTarget(this, i);
  7595. renderer.clear(color, depth, stencil);
  7596. }
  7597. renderer.setRenderTarget(currentRenderTarget);
  7598. }
  7599. }
  7600. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  7601. const _sphere$2 = /*@__PURE__*/new Sphere();
  7602. const _vector$7 = /*@__PURE__*/new Vector3();
  7603. class Frustum {
  7604. constructor(p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane()) {
  7605. this.planes = [p0, p1, p2, p3, p4, p5];
  7606. }
  7607. set(p0, p1, p2, p3, p4, p5) {
  7608. const planes = this.planes;
  7609. planes[0].copy(p0);
  7610. planes[1].copy(p1);
  7611. planes[2].copy(p2);
  7612. planes[3].copy(p3);
  7613. planes[4].copy(p4);
  7614. planes[5].copy(p5);
  7615. return this;
  7616. }
  7617. copy(frustum) {
  7618. const planes = this.planes;
  7619. for (let i = 0; i < 6; i++) {
  7620. planes[i].copy(frustum.planes[i]);
  7621. }
  7622. return this;
  7623. }
  7624. setFromProjectionMatrix(m) {
  7625. const planes = this.planes;
  7626. const me = m.elements;
  7627. const me0 = me[0],
  7628. me1 = me[1],
  7629. me2 = me[2],
  7630. me3 = me[3];
  7631. const me4 = me[4],
  7632. me5 = me[5],
  7633. me6 = me[6],
  7634. me7 = me[7];
  7635. const me8 = me[8],
  7636. me9 = me[9],
  7637. me10 = me[10],
  7638. me11 = me[11];
  7639. const me12 = me[12],
  7640. me13 = me[13],
  7641. me14 = me[14],
  7642. me15 = me[15];
  7643. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  7644. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  7645. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  7646. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  7647. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  7648. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  7649. return this;
  7650. }
  7651. intersectsObject(object) {
  7652. const geometry = object.geometry;
  7653. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  7654. _sphere$2.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  7655. return this.intersectsSphere(_sphere$2);
  7656. }
  7657. intersectsSprite(sprite) {
  7658. _sphere$2.center.set(0, 0, 0);
  7659. _sphere$2.radius = 0.7071067811865476;
  7660. _sphere$2.applyMatrix4(sprite.matrixWorld);
  7661. return this.intersectsSphere(_sphere$2);
  7662. }
  7663. intersectsSphere(sphere) {
  7664. const planes = this.planes;
  7665. const center = sphere.center;
  7666. const negRadius = -sphere.radius;
  7667. for (let i = 0; i < 6; i++) {
  7668. const distance = planes[i].distanceToPoint(center);
  7669. if (distance < negRadius) {
  7670. return false;
  7671. }
  7672. }
  7673. return true;
  7674. }
  7675. intersectsBox(box) {
  7676. const planes = this.planes;
  7677. for (let i = 0; i < 6; i++) {
  7678. const plane = planes[i]; // corner at max distance
  7679. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7680. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7681. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7682. if (plane.distanceToPoint(_vector$7) < 0) {
  7683. return false;
  7684. }
  7685. }
  7686. return true;
  7687. }
  7688. containsPoint(point) {
  7689. const planes = this.planes;
  7690. for (let i = 0; i < 6; i++) {
  7691. if (planes[i].distanceToPoint(point) < 0) {
  7692. return false;
  7693. }
  7694. }
  7695. return true;
  7696. }
  7697. clone() {
  7698. return new this.constructor().copy(this);
  7699. }
  7700. }
  7701. function WebGLAnimation() {
  7702. let context = null;
  7703. let isAnimating = false;
  7704. let animationLoop = null;
  7705. let requestId = null;
  7706. function onAnimationFrame(time, frame) {
  7707. animationLoop(time, frame);
  7708. requestId = context.requestAnimationFrame(onAnimationFrame);
  7709. }
  7710. return {
  7711. start: function () {
  7712. if (isAnimating === true) return;
  7713. if (animationLoop === null) return;
  7714. requestId = context.requestAnimationFrame(onAnimationFrame);
  7715. isAnimating = true;
  7716. },
  7717. stop: function () {
  7718. context.cancelAnimationFrame(requestId);
  7719. isAnimating = false;
  7720. },
  7721. setAnimationLoop: function (callback) {
  7722. animationLoop = callback;
  7723. },
  7724. setContext: function (value) {
  7725. context = value;
  7726. }
  7727. };
  7728. }
  7729. function WebGLAttributes(gl, capabilities) {
  7730. const isWebGL2 = capabilities.isWebGL2;
  7731. const buffers = new WeakMap();
  7732. function createBuffer(attribute, bufferType) {
  7733. const array = attribute.array;
  7734. const usage = attribute.usage;
  7735. const buffer = gl.createBuffer();
  7736. gl.bindBuffer(bufferType, buffer);
  7737. gl.bufferData(bufferType, array, usage);
  7738. attribute.onUploadCallback();
  7739. let type = gl.FLOAT;
  7740. if (array instanceof Float32Array) {
  7741. type = gl.FLOAT;
  7742. } else if (array instanceof Float64Array) {
  7743. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  7744. } else if (array instanceof Uint16Array) {
  7745. if (attribute.isFloat16BufferAttribute) {
  7746. if (isWebGL2) {
  7747. type = gl.HALF_FLOAT;
  7748. } else {
  7749. console.warn('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
  7750. }
  7751. } else {
  7752. type = gl.UNSIGNED_SHORT;
  7753. }
  7754. } else if (array instanceof Int16Array) {
  7755. type = gl.SHORT;
  7756. } else if (array instanceof Uint32Array) {
  7757. type = gl.UNSIGNED_INT;
  7758. } else if (array instanceof Int32Array) {
  7759. type = gl.INT;
  7760. } else if (array instanceof Int8Array) {
  7761. type = gl.BYTE;
  7762. } else if (array instanceof Uint8Array) {
  7763. type = gl.UNSIGNED_BYTE;
  7764. } else if (array instanceof Uint8ClampedArray) {
  7765. type = gl.UNSIGNED_BYTE;
  7766. }
  7767. return {
  7768. buffer: buffer,
  7769. type: type,
  7770. bytesPerElement: array.BYTES_PER_ELEMENT,
  7771. version: attribute.version
  7772. };
  7773. }
  7774. function updateBuffer(buffer, attribute, bufferType) {
  7775. const array = attribute.array;
  7776. const updateRange = attribute.updateRange;
  7777. gl.bindBuffer(bufferType, buffer);
  7778. if (updateRange.count === -1) {
  7779. // Not using update ranges
  7780. gl.bufferSubData(bufferType, 0, array);
  7781. } else {
  7782. if (isWebGL2) {
  7783. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  7784. } else {
  7785. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  7786. }
  7787. updateRange.count = -1; // reset range
  7788. }
  7789. } //
  7790. function get(attribute) {
  7791. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7792. return buffers.get(attribute);
  7793. }
  7794. function remove(attribute) {
  7795. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7796. const data = buffers.get(attribute);
  7797. if (data) {
  7798. gl.deleteBuffer(data.buffer);
  7799. buffers.delete(attribute);
  7800. }
  7801. }
  7802. function update(attribute, bufferType) {
  7803. if (attribute.isGLBufferAttribute) {
  7804. const cached = buffers.get(attribute);
  7805. if (!cached || cached.version < attribute.version) {
  7806. buffers.set(attribute, {
  7807. buffer: attribute.buffer,
  7808. type: attribute.type,
  7809. bytesPerElement: attribute.elementSize,
  7810. version: attribute.version
  7811. });
  7812. }
  7813. return;
  7814. }
  7815. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7816. const data = buffers.get(attribute);
  7817. if (data === undefined) {
  7818. buffers.set(attribute, createBuffer(attribute, bufferType));
  7819. } else if (data.version < attribute.version) {
  7820. updateBuffer(data.buffer, attribute, bufferType);
  7821. data.version = attribute.version;
  7822. }
  7823. }
  7824. return {
  7825. get: get,
  7826. remove: remove,
  7827. update: update
  7828. };
  7829. }
  7830. class PlaneGeometry extends BufferGeometry {
  7831. constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) {
  7832. super();
  7833. this.type = 'PlaneGeometry';
  7834. this.parameters = {
  7835. width: width,
  7836. height: height,
  7837. widthSegments: widthSegments,
  7838. heightSegments: heightSegments
  7839. };
  7840. const width_half = width / 2;
  7841. const height_half = height / 2;
  7842. const gridX = Math.floor(widthSegments);
  7843. const gridY = Math.floor(heightSegments);
  7844. const gridX1 = gridX + 1;
  7845. const gridY1 = gridY + 1;
  7846. const segment_width = width / gridX;
  7847. const segment_height = height / gridY; //
  7848. const indices = [];
  7849. const vertices = [];
  7850. const normals = [];
  7851. const uvs = [];
  7852. for (let iy = 0; iy < gridY1; iy++) {
  7853. const y = iy * segment_height - height_half;
  7854. for (let ix = 0; ix < gridX1; ix++) {
  7855. const x = ix * segment_width - width_half;
  7856. vertices.push(x, -y, 0);
  7857. normals.push(0, 0, 1);
  7858. uvs.push(ix / gridX);
  7859. uvs.push(1 - iy / gridY);
  7860. }
  7861. }
  7862. for (let iy = 0; iy < gridY; iy++) {
  7863. for (let ix = 0; ix < gridX; ix++) {
  7864. const a = ix + gridX1 * iy;
  7865. const b = ix + gridX1 * (iy + 1);
  7866. const c = ix + 1 + gridX1 * (iy + 1);
  7867. const d = ix + 1 + gridX1 * iy;
  7868. indices.push(a, b, d);
  7869. indices.push(b, c, d);
  7870. }
  7871. }
  7872. this.setIndex(indices);
  7873. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  7874. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  7875. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  7876. }
  7877. }
  7878. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7879. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7880. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  7881. 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";
  7882. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7883. var begin_vertex = "vec3 transformed = vec3( position );";
  7884. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7885. var bsdfs = "vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif";
  7886. 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";
  7887. 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";
  7888. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7889. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7890. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7891. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7892. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7893. 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";
  7894. 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";
  7895. 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}";
  7896. 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";
  7897. 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";
  7898. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7899. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7900. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7901. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7902. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7903. 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}";
  7904. 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";
  7905. 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";
  7906. 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";
  7907. 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";
  7908. 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";
  7909. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = - mvPosition.z;\n#endif";
  7910. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  7911. 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";
  7912. 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";
  7913. 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}";
  7914. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";
  7915. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7916. 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";
  7917. 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";
  7918. 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";
  7919. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7920. 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)";
  7921. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7922. 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)";
  7923. 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 ) ), rawDiffuseColor, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), rawDiffuseColor, 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";
  7924. 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}";
  7925. 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";
  7926. 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";
  7927. 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";
  7928. 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";
  7929. 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";
  7930. 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";
  7931. 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";
  7932. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  7933. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7934. 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";
  7935. 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";
  7936. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7937. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7938. 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";
  7939. 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";
  7940. 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";
  7941. 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;";
  7942. 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";
  7943. 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";
  7944. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7945. 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";
  7946. 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";
  7947. 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}";
  7948. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7949. 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;";
  7950. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7951. 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";
  7952. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7953. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7954. 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";
  7955. 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";
  7956. 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";
  7957. 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}";
  7958. 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";
  7959. 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";
  7960. 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";
  7961. 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";
  7962. 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";
  7963. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7964. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7965. 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; }";
  7966. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\t#ifdef USE_TRANSMISSIONMAP\n\t\ttotalTransmission *= 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\tvec3 viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n\tfloat ior = ( 1.0 + 0.4 * reflectivity ) / ( 1.0 - 0.4 * reflectivity );\n\tvec3 f0 = vec3( pow( ior - 1.0, 2.0 ) / pow( ior + 1.0, 2.0 ) );\n\tvec3 f90 = vec3( 1.0 );\n\tvec3 f_transmission = totalTransmission * getIBLVolumeRefraction(\n\t\tnormal, v, viewDir, roughnessFactor, diffuseColor.rgb, f0, f90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, ior, thicknessFactor,\n\t\tattenuationColor, attenuationDistance);\n\tdiffuseColor.rgb = mix( diffuseColor.rgb, f_transmission, totalTransmission );\n#endif";
  7967. 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, vec3 viewDir, float perceptualRoughness, vec3 baseColor, vec3 f0, vec3 f90,\n\t\tvec3 position, mat4 modelMatrix, mat4 viewMatrix, mat4 projMatrix, float ior, float thickness, vec3 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\tfloat NdotV = saturate(dot(n, viewDir));\n\t\tvec2 brdf = integrateSpecularBRDF(NdotV, perceptualRoughness);\n\t\tvec3 specularColor = f0 * brdf.x + f90 * brdf.y;\n\t\treturn (1.0 - specularColor) * attenuatedColor * baseColor;\n\t}\n#endif";
  7968. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7969. 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";
  7970. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7971. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7972. 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";
  7973. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7974. 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";
  7975. 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}";
  7976. 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}";
  7977. 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}";
  7978. 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}";
  7979. 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}";
  7980. 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}";
  7981. 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}";
  7982. 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}";
  7983. 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}";
  7984. 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}";
  7985. 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}";
  7986. 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}";
  7987. 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}";
  7988. 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}";
  7989. 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}";
  7990. 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}";
  7991. 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}";
  7992. 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}";
  7993. 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}";
  7994. 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}";
  7995. 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}";
  7996. 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}";
  7997. 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#ifdef USE_TRANSMISSION\n\t\tfloat totalTransmission = transmission;\n\t\tfloat thicknessFactor = thickness;\n\t#endif\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\tvec3 rawDiffuseColor = diffuseColor.rgb;\n\t#include <transmission_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\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}";
  7998. 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}";
  7999. 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}";
  8000. 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}";
  8001. 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}";
  8002. 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}";
  8003. 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}";
  8004. 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}";
  8005. 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}";
  8006. 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}";
  8007. const ShaderChunk = {
  8008. alphamap_fragment: alphamap_fragment,
  8009. alphamap_pars_fragment: alphamap_pars_fragment,
  8010. alphatest_fragment: alphatest_fragment,
  8011. aomap_fragment: aomap_fragment,
  8012. aomap_pars_fragment: aomap_pars_fragment,
  8013. begin_vertex: begin_vertex,
  8014. beginnormal_vertex: beginnormal_vertex,
  8015. bsdfs: bsdfs,
  8016. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8017. clipping_planes_fragment: clipping_planes_fragment,
  8018. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8019. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8020. clipping_planes_vertex: clipping_planes_vertex,
  8021. color_fragment: color_fragment,
  8022. color_pars_fragment: color_pars_fragment,
  8023. color_pars_vertex: color_pars_vertex,
  8024. color_vertex: color_vertex,
  8025. common: common,
  8026. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8027. defaultnormal_vertex: defaultnormal_vertex,
  8028. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8029. displacementmap_vertex: displacementmap_vertex,
  8030. emissivemap_fragment: emissivemap_fragment,
  8031. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8032. encodings_fragment: encodings_fragment,
  8033. encodings_pars_fragment: encodings_pars_fragment,
  8034. envmap_fragment: envmap_fragment,
  8035. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8036. envmap_pars_fragment: envmap_pars_fragment,
  8037. envmap_pars_vertex: envmap_pars_vertex,
  8038. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8039. envmap_vertex: envmap_vertex,
  8040. fog_vertex: fog_vertex,
  8041. fog_pars_vertex: fog_pars_vertex,
  8042. fog_fragment: fog_fragment,
  8043. fog_pars_fragment: fog_pars_fragment,
  8044. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8045. lightmap_fragment: lightmap_fragment,
  8046. lightmap_pars_fragment: lightmap_pars_fragment,
  8047. lights_lambert_vertex: lights_lambert_vertex,
  8048. lights_pars_begin: lights_pars_begin,
  8049. lights_toon_fragment: lights_toon_fragment,
  8050. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8051. lights_phong_fragment: lights_phong_fragment,
  8052. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8053. lights_physical_fragment: lights_physical_fragment,
  8054. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8055. lights_fragment_begin: lights_fragment_begin,
  8056. lights_fragment_maps: lights_fragment_maps,
  8057. lights_fragment_end: lights_fragment_end,
  8058. logdepthbuf_fragment: logdepthbuf_fragment,
  8059. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8060. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8061. logdepthbuf_vertex: logdepthbuf_vertex,
  8062. map_fragment: map_fragment,
  8063. map_pars_fragment: map_pars_fragment,
  8064. map_particle_fragment: map_particle_fragment,
  8065. map_particle_pars_fragment: map_particle_pars_fragment,
  8066. metalnessmap_fragment: metalnessmap_fragment,
  8067. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8068. morphnormal_vertex: morphnormal_vertex,
  8069. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8070. morphtarget_vertex: morphtarget_vertex,
  8071. normal_fragment_begin: normal_fragment_begin,
  8072. normal_fragment_maps: normal_fragment_maps,
  8073. normalmap_pars_fragment: normalmap_pars_fragment,
  8074. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8075. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8076. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8077. packing: packing,
  8078. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8079. project_vertex: project_vertex,
  8080. dithering_fragment: dithering_fragment,
  8081. dithering_pars_fragment: dithering_pars_fragment,
  8082. roughnessmap_fragment: roughnessmap_fragment,
  8083. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8084. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8085. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8086. shadowmap_vertex: shadowmap_vertex,
  8087. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8088. skinbase_vertex: skinbase_vertex,
  8089. skinning_pars_vertex: skinning_pars_vertex,
  8090. skinning_vertex: skinning_vertex,
  8091. skinnormal_vertex: skinnormal_vertex,
  8092. specularmap_fragment: specularmap_fragment,
  8093. specularmap_pars_fragment: specularmap_pars_fragment,
  8094. tonemapping_fragment: tonemapping_fragment,
  8095. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8096. transmission_fragment: transmission_fragment,
  8097. transmission_pars_fragment: transmission_pars_fragment,
  8098. uv_pars_fragment: uv_pars_fragment,
  8099. uv_pars_vertex: uv_pars_vertex,
  8100. uv_vertex: uv_vertex,
  8101. uv2_pars_fragment: uv2_pars_fragment,
  8102. uv2_pars_vertex: uv2_pars_vertex,
  8103. uv2_vertex: uv2_vertex,
  8104. worldpos_vertex: worldpos_vertex,
  8105. background_frag: background_frag,
  8106. background_vert: background_vert,
  8107. cube_frag: cube_frag,
  8108. cube_vert: cube_vert,
  8109. depth_frag: depth_frag,
  8110. depth_vert: depth_vert,
  8111. distanceRGBA_frag: distanceRGBA_frag,
  8112. distanceRGBA_vert: distanceRGBA_vert,
  8113. equirect_frag: equirect_frag,
  8114. equirect_vert: equirect_vert,
  8115. linedashed_frag: linedashed_frag,
  8116. linedashed_vert: linedashed_vert,
  8117. meshbasic_frag: meshbasic_frag,
  8118. meshbasic_vert: meshbasic_vert,
  8119. meshlambert_frag: meshlambert_frag,
  8120. meshlambert_vert: meshlambert_vert,
  8121. meshmatcap_frag: meshmatcap_frag,
  8122. meshmatcap_vert: meshmatcap_vert,
  8123. meshtoon_frag: meshtoon_frag,
  8124. meshtoon_vert: meshtoon_vert,
  8125. meshphong_frag: meshphong_frag,
  8126. meshphong_vert: meshphong_vert,
  8127. meshphysical_frag: meshphysical_frag,
  8128. meshphysical_vert: meshphysical_vert,
  8129. normal_frag: normal_frag,
  8130. normal_vert: normal_vert,
  8131. points_frag: points_frag,
  8132. points_vert: points_vert,
  8133. shadow_frag: shadow_frag,
  8134. shadow_vert: shadow_vert,
  8135. sprite_frag: sprite_frag,
  8136. sprite_vert: sprite_vert
  8137. };
  8138. /**
  8139. * Uniforms library for shared webgl shaders
  8140. */
  8141. const UniformsLib = {
  8142. common: {
  8143. diffuse: {
  8144. value: new Color(0xffffff)
  8145. },
  8146. opacity: {
  8147. value: 1.0
  8148. },
  8149. map: {
  8150. value: null
  8151. },
  8152. uvTransform: {
  8153. value: new Matrix3()
  8154. },
  8155. uv2Transform: {
  8156. value: new Matrix3()
  8157. },
  8158. alphaMap: {
  8159. value: null
  8160. }
  8161. },
  8162. specularmap: {
  8163. specularMap: {
  8164. value: null
  8165. }
  8166. },
  8167. envmap: {
  8168. envMap: {
  8169. value: null
  8170. },
  8171. flipEnvMap: {
  8172. value: -1
  8173. },
  8174. reflectivity: {
  8175. value: 1.0
  8176. },
  8177. refractionRatio: {
  8178. value: 0.98
  8179. },
  8180. maxMipLevel: {
  8181. value: 0
  8182. }
  8183. },
  8184. aomap: {
  8185. aoMap: {
  8186. value: null
  8187. },
  8188. aoMapIntensity: {
  8189. value: 1
  8190. }
  8191. },
  8192. lightmap: {
  8193. lightMap: {
  8194. value: null
  8195. },
  8196. lightMapIntensity: {
  8197. value: 1
  8198. }
  8199. },
  8200. emissivemap: {
  8201. emissiveMap: {
  8202. value: null
  8203. }
  8204. },
  8205. bumpmap: {
  8206. bumpMap: {
  8207. value: null
  8208. },
  8209. bumpScale: {
  8210. value: 1
  8211. }
  8212. },
  8213. normalmap: {
  8214. normalMap: {
  8215. value: null
  8216. },
  8217. normalScale: {
  8218. value: new Vector2(1, 1)
  8219. }
  8220. },
  8221. displacementmap: {
  8222. displacementMap: {
  8223. value: null
  8224. },
  8225. displacementScale: {
  8226. value: 1
  8227. },
  8228. displacementBias: {
  8229. value: 0
  8230. }
  8231. },
  8232. roughnessmap: {
  8233. roughnessMap: {
  8234. value: null
  8235. }
  8236. },
  8237. metalnessmap: {
  8238. metalnessMap: {
  8239. value: null
  8240. }
  8241. },
  8242. gradientmap: {
  8243. gradientMap: {
  8244. value: null
  8245. }
  8246. },
  8247. fog: {
  8248. fogDensity: {
  8249. value: 0.00025
  8250. },
  8251. fogNear: {
  8252. value: 1
  8253. },
  8254. fogFar: {
  8255. value: 2000
  8256. },
  8257. fogColor: {
  8258. value: new Color(0xffffff)
  8259. }
  8260. },
  8261. lights: {
  8262. ambientLightColor: {
  8263. value: []
  8264. },
  8265. lightProbe: {
  8266. value: []
  8267. },
  8268. directionalLights: {
  8269. value: [],
  8270. properties: {
  8271. direction: {},
  8272. color: {}
  8273. }
  8274. },
  8275. directionalLightShadows: {
  8276. value: [],
  8277. properties: {
  8278. shadowBias: {},
  8279. shadowNormalBias: {},
  8280. shadowRadius: {},
  8281. shadowMapSize: {}
  8282. }
  8283. },
  8284. directionalShadowMap: {
  8285. value: []
  8286. },
  8287. directionalShadowMatrix: {
  8288. value: []
  8289. },
  8290. spotLights: {
  8291. value: [],
  8292. properties: {
  8293. color: {},
  8294. position: {},
  8295. direction: {},
  8296. distance: {},
  8297. coneCos: {},
  8298. penumbraCos: {},
  8299. decay: {}
  8300. }
  8301. },
  8302. spotLightShadows: {
  8303. value: [],
  8304. properties: {
  8305. shadowBias: {},
  8306. shadowNormalBias: {},
  8307. shadowRadius: {},
  8308. shadowMapSize: {}
  8309. }
  8310. },
  8311. spotShadowMap: {
  8312. value: []
  8313. },
  8314. spotShadowMatrix: {
  8315. value: []
  8316. },
  8317. pointLights: {
  8318. value: [],
  8319. properties: {
  8320. color: {},
  8321. position: {},
  8322. decay: {},
  8323. distance: {}
  8324. }
  8325. },
  8326. pointLightShadows: {
  8327. value: [],
  8328. properties: {
  8329. shadowBias: {},
  8330. shadowNormalBias: {},
  8331. shadowRadius: {},
  8332. shadowMapSize: {},
  8333. shadowCameraNear: {},
  8334. shadowCameraFar: {}
  8335. }
  8336. },
  8337. pointShadowMap: {
  8338. value: []
  8339. },
  8340. pointShadowMatrix: {
  8341. value: []
  8342. },
  8343. hemisphereLights: {
  8344. value: [],
  8345. properties: {
  8346. direction: {},
  8347. skyColor: {},
  8348. groundColor: {}
  8349. }
  8350. },
  8351. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8352. rectAreaLights: {
  8353. value: [],
  8354. properties: {
  8355. color: {},
  8356. position: {},
  8357. width: {},
  8358. height: {}
  8359. }
  8360. },
  8361. ltc_1: {
  8362. value: null
  8363. },
  8364. ltc_2: {
  8365. value: null
  8366. }
  8367. },
  8368. points: {
  8369. diffuse: {
  8370. value: new Color(0xffffff)
  8371. },
  8372. opacity: {
  8373. value: 1.0
  8374. },
  8375. size: {
  8376. value: 1.0
  8377. },
  8378. scale: {
  8379. value: 1.0
  8380. },
  8381. map: {
  8382. value: null
  8383. },
  8384. alphaMap: {
  8385. value: null
  8386. },
  8387. uvTransform: {
  8388. value: new Matrix3()
  8389. }
  8390. },
  8391. sprite: {
  8392. diffuse: {
  8393. value: new Color(0xffffff)
  8394. },
  8395. opacity: {
  8396. value: 1.0
  8397. },
  8398. center: {
  8399. value: new Vector2(0.5, 0.5)
  8400. },
  8401. rotation: {
  8402. value: 0.0
  8403. },
  8404. map: {
  8405. value: null
  8406. },
  8407. alphaMap: {
  8408. value: null
  8409. },
  8410. uvTransform: {
  8411. value: new Matrix3()
  8412. }
  8413. }
  8414. };
  8415. const ShaderLib = {
  8416. basic: {
  8417. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  8418. vertexShader: ShaderChunk.meshbasic_vert,
  8419. fragmentShader: ShaderChunk.meshbasic_frag
  8420. },
  8421. lambert: {
  8422. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  8423. emissive: {
  8424. value: new Color(0x000000)
  8425. }
  8426. }]),
  8427. vertexShader: ShaderChunk.meshlambert_vert,
  8428. fragmentShader: ShaderChunk.meshlambert_frag
  8429. },
  8430. phong: {
  8431. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  8432. emissive: {
  8433. value: new Color(0x000000)
  8434. },
  8435. specular: {
  8436. value: new Color(0x111111)
  8437. },
  8438. shininess: {
  8439. value: 30
  8440. }
  8441. }]),
  8442. vertexShader: ShaderChunk.meshphong_vert,
  8443. fragmentShader: ShaderChunk.meshphong_frag
  8444. },
  8445. standard: {
  8446. 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, {
  8447. emissive: {
  8448. value: new Color(0x000000)
  8449. },
  8450. roughness: {
  8451. value: 1.0
  8452. },
  8453. metalness: {
  8454. value: 0.0
  8455. },
  8456. envMapIntensity: {
  8457. value: 1
  8458. } // temporary
  8459. }]),
  8460. vertexShader: ShaderChunk.meshphysical_vert,
  8461. fragmentShader: ShaderChunk.meshphysical_frag
  8462. },
  8463. toon: {
  8464. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  8465. emissive: {
  8466. value: new Color(0x000000)
  8467. }
  8468. }]),
  8469. vertexShader: ShaderChunk.meshtoon_vert,
  8470. fragmentShader: ShaderChunk.meshtoon_frag
  8471. },
  8472. matcap: {
  8473. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  8474. matcap: {
  8475. value: null
  8476. }
  8477. }]),
  8478. vertexShader: ShaderChunk.meshmatcap_vert,
  8479. fragmentShader: ShaderChunk.meshmatcap_frag
  8480. },
  8481. points: {
  8482. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  8483. vertexShader: ShaderChunk.points_vert,
  8484. fragmentShader: ShaderChunk.points_frag
  8485. },
  8486. dashed: {
  8487. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  8488. scale: {
  8489. value: 1
  8490. },
  8491. dashSize: {
  8492. value: 1
  8493. },
  8494. totalSize: {
  8495. value: 2
  8496. }
  8497. }]),
  8498. vertexShader: ShaderChunk.linedashed_vert,
  8499. fragmentShader: ShaderChunk.linedashed_frag
  8500. },
  8501. depth: {
  8502. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  8503. vertexShader: ShaderChunk.depth_vert,
  8504. fragmentShader: ShaderChunk.depth_frag
  8505. },
  8506. normal: {
  8507. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  8508. opacity: {
  8509. value: 1.0
  8510. }
  8511. }]),
  8512. vertexShader: ShaderChunk.normal_vert,
  8513. fragmentShader: ShaderChunk.normal_frag
  8514. },
  8515. sprite: {
  8516. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  8517. vertexShader: ShaderChunk.sprite_vert,
  8518. fragmentShader: ShaderChunk.sprite_frag
  8519. },
  8520. background: {
  8521. uniforms: {
  8522. uvTransform: {
  8523. value: new Matrix3()
  8524. },
  8525. t2D: {
  8526. value: null
  8527. }
  8528. },
  8529. vertexShader: ShaderChunk.background_vert,
  8530. fragmentShader: ShaderChunk.background_frag
  8531. },
  8532. /* -------------------------------------------------------------------------
  8533. // Cube map shader
  8534. ------------------------------------------------------------------------- */
  8535. cube: {
  8536. uniforms: mergeUniforms([UniformsLib.envmap, {
  8537. opacity: {
  8538. value: 1.0
  8539. }
  8540. }]),
  8541. vertexShader: ShaderChunk.cube_vert,
  8542. fragmentShader: ShaderChunk.cube_frag
  8543. },
  8544. equirect: {
  8545. uniforms: {
  8546. tEquirect: {
  8547. value: null
  8548. }
  8549. },
  8550. vertexShader: ShaderChunk.equirect_vert,
  8551. fragmentShader: ShaderChunk.equirect_frag
  8552. },
  8553. distanceRGBA: {
  8554. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  8555. referencePosition: {
  8556. value: new Vector3()
  8557. },
  8558. nearDistance: {
  8559. value: 1
  8560. },
  8561. farDistance: {
  8562. value: 1000
  8563. }
  8564. }]),
  8565. vertexShader: ShaderChunk.distanceRGBA_vert,
  8566. fragmentShader: ShaderChunk.distanceRGBA_frag
  8567. },
  8568. shadow: {
  8569. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  8570. color: {
  8571. value: new Color(0x00000)
  8572. },
  8573. opacity: {
  8574. value: 1.0
  8575. }
  8576. }]),
  8577. vertexShader: ShaderChunk.shadow_vert,
  8578. fragmentShader: ShaderChunk.shadow_frag
  8579. }
  8580. };
  8581. ShaderLib.physical = {
  8582. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  8583. clearcoat: {
  8584. value: 0
  8585. },
  8586. clearcoatMap: {
  8587. value: null
  8588. },
  8589. clearcoatRoughness: {
  8590. value: 0
  8591. },
  8592. clearcoatRoughnessMap: {
  8593. value: null
  8594. },
  8595. clearcoatNormalScale: {
  8596. value: new Vector2(1, 1)
  8597. },
  8598. clearcoatNormalMap: {
  8599. value: null
  8600. },
  8601. sheen: {
  8602. value: new Color(0x000000)
  8603. },
  8604. transmission: {
  8605. value: 0
  8606. },
  8607. transmissionMap: {
  8608. value: null
  8609. },
  8610. transmissionSamplerSize: {
  8611. value: new Vector2()
  8612. },
  8613. transmissionSamplerMap: {
  8614. value: null
  8615. },
  8616. thickness: {
  8617. value: 0
  8618. },
  8619. thicknessMap: {
  8620. value: null
  8621. },
  8622. attenuationDistance: {
  8623. value: 0
  8624. },
  8625. attenuationColor: {
  8626. value: new Color(0x000000)
  8627. }
  8628. }]),
  8629. vertexShader: ShaderChunk.meshphysical_vert,
  8630. fragmentShader: ShaderChunk.meshphysical_frag
  8631. };
  8632. function WebGLBackground(renderer, cubemaps, state, objects, premultipliedAlpha) {
  8633. const clearColor = new Color(0x000000);
  8634. let clearAlpha = 0;
  8635. let planeMesh;
  8636. let boxMesh;
  8637. let currentBackground = null;
  8638. let currentBackgroundVersion = 0;
  8639. let currentTonemapping = null;
  8640. function render(renderList, scene) {
  8641. let forceClear = false;
  8642. let background = scene.isScene === true ? scene.background : null;
  8643. if (background && background.isTexture) {
  8644. background = cubemaps.get(background);
  8645. } // Ignore background in AR
  8646. // TODO: Reconsider this.
  8647. const xr = renderer.xr;
  8648. const session = xr.getSession && xr.getSession();
  8649. if (session && session.environmentBlendMode === 'additive') {
  8650. background = null;
  8651. }
  8652. if (background === null) {
  8653. setClear(clearColor, clearAlpha);
  8654. } else if (background && background.isColor) {
  8655. setClear(background, 1);
  8656. forceClear = true;
  8657. }
  8658. if (renderer.autoClear || forceClear) {
  8659. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  8660. }
  8661. if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) {
  8662. if (boxMesh === undefined) {
  8663. boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({
  8664. name: 'BackgroundCubeMaterial',
  8665. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  8666. vertexShader: ShaderLib.cube.vertexShader,
  8667. fragmentShader: ShaderLib.cube.fragmentShader,
  8668. side: BackSide,
  8669. depthTest: false,
  8670. depthWrite: false,
  8671. fog: false
  8672. }));
  8673. boxMesh.geometry.deleteAttribute('normal');
  8674. boxMesh.geometry.deleteAttribute('uv');
  8675. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  8676. this.matrixWorld.copyPosition(camera.matrixWorld);
  8677. }; // enable code injection for non-built-in material
  8678. Object.defineProperty(boxMesh.material, 'envMap', {
  8679. get: function () {
  8680. return this.uniforms.envMap.value;
  8681. }
  8682. });
  8683. objects.update(boxMesh);
  8684. }
  8685. boxMesh.material.uniforms.envMap.value = background;
  8686. boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background._needsFlipEnvMap ? -1 : 1;
  8687. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8688. boxMesh.material.needsUpdate = true;
  8689. currentBackground = background;
  8690. currentBackgroundVersion = background.version;
  8691. currentTonemapping = renderer.toneMapping;
  8692. } // push to the pre-sorted opaque render list
  8693. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  8694. } else if (background && background.isTexture) {
  8695. if (planeMesh === undefined) {
  8696. planeMesh = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({
  8697. name: 'BackgroundMaterial',
  8698. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  8699. vertexShader: ShaderLib.background.vertexShader,
  8700. fragmentShader: ShaderLib.background.fragmentShader,
  8701. side: FrontSide,
  8702. depthTest: false,
  8703. depthWrite: false,
  8704. fog: false
  8705. }));
  8706. planeMesh.geometry.deleteAttribute('normal'); // enable code injection for non-built-in material
  8707. Object.defineProperty(planeMesh.material, 'map', {
  8708. get: function () {
  8709. return this.uniforms.t2D.value;
  8710. }
  8711. });
  8712. objects.update(planeMesh);
  8713. }
  8714. planeMesh.material.uniforms.t2D.value = background;
  8715. if (background.matrixAutoUpdate === true) {
  8716. background.updateMatrix();
  8717. }
  8718. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  8719. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8720. planeMesh.material.needsUpdate = true;
  8721. currentBackground = background;
  8722. currentBackgroundVersion = background.version;
  8723. currentTonemapping = renderer.toneMapping;
  8724. } // push to the pre-sorted opaque render list
  8725. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  8726. }
  8727. }
  8728. function setClear(color, alpha) {
  8729. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  8730. }
  8731. return {
  8732. getClearColor: function () {
  8733. return clearColor;
  8734. },
  8735. setClearColor: function (color, alpha = 1) {
  8736. clearColor.set(color);
  8737. clearAlpha = alpha;
  8738. setClear(clearColor, clearAlpha);
  8739. },
  8740. getClearAlpha: function () {
  8741. return clearAlpha;
  8742. },
  8743. setClearAlpha: function (alpha) {
  8744. clearAlpha = alpha;
  8745. setClear(clearColor, clearAlpha);
  8746. },
  8747. render: render
  8748. };
  8749. }
  8750. function WebGLBindingStates(gl, extensions, attributes, capabilities) {
  8751. const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  8752. const extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
  8753. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8754. const bindingStates = {};
  8755. const defaultState = createBindingState(null);
  8756. let currentState = defaultState;
  8757. function setup(object, material, program, geometry, index) {
  8758. let updateBuffers = false;
  8759. if (vaoAvailable) {
  8760. const state = getBindingState(geometry, program, material);
  8761. if (currentState !== state) {
  8762. currentState = state;
  8763. bindVertexArrayObject(currentState.object);
  8764. }
  8765. updateBuffers = needsUpdate(geometry, index);
  8766. if (updateBuffers) saveCache(geometry, index);
  8767. } else {
  8768. const wireframe = material.wireframe === true;
  8769. if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
  8770. currentState.geometry = geometry.id;
  8771. currentState.program = program.id;
  8772. currentState.wireframe = wireframe;
  8773. updateBuffers = true;
  8774. }
  8775. }
  8776. if (object.isInstancedMesh === true) {
  8777. updateBuffers = true;
  8778. }
  8779. if (index !== null) {
  8780. attributes.update(index, gl.ELEMENT_ARRAY_BUFFER);
  8781. }
  8782. if (updateBuffers) {
  8783. setupVertexAttributes(object, material, program, geometry);
  8784. if (index !== null) {
  8785. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index).buffer);
  8786. }
  8787. }
  8788. }
  8789. function createVertexArrayObject() {
  8790. if (capabilities.isWebGL2) return gl.createVertexArray();
  8791. return extension.createVertexArrayOES();
  8792. }
  8793. function bindVertexArrayObject(vao) {
  8794. if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
  8795. return extension.bindVertexArrayOES(vao);
  8796. }
  8797. function deleteVertexArrayObject(vao) {
  8798. if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
  8799. return extension.deleteVertexArrayOES(vao);
  8800. }
  8801. function getBindingState(geometry, program, material) {
  8802. const wireframe = material.wireframe === true;
  8803. let programMap = bindingStates[geometry.id];
  8804. if (programMap === undefined) {
  8805. programMap = {};
  8806. bindingStates[geometry.id] = programMap;
  8807. }
  8808. let stateMap = programMap[program.id];
  8809. if (stateMap === undefined) {
  8810. stateMap = {};
  8811. programMap[program.id] = stateMap;
  8812. }
  8813. let state = stateMap[wireframe];
  8814. if (state === undefined) {
  8815. state = createBindingState(createVertexArrayObject());
  8816. stateMap[wireframe] = state;
  8817. }
  8818. return state;
  8819. }
  8820. function createBindingState(vao) {
  8821. const newAttributes = [];
  8822. const enabledAttributes = [];
  8823. const attributeDivisors = [];
  8824. for (let i = 0; i < maxVertexAttributes; i++) {
  8825. newAttributes[i] = 0;
  8826. enabledAttributes[i] = 0;
  8827. attributeDivisors[i] = 0;
  8828. }
  8829. return {
  8830. // for backward compatibility on non-VAO support browser
  8831. geometry: null,
  8832. program: null,
  8833. wireframe: false,
  8834. newAttributes: newAttributes,
  8835. enabledAttributes: enabledAttributes,
  8836. attributeDivisors: attributeDivisors,
  8837. object: vao,
  8838. attributes: {},
  8839. index: null
  8840. };
  8841. }
  8842. function needsUpdate(geometry, index) {
  8843. const cachedAttributes = currentState.attributes;
  8844. const geometryAttributes = geometry.attributes;
  8845. let attributesNum = 0;
  8846. for (const key in geometryAttributes) {
  8847. const cachedAttribute = cachedAttributes[key];
  8848. const geometryAttribute = geometryAttributes[key];
  8849. if (cachedAttribute === undefined) return true;
  8850. if (cachedAttribute.attribute !== geometryAttribute) return true;
  8851. if (cachedAttribute.data !== geometryAttribute.data) return true;
  8852. attributesNum++;
  8853. }
  8854. if (currentState.attributesNum !== attributesNum) return true;
  8855. if (currentState.index !== index) return true;
  8856. return false;
  8857. }
  8858. function saveCache(geometry, index) {
  8859. const cache = {};
  8860. const attributes = geometry.attributes;
  8861. let attributesNum = 0;
  8862. for (const key in attributes) {
  8863. const attribute = attributes[key];
  8864. const data = {};
  8865. data.attribute = attribute;
  8866. if (attribute.data) {
  8867. data.data = attribute.data;
  8868. }
  8869. cache[key] = data;
  8870. attributesNum++;
  8871. }
  8872. currentState.attributes = cache;
  8873. currentState.attributesNum = attributesNum;
  8874. currentState.index = index;
  8875. }
  8876. function initAttributes() {
  8877. const newAttributes = currentState.newAttributes;
  8878. for (let i = 0, il = newAttributes.length; i < il; i++) {
  8879. newAttributes[i] = 0;
  8880. }
  8881. }
  8882. function enableAttribute(attribute) {
  8883. enableAttributeAndDivisor(attribute, 0);
  8884. }
  8885. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  8886. const newAttributes = currentState.newAttributes;
  8887. const enabledAttributes = currentState.enabledAttributes;
  8888. const attributeDivisors = currentState.attributeDivisors;
  8889. newAttributes[attribute] = 1;
  8890. if (enabledAttributes[attribute] === 0) {
  8891. gl.enableVertexAttribArray(attribute);
  8892. enabledAttributes[attribute] = 1;
  8893. }
  8894. if (attributeDivisors[attribute] !== meshPerAttribute) {
  8895. const extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  8896. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  8897. attributeDivisors[attribute] = meshPerAttribute;
  8898. }
  8899. }
  8900. function disableUnusedAttributes() {
  8901. const newAttributes = currentState.newAttributes;
  8902. const enabledAttributes = currentState.enabledAttributes;
  8903. for (let i = 0, il = enabledAttributes.length; i < il; i++) {
  8904. if (enabledAttributes[i] !== newAttributes[i]) {
  8905. gl.disableVertexAttribArray(i);
  8906. enabledAttributes[i] = 0;
  8907. }
  8908. }
  8909. }
  8910. function vertexAttribPointer(index, size, type, normalized, stride, offset) {
  8911. if (capabilities.isWebGL2 === true && (type === gl.INT || type === gl.UNSIGNED_INT)) {
  8912. gl.vertexAttribIPointer(index, size, type, stride, offset);
  8913. } else {
  8914. gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
  8915. }
  8916. }
  8917. function setupVertexAttributes(object, material, program, geometry) {
  8918. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  8919. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  8920. }
  8921. initAttributes();
  8922. const geometryAttributes = geometry.attributes;
  8923. const programAttributes = program.getAttributes();
  8924. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8925. for (const name in programAttributes) {
  8926. const programAttribute = programAttributes[name];
  8927. if (programAttribute >= 0) {
  8928. const geometryAttribute = geometryAttributes[name];
  8929. if (geometryAttribute !== undefined) {
  8930. const normalized = geometryAttribute.normalized;
  8931. const size = geometryAttribute.itemSize;
  8932. const attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  8933. if (attribute === undefined) continue;
  8934. const buffer = attribute.buffer;
  8935. const type = attribute.type;
  8936. const bytesPerElement = attribute.bytesPerElement;
  8937. if (geometryAttribute.isInterleavedBufferAttribute) {
  8938. const data = geometryAttribute.data;
  8939. const stride = data.stride;
  8940. const offset = geometryAttribute.offset;
  8941. if (data && data.isInstancedInterleavedBuffer) {
  8942. enableAttributeAndDivisor(programAttribute, data.meshPerAttribute);
  8943. if (geometry._maxInstanceCount === undefined) {
  8944. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8945. }
  8946. } else {
  8947. enableAttribute(programAttribute);
  8948. }
  8949. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8950. vertexAttribPointer(programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement);
  8951. } else {
  8952. if (geometryAttribute.isInstancedBufferAttribute) {
  8953. enableAttributeAndDivisor(programAttribute, geometryAttribute.meshPerAttribute);
  8954. if (geometry._maxInstanceCount === undefined) {
  8955. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8956. }
  8957. } else {
  8958. enableAttribute(programAttribute);
  8959. }
  8960. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8961. vertexAttribPointer(programAttribute, size, type, normalized, 0, 0);
  8962. }
  8963. } else if (name === 'instanceMatrix') {
  8964. const attribute = attributes.get(object.instanceMatrix); // TODO Attribute may not be available on context restore
  8965. if (attribute === undefined) continue;
  8966. const buffer = attribute.buffer;
  8967. const type = attribute.type;
  8968. enableAttributeAndDivisor(programAttribute + 0, 1);
  8969. enableAttributeAndDivisor(programAttribute + 1, 1);
  8970. enableAttributeAndDivisor(programAttribute + 2, 1);
  8971. enableAttributeAndDivisor(programAttribute + 3, 1);
  8972. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8973. gl.vertexAttribPointer(programAttribute + 0, 4, type, false, 64, 0);
  8974. gl.vertexAttribPointer(programAttribute + 1, 4, type, false, 64, 16);
  8975. gl.vertexAttribPointer(programAttribute + 2, 4, type, false, 64, 32);
  8976. gl.vertexAttribPointer(programAttribute + 3, 4, type, false, 64, 48);
  8977. } else if (name === 'instanceColor') {
  8978. const attribute = attributes.get(object.instanceColor); // TODO Attribute may not be available on context restore
  8979. if (attribute === undefined) continue;
  8980. const buffer = attribute.buffer;
  8981. const type = attribute.type;
  8982. enableAttributeAndDivisor(programAttribute, 1);
  8983. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  8984. gl.vertexAttribPointer(programAttribute, 3, type, false, 12, 0);
  8985. } else if (materialDefaultAttributeValues !== undefined) {
  8986. const value = materialDefaultAttributeValues[name];
  8987. if (value !== undefined) {
  8988. switch (value.length) {
  8989. case 2:
  8990. gl.vertexAttrib2fv(programAttribute, value);
  8991. break;
  8992. case 3:
  8993. gl.vertexAttrib3fv(programAttribute, value);
  8994. break;
  8995. case 4:
  8996. gl.vertexAttrib4fv(programAttribute, value);
  8997. break;
  8998. default:
  8999. gl.vertexAttrib1fv(programAttribute, value);
  9000. }
  9001. }
  9002. }
  9003. }
  9004. }
  9005. disableUnusedAttributes();
  9006. }
  9007. function dispose() {
  9008. reset();
  9009. for (const geometryId in bindingStates) {
  9010. const programMap = bindingStates[geometryId];
  9011. for (const programId in programMap) {
  9012. const stateMap = programMap[programId];
  9013. for (const wireframe in stateMap) {
  9014. deleteVertexArrayObject(stateMap[wireframe].object);
  9015. delete stateMap[wireframe];
  9016. }
  9017. delete programMap[programId];
  9018. }
  9019. delete bindingStates[geometryId];
  9020. }
  9021. }
  9022. function releaseStatesOfGeometry(geometry) {
  9023. if (bindingStates[geometry.id] === undefined) return;
  9024. const programMap = bindingStates[geometry.id];
  9025. for (const programId in programMap) {
  9026. const stateMap = programMap[programId];
  9027. for (const wireframe in stateMap) {
  9028. deleteVertexArrayObject(stateMap[wireframe].object);
  9029. delete stateMap[wireframe];
  9030. }
  9031. delete programMap[programId];
  9032. }
  9033. delete bindingStates[geometry.id];
  9034. }
  9035. function releaseStatesOfProgram(program) {
  9036. for (const geometryId in bindingStates) {
  9037. const programMap = bindingStates[geometryId];
  9038. if (programMap[program.id] === undefined) continue;
  9039. const stateMap = programMap[program.id];
  9040. for (const wireframe in stateMap) {
  9041. deleteVertexArrayObject(stateMap[wireframe].object);
  9042. delete stateMap[wireframe];
  9043. }
  9044. delete programMap[program.id];
  9045. }
  9046. }
  9047. function reset() {
  9048. resetDefaultState();
  9049. if (currentState === defaultState) return;
  9050. currentState = defaultState;
  9051. bindVertexArrayObject(currentState.object);
  9052. } // for backward-compatilibity
  9053. function resetDefaultState() {
  9054. defaultState.geometry = null;
  9055. defaultState.program = null;
  9056. defaultState.wireframe = false;
  9057. }
  9058. return {
  9059. setup: setup,
  9060. reset: reset,
  9061. resetDefaultState: resetDefaultState,
  9062. dispose: dispose,
  9063. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9064. releaseStatesOfProgram: releaseStatesOfProgram,
  9065. initAttributes: initAttributes,
  9066. enableAttribute: enableAttribute,
  9067. disableUnusedAttributes: disableUnusedAttributes
  9068. };
  9069. }
  9070. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  9071. const isWebGL2 = capabilities.isWebGL2;
  9072. let mode;
  9073. function setMode(value) {
  9074. mode = value;
  9075. }
  9076. function render(start, count) {
  9077. gl.drawArrays(mode, start, count);
  9078. info.update(count, mode, 1);
  9079. }
  9080. function renderInstances(start, count, primcount) {
  9081. if (primcount === 0) return;
  9082. let extension, methodName;
  9083. if (isWebGL2) {
  9084. extension = gl;
  9085. methodName = 'drawArraysInstanced';
  9086. } else {
  9087. extension = extensions.get('ANGLE_instanced_arrays');
  9088. methodName = 'drawArraysInstancedANGLE';
  9089. if (extension === null) {
  9090. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9091. return;
  9092. }
  9093. }
  9094. extension[methodName](mode, start, count, primcount);
  9095. info.update(count, mode, primcount);
  9096. } //
  9097. this.setMode = setMode;
  9098. this.render = render;
  9099. this.renderInstances = renderInstances;
  9100. }
  9101. function WebGLCapabilities(gl, extensions, parameters) {
  9102. let maxAnisotropy;
  9103. function getMaxAnisotropy() {
  9104. if (maxAnisotropy !== undefined) return maxAnisotropy;
  9105. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  9106. const extension = extensions.get('EXT_texture_filter_anisotropic');
  9107. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  9108. } else {
  9109. maxAnisotropy = 0;
  9110. }
  9111. return maxAnisotropy;
  9112. }
  9113. function getMaxPrecision(precision) {
  9114. if (precision === 'highp') {
  9115. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) {
  9116. return 'highp';
  9117. }
  9118. precision = 'mediump';
  9119. }
  9120. if (precision === 'mediump') {
  9121. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) {
  9122. return 'mediump';
  9123. }
  9124. }
  9125. return 'lowp';
  9126. }
  9127. /* eslint-disable no-undef */
  9128. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  9129. /* eslint-enable no-undef */
  9130. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9131. const maxPrecision = getMaxPrecision(precision);
  9132. if (maxPrecision !== precision) {
  9133. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  9134. precision = maxPrecision;
  9135. }
  9136. const drawBuffers = isWebGL2 || extensions.has('WEBGL_draw_buffers');
  9137. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9138. const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
  9139. const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9140. const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
  9141. const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9142. const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  9143. const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
  9144. const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS);
  9145. const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9146. const vertexTextures = maxVertexTextures > 0;
  9147. const floatFragmentTextures = isWebGL2 || extensions.has('OES_texture_float');
  9148. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9149. const maxSamples = isWebGL2 ? gl.getParameter(gl.MAX_SAMPLES) : 0;
  9150. return {
  9151. isWebGL2: isWebGL2,
  9152. drawBuffers: drawBuffers,
  9153. getMaxAnisotropy: getMaxAnisotropy,
  9154. getMaxPrecision: getMaxPrecision,
  9155. precision: precision,
  9156. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9157. maxTextures: maxTextures,
  9158. maxVertexTextures: maxVertexTextures,
  9159. maxTextureSize: maxTextureSize,
  9160. maxCubemapSize: maxCubemapSize,
  9161. maxAttributes: maxAttributes,
  9162. maxVertexUniforms: maxVertexUniforms,
  9163. maxVaryings: maxVaryings,
  9164. maxFragmentUniforms: maxFragmentUniforms,
  9165. vertexTextures: vertexTextures,
  9166. floatFragmentTextures: floatFragmentTextures,
  9167. floatVertexTextures: floatVertexTextures,
  9168. maxSamples: maxSamples
  9169. };
  9170. }
  9171. function WebGLClipping(properties) {
  9172. const scope = this;
  9173. let globalState = null,
  9174. numGlobalPlanes = 0,
  9175. localClippingEnabled = false,
  9176. renderingShadows = false;
  9177. const plane = new Plane(),
  9178. viewNormalMatrix = new Matrix3(),
  9179. uniform = {
  9180. value: null,
  9181. needsUpdate: false
  9182. };
  9183. this.uniform = uniform;
  9184. this.numPlanes = 0;
  9185. this.numIntersection = 0;
  9186. this.init = function (planes, enableLocalClipping, camera) {
  9187. const enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  9188. // run another frame in order to reset the state:
  9189. numGlobalPlanes !== 0 || localClippingEnabled;
  9190. localClippingEnabled = enableLocalClipping;
  9191. globalState = projectPlanes(planes, camera, 0);
  9192. numGlobalPlanes = planes.length;
  9193. return enabled;
  9194. };
  9195. this.beginShadows = function () {
  9196. renderingShadows = true;
  9197. projectPlanes(null);
  9198. };
  9199. this.endShadows = function () {
  9200. renderingShadows = false;
  9201. resetGlobalState();
  9202. };
  9203. this.setState = function (material, camera, useCache) {
  9204. const planes = material.clippingPlanes,
  9205. clipIntersection = material.clipIntersection,
  9206. clipShadows = material.clipShadows;
  9207. const materialProperties = properties.get(material);
  9208. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  9209. // there's no local clipping
  9210. if (renderingShadows) {
  9211. // there's no global clipping
  9212. projectPlanes(null);
  9213. } else {
  9214. resetGlobalState();
  9215. }
  9216. } else {
  9217. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9218. lGlobal = nGlobal * 4;
  9219. let dstArray = materialProperties.clippingState || null;
  9220. uniform.value = dstArray; // ensure unique state
  9221. dstArray = projectPlanes(planes, camera, lGlobal, useCache);
  9222. for (let i = 0; i !== lGlobal; ++i) {
  9223. dstArray[i] = globalState[i];
  9224. }
  9225. materialProperties.clippingState = dstArray;
  9226. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9227. this.numPlanes += nGlobal;
  9228. }
  9229. };
  9230. function resetGlobalState() {
  9231. if (uniform.value !== globalState) {
  9232. uniform.value = globalState;
  9233. uniform.needsUpdate = numGlobalPlanes > 0;
  9234. }
  9235. scope.numPlanes = numGlobalPlanes;
  9236. scope.numIntersection = 0;
  9237. }
  9238. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  9239. const nPlanes = planes !== null ? planes.length : 0;
  9240. let dstArray = null;
  9241. if (nPlanes !== 0) {
  9242. dstArray = uniform.value;
  9243. if (skipTransform !== true || dstArray === null) {
  9244. const flatSize = dstOffset + nPlanes * 4,
  9245. viewMatrix = camera.matrixWorldInverse;
  9246. viewNormalMatrix.getNormalMatrix(viewMatrix);
  9247. if (dstArray === null || dstArray.length < flatSize) {
  9248. dstArray = new Float32Array(flatSize);
  9249. }
  9250. for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  9251. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  9252. plane.normal.toArray(dstArray, i4);
  9253. dstArray[i4 + 3] = plane.constant;
  9254. }
  9255. }
  9256. uniform.value = dstArray;
  9257. uniform.needsUpdate = true;
  9258. }
  9259. scope.numPlanes = nPlanes;
  9260. scope.numIntersection = 0;
  9261. return dstArray;
  9262. }
  9263. }
  9264. function WebGLCubeMaps(renderer) {
  9265. let cubemaps = new WeakMap();
  9266. function mapTextureMapping(texture, mapping) {
  9267. if (mapping === EquirectangularReflectionMapping) {
  9268. texture.mapping = CubeReflectionMapping;
  9269. } else if (mapping === EquirectangularRefractionMapping) {
  9270. texture.mapping = CubeRefractionMapping;
  9271. }
  9272. return texture;
  9273. }
  9274. function get(texture) {
  9275. if (texture && texture.isTexture) {
  9276. const mapping = texture.mapping;
  9277. if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
  9278. if (cubemaps.has(texture)) {
  9279. const cubemap = cubemaps.get(texture).texture;
  9280. return mapTextureMapping(cubemap, texture.mapping);
  9281. } else {
  9282. const image = texture.image;
  9283. if (image && image.height > 0) {
  9284. const currentRenderTarget = renderer.getRenderTarget();
  9285. const renderTarget = new WebGLCubeRenderTarget(image.height / 2);
  9286. renderTarget.fromEquirectangularTexture(renderer, texture);
  9287. cubemaps.set(texture, renderTarget);
  9288. renderer.setRenderTarget(currentRenderTarget);
  9289. texture.addEventListener('dispose', onTextureDispose);
  9290. return mapTextureMapping(renderTarget.texture, texture.mapping);
  9291. } else {
  9292. // image not yet ready. try the conversion next frame
  9293. return null;
  9294. }
  9295. }
  9296. }
  9297. }
  9298. return texture;
  9299. }
  9300. function onTextureDispose(event) {
  9301. const texture = event.target;
  9302. texture.removeEventListener('dispose', onTextureDispose);
  9303. const cubemap = cubemaps.get(texture);
  9304. if (cubemap !== undefined) {
  9305. cubemaps.delete(texture);
  9306. cubemap.dispose();
  9307. }
  9308. }
  9309. function dispose() {
  9310. cubemaps = new WeakMap();
  9311. }
  9312. return {
  9313. get: get,
  9314. dispose: dispose
  9315. };
  9316. }
  9317. function WebGLExtensions(gl) {
  9318. const extensions = {};
  9319. function getExtension(name) {
  9320. if (extensions[name] !== undefined) {
  9321. return extensions[name];
  9322. }
  9323. let extension;
  9324. switch (name) {
  9325. case 'WEBGL_depth_texture':
  9326. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  9327. break;
  9328. case 'EXT_texture_filter_anisotropic':
  9329. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  9330. break;
  9331. case 'WEBGL_compressed_texture_s3tc':
  9332. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  9333. break;
  9334. case 'WEBGL_compressed_texture_pvrtc':
  9335. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  9336. break;
  9337. default:
  9338. extension = gl.getExtension(name);
  9339. }
  9340. extensions[name] = extension;
  9341. return extension;
  9342. }
  9343. return {
  9344. has: function (name) {
  9345. return getExtension(name) !== null;
  9346. },
  9347. init: function (capabilities) {
  9348. if (capabilities.isWebGL2) {
  9349. getExtension('EXT_color_buffer_float');
  9350. } else {
  9351. getExtension('WEBGL_depth_texture');
  9352. getExtension('OES_texture_float');
  9353. getExtension('OES_texture_half_float');
  9354. getExtension('OES_texture_half_float_linear');
  9355. getExtension('OES_standard_derivatives');
  9356. getExtension('OES_element_index_uint');
  9357. getExtension('OES_vertex_array_object');
  9358. getExtension('ANGLE_instanced_arrays');
  9359. }
  9360. getExtension('OES_texture_float_linear');
  9361. getExtension('EXT_color_buffer_half_float');
  9362. },
  9363. get: function (name) {
  9364. const extension = getExtension(name);
  9365. if (extension === null) {
  9366. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  9367. }
  9368. return extension;
  9369. }
  9370. };
  9371. }
  9372. function WebGLGeometries(gl, attributes, info, bindingStates) {
  9373. const geometries = {};
  9374. const wireframeAttributes = new WeakMap();
  9375. function onGeometryDispose(event) {
  9376. const geometry = event.target;
  9377. if (geometry.index !== null) {
  9378. attributes.remove(geometry.index);
  9379. }
  9380. for (const name in geometry.attributes) {
  9381. attributes.remove(geometry.attributes[name]);
  9382. }
  9383. geometry.removeEventListener('dispose', onGeometryDispose);
  9384. delete geometries[geometry.id];
  9385. const attribute = wireframeAttributes.get(geometry);
  9386. if (attribute) {
  9387. attributes.remove(attribute);
  9388. wireframeAttributes.delete(geometry);
  9389. }
  9390. bindingStates.releaseStatesOfGeometry(geometry);
  9391. if (geometry.isInstancedBufferGeometry === true) {
  9392. delete geometry._maxInstanceCount;
  9393. } //
  9394. info.memory.geometries--;
  9395. }
  9396. function get(object, geometry) {
  9397. if (geometries[geometry.id] === true) return geometry;
  9398. geometry.addEventListener('dispose', onGeometryDispose);
  9399. geometries[geometry.id] = true;
  9400. info.memory.geometries++;
  9401. return geometry;
  9402. }
  9403. function update(geometry) {
  9404. const geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates.
  9405. for (const name in geometryAttributes) {
  9406. attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER);
  9407. } // morph targets
  9408. const morphAttributes = geometry.morphAttributes;
  9409. for (const name in morphAttributes) {
  9410. const array = morphAttributes[name];
  9411. for (let i = 0, l = array.length; i < l; i++) {
  9412. attributes.update(array[i], gl.ARRAY_BUFFER);
  9413. }
  9414. }
  9415. }
  9416. function updateWireframeAttribute(geometry) {
  9417. const indices = [];
  9418. const geometryIndex = geometry.index;
  9419. const geometryPosition = geometry.attributes.position;
  9420. let version = 0;
  9421. if (geometryIndex !== null) {
  9422. const array = geometryIndex.array;
  9423. version = geometryIndex.version;
  9424. for (let i = 0, l = array.length; i < l; i += 3) {
  9425. const a = array[i + 0];
  9426. const b = array[i + 1];
  9427. const c = array[i + 2];
  9428. indices.push(a, b, b, c, c, a);
  9429. }
  9430. } else {
  9431. const array = geometryPosition.array;
  9432. version = geometryPosition.version;
  9433. for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  9434. const a = i + 0;
  9435. const b = i + 1;
  9436. const c = i + 2;
  9437. indices.push(a, b, b, c, c, a);
  9438. }
  9439. }
  9440. const attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  9441. attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
  9442. //
  9443. const previousAttribute = wireframeAttributes.get(geometry);
  9444. if (previousAttribute) attributes.remove(previousAttribute); //
  9445. wireframeAttributes.set(geometry, attribute);
  9446. }
  9447. function getWireframeAttribute(geometry) {
  9448. const currentAttribute = wireframeAttributes.get(geometry);
  9449. if (currentAttribute) {
  9450. const geometryIndex = geometry.index;
  9451. if (geometryIndex !== null) {
  9452. // if the attribute is obsolete, create a new one
  9453. if (currentAttribute.version < geometryIndex.version) {
  9454. updateWireframeAttribute(geometry);
  9455. }
  9456. }
  9457. } else {
  9458. updateWireframeAttribute(geometry);
  9459. }
  9460. return wireframeAttributes.get(geometry);
  9461. }
  9462. return {
  9463. get: get,
  9464. update: update,
  9465. getWireframeAttribute: getWireframeAttribute
  9466. };
  9467. }
  9468. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  9469. const isWebGL2 = capabilities.isWebGL2;
  9470. let mode;
  9471. function setMode(value) {
  9472. mode = value;
  9473. }
  9474. let type, bytesPerElement;
  9475. function setIndex(value) {
  9476. type = value.type;
  9477. bytesPerElement = value.bytesPerElement;
  9478. }
  9479. function render(start, count) {
  9480. gl.drawElements(mode, count, type, start * bytesPerElement);
  9481. info.update(count, mode, 1);
  9482. }
  9483. function renderInstances(start, count, primcount) {
  9484. if (primcount === 0) return;
  9485. let extension, methodName;
  9486. if (isWebGL2) {
  9487. extension = gl;
  9488. methodName = 'drawElementsInstanced';
  9489. } else {
  9490. extension = extensions.get('ANGLE_instanced_arrays');
  9491. methodName = 'drawElementsInstancedANGLE';
  9492. if (extension === null) {
  9493. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9494. return;
  9495. }
  9496. }
  9497. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  9498. info.update(count, mode, primcount);
  9499. } //
  9500. this.setMode = setMode;
  9501. this.setIndex = setIndex;
  9502. this.render = render;
  9503. this.renderInstances = renderInstances;
  9504. }
  9505. function WebGLInfo(gl) {
  9506. const memory = {
  9507. geometries: 0,
  9508. textures: 0
  9509. };
  9510. const render = {
  9511. frame: 0,
  9512. calls: 0,
  9513. triangles: 0,
  9514. points: 0,
  9515. lines: 0
  9516. };
  9517. function update(count, mode, instanceCount) {
  9518. render.calls++;
  9519. switch (mode) {
  9520. case gl.TRIANGLES:
  9521. render.triangles += instanceCount * (count / 3);
  9522. break;
  9523. case gl.LINES:
  9524. render.lines += instanceCount * (count / 2);
  9525. break;
  9526. case gl.LINE_STRIP:
  9527. render.lines += instanceCount * (count - 1);
  9528. break;
  9529. case gl.LINE_LOOP:
  9530. render.lines += instanceCount * count;
  9531. break;
  9532. case gl.POINTS:
  9533. render.points += instanceCount * count;
  9534. break;
  9535. default:
  9536. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  9537. break;
  9538. }
  9539. }
  9540. function reset() {
  9541. render.frame++;
  9542. render.calls = 0;
  9543. render.triangles = 0;
  9544. render.points = 0;
  9545. render.lines = 0;
  9546. }
  9547. return {
  9548. memory: memory,
  9549. render: render,
  9550. programs: null,
  9551. autoReset: true,
  9552. reset: reset,
  9553. update: update
  9554. };
  9555. }
  9556. function numericalSort(a, b) {
  9557. return a[0] - b[0];
  9558. }
  9559. function absNumericalSort(a, b) {
  9560. return Math.abs(b[1]) - Math.abs(a[1]);
  9561. }
  9562. function WebGLMorphtargets(gl) {
  9563. const influencesList = {};
  9564. const morphInfluences = new Float32Array(8);
  9565. const workInfluences = [];
  9566. for (let i = 0; i < 8; i++) {
  9567. workInfluences[i] = [i, 0];
  9568. }
  9569. function update(object, geometry, material, program) {
  9570. const objectInfluences = object.morphTargetInfluences; // When object doesn't have morph target influences defined, we treat it as a 0-length array
  9571. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  9572. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  9573. let influences = influencesList[geometry.id];
  9574. if (influences === undefined) {
  9575. // initialise list
  9576. influences = [];
  9577. for (let i = 0; i < length; i++) {
  9578. influences[i] = [i, 0];
  9579. }
  9580. influencesList[geometry.id] = influences;
  9581. } // Collect influences
  9582. for (let i = 0; i < length; i++) {
  9583. const influence = influences[i];
  9584. influence[0] = i;
  9585. influence[1] = objectInfluences[i];
  9586. }
  9587. influences.sort(absNumericalSort);
  9588. for (let i = 0; i < 8; i++) {
  9589. if (i < length && influences[i][1]) {
  9590. workInfluences[i][0] = influences[i][0];
  9591. workInfluences[i][1] = influences[i][1];
  9592. } else {
  9593. workInfluences[i][0] = Number.MAX_SAFE_INTEGER;
  9594. workInfluences[i][1] = 0;
  9595. }
  9596. }
  9597. workInfluences.sort(numericalSort);
  9598. const morphTargets = material.morphTargets && geometry.morphAttributes.position;
  9599. const morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  9600. let morphInfluencesSum = 0;
  9601. for (let i = 0; i < 8; i++) {
  9602. const influence = workInfluences[i];
  9603. const index = influence[0];
  9604. const value = influence[1];
  9605. if (index !== Number.MAX_SAFE_INTEGER && value) {
  9606. if (morphTargets && geometry.getAttribute('morphTarget' + i) !== morphTargets[index]) {
  9607. geometry.setAttribute('morphTarget' + i, morphTargets[index]);
  9608. }
  9609. if (morphNormals && geometry.getAttribute('morphNormal' + i) !== morphNormals[index]) {
  9610. geometry.setAttribute('morphNormal' + i, morphNormals[index]);
  9611. }
  9612. morphInfluences[i] = value;
  9613. morphInfluencesSum += value;
  9614. } else {
  9615. if (morphTargets && geometry.hasAttribute('morphTarget' + i) === true) {
  9616. geometry.deleteAttribute('morphTarget' + i);
  9617. }
  9618. if (morphNormals && geometry.hasAttribute('morphNormal' + i) === true) {
  9619. geometry.deleteAttribute('morphNormal' + i);
  9620. }
  9621. morphInfluences[i] = 0;
  9622. }
  9623. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  9624. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  9625. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  9626. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  9627. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  9628. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  9629. }
  9630. return {
  9631. update: update
  9632. };
  9633. }
  9634. function WebGLObjects(gl, geometries, attributes, info) {
  9635. let updateMap = new WeakMap();
  9636. function update(object) {
  9637. const frame = info.render.frame;
  9638. const geometry = object.geometry;
  9639. const buffergeometry = geometries.get(object, geometry); // Update once per frame
  9640. if (updateMap.get(buffergeometry) !== frame) {
  9641. geometries.update(buffergeometry);
  9642. updateMap.set(buffergeometry, frame);
  9643. }
  9644. if (object.isInstancedMesh) {
  9645. if (object.hasEventListener('dispose', onInstancedMeshDispose) === false) {
  9646. object.addEventListener('dispose', onInstancedMeshDispose);
  9647. }
  9648. attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER);
  9649. if (object.instanceColor !== null) {
  9650. attributes.update(object.instanceColor, gl.ARRAY_BUFFER);
  9651. }
  9652. }
  9653. return buffergeometry;
  9654. }
  9655. function dispose() {
  9656. updateMap = new WeakMap();
  9657. }
  9658. function onInstancedMeshDispose(event) {
  9659. const instancedMesh = event.target;
  9660. instancedMesh.removeEventListener('dispose', onInstancedMeshDispose);
  9661. attributes.remove(instancedMesh.instanceMatrix);
  9662. if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor);
  9663. }
  9664. return {
  9665. update: update,
  9666. dispose: dispose
  9667. };
  9668. }
  9669. class DataTexture2DArray extends Texture {
  9670. constructor(data = null, width = 1, height = 1, depth = 1) {
  9671. super(null);
  9672. this.image = {
  9673. data,
  9674. width,
  9675. height,
  9676. depth
  9677. };
  9678. this.magFilter = NearestFilter;
  9679. this.minFilter = NearestFilter;
  9680. this.wrapR = ClampToEdgeWrapping;
  9681. this.generateMipmaps = false;
  9682. this.flipY = false;
  9683. this.unpackAlignment = 1;
  9684. this.needsUpdate = true;
  9685. }
  9686. }
  9687. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  9688. class DataTexture3D extends Texture {
  9689. constructor(data = null, width = 1, height = 1, depth = 1) {
  9690. // We're going to add .setXXX() methods for setting properties later.
  9691. // Users can still set in DataTexture3D directly.
  9692. //
  9693. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  9694. // texture.anisotropy = 16;
  9695. //
  9696. // See #14839
  9697. super(null);
  9698. this.image = {
  9699. data,
  9700. width,
  9701. height,
  9702. depth
  9703. };
  9704. this.magFilter = NearestFilter;
  9705. this.minFilter = NearestFilter;
  9706. this.wrapR = ClampToEdgeWrapping;
  9707. this.generateMipmaps = false;
  9708. this.flipY = false;
  9709. this.unpackAlignment = 1;
  9710. this.needsUpdate = true;
  9711. }
  9712. }
  9713. DataTexture3D.prototype.isDataTexture3D = true;
  9714. /**
  9715. * Uniforms of a program.
  9716. * Those form a tree structure with a special top-level container for the root,
  9717. * which you get by calling 'new WebGLUniforms( gl, program )'.
  9718. *
  9719. *
  9720. * Properties of inner nodes including the top-level container:
  9721. *
  9722. * .seq - array of nested uniforms
  9723. * .map - nested uniforms by name
  9724. *
  9725. *
  9726. * Methods of all nodes except the top-level container:
  9727. *
  9728. * .setValue( gl, value, [textures] )
  9729. *
  9730. * uploads a uniform value(s)
  9731. * the 'textures' parameter is needed for sampler uniforms
  9732. *
  9733. *
  9734. * Static methods of the top-level container (textures factorizations):
  9735. *
  9736. * .upload( gl, seq, values, textures )
  9737. *
  9738. * sets uniforms in 'seq' to 'values[id].value'
  9739. *
  9740. * .seqWithValue( seq, values ) : filteredSeq
  9741. *
  9742. * filters 'seq' entries with corresponding entry in values
  9743. *
  9744. *
  9745. * Methods of the top-level container (textures factorizations):
  9746. *
  9747. * .setValue( gl, name, value, textures )
  9748. *
  9749. * sets uniform with name 'name' to 'value'
  9750. *
  9751. * .setOptional( gl, obj, prop )
  9752. *
  9753. * like .set for an optional property of the object
  9754. *
  9755. */
  9756. const emptyTexture = new Texture();
  9757. const emptyTexture2dArray = new DataTexture2DArray();
  9758. const emptyTexture3d = new DataTexture3D();
  9759. const emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  9760. // Array Caches (provide typed arrays for temporary by size)
  9761. const arrayCacheF32 = [];
  9762. const arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  9763. const mat4array = new Float32Array(16);
  9764. const mat3array = new Float32Array(9);
  9765. const mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  9766. function flatten(array, nBlocks, blockSize) {
  9767. const firstElem = array[0];
  9768. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  9769. // see http://jacksondunstan.com/articles/983
  9770. const n = nBlocks * blockSize;
  9771. let r = arrayCacheF32[n];
  9772. if (r === undefined) {
  9773. r = new Float32Array(n);
  9774. arrayCacheF32[n] = r;
  9775. }
  9776. if (nBlocks !== 0) {
  9777. firstElem.toArray(r, 0);
  9778. for (let i = 1, offset = 0; i !== nBlocks; ++i) {
  9779. offset += blockSize;
  9780. array[i].toArray(r, offset);
  9781. }
  9782. }
  9783. return r;
  9784. }
  9785. function arraysEqual(a, b) {
  9786. if (a.length !== b.length) return false;
  9787. for (let i = 0, l = a.length; i < l; i++) {
  9788. if (a[i] !== b[i]) return false;
  9789. }
  9790. return true;
  9791. }
  9792. function copyArray(a, b) {
  9793. for (let i = 0, l = b.length; i < l; i++) {
  9794. a[i] = b[i];
  9795. }
  9796. } // Texture unit allocation
  9797. function allocTexUnits(textures, n) {
  9798. let r = arrayCacheI32[n];
  9799. if (r === undefined) {
  9800. r = new Int32Array(n);
  9801. arrayCacheI32[n] = r;
  9802. }
  9803. for (let i = 0; i !== n; ++i) {
  9804. r[i] = textures.allocateTextureUnit();
  9805. }
  9806. return r;
  9807. } // --- Setters ---
  9808. // Note: Defining these methods externally, because they come in a bunch
  9809. // and this way their names minify.
  9810. // Single scalar
  9811. function setValueV1f(gl, v) {
  9812. const cache = this.cache;
  9813. if (cache[0] === v) return;
  9814. gl.uniform1f(this.addr, v);
  9815. cache[0] = v;
  9816. } // Single float vector (from flat array or THREE.VectorN)
  9817. function setValueV2f(gl, v) {
  9818. const cache = this.cache;
  9819. if (v.x !== undefined) {
  9820. if (cache[0] !== v.x || cache[1] !== v.y) {
  9821. gl.uniform2f(this.addr, v.x, v.y);
  9822. cache[0] = v.x;
  9823. cache[1] = v.y;
  9824. }
  9825. } else {
  9826. if (arraysEqual(cache, v)) return;
  9827. gl.uniform2fv(this.addr, v);
  9828. copyArray(cache, v);
  9829. }
  9830. }
  9831. function setValueV3f(gl, v) {
  9832. const cache = this.cache;
  9833. if (v.x !== undefined) {
  9834. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  9835. gl.uniform3f(this.addr, v.x, v.y, v.z);
  9836. cache[0] = v.x;
  9837. cache[1] = v.y;
  9838. cache[2] = v.z;
  9839. }
  9840. } else if (v.r !== undefined) {
  9841. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  9842. gl.uniform3f(this.addr, v.r, v.g, v.b);
  9843. cache[0] = v.r;
  9844. cache[1] = v.g;
  9845. cache[2] = v.b;
  9846. }
  9847. } else {
  9848. if (arraysEqual(cache, v)) return;
  9849. gl.uniform3fv(this.addr, v);
  9850. copyArray(cache, v);
  9851. }
  9852. }
  9853. function setValueV4f(gl, v) {
  9854. const cache = this.cache;
  9855. if (v.x !== undefined) {
  9856. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  9857. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  9858. cache[0] = v.x;
  9859. cache[1] = v.y;
  9860. cache[2] = v.z;
  9861. cache[3] = v.w;
  9862. }
  9863. } else {
  9864. if (arraysEqual(cache, v)) return;
  9865. gl.uniform4fv(this.addr, v);
  9866. copyArray(cache, v);
  9867. }
  9868. } // Single matrix (from flat array or THREE.MatrixN)
  9869. function setValueM2(gl, v) {
  9870. const cache = this.cache;
  9871. const elements = v.elements;
  9872. if (elements === undefined) {
  9873. if (arraysEqual(cache, v)) return;
  9874. gl.uniformMatrix2fv(this.addr, false, v);
  9875. copyArray(cache, v);
  9876. } else {
  9877. if (arraysEqual(cache, elements)) return;
  9878. mat2array.set(elements);
  9879. gl.uniformMatrix2fv(this.addr, false, mat2array);
  9880. copyArray(cache, elements);
  9881. }
  9882. }
  9883. function setValueM3(gl, v) {
  9884. const cache = this.cache;
  9885. const elements = v.elements;
  9886. if (elements === undefined) {
  9887. if (arraysEqual(cache, v)) return;
  9888. gl.uniformMatrix3fv(this.addr, false, v);
  9889. copyArray(cache, v);
  9890. } else {
  9891. if (arraysEqual(cache, elements)) return;
  9892. mat3array.set(elements);
  9893. gl.uniformMatrix3fv(this.addr, false, mat3array);
  9894. copyArray(cache, elements);
  9895. }
  9896. }
  9897. function setValueM4(gl, v) {
  9898. const cache = this.cache;
  9899. const elements = v.elements;
  9900. if (elements === undefined) {
  9901. if (arraysEqual(cache, v)) return;
  9902. gl.uniformMatrix4fv(this.addr, false, v);
  9903. copyArray(cache, v);
  9904. } else {
  9905. if (arraysEqual(cache, elements)) return;
  9906. mat4array.set(elements);
  9907. gl.uniformMatrix4fv(this.addr, false, mat4array);
  9908. copyArray(cache, elements);
  9909. }
  9910. } // Single integer / boolean
  9911. function setValueV1i(gl, v) {
  9912. const cache = this.cache;
  9913. if (cache[0] === v) return;
  9914. gl.uniform1i(this.addr, v);
  9915. cache[0] = v;
  9916. } // Single integer / boolean vector (from flat array)
  9917. function setValueV2i(gl, v) {
  9918. const cache = this.cache;
  9919. if (arraysEqual(cache, v)) return;
  9920. gl.uniform2iv(this.addr, v);
  9921. copyArray(cache, v);
  9922. }
  9923. function setValueV3i(gl, v) {
  9924. const cache = this.cache;
  9925. if (arraysEqual(cache, v)) return;
  9926. gl.uniform3iv(this.addr, v);
  9927. copyArray(cache, v);
  9928. }
  9929. function setValueV4i(gl, v) {
  9930. const cache = this.cache;
  9931. if (arraysEqual(cache, v)) return;
  9932. gl.uniform4iv(this.addr, v);
  9933. copyArray(cache, v);
  9934. } // Single unsigned integer
  9935. function setValueV1ui(gl, v) {
  9936. const cache = this.cache;
  9937. if (cache[0] === v) return;
  9938. gl.uniform1ui(this.addr, v);
  9939. cache[0] = v;
  9940. } // Single unsigned integer vector (from flat array)
  9941. function setValueV2ui(gl, v) {
  9942. const cache = this.cache;
  9943. if (arraysEqual(cache, v)) return;
  9944. gl.uniform2uiv(this.addr, v);
  9945. copyArray(cache, v);
  9946. }
  9947. function setValueV3ui(gl, v) {
  9948. const cache = this.cache;
  9949. if (arraysEqual(cache, v)) return;
  9950. gl.uniform3uiv(this.addr, v);
  9951. copyArray(cache, v);
  9952. }
  9953. function setValueV4ui(gl, v) {
  9954. const cache = this.cache;
  9955. if (arraysEqual(cache, v)) return;
  9956. gl.uniform4uiv(this.addr, v);
  9957. copyArray(cache, v);
  9958. } // Single texture (2D / Cube)
  9959. function setValueT1(gl, v, textures) {
  9960. const cache = this.cache;
  9961. const unit = textures.allocateTextureUnit();
  9962. if (cache[0] !== unit) {
  9963. gl.uniform1i(this.addr, unit);
  9964. cache[0] = unit;
  9965. }
  9966. textures.safeSetTexture2D(v || emptyTexture, unit);
  9967. }
  9968. function setValueT3D1(gl, v, textures) {
  9969. const cache = this.cache;
  9970. const unit = textures.allocateTextureUnit();
  9971. if (cache[0] !== unit) {
  9972. gl.uniform1i(this.addr, unit);
  9973. cache[0] = unit;
  9974. }
  9975. textures.setTexture3D(v || emptyTexture3d, unit);
  9976. }
  9977. function setValueT6(gl, v, textures) {
  9978. const cache = this.cache;
  9979. const unit = textures.allocateTextureUnit();
  9980. if (cache[0] !== unit) {
  9981. gl.uniform1i(this.addr, unit);
  9982. cache[0] = unit;
  9983. }
  9984. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  9985. }
  9986. function setValueT2DArray1(gl, v, textures) {
  9987. const cache = this.cache;
  9988. const unit = textures.allocateTextureUnit();
  9989. if (cache[0] !== unit) {
  9990. gl.uniform1i(this.addr, unit);
  9991. cache[0] = unit;
  9992. }
  9993. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  9994. } // Helper to pick the right setter for the singular case
  9995. function getSingularSetter(type) {
  9996. switch (type) {
  9997. case 0x1406:
  9998. return setValueV1f;
  9999. // FLOAT
  10000. case 0x8b50:
  10001. return setValueV2f;
  10002. // _VEC2
  10003. case 0x8b51:
  10004. return setValueV3f;
  10005. // _VEC3
  10006. case 0x8b52:
  10007. return setValueV4f;
  10008. // _VEC4
  10009. case 0x8b5a:
  10010. return setValueM2;
  10011. // _MAT2
  10012. case 0x8b5b:
  10013. return setValueM3;
  10014. // _MAT3
  10015. case 0x8b5c:
  10016. return setValueM4;
  10017. // _MAT4
  10018. case 0x1404:
  10019. case 0x8b56:
  10020. return setValueV1i;
  10021. // INT, BOOL
  10022. case 0x8b53:
  10023. case 0x8b57:
  10024. return setValueV2i;
  10025. // _VEC2
  10026. case 0x8b54:
  10027. case 0x8b58:
  10028. return setValueV3i;
  10029. // _VEC3
  10030. case 0x8b55:
  10031. case 0x8b59:
  10032. return setValueV4i;
  10033. // _VEC4
  10034. case 0x1405:
  10035. return setValueV1ui;
  10036. // UINT
  10037. case 0x8dc6:
  10038. return setValueV2ui;
  10039. // _VEC2
  10040. case 0x8dc7:
  10041. return setValueV3ui;
  10042. // _VEC3
  10043. case 0x8dc8:
  10044. return setValueV4ui;
  10045. // _VEC4
  10046. case 0x8b5e: // SAMPLER_2D
  10047. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10048. case 0x8dca: // INT_SAMPLER_2D
  10049. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10050. case 0x8b62:
  10051. // SAMPLER_2D_SHADOW
  10052. return setValueT1;
  10053. case 0x8b5f: // SAMPLER_3D
  10054. case 0x8dcb: // INT_SAMPLER_3D
  10055. case 0x8dd3:
  10056. // UNSIGNED_INT_SAMPLER_3D
  10057. return setValueT3D1;
  10058. case 0x8b60: // SAMPLER_CUBE
  10059. case 0x8dcc: // INT_SAMPLER_CUBE
  10060. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10061. case 0x8dc5:
  10062. // SAMPLER_CUBE_SHADOW
  10063. return setValueT6;
  10064. case 0x8dc1: // SAMPLER_2D_ARRAY
  10065. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10066. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10067. case 0x8dc4:
  10068. // SAMPLER_2D_ARRAY_SHADOW
  10069. return setValueT2DArray1;
  10070. }
  10071. } // Array of scalars
  10072. function setValueV1fArray(gl, v) {
  10073. gl.uniform1fv(this.addr, v);
  10074. } // Array of vectors (from flat array or array of THREE.VectorN)
  10075. function setValueV2fArray(gl, v) {
  10076. const data = flatten(v, this.size, 2);
  10077. gl.uniform2fv(this.addr, data);
  10078. }
  10079. function setValueV3fArray(gl, v) {
  10080. const data = flatten(v, this.size, 3);
  10081. gl.uniform3fv(this.addr, data);
  10082. }
  10083. function setValueV4fArray(gl, v) {
  10084. const data = flatten(v, this.size, 4);
  10085. gl.uniform4fv(this.addr, data);
  10086. } // Array of matrices (from flat array or array of THREE.MatrixN)
  10087. function setValueM2Array(gl, v) {
  10088. const data = flatten(v, this.size, 4);
  10089. gl.uniformMatrix2fv(this.addr, false, data);
  10090. }
  10091. function setValueM3Array(gl, v) {
  10092. const data = flatten(v, this.size, 9);
  10093. gl.uniformMatrix3fv(this.addr, false, data);
  10094. }
  10095. function setValueM4Array(gl, v) {
  10096. const data = flatten(v, this.size, 16);
  10097. gl.uniformMatrix4fv(this.addr, false, data);
  10098. } // Array of integer / boolean
  10099. function setValueV1iArray(gl, v) {
  10100. gl.uniform1iv(this.addr, v);
  10101. } // Array of integer / boolean vectors (from flat array)
  10102. function setValueV2iArray(gl, v) {
  10103. gl.uniform2iv(this.addr, v);
  10104. }
  10105. function setValueV3iArray(gl, v) {
  10106. gl.uniform3iv(this.addr, v);
  10107. }
  10108. function setValueV4iArray(gl, v) {
  10109. gl.uniform4iv(this.addr, v);
  10110. } // Array of unsigned integer
  10111. function setValueV1uiArray(gl, v) {
  10112. gl.uniform1uiv(this.addr, v);
  10113. } // Array of unsigned integer vectors (from flat array)
  10114. function setValueV2uiArray(gl, v) {
  10115. gl.uniform2uiv(this.addr, v);
  10116. }
  10117. function setValueV3uiArray(gl, v) {
  10118. gl.uniform3uiv(this.addr, v);
  10119. }
  10120. function setValueV4uiArray(gl, v) {
  10121. gl.uniform4uiv(this.addr, v);
  10122. } // Array of textures (2D / Cube)
  10123. function setValueT1Array(gl, v, textures) {
  10124. const n = v.length;
  10125. const units = allocTexUnits(textures, n);
  10126. gl.uniform1iv(this.addr, units);
  10127. for (let i = 0; i !== n; ++i) {
  10128. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  10129. }
  10130. }
  10131. function setValueT6Array(gl, v, textures) {
  10132. const n = v.length;
  10133. const units = allocTexUnits(textures, n);
  10134. gl.uniform1iv(this.addr, units);
  10135. for (let i = 0; i !== n; ++i) {
  10136. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  10137. }
  10138. } // Helper to pick the right setter for a pure (bottom-level) array
  10139. function getPureArraySetter(type) {
  10140. switch (type) {
  10141. case 0x1406:
  10142. return setValueV1fArray;
  10143. // FLOAT
  10144. case 0x8b50:
  10145. return setValueV2fArray;
  10146. // _VEC2
  10147. case 0x8b51:
  10148. return setValueV3fArray;
  10149. // _VEC3
  10150. case 0x8b52:
  10151. return setValueV4fArray;
  10152. // _VEC4
  10153. case 0x8b5a:
  10154. return setValueM2Array;
  10155. // _MAT2
  10156. case 0x8b5b:
  10157. return setValueM3Array;
  10158. // _MAT3
  10159. case 0x8b5c:
  10160. return setValueM4Array;
  10161. // _MAT4
  10162. case 0x1404:
  10163. case 0x8b56:
  10164. return setValueV1iArray;
  10165. // INT, BOOL
  10166. case 0x8b53:
  10167. case 0x8b57:
  10168. return setValueV2iArray;
  10169. // _VEC2
  10170. case 0x8b54:
  10171. case 0x8b58:
  10172. return setValueV3iArray;
  10173. // _VEC3
  10174. case 0x8b55:
  10175. case 0x8b59:
  10176. return setValueV4iArray;
  10177. // _VEC4
  10178. case 0x1405:
  10179. return setValueV1uiArray;
  10180. // UINT
  10181. case 0x8dc6:
  10182. return setValueV2uiArray;
  10183. // _VEC2
  10184. case 0x8dc7:
  10185. return setValueV3uiArray;
  10186. // _VEC3
  10187. case 0x8dc8:
  10188. return setValueV4uiArray;
  10189. // _VEC4
  10190. case 0x8b5e: // SAMPLER_2D
  10191. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10192. case 0x8dca: // INT_SAMPLER_2D
  10193. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10194. case 0x8b62:
  10195. // SAMPLER_2D_SHADOW
  10196. return setValueT1Array;
  10197. case 0x8b60: // SAMPLER_CUBE
  10198. case 0x8dcc: // INT_SAMPLER_CUBE
  10199. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10200. case 0x8dc5:
  10201. // SAMPLER_CUBE_SHADOW
  10202. return setValueT6Array;
  10203. }
  10204. } // --- Uniform Classes ---
  10205. function SingleUniform(id, activeInfo, addr) {
  10206. this.id = id;
  10207. this.addr = addr;
  10208. this.cache = [];
  10209. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  10210. }
  10211. function PureArrayUniform(id, activeInfo, addr) {
  10212. this.id = id;
  10213. this.addr = addr;
  10214. this.cache = [];
  10215. this.size = activeInfo.size;
  10216. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  10217. }
  10218. PureArrayUniform.prototype.updateCache = function (data) {
  10219. const cache = this.cache;
  10220. if (data instanceof Float32Array && cache.length !== data.length) {
  10221. this.cache = new Float32Array(data.length);
  10222. }
  10223. copyArray(cache, data);
  10224. };
  10225. function StructuredUniform(id) {
  10226. this.id = id;
  10227. this.seq = [];
  10228. this.map = {};
  10229. }
  10230. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  10231. const seq = this.seq;
  10232. for (let i = 0, n = seq.length; i !== n; ++i) {
  10233. const u = seq[i];
  10234. u.setValue(gl, value[u.id], textures);
  10235. }
  10236. }; // --- Top-level ---
  10237. // Parser - builds up the property tree from the path strings
  10238. const RePathPart = /(\w+)(\])?(\[|\.)?/g; // extracts
  10239. // - the identifier (member name or array index)
  10240. // - followed by an optional right bracket (found when array index)
  10241. // - followed by an optional left bracket or dot (type of subscript)
  10242. //
  10243. // Note: These portions can be read in a non-overlapping fashion and
  10244. // allow straightforward parsing of the hierarchy that WebGL encodes
  10245. // in the uniform names.
  10246. function addUniform(container, uniformObject) {
  10247. container.seq.push(uniformObject);
  10248. container.map[uniformObject.id] = uniformObject;
  10249. }
  10250. function parseUniform(activeInfo, addr, container) {
  10251. const path = activeInfo.name,
  10252. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  10253. RePathPart.lastIndex = 0;
  10254. while (true) {
  10255. const match = RePathPart.exec(path),
  10256. matchEnd = RePathPart.lastIndex;
  10257. let id = match[1];
  10258. const idIsIndex = match[2] === ']',
  10259. subscript = match[3];
  10260. if (idIsIndex) id = id | 0; // convert to integer
  10261. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  10262. // bare name or "pure" bottom-level array "[0]" suffix
  10263. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  10264. break;
  10265. } else {
  10266. // step into inner node / create it in case it doesn't exist
  10267. const map = container.map;
  10268. let next = map[id];
  10269. if (next === undefined) {
  10270. next = new StructuredUniform(id);
  10271. addUniform(container, next);
  10272. }
  10273. container = next;
  10274. }
  10275. }
  10276. } // Root Container
  10277. function WebGLUniforms(gl, program) {
  10278. this.seq = [];
  10279. this.map = {};
  10280. const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  10281. for (let i = 0; i < n; ++i) {
  10282. const info = gl.getActiveUniform(program, i),
  10283. addr = gl.getUniformLocation(program, info.name);
  10284. parseUniform(info, addr, this);
  10285. }
  10286. }
  10287. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  10288. const u = this.map[name];
  10289. if (u !== undefined) u.setValue(gl, value, textures);
  10290. };
  10291. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  10292. const v = object[name];
  10293. if (v !== undefined) this.setValue(gl, name, v);
  10294. }; // Static interface
  10295. WebGLUniforms.upload = function (gl, seq, values, textures) {
  10296. for (let i = 0, n = seq.length; i !== n; ++i) {
  10297. const u = seq[i],
  10298. v = values[u.id];
  10299. if (v.needsUpdate !== false) {
  10300. // note: always updating when .needsUpdate is undefined
  10301. u.setValue(gl, v.value, textures);
  10302. }
  10303. }
  10304. };
  10305. WebGLUniforms.seqWithValue = function (seq, values) {
  10306. const r = [];
  10307. for (let i = 0, n = seq.length; i !== n; ++i) {
  10308. const u = seq[i];
  10309. if (u.id in values) r.push(u);
  10310. }
  10311. return r;
  10312. };
  10313. function WebGLShader(gl, type, string) {
  10314. const shader = gl.createShader(type);
  10315. gl.shaderSource(shader, string);
  10316. gl.compileShader(shader);
  10317. return shader;
  10318. }
  10319. let programIdCount = 0;
  10320. function addLineNumbers(string) {
  10321. const lines = string.split('\n');
  10322. for (let i = 0; i < lines.length; i++) {
  10323. lines[i] = i + 1 + ': ' + lines[i];
  10324. }
  10325. return lines.join('\n');
  10326. }
  10327. function getEncodingComponents(encoding) {
  10328. switch (encoding) {
  10329. case LinearEncoding:
  10330. return ['Linear', '( value )'];
  10331. case sRGBEncoding:
  10332. return ['sRGB', '( value )'];
  10333. case RGBEEncoding:
  10334. return ['RGBE', '( value )'];
  10335. case RGBM7Encoding:
  10336. return ['RGBM', '( value, 7.0 )'];
  10337. case RGBM16Encoding:
  10338. return ['RGBM', '( value, 16.0 )'];
  10339. case RGBDEncoding:
  10340. return ['RGBD', '( value, 256.0 )'];
  10341. case GammaEncoding:
  10342. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  10343. case LogLuvEncoding:
  10344. return ['LogLuv', '( value )'];
  10345. default:
  10346. console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
  10347. return ['Linear', '( value )'];
  10348. }
  10349. }
  10350. function getShaderErrors(gl, shader, type) {
  10351. const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  10352. const log = gl.getShaderInfoLog(shader).trim();
  10353. if (status && log === '') return ''; // --enable-privileged-webgl-extension
  10354. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10355. const source = gl.getShaderSource(shader);
  10356. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers(source);
  10357. }
  10358. function getTexelDecodingFunction(functionName, encoding) {
  10359. const components = getEncodingComponents(encoding);
  10360. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  10361. }
  10362. function getTexelEncodingFunction(functionName, encoding) {
  10363. const components = getEncodingComponents(encoding);
  10364. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  10365. }
  10366. function getToneMappingFunction(functionName, toneMapping) {
  10367. let toneMappingName;
  10368. switch (toneMapping) {
  10369. case LinearToneMapping:
  10370. toneMappingName = 'Linear';
  10371. break;
  10372. case ReinhardToneMapping:
  10373. toneMappingName = 'Reinhard';
  10374. break;
  10375. case CineonToneMapping:
  10376. toneMappingName = 'OptimizedCineon';
  10377. break;
  10378. case ACESFilmicToneMapping:
  10379. toneMappingName = 'ACESFilmic';
  10380. break;
  10381. case CustomToneMapping:
  10382. toneMappingName = 'Custom';
  10383. break;
  10384. default:
  10385. console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
  10386. toneMappingName = 'Linear';
  10387. }
  10388. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  10389. }
  10390. function generateExtensions(parameters) {
  10391. 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' : ''];
  10392. return chunks.filter(filterEmptyLine).join('\n');
  10393. }
  10394. function generateDefines(defines) {
  10395. const chunks = [];
  10396. for (const name in defines) {
  10397. const value = defines[name];
  10398. if (value === false) continue;
  10399. chunks.push('#define ' + name + ' ' + value);
  10400. }
  10401. return chunks.join('\n');
  10402. }
  10403. function fetchAttributeLocations(gl, program) {
  10404. const attributes = {};
  10405. const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  10406. for (let i = 0; i < n; i++) {
  10407. const info = gl.getActiveAttrib(program, i);
  10408. const name = info.name; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  10409. attributes[name] = gl.getAttribLocation(program, name);
  10410. }
  10411. return attributes;
  10412. }
  10413. function filterEmptyLine(string) {
  10414. return string !== '';
  10415. }
  10416. function replaceLightNums(string, parameters) {
  10417. 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);
  10418. }
  10419. function replaceClippingPlaneNums(string, parameters) {
  10420. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  10421. } // Resolve Includes
  10422. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  10423. function resolveIncludes(string) {
  10424. return string.replace(includePattern, includeReplacer);
  10425. }
  10426. function includeReplacer(match, include) {
  10427. const string = ShaderChunk[include];
  10428. if (string === undefined) {
  10429. throw new Error('Can not resolve #include <' + include + '>');
  10430. }
  10431. return resolveIncludes(string);
  10432. } // Unroll Loops
  10433. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  10434. 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;
  10435. function unrollLoops(string) {
  10436. return string.replace(unrollLoopPattern, loopReplacer).replace(deprecatedUnrollLoopPattern, deprecatedLoopReplacer);
  10437. }
  10438. function deprecatedLoopReplacer(match, start, end, snippet) {
  10439. console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');
  10440. return loopReplacer(match, start, end, snippet);
  10441. }
  10442. function loopReplacer(match, start, end, snippet) {
  10443. let string = '';
  10444. for (let i = parseInt(start); i < parseInt(end); i++) {
  10445. string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  10446. }
  10447. return string;
  10448. } //
  10449. function generatePrecision(parameters) {
  10450. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  10451. if (parameters.precision === 'highp') {
  10452. precisionstring += '\n#define HIGH_PRECISION';
  10453. } else if (parameters.precision === 'mediump') {
  10454. precisionstring += '\n#define MEDIUM_PRECISION';
  10455. } else if (parameters.precision === 'lowp') {
  10456. precisionstring += '\n#define LOW_PRECISION';
  10457. }
  10458. return precisionstring;
  10459. }
  10460. function generateShadowMapTypeDefine(parameters) {
  10461. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  10462. if (parameters.shadowMapType === PCFShadowMap) {
  10463. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  10464. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  10465. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  10466. } else if (parameters.shadowMapType === VSMShadowMap) {
  10467. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  10468. }
  10469. return shadowMapTypeDefine;
  10470. }
  10471. function generateEnvMapTypeDefine(parameters) {
  10472. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10473. if (parameters.envMap) {
  10474. switch (parameters.envMapMode) {
  10475. case CubeReflectionMapping:
  10476. case CubeRefractionMapping:
  10477. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10478. break;
  10479. case CubeUVReflectionMapping:
  10480. case CubeUVRefractionMapping:
  10481. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  10482. break;
  10483. }
  10484. }
  10485. return envMapTypeDefine;
  10486. }
  10487. function generateEnvMapModeDefine(parameters) {
  10488. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  10489. if (parameters.envMap) {
  10490. switch (parameters.envMapMode) {
  10491. case CubeRefractionMapping:
  10492. case CubeUVRefractionMapping:
  10493. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  10494. break;
  10495. }
  10496. }
  10497. return envMapModeDefine;
  10498. }
  10499. function generateEnvMapBlendingDefine(parameters) {
  10500. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  10501. if (parameters.envMap) {
  10502. switch (parameters.combine) {
  10503. case MultiplyOperation:
  10504. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10505. break;
  10506. case MixOperation:
  10507. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  10508. break;
  10509. case AddOperation:
  10510. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  10511. break;
  10512. }
  10513. }
  10514. return envMapBlendingDefine;
  10515. }
  10516. function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
  10517. const gl = renderer.getContext();
  10518. const defines = parameters.defines;
  10519. let vertexShader = parameters.vertexShader;
  10520. let fragmentShader = parameters.fragmentShader;
  10521. const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  10522. const envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  10523. const envMapModeDefine = generateEnvMapModeDefine(parameters);
  10524. const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  10525. const gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  10526. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  10527. const customDefines = generateDefines(defines);
  10528. const program = gl.createProgram();
  10529. let prefixVertex, prefixFragment;
  10530. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  10531. if (parameters.isRawShaderMaterial) {
  10532. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  10533. if (prefixVertex.length > 0) {
  10534. prefixVertex += '\n';
  10535. }
  10536. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  10537. if (prefixFragment.length > 0) {
  10538. prefixFragment += '\n';
  10539. }
  10540. } else {
  10541. 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');
  10542. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + (parameters.alphaTest % 1 ? '' : '.0') : '', // add '.0' if integer
  10543. '#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
  10544. 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
  10545. 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');
  10546. }
  10547. vertexShader = resolveIncludes(vertexShader);
  10548. vertexShader = replaceLightNums(vertexShader, parameters);
  10549. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  10550. fragmentShader = resolveIncludes(fragmentShader);
  10551. fragmentShader = replaceLightNums(fragmentShader, parameters);
  10552. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  10553. vertexShader = unrollLoops(vertexShader);
  10554. fragmentShader = unrollLoops(fragmentShader);
  10555. if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
  10556. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  10557. versionString = '#version 300 es\n';
  10558. prefixVertex = ['#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  10559. 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;
  10560. }
  10561. const vertexGlsl = versionString + prefixVertex + vertexShader;
  10562. const fragmentGlsl = versionString + prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  10563. // console.log( '*FRAGMENT*', fragmentGlsl );
  10564. const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl);
  10565. const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl);
  10566. gl.attachShader(program, glVertexShader);
  10567. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  10568. if (parameters.index0AttributeName !== undefined) {
  10569. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  10570. } else if (parameters.morphTargets === true) {
  10571. // programs with morphTargets displace position out of attribute 0
  10572. gl.bindAttribLocation(program, 0, 'position');
  10573. }
  10574. gl.linkProgram(program); // check for link errors
  10575. if (renderer.debug.checkShaderErrors) {
  10576. const programLog = gl.getProgramInfoLog(program).trim();
  10577. const vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  10578. const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  10579. let runnable = true;
  10580. let haveDiagnostics = true;
  10581. if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {
  10582. runnable = false;
  10583. const vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  10584. const fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  10585. console.error('THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors);
  10586. } else if (programLog !== '') {
  10587. console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()', programLog);
  10588. } else if (vertexLog === '' || fragmentLog === '') {
  10589. haveDiagnostics = false;
  10590. }
  10591. if (haveDiagnostics) {
  10592. this.diagnostics = {
  10593. runnable: runnable,
  10594. programLog: programLog,
  10595. vertexShader: {
  10596. log: vertexLog,
  10597. prefix: prefixVertex
  10598. },
  10599. fragmentShader: {
  10600. log: fragmentLog,
  10601. prefix: prefixFragment
  10602. }
  10603. };
  10604. }
  10605. } // Clean up
  10606. // Crashes in iOS9 and iOS10. #18402
  10607. // gl.detachShader( program, glVertexShader );
  10608. // gl.detachShader( program, glFragmentShader );
  10609. gl.deleteShader(glVertexShader);
  10610. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  10611. let cachedUniforms;
  10612. this.getUniforms = function () {
  10613. if (cachedUniforms === undefined) {
  10614. cachedUniforms = new WebGLUniforms(gl, program);
  10615. }
  10616. return cachedUniforms;
  10617. }; // set up caching for attribute locations
  10618. let cachedAttributes;
  10619. this.getAttributes = function () {
  10620. if (cachedAttributes === undefined) {
  10621. cachedAttributes = fetchAttributeLocations(gl, program);
  10622. }
  10623. return cachedAttributes;
  10624. }; // free resource
  10625. this.destroy = function () {
  10626. bindingStates.releaseStatesOfProgram(this);
  10627. gl.deleteProgram(program);
  10628. this.program = undefined;
  10629. }; //
  10630. this.name = parameters.shaderName;
  10631. this.id = programIdCount++;
  10632. this.cacheKey = cacheKey;
  10633. this.usedTimes = 1;
  10634. this.program = program;
  10635. this.vertexShader = glVertexShader;
  10636. this.fragmentShader = glFragmentShader;
  10637. return this;
  10638. }
  10639. function WebGLPrograms(renderer, cubemaps, extensions, capabilities, bindingStates, clipping) {
  10640. const programs = [];
  10641. const isWebGL2 = capabilities.isWebGL2;
  10642. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  10643. const floatVertexTextures = capabilities.floatVertexTextures;
  10644. const maxVertexUniforms = capabilities.maxVertexUniforms;
  10645. const vertexTextures = capabilities.vertexTextures;
  10646. let precision = capabilities.precision;
  10647. const shaderIDs = {
  10648. MeshDepthMaterial: 'depth',
  10649. MeshDistanceMaterial: 'distanceRGBA',
  10650. MeshNormalMaterial: 'normal',
  10651. MeshBasicMaterial: 'basic',
  10652. MeshLambertMaterial: 'lambert',
  10653. MeshPhongMaterial: 'phong',
  10654. MeshToonMaterial: 'toon',
  10655. MeshStandardMaterial: 'physical',
  10656. MeshPhysicalMaterial: 'physical',
  10657. MeshMatcapMaterial: 'matcap',
  10658. LineBasicMaterial: 'basic',
  10659. LineDashedMaterial: 'dashed',
  10660. PointsMaterial: 'points',
  10661. ShadowMaterial: 'shadow',
  10662. SpriteMaterial: 'sprite'
  10663. };
  10664. 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'];
  10665. function getMaxBones(object) {
  10666. const skeleton = object.skeleton;
  10667. const bones = skeleton.bones;
  10668. if (floatVertexTextures) {
  10669. return 1024;
  10670. } else {
  10671. // default for when object is not specified
  10672. // ( for example when prebuilding shader to be used with multiple objects )
  10673. //
  10674. // - leave some extra space for other uniforms
  10675. // - limit here is ANGLE's 254 max uniform vectors
  10676. // (up to 54 should be safe)
  10677. const nVertexUniforms = maxVertexUniforms;
  10678. const nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  10679. const maxBones = Math.min(nVertexMatrices, bones.length);
  10680. if (maxBones < bones.length) {
  10681. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  10682. return 0;
  10683. }
  10684. return maxBones;
  10685. }
  10686. }
  10687. function getTextureEncodingFromMap(map) {
  10688. let encoding;
  10689. if (map && map.isTexture) {
  10690. encoding = map.encoding;
  10691. } else if (map && map.isWebGLRenderTarget) {
  10692. console.warn('THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.');
  10693. encoding = map.texture.encoding;
  10694. } else {
  10695. encoding = LinearEncoding;
  10696. }
  10697. return encoding;
  10698. }
  10699. function getParameters(material, lights, shadows, scene, object) {
  10700. const fog = scene.fog;
  10701. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  10702. const envMap = cubemaps.get(material.envMap || environment);
  10703. const shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  10704. // (not to blow over maxLights budget)
  10705. const maxBones = object.isSkinnedMesh ? getMaxBones(object) : 0;
  10706. if (material.precision !== null) {
  10707. precision = capabilities.getMaxPrecision(material.precision);
  10708. if (precision !== material.precision) {
  10709. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  10710. }
  10711. }
  10712. let vertexShader, fragmentShader;
  10713. if (shaderID) {
  10714. const shader = ShaderLib[shaderID];
  10715. vertexShader = shader.vertexShader;
  10716. fragmentShader = shader.fragmentShader;
  10717. } else {
  10718. vertexShader = material.vertexShader;
  10719. fragmentShader = material.fragmentShader;
  10720. }
  10721. const currentRenderTarget = renderer.getRenderTarget();
  10722. const parameters = {
  10723. isWebGL2: isWebGL2,
  10724. shaderID: shaderID,
  10725. shaderName: material.type,
  10726. vertexShader: vertexShader,
  10727. fragmentShader: fragmentShader,
  10728. defines: material.defines,
  10729. isRawShaderMaterial: material.isRawShaderMaterial === true,
  10730. glslVersion: material.glslVersion,
  10731. precision: precision,
  10732. instancing: object.isInstancedMesh === true,
  10733. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  10734. supportsVertexTextures: vertexTextures,
  10735. outputEncoding: currentRenderTarget !== null ? getTextureEncodingFromMap(currentRenderTarget.texture) : renderer.outputEncoding,
  10736. map: !!material.map,
  10737. mapEncoding: getTextureEncodingFromMap(material.map),
  10738. matcap: !!material.matcap,
  10739. matcapEncoding: getTextureEncodingFromMap(material.matcap),
  10740. envMap: !!envMap,
  10741. envMapMode: envMap && envMap.mapping,
  10742. envMapEncoding: getTextureEncodingFromMap(envMap),
  10743. envMapCubeUV: !!envMap && (envMap.mapping === CubeUVReflectionMapping || envMap.mapping === CubeUVRefractionMapping),
  10744. lightMap: !!material.lightMap,
  10745. lightMapEncoding: getTextureEncodingFromMap(material.lightMap),
  10746. aoMap: !!material.aoMap,
  10747. emissiveMap: !!material.emissiveMap,
  10748. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap),
  10749. bumpMap: !!material.bumpMap,
  10750. normalMap: !!material.normalMap,
  10751. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  10752. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  10753. clearcoatMap: !!material.clearcoatMap,
  10754. clearcoatRoughnessMap: !!material.clearcoatRoughnessMap,
  10755. clearcoatNormalMap: !!material.clearcoatNormalMap,
  10756. displacementMap: !!material.displacementMap,
  10757. roughnessMap: !!material.roughnessMap,
  10758. metalnessMap: !!material.metalnessMap,
  10759. specularMap: !!material.specularMap,
  10760. alphaMap: !!material.alphaMap,
  10761. gradientMap: !!material.gradientMap,
  10762. sheen: !!material.sheen,
  10763. transmission: !!material.transmission,
  10764. transmissionMap: !!material.transmissionMap,
  10765. thicknessMap: !!material.thicknessMap,
  10766. combine: material.combine,
  10767. vertexTangents: material.normalMap && material.vertexTangents,
  10768. vertexColors: material.vertexColors,
  10769. vertexAlphas: material.vertexColors === true && object.geometry && object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4,
  10770. 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.transmission || !!material.transmissionMap || !!material.thicknessMap,
  10771. 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,
  10772. fog: !!fog,
  10773. useFog: material.fog,
  10774. fogExp2: fog && fog.isFogExp2,
  10775. flatShading: !!material.flatShading,
  10776. sizeAttenuation: material.sizeAttenuation,
  10777. logarithmicDepthBuffer: logarithmicDepthBuffer,
  10778. skinning: object.isSkinnedMesh === true && maxBones > 0,
  10779. maxBones: maxBones,
  10780. useVertexTexture: floatVertexTextures,
  10781. morphTargets: material.morphTargets,
  10782. morphNormals: material.morphNormals,
  10783. numDirLights: lights.directional.length,
  10784. numPointLights: lights.point.length,
  10785. numSpotLights: lights.spot.length,
  10786. numRectAreaLights: lights.rectArea.length,
  10787. numHemiLights: lights.hemi.length,
  10788. numDirLightShadows: lights.directionalShadowMap.length,
  10789. numPointLightShadows: lights.pointShadowMap.length,
  10790. numSpotLightShadows: lights.spotShadowMap.length,
  10791. numClippingPlanes: clipping.numPlanes,
  10792. numClipIntersection: clipping.numIntersection,
  10793. dithering: material.dithering,
  10794. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  10795. shadowMapType: renderer.shadowMap.type,
  10796. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  10797. physicallyCorrectLights: renderer.physicallyCorrectLights,
  10798. premultipliedAlpha: material.premultipliedAlpha,
  10799. alphaTest: material.alphaTest,
  10800. doubleSided: material.side === DoubleSide,
  10801. flipSided: material.side === BackSide,
  10802. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false,
  10803. index0AttributeName: material.index0AttributeName,
  10804. extensionDerivatives: material.extensions && material.extensions.derivatives,
  10805. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  10806. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  10807. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  10808. rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
  10809. rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
  10810. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
  10811. customProgramCacheKey: material.customProgramCacheKey()
  10812. };
  10813. return parameters;
  10814. }
  10815. function getProgramCacheKey(parameters) {
  10816. const array = [];
  10817. if (parameters.shaderID) {
  10818. array.push(parameters.shaderID);
  10819. } else {
  10820. array.push(parameters.fragmentShader);
  10821. array.push(parameters.vertexShader);
  10822. }
  10823. if (parameters.defines !== undefined) {
  10824. for (const name in parameters.defines) {
  10825. array.push(name);
  10826. array.push(parameters.defines[name]);
  10827. }
  10828. }
  10829. if (parameters.isRawShaderMaterial === false) {
  10830. for (let i = 0; i < parameterNames.length; i++) {
  10831. array.push(parameters[parameterNames[i]]);
  10832. }
  10833. array.push(renderer.outputEncoding);
  10834. array.push(renderer.gammaFactor);
  10835. }
  10836. array.push(parameters.customProgramCacheKey);
  10837. return array.join();
  10838. }
  10839. function getUniforms(material) {
  10840. const shaderID = shaderIDs[material.type];
  10841. let uniforms;
  10842. if (shaderID) {
  10843. const shader = ShaderLib[shaderID];
  10844. uniforms = UniformsUtils.clone(shader.uniforms);
  10845. } else {
  10846. uniforms = material.uniforms;
  10847. }
  10848. return uniforms;
  10849. }
  10850. function acquireProgram(parameters, cacheKey) {
  10851. let program; // Check if code has been already compiled
  10852. for (let p = 0, pl = programs.length; p < pl; p++) {
  10853. const preexistingProgram = programs[p];
  10854. if (preexistingProgram.cacheKey === cacheKey) {
  10855. program = preexistingProgram;
  10856. ++program.usedTimes;
  10857. break;
  10858. }
  10859. }
  10860. if (program === undefined) {
  10861. program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
  10862. programs.push(program);
  10863. }
  10864. return program;
  10865. }
  10866. function releaseProgram(program) {
  10867. if (--program.usedTimes === 0) {
  10868. // Remove from unordered set
  10869. const i = programs.indexOf(program);
  10870. programs[i] = programs[programs.length - 1];
  10871. programs.pop(); // Free WebGL resources
  10872. program.destroy();
  10873. }
  10874. }
  10875. return {
  10876. getParameters: getParameters,
  10877. getProgramCacheKey: getProgramCacheKey,
  10878. getUniforms: getUniforms,
  10879. acquireProgram: acquireProgram,
  10880. releaseProgram: releaseProgram,
  10881. // Exposed for resource monitoring & error feedback via renderer.info:
  10882. programs: programs
  10883. };
  10884. }
  10885. function WebGLProperties() {
  10886. let properties = new WeakMap();
  10887. function get(object) {
  10888. let map = properties.get(object);
  10889. if (map === undefined) {
  10890. map = {};
  10891. properties.set(object, map);
  10892. }
  10893. return map;
  10894. }
  10895. function remove(object) {
  10896. properties.delete(object);
  10897. }
  10898. function update(object, key, value) {
  10899. properties.get(object)[key] = value;
  10900. }
  10901. function dispose() {
  10902. properties = new WeakMap();
  10903. }
  10904. return {
  10905. get: get,
  10906. remove: remove,
  10907. update: update,
  10908. dispose: dispose
  10909. };
  10910. }
  10911. function painterSortStable(a, b) {
  10912. if (a.groupOrder !== b.groupOrder) {
  10913. return a.groupOrder - b.groupOrder;
  10914. } else if (a.renderOrder !== b.renderOrder) {
  10915. return a.renderOrder - b.renderOrder;
  10916. } else if (a.program !== b.program) {
  10917. return a.program.id - b.program.id;
  10918. } else if (a.material.id !== b.material.id) {
  10919. return a.material.id - b.material.id;
  10920. } else if (a.z !== b.z) {
  10921. return a.z - b.z;
  10922. } else {
  10923. return a.id - b.id;
  10924. }
  10925. }
  10926. function reversePainterSortStable(a, b) {
  10927. if (a.groupOrder !== b.groupOrder) {
  10928. return a.groupOrder - b.groupOrder;
  10929. } else if (a.renderOrder !== b.renderOrder) {
  10930. return a.renderOrder - b.renderOrder;
  10931. } else if (a.z !== b.z) {
  10932. return b.z - a.z;
  10933. } else {
  10934. return a.id - b.id;
  10935. }
  10936. }
  10937. function WebGLRenderList(properties) {
  10938. const renderItems = [];
  10939. let renderItemsIndex = 0;
  10940. const opaque = [];
  10941. const transmissive = [];
  10942. const transparent = [];
  10943. const defaultProgram = {
  10944. id: -1
  10945. };
  10946. function init() {
  10947. renderItemsIndex = 0;
  10948. opaque.length = 0;
  10949. transmissive.length = 0;
  10950. transparent.length = 0;
  10951. }
  10952. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  10953. let renderItem = renderItems[renderItemsIndex];
  10954. const materialProperties = properties.get(material);
  10955. if (renderItem === undefined) {
  10956. renderItem = {
  10957. id: object.id,
  10958. object: object,
  10959. geometry: geometry,
  10960. material: material,
  10961. program: materialProperties.program || defaultProgram,
  10962. groupOrder: groupOrder,
  10963. renderOrder: object.renderOrder,
  10964. z: z,
  10965. group: group
  10966. };
  10967. renderItems[renderItemsIndex] = renderItem;
  10968. } else {
  10969. renderItem.id = object.id;
  10970. renderItem.object = object;
  10971. renderItem.geometry = geometry;
  10972. renderItem.material = material;
  10973. renderItem.program = materialProperties.program || defaultProgram;
  10974. renderItem.groupOrder = groupOrder;
  10975. renderItem.renderOrder = object.renderOrder;
  10976. renderItem.z = z;
  10977. renderItem.group = group;
  10978. }
  10979. renderItemsIndex++;
  10980. return renderItem;
  10981. }
  10982. function push(object, geometry, material, groupOrder, z, group) {
  10983. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  10984. if (material.transmission > 0.0) {
  10985. transmissive.push(renderItem);
  10986. } else if (material.transparent === true) {
  10987. transparent.push(renderItem);
  10988. } else {
  10989. opaque.push(renderItem);
  10990. }
  10991. }
  10992. function unshift(object, geometry, material, groupOrder, z, group) {
  10993. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  10994. if (material.transmission > 0.0) {
  10995. transmissive.unshift(renderItem);
  10996. } else if (material.transparent === true) {
  10997. transparent.unshift(renderItem);
  10998. } else {
  10999. opaque.unshift(renderItem);
  11000. }
  11001. }
  11002. function sort(customOpaqueSort, customTransparentSort) {
  11003. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  11004. if (transmissive.length > 1) transmissive.sort(customTransparentSort || reversePainterSortStable);
  11005. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  11006. }
  11007. function finish() {
  11008. // Clear references from inactive renderItems in the list
  11009. for (let i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  11010. const renderItem = renderItems[i];
  11011. if (renderItem.id === null) break;
  11012. renderItem.id = null;
  11013. renderItem.object = null;
  11014. renderItem.geometry = null;
  11015. renderItem.material = null;
  11016. renderItem.program = null;
  11017. renderItem.group = null;
  11018. }
  11019. }
  11020. return {
  11021. opaque: opaque,
  11022. transmissive: transmissive,
  11023. transparent: transparent,
  11024. init: init,
  11025. push: push,
  11026. unshift: unshift,
  11027. finish: finish,
  11028. sort: sort
  11029. };
  11030. }
  11031. function WebGLRenderLists(properties) {
  11032. let lists = new WeakMap();
  11033. function get(scene, renderCallDepth) {
  11034. let list;
  11035. if (lists.has(scene) === false) {
  11036. list = new WebGLRenderList(properties);
  11037. lists.set(scene, [list]);
  11038. } else {
  11039. if (renderCallDepth >= lists.get(scene).length) {
  11040. list = new WebGLRenderList(properties);
  11041. lists.get(scene).push(list);
  11042. } else {
  11043. list = lists.get(scene)[renderCallDepth];
  11044. }
  11045. }
  11046. return list;
  11047. }
  11048. function dispose() {
  11049. lists = new WeakMap();
  11050. }
  11051. return {
  11052. get: get,
  11053. dispose: dispose
  11054. };
  11055. }
  11056. function UniformsCache() {
  11057. const lights = {};
  11058. return {
  11059. get: function (light) {
  11060. if (lights[light.id] !== undefined) {
  11061. return lights[light.id];
  11062. }
  11063. let uniforms;
  11064. switch (light.type) {
  11065. case 'DirectionalLight':
  11066. uniforms = {
  11067. direction: new Vector3(),
  11068. color: new Color()
  11069. };
  11070. break;
  11071. case 'SpotLight':
  11072. uniforms = {
  11073. position: new Vector3(),
  11074. direction: new Vector3(),
  11075. color: new Color(),
  11076. distance: 0,
  11077. coneCos: 0,
  11078. penumbraCos: 0,
  11079. decay: 0
  11080. };
  11081. break;
  11082. case 'PointLight':
  11083. uniforms = {
  11084. position: new Vector3(),
  11085. color: new Color(),
  11086. distance: 0,
  11087. decay: 0
  11088. };
  11089. break;
  11090. case 'HemisphereLight':
  11091. uniforms = {
  11092. direction: new Vector3(),
  11093. skyColor: new Color(),
  11094. groundColor: new Color()
  11095. };
  11096. break;
  11097. case 'RectAreaLight':
  11098. uniforms = {
  11099. color: new Color(),
  11100. position: new Vector3(),
  11101. halfWidth: new Vector3(),
  11102. halfHeight: new Vector3()
  11103. };
  11104. break;
  11105. }
  11106. lights[light.id] = uniforms;
  11107. return uniforms;
  11108. }
  11109. };
  11110. }
  11111. function ShadowUniformsCache() {
  11112. const lights = {};
  11113. return {
  11114. get: function (light) {
  11115. if (lights[light.id] !== undefined) {
  11116. return lights[light.id];
  11117. }
  11118. let uniforms;
  11119. switch (light.type) {
  11120. case 'DirectionalLight':
  11121. uniforms = {
  11122. shadowBias: 0,
  11123. shadowNormalBias: 0,
  11124. shadowRadius: 1,
  11125. shadowMapSize: new Vector2()
  11126. };
  11127. break;
  11128. case 'SpotLight':
  11129. uniforms = {
  11130. shadowBias: 0,
  11131. shadowNormalBias: 0,
  11132. shadowRadius: 1,
  11133. shadowMapSize: new Vector2()
  11134. };
  11135. break;
  11136. case 'PointLight':
  11137. uniforms = {
  11138. shadowBias: 0,
  11139. shadowNormalBias: 0,
  11140. shadowRadius: 1,
  11141. shadowMapSize: new Vector2(),
  11142. shadowCameraNear: 1,
  11143. shadowCameraFar: 1000
  11144. };
  11145. break;
  11146. // TODO (abelnation): set RectAreaLight shadow uniforms
  11147. }
  11148. lights[light.id] = uniforms;
  11149. return uniforms;
  11150. }
  11151. };
  11152. }
  11153. let nextVersion = 0;
  11154. function shadowCastingLightsFirst(lightA, lightB) {
  11155. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  11156. }
  11157. function WebGLLights(extensions, capabilities) {
  11158. const cache = new UniformsCache();
  11159. const shadowCache = ShadowUniformsCache();
  11160. const state = {
  11161. version: 0,
  11162. hash: {
  11163. directionalLength: -1,
  11164. pointLength: -1,
  11165. spotLength: -1,
  11166. rectAreaLength: -1,
  11167. hemiLength: -1,
  11168. numDirectionalShadows: -1,
  11169. numPointShadows: -1,
  11170. numSpotShadows: -1
  11171. },
  11172. ambient: [0, 0, 0],
  11173. probe: [],
  11174. directional: [],
  11175. directionalShadow: [],
  11176. directionalShadowMap: [],
  11177. directionalShadowMatrix: [],
  11178. spot: [],
  11179. spotShadow: [],
  11180. spotShadowMap: [],
  11181. spotShadowMatrix: [],
  11182. rectArea: [],
  11183. rectAreaLTC1: null,
  11184. rectAreaLTC2: null,
  11185. point: [],
  11186. pointShadow: [],
  11187. pointShadowMap: [],
  11188. pointShadowMatrix: [],
  11189. hemi: []
  11190. };
  11191. for (let i = 0; i < 9; i++) state.probe.push(new Vector3());
  11192. const vector3 = new Vector3();
  11193. const matrix4 = new Matrix4();
  11194. const matrix42 = new Matrix4();
  11195. function setup(lights) {
  11196. let r = 0,
  11197. g = 0,
  11198. b = 0;
  11199. for (let i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  11200. let directionalLength = 0;
  11201. let pointLength = 0;
  11202. let spotLength = 0;
  11203. let rectAreaLength = 0;
  11204. let hemiLength = 0;
  11205. let numDirectionalShadows = 0;
  11206. let numPointShadows = 0;
  11207. let numSpotShadows = 0;
  11208. lights.sort(shadowCastingLightsFirst);
  11209. for (let i = 0, l = lights.length; i < l; i++) {
  11210. const light = lights[i];
  11211. const color = light.color;
  11212. const intensity = light.intensity;
  11213. const distance = light.distance;
  11214. const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  11215. if (light.isAmbientLight) {
  11216. r += color.r * intensity;
  11217. g += color.g * intensity;
  11218. b += color.b * intensity;
  11219. } else if (light.isLightProbe) {
  11220. for (let j = 0; j < 9; j++) {
  11221. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  11222. }
  11223. } else if (light.isDirectionalLight) {
  11224. const uniforms = cache.get(light);
  11225. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  11226. if (light.castShadow) {
  11227. const shadow = light.shadow;
  11228. const shadowUniforms = shadowCache.get(light);
  11229. shadowUniforms.shadowBias = shadow.bias;
  11230. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11231. shadowUniforms.shadowRadius = shadow.radius;
  11232. shadowUniforms.shadowMapSize = shadow.mapSize;
  11233. state.directionalShadow[directionalLength] = shadowUniforms;
  11234. state.directionalShadowMap[directionalLength] = shadowMap;
  11235. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  11236. numDirectionalShadows++;
  11237. }
  11238. state.directional[directionalLength] = uniforms;
  11239. directionalLength++;
  11240. } else if (light.isSpotLight) {
  11241. const uniforms = cache.get(light);
  11242. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11243. uniforms.color.copy(color).multiplyScalar(intensity);
  11244. uniforms.distance = distance;
  11245. uniforms.coneCos = Math.cos(light.angle);
  11246. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  11247. uniforms.decay = light.decay;
  11248. if (light.castShadow) {
  11249. const shadow = light.shadow;
  11250. const shadowUniforms = shadowCache.get(light);
  11251. shadowUniforms.shadowBias = shadow.bias;
  11252. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11253. shadowUniforms.shadowRadius = shadow.radius;
  11254. shadowUniforms.shadowMapSize = shadow.mapSize;
  11255. state.spotShadow[spotLength] = shadowUniforms;
  11256. state.spotShadowMap[spotLength] = shadowMap;
  11257. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  11258. numSpotShadows++;
  11259. }
  11260. state.spot[spotLength] = uniforms;
  11261. spotLength++;
  11262. } else if (light.isRectAreaLight) {
  11263. const uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  11264. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  11265. // (b) intensity is the brightness of the light
  11266. uniforms.color.copy(color).multiplyScalar(intensity);
  11267. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  11268. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  11269. state.rectArea[rectAreaLength] = uniforms;
  11270. rectAreaLength++;
  11271. } else if (light.isPointLight) {
  11272. const uniforms = cache.get(light);
  11273. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  11274. uniforms.distance = light.distance;
  11275. uniforms.decay = light.decay;
  11276. if (light.castShadow) {
  11277. const shadow = light.shadow;
  11278. const shadowUniforms = shadowCache.get(light);
  11279. shadowUniforms.shadowBias = shadow.bias;
  11280. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11281. shadowUniforms.shadowRadius = shadow.radius;
  11282. shadowUniforms.shadowMapSize = shadow.mapSize;
  11283. shadowUniforms.shadowCameraNear = shadow.camera.near;
  11284. shadowUniforms.shadowCameraFar = shadow.camera.far;
  11285. state.pointShadow[pointLength] = shadowUniforms;
  11286. state.pointShadowMap[pointLength] = shadowMap;
  11287. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  11288. numPointShadows++;
  11289. }
  11290. state.point[pointLength] = uniforms;
  11291. pointLength++;
  11292. } else if (light.isHemisphereLight) {
  11293. const uniforms = cache.get(light);
  11294. uniforms.skyColor.copy(light.color).multiplyScalar(intensity);
  11295. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity);
  11296. state.hemi[hemiLength] = uniforms;
  11297. hemiLength++;
  11298. }
  11299. }
  11300. if (rectAreaLength > 0) {
  11301. if (capabilities.isWebGL2) {
  11302. // WebGL 2
  11303. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11304. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11305. } else {
  11306. // WebGL 1
  11307. if (extensions.has('OES_texture_float_linear') === true) {
  11308. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11309. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11310. } else if (extensions.has('OES_texture_half_float_linear') === true) {
  11311. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  11312. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  11313. } else {
  11314. console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
  11315. }
  11316. }
  11317. }
  11318. state.ambient[0] = r;
  11319. state.ambient[1] = g;
  11320. state.ambient[2] = b;
  11321. const hash = state.hash;
  11322. 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) {
  11323. state.directional.length = directionalLength;
  11324. state.spot.length = spotLength;
  11325. state.rectArea.length = rectAreaLength;
  11326. state.point.length = pointLength;
  11327. state.hemi.length = hemiLength;
  11328. state.directionalShadow.length = numDirectionalShadows;
  11329. state.directionalShadowMap.length = numDirectionalShadows;
  11330. state.pointShadow.length = numPointShadows;
  11331. state.pointShadowMap.length = numPointShadows;
  11332. state.spotShadow.length = numSpotShadows;
  11333. state.spotShadowMap.length = numSpotShadows;
  11334. state.directionalShadowMatrix.length = numDirectionalShadows;
  11335. state.pointShadowMatrix.length = numPointShadows;
  11336. state.spotShadowMatrix.length = numSpotShadows;
  11337. hash.directionalLength = directionalLength;
  11338. hash.pointLength = pointLength;
  11339. hash.spotLength = spotLength;
  11340. hash.rectAreaLength = rectAreaLength;
  11341. hash.hemiLength = hemiLength;
  11342. hash.numDirectionalShadows = numDirectionalShadows;
  11343. hash.numPointShadows = numPointShadows;
  11344. hash.numSpotShadows = numSpotShadows;
  11345. state.version = nextVersion++;
  11346. }
  11347. }
  11348. function setupView(lights, camera) {
  11349. let directionalLength = 0;
  11350. let pointLength = 0;
  11351. let spotLength = 0;
  11352. let rectAreaLength = 0;
  11353. let hemiLength = 0;
  11354. const viewMatrix = camera.matrixWorldInverse;
  11355. for (let i = 0, l = lights.length; i < l; i++) {
  11356. const light = lights[i];
  11357. if (light.isDirectionalLight) {
  11358. const uniforms = state.directional[directionalLength];
  11359. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11360. vector3.setFromMatrixPosition(light.target.matrixWorld);
  11361. uniforms.direction.sub(vector3);
  11362. uniforms.direction.transformDirection(viewMatrix);
  11363. directionalLength++;
  11364. } else if (light.isSpotLight) {
  11365. const uniforms = state.spot[spotLength];
  11366. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11367. uniforms.position.applyMatrix4(viewMatrix);
  11368. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11369. vector3.setFromMatrixPosition(light.target.matrixWorld);
  11370. uniforms.direction.sub(vector3);
  11371. uniforms.direction.transformDirection(viewMatrix);
  11372. spotLength++;
  11373. } else if (light.isRectAreaLight) {
  11374. const uniforms = state.rectArea[rectAreaLength];
  11375. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11376. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  11377. matrix42.identity();
  11378. matrix4.copy(light.matrixWorld);
  11379. matrix4.premultiply(viewMatrix);
  11380. matrix42.extractRotation(matrix4);
  11381. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  11382. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  11383. uniforms.halfWidth.applyMatrix4(matrix42);
  11384. uniforms.halfHeight.applyMatrix4(matrix42);
  11385. rectAreaLength++;
  11386. } else if (light.isPointLight) {
  11387. const uniforms = state.point[pointLength];
  11388. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11389. uniforms.position.applyMatrix4(viewMatrix);
  11390. pointLength++;
  11391. } else if (light.isHemisphereLight) {
  11392. const uniforms = state.hemi[hemiLength];
  11393. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11394. uniforms.direction.transformDirection(viewMatrix);
  11395. uniforms.direction.normalize();
  11396. hemiLength++;
  11397. }
  11398. }
  11399. }
  11400. return {
  11401. setup: setup,
  11402. setupView: setupView,
  11403. state: state
  11404. };
  11405. }
  11406. function WebGLRenderState(extensions, capabilities) {
  11407. const lights = new WebGLLights(extensions, capabilities);
  11408. const lightsArray = [];
  11409. const shadowsArray = [];
  11410. function init() {
  11411. lightsArray.length = 0;
  11412. shadowsArray.length = 0;
  11413. }
  11414. function pushLight(light) {
  11415. lightsArray.push(light);
  11416. }
  11417. function pushShadow(shadowLight) {
  11418. shadowsArray.push(shadowLight);
  11419. }
  11420. function setupLights() {
  11421. lights.setup(lightsArray);
  11422. }
  11423. function setupLightsView(camera) {
  11424. lights.setupView(lightsArray, camera);
  11425. }
  11426. const state = {
  11427. lightsArray: lightsArray,
  11428. shadowsArray: shadowsArray,
  11429. lights: lights
  11430. };
  11431. return {
  11432. init: init,
  11433. state: state,
  11434. setupLights: setupLights,
  11435. setupLightsView: setupLightsView,
  11436. pushLight: pushLight,
  11437. pushShadow: pushShadow
  11438. };
  11439. }
  11440. function WebGLRenderStates(extensions, capabilities) {
  11441. let renderStates = new WeakMap();
  11442. function get(scene, renderCallDepth = 0) {
  11443. let renderState;
  11444. if (renderStates.has(scene) === false) {
  11445. renderState = new WebGLRenderState(extensions, capabilities);
  11446. renderStates.set(scene, [renderState]);
  11447. } else {
  11448. if (renderCallDepth >= renderStates.get(scene).length) {
  11449. renderState = new WebGLRenderState(extensions, capabilities);
  11450. renderStates.get(scene).push(renderState);
  11451. } else {
  11452. renderState = renderStates.get(scene)[renderCallDepth];
  11453. }
  11454. }
  11455. return renderState;
  11456. }
  11457. function dispose() {
  11458. renderStates = new WeakMap();
  11459. }
  11460. return {
  11461. get: get,
  11462. dispose: dispose
  11463. };
  11464. }
  11465. /**
  11466. * parameters = {
  11467. *
  11468. * opacity: <float>,
  11469. *
  11470. * map: new THREE.Texture( <Image> ),
  11471. *
  11472. * alphaMap: new THREE.Texture( <Image> ),
  11473. *
  11474. * displacementMap: new THREE.Texture( <Image> ),
  11475. * displacementScale: <float>,
  11476. * displacementBias: <float>,
  11477. *
  11478. * wireframe: <boolean>,
  11479. * wireframeLinewidth: <float>
  11480. * }
  11481. */
  11482. class MeshDepthMaterial extends Material {
  11483. constructor(parameters) {
  11484. super();
  11485. this.type = 'MeshDepthMaterial';
  11486. this.depthPacking = BasicDepthPacking;
  11487. this.morphTargets = false;
  11488. this.map = null;
  11489. this.alphaMap = null;
  11490. this.displacementMap = null;
  11491. this.displacementScale = 1;
  11492. this.displacementBias = 0;
  11493. this.wireframe = false;
  11494. this.wireframeLinewidth = 1;
  11495. this.fog = false;
  11496. this.setValues(parameters);
  11497. }
  11498. copy(source) {
  11499. super.copy(source);
  11500. this.depthPacking = source.depthPacking;
  11501. this.morphTargets = source.morphTargets;
  11502. this.map = source.map;
  11503. this.alphaMap = source.alphaMap;
  11504. this.displacementMap = source.displacementMap;
  11505. this.displacementScale = source.displacementScale;
  11506. this.displacementBias = source.displacementBias;
  11507. this.wireframe = source.wireframe;
  11508. this.wireframeLinewidth = source.wireframeLinewidth;
  11509. return this;
  11510. }
  11511. }
  11512. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  11513. /**
  11514. * parameters = {
  11515. *
  11516. * referencePosition: <float>,
  11517. * nearDistance: <float>,
  11518. * farDistance: <float>,
  11519. *
  11520. * morphTargets: <bool>,
  11521. *
  11522. * map: new THREE.Texture( <Image> ),
  11523. *
  11524. * alphaMap: new THREE.Texture( <Image> ),
  11525. *
  11526. * displacementMap: new THREE.Texture( <Image> ),
  11527. * displacementScale: <float>,
  11528. * displacementBias: <float>
  11529. *
  11530. * }
  11531. */
  11532. class MeshDistanceMaterial extends Material {
  11533. constructor(parameters) {
  11534. super();
  11535. this.type = 'MeshDistanceMaterial';
  11536. this.referencePosition = new Vector3();
  11537. this.nearDistance = 1;
  11538. this.farDistance = 1000;
  11539. this.morphTargets = false;
  11540. this.map = null;
  11541. this.alphaMap = null;
  11542. this.displacementMap = null;
  11543. this.displacementScale = 1;
  11544. this.displacementBias = 0;
  11545. this.fog = false;
  11546. this.setValues(parameters);
  11547. }
  11548. copy(source) {
  11549. super.copy(source);
  11550. this.referencePosition.copy(source.referencePosition);
  11551. this.nearDistance = source.nearDistance;
  11552. this.farDistance = source.farDistance;
  11553. this.morphTargets = source.morphTargets;
  11554. this.map = source.map;
  11555. this.alphaMap = source.alphaMap;
  11556. this.displacementMap = source.displacementMap;
  11557. this.displacementScale = source.displacementScale;
  11558. this.displacementBias = source.displacementBias;
  11559. return this;
  11560. }
  11561. }
  11562. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  11563. 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}";
  11564. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  11565. function WebGLShadowMap(_renderer, _objects, _capabilities) {
  11566. let _frustum = new Frustum();
  11567. const _shadowMapSize = new Vector2(),
  11568. _viewportSize = new Vector2(),
  11569. _viewport = new Vector4(),
  11570. _depthMaterials = [],
  11571. _distanceMaterials = [],
  11572. _materialCache = {},
  11573. _maxTextureSize = _capabilities.maxTextureSize;
  11574. const shadowSide = {
  11575. 0: BackSide,
  11576. 1: FrontSide,
  11577. 2: DoubleSide
  11578. };
  11579. const shadowMaterialVertical = new ShaderMaterial({
  11580. defines: {
  11581. SAMPLE_RATE: 2.0 / 8.0,
  11582. HALF_SAMPLE_RATE: 1.0 / 8.0
  11583. },
  11584. uniforms: {
  11585. shadow_pass: {
  11586. value: null
  11587. },
  11588. resolution: {
  11589. value: new Vector2()
  11590. },
  11591. radius: {
  11592. value: 4.0
  11593. }
  11594. },
  11595. vertexShader: vsm_vert,
  11596. fragmentShader: vsm_frag
  11597. });
  11598. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  11599. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  11600. const fullScreenTri = new BufferGeometry();
  11601. fullScreenTri.setAttribute('position', new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  11602. const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  11603. const scope = this;
  11604. this.enabled = false;
  11605. this.autoUpdate = true;
  11606. this.needsUpdate = false;
  11607. this.type = PCFShadowMap;
  11608. this.render = function (lights, scene, camera) {
  11609. if (scope.enabled === false) return;
  11610. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  11611. if (lights.length === 0) return;
  11612. const currentRenderTarget = _renderer.getRenderTarget();
  11613. const activeCubeFace = _renderer.getActiveCubeFace();
  11614. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  11615. const _state = _renderer.state; // Set GL state for depth map.
  11616. _state.setBlending(NoBlending);
  11617. _state.buffers.color.setClear(1, 1, 1, 1);
  11618. _state.buffers.depth.setTest(true);
  11619. _state.setScissorTest(false); // render depth map
  11620. for (let i = 0, il = lights.length; i < il; i++) {
  11621. const light = lights[i];
  11622. const shadow = light.shadow;
  11623. if (shadow === undefined) {
  11624. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  11625. continue;
  11626. }
  11627. if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
  11628. _shadowMapSize.copy(shadow.mapSize);
  11629. const shadowFrameExtents = shadow.getFrameExtents();
  11630. _shadowMapSize.multiply(shadowFrameExtents);
  11631. _viewportSize.copy(shadow.mapSize);
  11632. if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) {
  11633. if (_shadowMapSize.x > _maxTextureSize) {
  11634. _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x);
  11635. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  11636. shadow.mapSize.x = _viewportSize.x;
  11637. }
  11638. if (_shadowMapSize.y > _maxTextureSize) {
  11639. _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y);
  11640. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  11641. shadow.mapSize.y = _viewportSize.y;
  11642. }
  11643. }
  11644. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  11645. const pars = {
  11646. minFilter: LinearFilter,
  11647. magFilter: LinearFilter,
  11648. format: RGBAFormat
  11649. };
  11650. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  11651. shadow.map.texture.name = light.name + '.shadowMap';
  11652. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  11653. shadow.camera.updateProjectionMatrix();
  11654. }
  11655. if (shadow.map === null) {
  11656. const pars = {
  11657. minFilter: NearestFilter,
  11658. magFilter: NearestFilter,
  11659. format: RGBAFormat
  11660. };
  11661. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  11662. shadow.map.texture.name = light.name + '.shadowMap';
  11663. shadow.camera.updateProjectionMatrix();
  11664. }
  11665. _renderer.setRenderTarget(shadow.map);
  11666. _renderer.clear();
  11667. const viewportCount = shadow.getViewportCount();
  11668. for (let vp = 0; vp < viewportCount; vp++) {
  11669. const viewport = shadow.getViewport(vp);
  11670. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  11671. _state.viewport(_viewport);
  11672. shadow.updateMatrices(light, vp);
  11673. _frustum = shadow.getFrustum();
  11674. renderObject(scene, camera, shadow.camera, light, this.type);
  11675. } // do blur pass for VSM
  11676. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  11677. VSMPass(shadow, camera);
  11678. }
  11679. shadow.needsUpdate = false;
  11680. }
  11681. scope.needsUpdate = false;
  11682. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  11683. };
  11684. function VSMPass(shadow, camera) {
  11685. const geometry = _objects.update(fullScreenMesh); // vertical pass
  11686. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  11687. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  11688. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  11689. _renderer.setRenderTarget(shadow.mapPass);
  11690. _renderer.clear();
  11691. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizontal pass
  11692. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  11693. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  11694. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  11695. _renderer.setRenderTarget(shadow.map);
  11696. _renderer.clear();
  11697. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null);
  11698. }
  11699. function getDepthMaterialVariant(useMorphing) {
  11700. const index = useMorphing << 0;
  11701. let material = _depthMaterials[index];
  11702. if (material === undefined) {
  11703. material = new MeshDepthMaterial({
  11704. depthPacking: RGBADepthPacking,
  11705. morphTargets: useMorphing
  11706. });
  11707. _depthMaterials[index] = material;
  11708. }
  11709. return material;
  11710. }
  11711. function getDistanceMaterialVariant(useMorphing) {
  11712. const index = useMorphing << 0;
  11713. let material = _distanceMaterials[index];
  11714. if (material === undefined) {
  11715. material = new MeshDistanceMaterial({
  11716. morphTargets: useMorphing
  11717. });
  11718. _distanceMaterials[index] = material;
  11719. }
  11720. return material;
  11721. }
  11722. function getDepthMaterial(object, geometry, material, light, shadowCameraNear, shadowCameraFar, type) {
  11723. let result = null;
  11724. let getMaterialVariant = getDepthMaterialVariant;
  11725. let customMaterial = object.customDepthMaterial;
  11726. if (light.isPointLight === true) {
  11727. getMaterialVariant = getDistanceMaterialVariant;
  11728. customMaterial = object.customDistanceMaterial;
  11729. }
  11730. if (customMaterial === undefined) {
  11731. let useMorphing = false;
  11732. if (material.morphTargets === true) {
  11733. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  11734. }
  11735. result = getMaterialVariant(useMorphing);
  11736. } else {
  11737. result = customMaterial;
  11738. }
  11739. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0) {
  11740. // in this case we need a unique material instance reflecting the
  11741. // appropriate state
  11742. const keyA = result.uuid,
  11743. keyB = material.uuid;
  11744. let materialsForVariant = _materialCache[keyA];
  11745. if (materialsForVariant === undefined) {
  11746. materialsForVariant = {};
  11747. _materialCache[keyA] = materialsForVariant;
  11748. }
  11749. let cachedMaterial = materialsForVariant[keyB];
  11750. if (cachedMaterial === undefined) {
  11751. cachedMaterial = result.clone();
  11752. materialsForVariant[keyB] = cachedMaterial;
  11753. }
  11754. result = cachedMaterial;
  11755. }
  11756. result.visible = material.visible;
  11757. result.wireframe = material.wireframe;
  11758. if (type === VSMShadowMap) {
  11759. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  11760. } else {
  11761. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  11762. }
  11763. result.clipShadows = material.clipShadows;
  11764. result.clippingPlanes = material.clippingPlanes;
  11765. result.clipIntersection = material.clipIntersection;
  11766. result.wireframeLinewidth = material.wireframeLinewidth;
  11767. result.linewidth = material.linewidth;
  11768. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  11769. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  11770. result.nearDistance = shadowCameraNear;
  11771. result.farDistance = shadowCameraFar;
  11772. }
  11773. return result;
  11774. }
  11775. function renderObject(object, camera, shadowCamera, light, type) {
  11776. if (object.visible === false) return;
  11777. const visible = object.layers.test(camera.layers);
  11778. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  11779. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  11780. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  11781. const geometry = _objects.update(object);
  11782. const material = object.material;
  11783. if (Array.isArray(material)) {
  11784. const groups = geometry.groups;
  11785. for (let k = 0, kl = groups.length; k < kl; k++) {
  11786. const group = groups[k];
  11787. const groupMaterial = material[group.materialIndex];
  11788. if (groupMaterial && groupMaterial.visible) {
  11789. const depthMaterial = getDepthMaterial(object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  11790. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  11791. }
  11792. }
  11793. } else if (material.visible) {
  11794. const depthMaterial = getDepthMaterial(object, geometry, material, light, shadowCamera.near, shadowCamera.far, type);
  11795. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  11796. }
  11797. }
  11798. }
  11799. const children = object.children;
  11800. for (let i = 0, l = children.length; i < l; i++) {
  11801. renderObject(children[i], camera, shadowCamera, light, type);
  11802. }
  11803. }
  11804. }
  11805. function WebGLState(gl, extensions, capabilities) {
  11806. const isWebGL2 = capabilities.isWebGL2;
  11807. function ColorBuffer() {
  11808. let locked = false;
  11809. const color = new Vector4();
  11810. let currentColorMask = null;
  11811. const currentColorClear = new Vector4(0, 0, 0, 0);
  11812. return {
  11813. setMask: function (colorMask) {
  11814. if (currentColorMask !== colorMask && !locked) {
  11815. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  11816. currentColorMask = colorMask;
  11817. }
  11818. },
  11819. setLocked: function (lock) {
  11820. locked = lock;
  11821. },
  11822. setClear: function (r, g, b, a, premultipliedAlpha) {
  11823. if (premultipliedAlpha === true) {
  11824. r *= a;
  11825. g *= a;
  11826. b *= a;
  11827. }
  11828. color.set(r, g, b, a);
  11829. if (currentColorClear.equals(color) === false) {
  11830. gl.clearColor(r, g, b, a);
  11831. currentColorClear.copy(color);
  11832. }
  11833. },
  11834. reset: function () {
  11835. locked = false;
  11836. currentColorMask = null;
  11837. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  11838. }
  11839. };
  11840. }
  11841. function DepthBuffer() {
  11842. let locked = false;
  11843. let currentDepthMask = null;
  11844. let currentDepthFunc = null;
  11845. let currentDepthClear = null;
  11846. return {
  11847. setTest: function (depthTest) {
  11848. if (depthTest) {
  11849. enable(gl.DEPTH_TEST);
  11850. } else {
  11851. disable(gl.DEPTH_TEST);
  11852. }
  11853. },
  11854. setMask: function (depthMask) {
  11855. if (currentDepthMask !== depthMask && !locked) {
  11856. gl.depthMask(depthMask);
  11857. currentDepthMask = depthMask;
  11858. }
  11859. },
  11860. setFunc: function (depthFunc) {
  11861. if (currentDepthFunc !== depthFunc) {
  11862. if (depthFunc) {
  11863. switch (depthFunc) {
  11864. case NeverDepth:
  11865. gl.depthFunc(gl.NEVER);
  11866. break;
  11867. case AlwaysDepth:
  11868. gl.depthFunc(gl.ALWAYS);
  11869. break;
  11870. case LessDepth:
  11871. gl.depthFunc(gl.LESS);
  11872. break;
  11873. case LessEqualDepth:
  11874. gl.depthFunc(gl.LEQUAL);
  11875. break;
  11876. case EqualDepth:
  11877. gl.depthFunc(gl.EQUAL);
  11878. break;
  11879. case GreaterEqualDepth:
  11880. gl.depthFunc(gl.GEQUAL);
  11881. break;
  11882. case GreaterDepth:
  11883. gl.depthFunc(gl.GREATER);
  11884. break;
  11885. case NotEqualDepth:
  11886. gl.depthFunc(gl.NOTEQUAL);
  11887. break;
  11888. default:
  11889. gl.depthFunc(gl.LEQUAL);
  11890. }
  11891. } else {
  11892. gl.depthFunc(gl.LEQUAL);
  11893. }
  11894. currentDepthFunc = depthFunc;
  11895. }
  11896. },
  11897. setLocked: function (lock) {
  11898. locked = lock;
  11899. },
  11900. setClear: function (depth) {
  11901. if (currentDepthClear !== depth) {
  11902. gl.clearDepth(depth);
  11903. currentDepthClear = depth;
  11904. }
  11905. },
  11906. reset: function () {
  11907. locked = false;
  11908. currentDepthMask = null;
  11909. currentDepthFunc = null;
  11910. currentDepthClear = null;
  11911. }
  11912. };
  11913. }
  11914. function StencilBuffer() {
  11915. let locked = false;
  11916. let currentStencilMask = null;
  11917. let currentStencilFunc = null;
  11918. let currentStencilRef = null;
  11919. let currentStencilFuncMask = null;
  11920. let currentStencilFail = null;
  11921. let currentStencilZFail = null;
  11922. let currentStencilZPass = null;
  11923. let currentStencilClear = null;
  11924. return {
  11925. setTest: function (stencilTest) {
  11926. if (!locked) {
  11927. if (stencilTest) {
  11928. enable(gl.STENCIL_TEST);
  11929. } else {
  11930. disable(gl.STENCIL_TEST);
  11931. }
  11932. }
  11933. },
  11934. setMask: function (stencilMask) {
  11935. if (currentStencilMask !== stencilMask && !locked) {
  11936. gl.stencilMask(stencilMask);
  11937. currentStencilMask = stencilMask;
  11938. }
  11939. },
  11940. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  11941. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  11942. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  11943. currentStencilFunc = stencilFunc;
  11944. currentStencilRef = stencilRef;
  11945. currentStencilFuncMask = stencilMask;
  11946. }
  11947. },
  11948. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  11949. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  11950. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  11951. currentStencilFail = stencilFail;
  11952. currentStencilZFail = stencilZFail;
  11953. currentStencilZPass = stencilZPass;
  11954. }
  11955. },
  11956. setLocked: function (lock) {
  11957. locked = lock;
  11958. },
  11959. setClear: function (stencil) {
  11960. if (currentStencilClear !== stencil) {
  11961. gl.clearStencil(stencil);
  11962. currentStencilClear = stencil;
  11963. }
  11964. },
  11965. reset: function () {
  11966. locked = false;
  11967. currentStencilMask = null;
  11968. currentStencilFunc = null;
  11969. currentStencilRef = null;
  11970. currentStencilFuncMask = null;
  11971. currentStencilFail = null;
  11972. currentStencilZFail = null;
  11973. currentStencilZPass = null;
  11974. currentStencilClear = null;
  11975. }
  11976. };
  11977. } //
  11978. const colorBuffer = new ColorBuffer();
  11979. const depthBuffer = new DepthBuffer();
  11980. const stencilBuffer = new StencilBuffer();
  11981. let enabledCapabilities = {};
  11982. let xrFramebuffer = null;
  11983. let currentBoundFramebuffers = {};
  11984. let currentProgram = null;
  11985. let currentBlendingEnabled = false;
  11986. let currentBlending = null;
  11987. let currentBlendEquation = null;
  11988. let currentBlendSrc = null;
  11989. let currentBlendDst = null;
  11990. let currentBlendEquationAlpha = null;
  11991. let currentBlendSrcAlpha = null;
  11992. let currentBlendDstAlpha = null;
  11993. let currentPremultipledAlpha = false;
  11994. let currentFlipSided = null;
  11995. let currentCullFace = null;
  11996. let currentLineWidth = null;
  11997. let currentPolygonOffsetFactor = null;
  11998. let currentPolygonOffsetUnits = null;
  11999. const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12000. let lineWidthAvailable = false;
  12001. let version = 0;
  12002. const glVersion = gl.getParameter(gl.VERSION);
  12003. if (glVersion.indexOf('WebGL') !== -1) {
  12004. version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]);
  12005. lineWidthAvailable = version >= 1.0;
  12006. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  12007. version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);
  12008. lineWidthAvailable = version >= 2.0;
  12009. }
  12010. let currentTextureSlot = null;
  12011. let currentBoundTextures = {};
  12012. const scissorParam = gl.getParameter(gl.SCISSOR_BOX);
  12013. const viewportParam = gl.getParameter(gl.VIEWPORT);
  12014. const currentScissor = new Vector4().fromArray(scissorParam);
  12015. const currentViewport = new Vector4().fromArray(viewportParam);
  12016. function createTexture(type, target, count) {
  12017. const data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  12018. const texture = gl.createTexture();
  12019. gl.bindTexture(type, texture);
  12020. gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12021. gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12022. for (let i = 0; i < count; i++) {
  12023. gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
  12024. }
  12025. return texture;
  12026. }
  12027. const emptyTextures = {};
  12028. emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1);
  12029. emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); // init
  12030. colorBuffer.setClear(0, 0, 0, 1);
  12031. depthBuffer.setClear(1);
  12032. stencilBuffer.setClear(0);
  12033. enable(gl.DEPTH_TEST);
  12034. depthBuffer.setFunc(LessEqualDepth);
  12035. setFlipSided(false);
  12036. setCullFace(CullFaceBack);
  12037. enable(gl.CULL_FACE);
  12038. setBlending(NoBlending); //
  12039. function enable(id) {
  12040. if (enabledCapabilities[id] !== true) {
  12041. gl.enable(id);
  12042. enabledCapabilities[id] = true;
  12043. }
  12044. }
  12045. function disable(id) {
  12046. if (enabledCapabilities[id] !== false) {
  12047. gl.disable(id);
  12048. enabledCapabilities[id] = false;
  12049. }
  12050. }
  12051. function bindXRFramebuffer(framebuffer) {
  12052. if (framebuffer !== xrFramebuffer) {
  12053. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  12054. xrFramebuffer = framebuffer;
  12055. }
  12056. }
  12057. function bindFramebuffer(target, framebuffer) {
  12058. if (framebuffer === null && xrFramebuffer !== null) framebuffer = xrFramebuffer; // use active XR framebuffer if available
  12059. if (currentBoundFramebuffers[target] !== framebuffer) {
  12060. gl.bindFramebuffer(target, framebuffer);
  12061. currentBoundFramebuffers[target] = framebuffer;
  12062. if (isWebGL2) {
  12063. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  12064. if (target === gl.DRAW_FRAMEBUFFER) {
  12065. currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer;
  12066. }
  12067. if (target === gl.FRAMEBUFFER) {
  12068. currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer;
  12069. }
  12070. }
  12071. return true;
  12072. }
  12073. return false;
  12074. }
  12075. function useProgram(program) {
  12076. if (currentProgram !== program) {
  12077. gl.useProgram(program);
  12078. currentProgram = program;
  12079. return true;
  12080. }
  12081. return false;
  12082. }
  12083. const equationToGL = {
  12084. [AddEquation]: gl.FUNC_ADD,
  12085. [SubtractEquation]: gl.FUNC_SUBTRACT,
  12086. [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT
  12087. };
  12088. if (isWebGL2) {
  12089. equationToGL[MinEquation] = gl.MIN;
  12090. equationToGL[MaxEquation] = gl.MAX;
  12091. } else {
  12092. const extension = extensions.get('EXT_blend_minmax');
  12093. if (extension !== null) {
  12094. equationToGL[MinEquation] = extension.MIN_EXT;
  12095. equationToGL[MaxEquation] = extension.MAX_EXT;
  12096. }
  12097. }
  12098. const factorToGL = {
  12099. [ZeroFactor]: gl.ZERO,
  12100. [OneFactor]: gl.ONE,
  12101. [SrcColorFactor]: gl.SRC_COLOR,
  12102. [SrcAlphaFactor]: gl.SRC_ALPHA,
  12103. [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE,
  12104. [DstColorFactor]: gl.DST_COLOR,
  12105. [DstAlphaFactor]: gl.DST_ALPHA,
  12106. [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR,
  12107. [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA,
  12108. [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR,
  12109. [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA
  12110. };
  12111. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  12112. if (blending === NoBlending) {
  12113. if (currentBlendingEnabled === true) {
  12114. disable(gl.BLEND);
  12115. currentBlendingEnabled = false;
  12116. }
  12117. return;
  12118. }
  12119. if (currentBlendingEnabled === false) {
  12120. enable(gl.BLEND);
  12121. currentBlendingEnabled = true;
  12122. }
  12123. if (blending !== CustomBlending) {
  12124. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  12125. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  12126. gl.blendEquation(gl.FUNC_ADD);
  12127. currentBlendEquation = AddEquation;
  12128. currentBlendEquationAlpha = AddEquation;
  12129. }
  12130. if (premultipliedAlpha) {
  12131. switch (blending) {
  12132. case NormalBlending:
  12133. gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  12134. break;
  12135. case AdditiveBlending:
  12136. gl.blendFunc(gl.ONE, gl.ONE);
  12137. break;
  12138. case SubtractiveBlending:
  12139. gl.blendFuncSeparate(gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA);
  12140. break;
  12141. case MultiplyBlending:
  12142. gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA);
  12143. break;
  12144. default:
  12145. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12146. break;
  12147. }
  12148. } else {
  12149. switch (blending) {
  12150. case NormalBlending:
  12151. gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  12152. break;
  12153. case AdditiveBlending:
  12154. gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  12155. break;
  12156. case SubtractiveBlending:
  12157. gl.blendFunc(gl.ZERO, gl.ONE_MINUS_SRC_COLOR);
  12158. break;
  12159. case MultiplyBlending:
  12160. gl.blendFunc(gl.ZERO, gl.SRC_COLOR);
  12161. break;
  12162. default:
  12163. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12164. break;
  12165. }
  12166. }
  12167. currentBlendSrc = null;
  12168. currentBlendDst = null;
  12169. currentBlendSrcAlpha = null;
  12170. currentBlendDstAlpha = null;
  12171. currentBlending = blending;
  12172. currentPremultipledAlpha = premultipliedAlpha;
  12173. }
  12174. return;
  12175. } // custom blending
  12176. blendEquationAlpha = blendEquationAlpha || blendEquation;
  12177. blendSrcAlpha = blendSrcAlpha || blendSrc;
  12178. blendDstAlpha = blendDstAlpha || blendDst;
  12179. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  12180. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  12181. currentBlendEquation = blendEquation;
  12182. currentBlendEquationAlpha = blendEquationAlpha;
  12183. }
  12184. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  12185. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  12186. currentBlendSrc = blendSrc;
  12187. currentBlendDst = blendDst;
  12188. currentBlendSrcAlpha = blendSrcAlpha;
  12189. currentBlendDstAlpha = blendDstAlpha;
  12190. }
  12191. currentBlending = blending;
  12192. currentPremultipledAlpha = null;
  12193. }
  12194. function setMaterial(material, frontFaceCW) {
  12195. material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE);
  12196. let flipSided = material.side === BackSide;
  12197. if (frontFaceCW) flipSided = !flipSided;
  12198. setFlipSided(flipSided);
  12199. 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);
  12200. depthBuffer.setFunc(material.depthFunc);
  12201. depthBuffer.setTest(material.depthTest);
  12202. depthBuffer.setMask(material.depthWrite);
  12203. colorBuffer.setMask(material.colorWrite);
  12204. const stencilWrite = material.stencilWrite;
  12205. stencilBuffer.setTest(stencilWrite);
  12206. if (stencilWrite) {
  12207. stencilBuffer.setMask(material.stencilWriteMask);
  12208. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  12209. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  12210. }
  12211. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  12212. material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  12213. } //
  12214. function setFlipSided(flipSided) {
  12215. if (currentFlipSided !== flipSided) {
  12216. if (flipSided) {
  12217. gl.frontFace(gl.CW);
  12218. } else {
  12219. gl.frontFace(gl.CCW);
  12220. }
  12221. currentFlipSided = flipSided;
  12222. }
  12223. }
  12224. function setCullFace(cullFace) {
  12225. if (cullFace !== CullFaceNone) {
  12226. enable(gl.CULL_FACE);
  12227. if (cullFace !== currentCullFace) {
  12228. if (cullFace === CullFaceBack) {
  12229. gl.cullFace(gl.BACK);
  12230. } else if (cullFace === CullFaceFront) {
  12231. gl.cullFace(gl.FRONT);
  12232. } else {
  12233. gl.cullFace(gl.FRONT_AND_BACK);
  12234. }
  12235. }
  12236. } else {
  12237. disable(gl.CULL_FACE);
  12238. }
  12239. currentCullFace = cullFace;
  12240. }
  12241. function setLineWidth(width) {
  12242. if (width !== currentLineWidth) {
  12243. if (lineWidthAvailable) gl.lineWidth(width);
  12244. currentLineWidth = width;
  12245. }
  12246. }
  12247. function setPolygonOffset(polygonOffset, factor, units) {
  12248. if (polygonOffset) {
  12249. enable(gl.POLYGON_OFFSET_FILL);
  12250. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  12251. gl.polygonOffset(factor, units);
  12252. currentPolygonOffsetFactor = factor;
  12253. currentPolygonOffsetUnits = units;
  12254. }
  12255. } else {
  12256. disable(gl.POLYGON_OFFSET_FILL);
  12257. }
  12258. }
  12259. function setScissorTest(scissorTest) {
  12260. if (scissorTest) {
  12261. enable(gl.SCISSOR_TEST);
  12262. } else {
  12263. disable(gl.SCISSOR_TEST);
  12264. }
  12265. } // texture
  12266. function activeTexture(webglSlot) {
  12267. if (webglSlot === undefined) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  12268. if (currentTextureSlot !== webglSlot) {
  12269. gl.activeTexture(webglSlot);
  12270. currentTextureSlot = webglSlot;
  12271. }
  12272. }
  12273. function bindTexture(webglType, webglTexture) {
  12274. if (currentTextureSlot === null) {
  12275. activeTexture();
  12276. }
  12277. let boundTexture = currentBoundTextures[currentTextureSlot];
  12278. if (boundTexture === undefined) {
  12279. boundTexture = {
  12280. type: undefined,
  12281. texture: undefined
  12282. };
  12283. currentBoundTextures[currentTextureSlot] = boundTexture;
  12284. }
  12285. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  12286. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  12287. boundTexture.type = webglType;
  12288. boundTexture.texture = webglTexture;
  12289. }
  12290. }
  12291. function unbindTexture() {
  12292. const boundTexture = currentBoundTextures[currentTextureSlot];
  12293. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  12294. gl.bindTexture(boundTexture.type, null);
  12295. boundTexture.type = undefined;
  12296. boundTexture.texture = undefined;
  12297. }
  12298. }
  12299. function compressedTexImage2D() {
  12300. try {
  12301. gl.compressedTexImage2D.apply(gl, arguments);
  12302. } catch (error) {
  12303. console.error('THREE.WebGLState:', error);
  12304. }
  12305. }
  12306. function texImage2D() {
  12307. try {
  12308. gl.texImage2D.apply(gl, arguments);
  12309. } catch (error) {
  12310. console.error('THREE.WebGLState:', error);
  12311. }
  12312. }
  12313. function texImage3D() {
  12314. try {
  12315. gl.texImage3D.apply(gl, arguments);
  12316. } catch (error) {
  12317. console.error('THREE.WebGLState:', error);
  12318. }
  12319. } //
  12320. function scissor(scissor) {
  12321. if (currentScissor.equals(scissor) === false) {
  12322. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  12323. currentScissor.copy(scissor);
  12324. }
  12325. }
  12326. function viewport(viewport) {
  12327. if (currentViewport.equals(viewport) === false) {
  12328. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  12329. currentViewport.copy(viewport);
  12330. }
  12331. } //
  12332. function reset() {
  12333. // reset state
  12334. gl.disable(gl.BLEND);
  12335. gl.disable(gl.CULL_FACE);
  12336. gl.disable(gl.DEPTH_TEST);
  12337. gl.disable(gl.POLYGON_OFFSET_FILL);
  12338. gl.disable(gl.SCISSOR_TEST);
  12339. gl.disable(gl.STENCIL_TEST);
  12340. gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  12341. gl.blendEquation(gl.FUNC_ADD);
  12342. gl.blendFunc(gl.ONE, gl.ZERO);
  12343. gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO);
  12344. gl.colorMask(true, true, true, true);
  12345. gl.clearColor(0, 0, 0, 0);
  12346. gl.depthMask(true);
  12347. gl.depthFunc(gl.LESS);
  12348. gl.clearDepth(1);
  12349. gl.stencilMask(0xffffffff);
  12350. gl.stencilFunc(gl.ALWAYS, 0, 0xffffffff);
  12351. gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
  12352. gl.clearStencil(0);
  12353. gl.cullFace(gl.BACK);
  12354. gl.frontFace(gl.CCW);
  12355. gl.polygonOffset(0, 0);
  12356. gl.activeTexture(gl.TEXTURE0);
  12357. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12358. if (isWebGL2 === true) {
  12359. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
  12360. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  12361. }
  12362. gl.useProgram(null);
  12363. gl.lineWidth(1);
  12364. gl.scissor(0, 0, gl.canvas.width, gl.canvas.height);
  12365. gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); // reset internals
  12366. enabledCapabilities = {};
  12367. currentTextureSlot = null;
  12368. currentBoundTextures = {};
  12369. xrFramebuffer = null;
  12370. currentBoundFramebuffers = {};
  12371. currentProgram = null;
  12372. currentBlendingEnabled = false;
  12373. currentBlending = null;
  12374. currentBlendEquation = null;
  12375. currentBlendSrc = null;
  12376. currentBlendDst = null;
  12377. currentBlendEquationAlpha = null;
  12378. currentBlendSrcAlpha = null;
  12379. currentBlendDstAlpha = null;
  12380. currentPremultipledAlpha = false;
  12381. currentFlipSided = null;
  12382. currentCullFace = null;
  12383. currentLineWidth = null;
  12384. currentPolygonOffsetFactor = null;
  12385. currentPolygonOffsetUnits = null;
  12386. currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height);
  12387. currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height);
  12388. colorBuffer.reset();
  12389. depthBuffer.reset();
  12390. stencilBuffer.reset();
  12391. }
  12392. return {
  12393. buffers: {
  12394. color: colorBuffer,
  12395. depth: depthBuffer,
  12396. stencil: stencilBuffer
  12397. },
  12398. enable: enable,
  12399. disable: disable,
  12400. bindFramebuffer: bindFramebuffer,
  12401. bindXRFramebuffer: bindXRFramebuffer,
  12402. useProgram: useProgram,
  12403. setBlending: setBlending,
  12404. setMaterial: setMaterial,
  12405. setFlipSided: setFlipSided,
  12406. setCullFace: setCullFace,
  12407. setLineWidth: setLineWidth,
  12408. setPolygonOffset: setPolygonOffset,
  12409. setScissorTest: setScissorTest,
  12410. activeTexture: activeTexture,
  12411. bindTexture: bindTexture,
  12412. unbindTexture: unbindTexture,
  12413. compressedTexImage2D: compressedTexImage2D,
  12414. texImage2D: texImage2D,
  12415. texImage3D: texImage3D,
  12416. scissor: scissor,
  12417. viewport: viewport,
  12418. reset: reset
  12419. };
  12420. }
  12421. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  12422. const isWebGL2 = capabilities.isWebGL2;
  12423. const maxTextures = capabilities.maxTextures;
  12424. const maxCubemapSize = capabilities.maxCubemapSize;
  12425. const maxTextureSize = capabilities.maxTextureSize;
  12426. const maxSamples = capabilities.maxSamples;
  12427. const _videoTextures = new WeakMap();
  12428. let _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  12429. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  12430. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  12431. let useOffscreenCanvas = false;
  12432. try {
  12433. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext('2d') !== null;
  12434. } catch (err) {// Ignore any errors
  12435. }
  12436. function createCanvas(width, height) {
  12437. // Use OffscreenCanvas when available. Specially needed in web workers
  12438. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  12439. }
  12440. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  12441. let scale = 1; // handle case if texture exceeds max size
  12442. if (image.width > maxSize || image.height > maxSize) {
  12443. scale = maxSize / Math.max(image.width, image.height);
  12444. } // only perform resize if necessary
  12445. if (scale < 1 || needsPowerOfTwo === true) {
  12446. // only perform resize for certain image types
  12447. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  12448. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  12449. const width = floor(scale * image.width);
  12450. const height = floor(scale * image.height);
  12451. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  12452. const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  12453. canvas.width = width;
  12454. canvas.height = height;
  12455. const context = canvas.getContext('2d');
  12456. context.drawImage(image, 0, 0, width, height);
  12457. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  12458. return canvas;
  12459. } else {
  12460. if ('data' in image) {
  12461. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  12462. }
  12463. return image;
  12464. }
  12465. }
  12466. return image;
  12467. }
  12468. function isPowerOfTwo$1(image) {
  12469. return isPowerOfTwo(image.width) && isPowerOfTwo(image.height);
  12470. }
  12471. function textureNeedsPowerOfTwo(texture) {
  12472. if (isWebGL2) return false;
  12473. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  12474. }
  12475. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  12476. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  12477. }
  12478. function generateMipmap(target, texture, width, height) {
  12479. _gl.generateMipmap(target);
  12480. const textureProperties = properties.get(texture);
  12481. textureProperties.__maxMipLevel = Math.log2(Math.max(width, height));
  12482. }
  12483. function getInternalFormat(internalFormatName, glFormat, glType) {
  12484. if (isWebGL2 === false) return glFormat;
  12485. if (internalFormatName !== null) {
  12486. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  12487. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  12488. }
  12489. let internalFormat = glFormat;
  12490. if (glFormat === _gl.RED) {
  12491. if (glType === _gl.FLOAT) internalFormat = _gl.R32F;
  12492. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.R16F;
  12493. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8;
  12494. }
  12495. if (glFormat === _gl.RGB) {
  12496. if (glType === _gl.FLOAT) internalFormat = _gl.RGB32F;
  12497. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGB16F;
  12498. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGB8;
  12499. }
  12500. if (glFormat === _gl.RGBA) {
  12501. if (glType === _gl.FLOAT) internalFormat = _gl.RGBA32F;
  12502. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGBA16F;
  12503. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RGBA8;
  12504. }
  12505. if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) {
  12506. extensions.get('EXT_color_buffer_float');
  12507. }
  12508. return internalFormat;
  12509. } // Fallback filters for non-power-of-2 textures
  12510. function filterFallback(f) {
  12511. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  12512. return _gl.NEAREST;
  12513. }
  12514. return _gl.LINEAR;
  12515. } //
  12516. function onTextureDispose(event) {
  12517. const texture = event.target;
  12518. texture.removeEventListener('dispose', onTextureDispose);
  12519. deallocateTexture(texture);
  12520. if (texture.isVideoTexture) {
  12521. _videoTextures.delete(texture);
  12522. }
  12523. info.memory.textures--;
  12524. }
  12525. function onRenderTargetDispose(event) {
  12526. const renderTarget = event.target;
  12527. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  12528. deallocateRenderTarget(renderTarget);
  12529. } //
  12530. function deallocateTexture(texture) {
  12531. const textureProperties = properties.get(texture);
  12532. if (textureProperties.__webglInit === undefined) return;
  12533. _gl.deleteTexture(textureProperties.__webglTexture);
  12534. properties.remove(texture);
  12535. }
  12536. function deallocateRenderTarget(renderTarget) {
  12537. const texture = renderTarget.texture;
  12538. const renderTargetProperties = properties.get(renderTarget);
  12539. const textureProperties = properties.get(texture);
  12540. if (!renderTarget) return;
  12541. if (textureProperties.__webglTexture !== undefined) {
  12542. _gl.deleteTexture(textureProperties.__webglTexture);
  12543. info.memory.textures--;
  12544. }
  12545. if (renderTarget.depthTexture) {
  12546. renderTarget.depthTexture.dispose();
  12547. }
  12548. if (renderTarget.isWebGLCubeRenderTarget) {
  12549. for (let i = 0; i < 6; i++) {
  12550. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  12551. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  12552. }
  12553. } else {
  12554. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  12555. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  12556. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  12557. if (renderTargetProperties.__webglColorRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);
  12558. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  12559. }
  12560. if (renderTarget.isWebGLMultipleRenderTargets) {
  12561. for (let i = 0, il = texture.length; i < il; i++) {
  12562. const attachmentProperties = properties.get(texture[i]);
  12563. if (attachmentProperties.__webglTexture) {
  12564. _gl.deleteTexture(attachmentProperties.__webglTexture);
  12565. info.memory.textures--;
  12566. }
  12567. properties.remove(texture[i]);
  12568. }
  12569. }
  12570. properties.remove(texture);
  12571. properties.remove(renderTarget);
  12572. } //
  12573. let textureUnits = 0;
  12574. function resetTextureUnits() {
  12575. textureUnits = 0;
  12576. }
  12577. function allocateTextureUnit() {
  12578. const textureUnit = textureUnits;
  12579. if (textureUnit >= maxTextures) {
  12580. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  12581. }
  12582. textureUnits += 1;
  12583. return textureUnit;
  12584. } //
  12585. function setTexture2D(texture, slot) {
  12586. const textureProperties = properties.get(texture);
  12587. if (texture.isVideoTexture) updateVideoTexture(texture);
  12588. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  12589. const image = texture.image;
  12590. if (image === undefined) {
  12591. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  12592. } else if (image.complete === false) {
  12593. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  12594. } else {
  12595. uploadTexture(textureProperties, texture, slot);
  12596. return;
  12597. }
  12598. }
  12599. state.activeTexture(_gl.TEXTURE0 + slot);
  12600. state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture);
  12601. }
  12602. function setTexture2DArray(texture, slot) {
  12603. const textureProperties = properties.get(texture);
  12604. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  12605. uploadTexture(textureProperties, texture, slot);
  12606. return;
  12607. }
  12608. state.activeTexture(_gl.TEXTURE0 + slot);
  12609. state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture);
  12610. }
  12611. function setTexture3D(texture, slot) {
  12612. const textureProperties = properties.get(texture);
  12613. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  12614. uploadTexture(textureProperties, texture, slot);
  12615. return;
  12616. }
  12617. state.activeTexture(_gl.TEXTURE0 + slot);
  12618. state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture);
  12619. }
  12620. function setTextureCube(texture, slot) {
  12621. const textureProperties = properties.get(texture);
  12622. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  12623. uploadCubeTexture(textureProperties, texture, slot);
  12624. return;
  12625. }
  12626. state.activeTexture(_gl.TEXTURE0 + slot);
  12627. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  12628. }
  12629. const wrappingToGL = {
  12630. [RepeatWrapping]: _gl.REPEAT,
  12631. [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE,
  12632. [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT
  12633. };
  12634. const filterToGL = {
  12635. [NearestFilter]: _gl.NEAREST,
  12636. [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST,
  12637. [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR,
  12638. [LinearFilter]: _gl.LINEAR,
  12639. [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST,
  12640. [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR
  12641. };
  12642. function setTextureParameters(textureType, texture, supportsMips) {
  12643. if (supportsMips) {
  12644. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]);
  12645. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]);
  12646. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  12647. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]);
  12648. }
  12649. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]);
  12650. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]);
  12651. } else {
  12652. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE);
  12653. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE);
  12654. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  12655. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE);
  12656. }
  12657. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  12658. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  12659. }
  12660. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterFallback(texture.magFilter));
  12661. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterFallback(texture.minFilter));
  12662. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  12663. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  12664. }
  12665. }
  12666. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  12667. const extension = extensions.get('EXT_texture_filter_anisotropic');
  12668. if (texture.type === FloatType && extensions.has('OES_texture_float_linear') === false) return; // verify extension for WebGL 1 and WebGL 2
  12669. if (isWebGL2 === false && texture.type === HalfFloatType && extensions.has('OES_texture_half_float_linear') === false) return; // verify extension for WebGL 1 only
  12670. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  12671. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  12672. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  12673. }
  12674. }
  12675. }
  12676. function initTexture(textureProperties, texture) {
  12677. if (textureProperties.__webglInit === undefined) {
  12678. textureProperties.__webglInit = true;
  12679. texture.addEventListener('dispose', onTextureDispose);
  12680. textureProperties.__webglTexture = _gl.createTexture();
  12681. info.memory.textures++;
  12682. }
  12683. }
  12684. function uploadTexture(textureProperties, texture, slot) {
  12685. let textureType = _gl.TEXTURE_2D;
  12686. if (texture.isDataTexture2DArray) textureType = _gl.TEXTURE_2D_ARRAY;
  12687. if (texture.isDataTexture3D) textureType = _gl.TEXTURE_3D;
  12688. initTexture(textureProperties, texture);
  12689. state.activeTexture(_gl.TEXTURE0 + slot);
  12690. state.bindTexture(textureType, textureProperties.__webglTexture);
  12691. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  12692. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  12693. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  12694. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  12695. const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo$1(texture.image) === false;
  12696. const image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  12697. const supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  12698. glFormat = utils.convert(texture.format);
  12699. let glType = utils.convert(texture.type),
  12700. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12701. setTextureParameters(textureType, texture, supportsMips);
  12702. let mipmap;
  12703. const mipmaps = texture.mipmaps;
  12704. if (texture.isDepthTexture) {
  12705. // populate depth texture with dummy data
  12706. glInternalFormat = _gl.DEPTH_COMPONENT;
  12707. if (isWebGL2) {
  12708. if (texture.type === FloatType) {
  12709. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  12710. } else if (texture.type === UnsignedIntType) {
  12711. glInternalFormat = _gl.DEPTH_COMPONENT24;
  12712. } else if (texture.type === UnsignedInt248Type) {
  12713. glInternalFormat = _gl.DEPTH24_STENCIL8;
  12714. } else {
  12715. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  12716. }
  12717. } else {
  12718. if (texture.type === FloatType) {
  12719. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  12720. }
  12721. } // validation checks for WebGL 1
  12722. if (texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  12723. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  12724. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  12725. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12726. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  12727. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  12728. texture.type = UnsignedShortType;
  12729. glType = utils.convert(texture.type);
  12730. }
  12731. }
  12732. if (texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  12733. // Depth stencil textures need the DEPTH_STENCIL internal format
  12734. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12735. glInternalFormat = _gl.DEPTH_STENCIL; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  12736. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  12737. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  12738. if (texture.type !== UnsignedInt248Type) {
  12739. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  12740. texture.type = UnsignedInt248Type;
  12741. glType = utils.convert(texture.type);
  12742. }
  12743. } //
  12744. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  12745. } else if (texture.isDataTexture) {
  12746. // use manually created mipmaps if available
  12747. // if there are no manual mipmaps
  12748. // set 0 level mipmap and then use GL to generate other mipmap levels
  12749. if (mipmaps.length > 0 && supportsMips) {
  12750. for (let i = 0, il = mipmaps.length; i < il; i++) {
  12751. mipmap = mipmaps[i];
  12752. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  12753. }
  12754. texture.generateMipmaps = false;
  12755. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12756. } else {
  12757. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  12758. textureProperties.__maxMipLevel = 0;
  12759. }
  12760. } else if (texture.isCompressedTexture) {
  12761. for (let i = 0, il = mipmaps.length; i < il; i++) {
  12762. mipmap = mipmaps[i];
  12763. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  12764. if (glFormat !== null) {
  12765. state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  12766. } else {
  12767. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  12768. }
  12769. } else {
  12770. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  12771. }
  12772. }
  12773. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12774. } else if (texture.isDataTexture2DArray) {
  12775. state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  12776. textureProperties.__maxMipLevel = 0;
  12777. } else if (texture.isDataTexture3D) {
  12778. state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  12779. textureProperties.__maxMipLevel = 0;
  12780. } else {
  12781. // regular Texture (image, video, canvas)
  12782. // use manually created mipmaps if available
  12783. // if there are no manual mipmaps
  12784. // set 0 level mipmap and then use GL to generate other mipmap levels
  12785. if (mipmaps.length > 0 && supportsMips) {
  12786. for (let i = 0, il = mipmaps.length; i < il; i++) {
  12787. mipmap = mipmaps[i];
  12788. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap);
  12789. }
  12790. texture.generateMipmaps = false;
  12791. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12792. } else {
  12793. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image);
  12794. textureProperties.__maxMipLevel = 0;
  12795. }
  12796. }
  12797. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  12798. generateMipmap(textureType, texture, image.width, image.height);
  12799. }
  12800. textureProperties.__version = texture.version;
  12801. if (texture.onUpdate) texture.onUpdate(texture);
  12802. }
  12803. function uploadCubeTexture(textureProperties, texture, slot) {
  12804. if (texture.image.length !== 6) return;
  12805. initTexture(textureProperties, texture);
  12806. state.activeTexture(_gl.TEXTURE0 + slot);
  12807. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  12808. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  12809. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  12810. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  12811. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  12812. const isCompressed = texture && (texture.isCompressedTexture || texture.image[0].isCompressedTexture);
  12813. const isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  12814. const cubeImage = [];
  12815. for (let i = 0; i < 6; i++) {
  12816. if (!isCompressed && !isDataTexture) {
  12817. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  12818. } else {
  12819. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  12820. }
  12821. }
  12822. const image = cubeImage[0],
  12823. supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  12824. glFormat = utils.convert(texture.format),
  12825. glType = utils.convert(texture.type),
  12826. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12827. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  12828. let mipmaps;
  12829. if (isCompressed) {
  12830. for (let i = 0; i < 6; i++) {
  12831. mipmaps = cubeImage[i].mipmaps;
  12832. for (let j = 0; j < mipmaps.length; j++) {
  12833. const mipmap = mipmaps[j];
  12834. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  12835. if (glFormat !== null) {
  12836. state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  12837. } else {
  12838. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  12839. }
  12840. } else {
  12841. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  12842. }
  12843. }
  12844. }
  12845. textureProperties.__maxMipLevel = mipmaps.length - 1;
  12846. } else {
  12847. mipmaps = texture.mipmaps;
  12848. for (let i = 0; i < 6; i++) {
  12849. if (isDataTexture) {
  12850. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  12851. for (let j = 0; j < mipmaps.length; j++) {
  12852. const mipmap = mipmaps[j];
  12853. const mipmapImage = mipmap.image[i].image;
  12854. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  12855. }
  12856. } else {
  12857. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  12858. for (let j = 0; j < mipmaps.length; j++) {
  12859. const mipmap = mipmaps[j];
  12860. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  12861. }
  12862. }
  12863. }
  12864. textureProperties.__maxMipLevel = mipmaps.length;
  12865. }
  12866. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  12867. // We assume images for cube map have the same size.
  12868. generateMipmap(_gl.TEXTURE_CUBE_MAP, texture, image.width, image.height);
  12869. }
  12870. textureProperties.__version = texture.version;
  12871. if (texture.onUpdate) texture.onUpdate(texture);
  12872. } // Render targets
  12873. // Setup storage for target texture and bind it to correct framebuffer
  12874. function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget) {
  12875. const glFormat = utils.convert(texture.format);
  12876. const glType = utils.convert(texture.type);
  12877. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12878. if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) {
  12879. state.texImage3D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null);
  12880. } else {
  12881. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  12882. }
  12883. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  12884. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0);
  12885. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  12886. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  12887. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  12888. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer);
  12889. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  12890. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  12891. if (isMultisample) {
  12892. const depthTexture = renderTarget.depthTexture;
  12893. if (depthTexture && depthTexture.isDepthTexture) {
  12894. if (depthTexture.type === FloatType) {
  12895. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  12896. } else if (depthTexture.type === UnsignedIntType) {
  12897. glInternalFormat = _gl.DEPTH_COMPONENT24;
  12898. }
  12899. }
  12900. const samples = getRenderTargetSamples(renderTarget);
  12901. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  12902. } else {
  12903. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  12904. }
  12905. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  12906. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  12907. if (isMultisample) {
  12908. const samples = getRenderTargetSamples(renderTarget);
  12909. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  12910. } else {
  12911. _gl.renderbufferStorage(_gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height);
  12912. }
  12913. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  12914. } else {
  12915. // Use the first texture for MRT so far
  12916. const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[0] : renderTarget.texture;
  12917. const glFormat = utils.convert(texture.format);
  12918. const glType = utils.convert(texture.type);
  12919. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  12920. if (isMultisample) {
  12921. const samples = getRenderTargetSamples(renderTarget);
  12922. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  12923. } else {
  12924. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  12925. }
  12926. }
  12927. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  12928. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  12929. function setupDepthTexture(framebuffer, renderTarget) {
  12930. const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  12931. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  12932. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  12933. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  12934. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  12935. } // upload an empty depth texture with framebuffer size
  12936. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  12937. renderTarget.depthTexture.image.width = renderTarget.width;
  12938. renderTarget.depthTexture.image.height = renderTarget.height;
  12939. renderTarget.depthTexture.needsUpdate = true;
  12940. }
  12941. setTexture2D(renderTarget.depthTexture, 0);
  12942. const webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  12943. if (renderTarget.depthTexture.format === DepthFormat) {
  12944. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  12945. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  12946. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  12947. } else {
  12948. throw new Error('Unknown depthTexture format');
  12949. }
  12950. } // Setup GL resources for a non-texture depth buffer
  12951. function setupDepthRenderbuffer(renderTarget) {
  12952. const renderTargetProperties = properties.get(renderTarget);
  12953. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  12954. if (renderTarget.depthTexture) {
  12955. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  12956. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  12957. } else {
  12958. if (isCube) {
  12959. renderTargetProperties.__webglDepthbuffer = [];
  12960. for (let i = 0; i < 6; i++) {
  12961. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]);
  12962. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  12963. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  12964. }
  12965. } else {
  12966. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  12967. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  12968. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  12969. }
  12970. }
  12971. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  12972. } // Set up GL resources for the render target
  12973. function setupRenderTarget(renderTarget) {
  12974. const texture = renderTarget.texture;
  12975. const renderTargetProperties = properties.get(renderTarget);
  12976. const textureProperties = properties.get(texture);
  12977. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  12978. if (renderTarget.isWebGLMultipleRenderTargets !== true) {
  12979. textureProperties.__webglTexture = _gl.createTexture();
  12980. textureProperties.__version = texture.version;
  12981. info.memory.textures++;
  12982. }
  12983. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  12984. const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true;
  12985. const isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
  12986. const isRenderTarget3D = texture.isDataTexture3D || texture.isDataTexture2DArray;
  12987. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2; // Handles WebGL2 RGBFormat fallback - #18858
  12988. if (isWebGL2 && texture.format === RGBFormat && (texture.type === FloatType || texture.type === HalfFloatType)) {
  12989. texture.format = RGBAFormat;
  12990. console.warn('THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.');
  12991. } // Setup framebuffer
  12992. if (isCube) {
  12993. renderTargetProperties.__webglFramebuffer = [];
  12994. for (let i = 0; i < 6; i++) {
  12995. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  12996. }
  12997. } else {
  12998. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  12999. if (isMultipleRenderTargets) {
  13000. if (capabilities.drawBuffers) {
  13001. const textures = renderTarget.texture;
  13002. for (let i = 0, il = textures.length; i < il; i++) {
  13003. const attachmentProperties = properties.get(textures[i]);
  13004. if (attachmentProperties.__webglTexture === undefined) {
  13005. attachmentProperties.__webglTexture = _gl.createTexture();
  13006. info.memory.textures++;
  13007. }
  13008. }
  13009. } else {
  13010. console.warn('THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.');
  13011. }
  13012. } else if (isMultisample) {
  13013. if (isWebGL2) {
  13014. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  13015. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  13016. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  13017. const glFormat = utils.convert(texture.format);
  13018. const glType = utils.convert(texture.type);
  13019. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13020. const samples = getRenderTargetSamples(renderTarget);
  13021. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13022. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  13023. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  13024. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  13025. if (renderTarget.depthBuffer) {
  13026. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  13027. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  13028. }
  13029. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  13030. } else {
  13031. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  13032. }
  13033. }
  13034. } // Setup color buffer
  13035. if (isCube) {
  13036. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  13037. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  13038. for (let i = 0; i < 6; i++) {
  13039. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i);
  13040. }
  13041. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13042. generateMipmap(_gl.TEXTURE_CUBE_MAP, texture, renderTarget.width, renderTarget.height);
  13043. }
  13044. state.bindTexture(_gl.TEXTURE_CUBE_MAP, null);
  13045. } else if (isMultipleRenderTargets) {
  13046. const textures = renderTarget.texture;
  13047. for (let i = 0, il = textures.length; i < il; i++) {
  13048. const attachment = textures[i];
  13049. const attachmentProperties = properties.get(attachment);
  13050. state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture);
  13051. setTextureParameters(_gl.TEXTURE_2D, attachment, supportsMips);
  13052. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D);
  13053. if (textureNeedsGenerateMipmaps(attachment, supportsMips)) {
  13054. generateMipmap(_gl.TEXTURE_2D, attachment, renderTarget.width, renderTarget.height);
  13055. }
  13056. }
  13057. state.bindTexture(_gl.TEXTURE_2D, null);
  13058. } else {
  13059. let glTextureType = _gl.TEXTURE_2D;
  13060. if (isRenderTarget3D) {
  13061. // Render targets containing layers, i.e: Texture 3D and 2d arrays
  13062. if (isWebGL2) {
  13063. const isTexture3D = texture.isDataTexture3D;
  13064. glTextureType = isTexture3D ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  13065. } else {
  13066. console.warn('THREE.DataTexture3D and THREE.DataTexture2DArray only supported with WebGL2.');
  13067. }
  13068. }
  13069. state.bindTexture(glTextureType, textureProperties.__webglTexture);
  13070. setTextureParameters(glTextureType, texture, supportsMips);
  13071. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType);
  13072. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13073. generateMipmap(_gl.TEXTURE_2D, texture, renderTarget.width, renderTarget.height);
  13074. }
  13075. state.bindTexture(_gl.TEXTURE_2D, null);
  13076. } // Setup depth and stencil buffers
  13077. if (renderTarget.depthBuffer) {
  13078. setupDepthRenderbuffer(renderTarget);
  13079. }
  13080. }
  13081. function updateRenderTargetMipmap(renderTarget) {
  13082. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2;
  13083. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture];
  13084. for (let i = 0, il = textures.length; i < il; i++) {
  13085. const texture = textures[i];
  13086. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13087. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  13088. const webglTexture = properties.get(texture).__webglTexture;
  13089. state.bindTexture(target, webglTexture);
  13090. generateMipmap(target, texture, renderTarget.width, renderTarget.height);
  13091. state.bindTexture(target, null);
  13092. }
  13093. }
  13094. }
  13095. function updateMultisampleRenderTarget(renderTarget) {
  13096. if (renderTarget.isWebGLMultisampleRenderTarget) {
  13097. if (isWebGL2) {
  13098. const width = renderTarget.width;
  13099. const height = renderTarget.height;
  13100. let mask = _gl.COLOR_BUFFER_BIT;
  13101. if (renderTarget.depthBuffer) mask |= _gl.DEPTH_BUFFER_BIT;
  13102. if (renderTarget.stencilBuffer) mask |= _gl.STENCIL_BUFFER_BIT;
  13103. const renderTargetProperties = properties.get(renderTarget);
  13104. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  13105. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  13106. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST);
  13107. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null);
  13108. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  13109. } else {
  13110. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  13111. }
  13112. }
  13113. }
  13114. function getRenderTargetSamples(renderTarget) {
  13115. return isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(maxSamples, renderTarget.samples) : 0;
  13116. }
  13117. function updateVideoTexture(texture) {
  13118. const frame = info.render.frame; // Check the last frame we updated the VideoTexture
  13119. if (_videoTextures.get(texture) !== frame) {
  13120. _videoTextures.set(texture, frame);
  13121. texture.update();
  13122. }
  13123. } // backwards compatibility
  13124. let warnedTexture2D = false;
  13125. let warnedTextureCube = false;
  13126. function safeSetTexture2D(texture, slot) {
  13127. if (texture && texture.isWebGLRenderTarget) {
  13128. if (warnedTexture2D === false) {
  13129. console.warn('THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.');
  13130. warnedTexture2D = true;
  13131. }
  13132. texture = texture.texture;
  13133. }
  13134. setTexture2D(texture, slot);
  13135. }
  13136. function safeSetTextureCube(texture, slot) {
  13137. if (texture && texture.isWebGLCubeRenderTarget) {
  13138. if (warnedTextureCube === false) {
  13139. console.warn('THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.');
  13140. warnedTextureCube = true;
  13141. }
  13142. texture = texture.texture;
  13143. }
  13144. setTextureCube(texture, slot);
  13145. } //
  13146. this.allocateTextureUnit = allocateTextureUnit;
  13147. this.resetTextureUnits = resetTextureUnits;
  13148. this.setTexture2D = setTexture2D;
  13149. this.setTexture2DArray = setTexture2DArray;
  13150. this.setTexture3D = setTexture3D;
  13151. this.setTextureCube = setTextureCube;
  13152. this.setupRenderTarget = setupRenderTarget;
  13153. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  13154. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  13155. this.safeSetTexture2D = safeSetTexture2D;
  13156. this.safeSetTextureCube = safeSetTextureCube;
  13157. }
  13158. function WebGLUtils(gl, extensions, capabilities) {
  13159. const isWebGL2 = capabilities.isWebGL2;
  13160. function convert(p) {
  13161. let extension;
  13162. if (p === UnsignedByteType) return gl.UNSIGNED_BYTE;
  13163. if (p === UnsignedShort4444Type) return gl.UNSIGNED_SHORT_4_4_4_4;
  13164. if (p === UnsignedShort5551Type) return gl.UNSIGNED_SHORT_5_5_5_1;
  13165. if (p === UnsignedShort565Type) return gl.UNSIGNED_SHORT_5_6_5;
  13166. if (p === ByteType) return gl.BYTE;
  13167. if (p === ShortType) return gl.SHORT;
  13168. if (p === UnsignedShortType) return gl.UNSIGNED_SHORT;
  13169. if (p === IntType) return gl.INT;
  13170. if (p === UnsignedIntType) return gl.UNSIGNED_INT;
  13171. if (p === FloatType) return gl.FLOAT;
  13172. if (p === HalfFloatType) {
  13173. if (isWebGL2) return gl.HALF_FLOAT;
  13174. extension = extensions.get('OES_texture_half_float');
  13175. if (extension !== null) {
  13176. return extension.HALF_FLOAT_OES;
  13177. } else {
  13178. return null;
  13179. }
  13180. }
  13181. if (p === AlphaFormat) return gl.ALPHA;
  13182. if (p === RGBFormat) return gl.RGB;
  13183. if (p === RGBAFormat) return gl.RGBA;
  13184. if (p === LuminanceFormat) return gl.LUMINANCE;
  13185. if (p === LuminanceAlphaFormat) return gl.LUMINANCE_ALPHA;
  13186. if (p === DepthFormat) return gl.DEPTH_COMPONENT;
  13187. if (p === DepthStencilFormat) return gl.DEPTH_STENCIL;
  13188. if (p === RedFormat) return gl.RED; // WebGL2 formats.
  13189. if (p === RedIntegerFormat) return gl.RED_INTEGER;
  13190. if (p === RGFormat) return gl.RG;
  13191. if (p === RGIntegerFormat) return gl.RG_INTEGER;
  13192. if (p === RGBIntegerFormat) return gl.RGB_INTEGER;
  13193. if (p === RGBAIntegerFormat) return gl.RGBA_INTEGER;
  13194. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  13195. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  13196. if (extension !== null) {
  13197. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13198. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13199. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13200. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13201. } else {
  13202. return null;
  13203. }
  13204. }
  13205. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  13206. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  13207. if (extension !== null) {
  13208. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13209. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13210. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13211. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13212. } else {
  13213. return null;
  13214. }
  13215. }
  13216. if (p === RGB_ETC1_Format) {
  13217. extension = extensions.get('WEBGL_compressed_texture_etc1');
  13218. if (extension !== null) {
  13219. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13220. } else {
  13221. return null;
  13222. }
  13223. }
  13224. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  13225. extension = extensions.get('WEBGL_compressed_texture_etc');
  13226. if (extension !== null) {
  13227. if (p === RGB_ETC2_Format) return extension.COMPRESSED_RGB8_ETC2;
  13228. if (p === RGBA_ETC2_EAC_Format) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  13229. }
  13230. }
  13231. 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) {
  13232. extension = extensions.get('WEBGL_compressed_texture_astc');
  13233. if (extension !== null) {
  13234. // TODO Complete?
  13235. return p;
  13236. } else {
  13237. return null;
  13238. }
  13239. }
  13240. if (p === RGBA_BPTC_Format) {
  13241. extension = extensions.get('EXT_texture_compression_bptc');
  13242. if (extension !== null) {
  13243. // TODO Complete?
  13244. return p;
  13245. } else {
  13246. return null;
  13247. }
  13248. }
  13249. if (p === UnsignedInt248Type) {
  13250. if (isWebGL2) return gl.UNSIGNED_INT_24_8;
  13251. extension = extensions.get('WEBGL_depth_texture');
  13252. if (extension !== null) {
  13253. return extension.UNSIGNED_INT_24_8_WEBGL;
  13254. } else {
  13255. return null;
  13256. }
  13257. }
  13258. }
  13259. return {
  13260. convert: convert
  13261. };
  13262. }
  13263. class ArrayCamera extends PerspectiveCamera {
  13264. constructor(array = []) {
  13265. super();
  13266. this.cameras = array;
  13267. }
  13268. }
  13269. ArrayCamera.prototype.isArrayCamera = true;
  13270. class Group extends Object3D {
  13271. constructor() {
  13272. super();
  13273. this.type = 'Group';
  13274. }
  13275. }
  13276. Group.prototype.isGroup = true;
  13277. const _moveEvent = {
  13278. type: 'move'
  13279. };
  13280. class WebXRController {
  13281. constructor() {
  13282. this._targetRay = null;
  13283. this._grip = null;
  13284. this._hand = null;
  13285. }
  13286. getHandSpace() {
  13287. if (this._hand === null) {
  13288. this._hand = new Group();
  13289. this._hand.matrixAutoUpdate = false;
  13290. this._hand.visible = false;
  13291. this._hand.joints = {};
  13292. this._hand.inputState = {
  13293. pinching: false
  13294. };
  13295. }
  13296. return this._hand;
  13297. }
  13298. getTargetRaySpace() {
  13299. if (this._targetRay === null) {
  13300. this._targetRay = new Group();
  13301. this._targetRay.matrixAutoUpdate = false;
  13302. this._targetRay.visible = false;
  13303. this._targetRay.hasLinearVelocity = false;
  13304. this._targetRay.linearVelocity = new Vector3();
  13305. this._targetRay.hasAngularVelocity = false;
  13306. this._targetRay.angularVelocity = new Vector3();
  13307. }
  13308. return this._targetRay;
  13309. }
  13310. getGripSpace() {
  13311. if (this._grip === null) {
  13312. this._grip = new Group();
  13313. this._grip.matrixAutoUpdate = false;
  13314. this._grip.visible = false;
  13315. this._grip.hasLinearVelocity = false;
  13316. this._grip.linearVelocity = new Vector3();
  13317. this._grip.hasAngularVelocity = false;
  13318. this._grip.angularVelocity = new Vector3();
  13319. }
  13320. return this._grip;
  13321. }
  13322. dispatchEvent(event) {
  13323. if (this._targetRay !== null) {
  13324. this._targetRay.dispatchEvent(event);
  13325. }
  13326. if (this._grip !== null) {
  13327. this._grip.dispatchEvent(event);
  13328. }
  13329. if (this._hand !== null) {
  13330. this._hand.dispatchEvent(event);
  13331. }
  13332. return this;
  13333. }
  13334. disconnect(inputSource) {
  13335. this.dispatchEvent({
  13336. type: 'disconnected',
  13337. data: inputSource
  13338. });
  13339. if (this._targetRay !== null) {
  13340. this._targetRay.visible = false;
  13341. }
  13342. if (this._grip !== null) {
  13343. this._grip.visible = false;
  13344. }
  13345. if (this._hand !== null) {
  13346. this._hand.visible = false;
  13347. }
  13348. return this;
  13349. }
  13350. update(inputSource, frame, referenceSpace) {
  13351. let inputPose = null;
  13352. let gripPose = null;
  13353. let handPose = null;
  13354. const targetRay = this._targetRay;
  13355. const grip = this._grip;
  13356. const hand = this._hand;
  13357. if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
  13358. if (targetRay !== null) {
  13359. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  13360. if (inputPose !== null) {
  13361. targetRay.matrix.fromArray(inputPose.transform.matrix);
  13362. targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
  13363. if (inputPose.linearVelocity) {
  13364. targetRay.hasLinearVelocity = true;
  13365. targetRay.linearVelocity.copy(inputPose.linearVelocity);
  13366. } else {
  13367. targetRay.hasLinearVelocity = false;
  13368. }
  13369. if (inputPose.angularVelocity) {
  13370. targetRay.hasAngularVelocity = true;
  13371. targetRay.angularVelocity.copy(inputPose.angularVelocity);
  13372. } else {
  13373. targetRay.hasAngularVelocity = false;
  13374. }
  13375. this.dispatchEvent(_moveEvent);
  13376. }
  13377. }
  13378. if (hand && inputSource.hand) {
  13379. handPose = true;
  13380. for (const inputjoint of inputSource.hand.values()) {
  13381. // Update the joints groups with the XRJoint poses
  13382. const jointPose = frame.getJointPose(inputjoint, referenceSpace);
  13383. if (hand.joints[inputjoint.jointName] === undefined) {
  13384. // The transform of this joint will be updated with the joint pose on each frame
  13385. const joint = new Group();
  13386. joint.matrixAutoUpdate = false;
  13387. joint.visible = false;
  13388. hand.joints[inputjoint.jointName] = joint; // ??
  13389. hand.add(joint);
  13390. }
  13391. const joint = hand.joints[inputjoint.jointName];
  13392. if (jointPose !== null) {
  13393. joint.matrix.fromArray(jointPose.transform.matrix);
  13394. joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
  13395. joint.jointRadius = jointPose.radius;
  13396. }
  13397. joint.visible = jointPose !== null;
  13398. } // Custom events
  13399. // Check pinchz
  13400. const indexTip = hand.joints['index-finger-tip'];
  13401. const thumbTip = hand.joints['thumb-tip'];
  13402. const distance = indexTip.position.distanceTo(thumbTip.position);
  13403. const distanceToPinch = 0.02;
  13404. const threshold = 0.005;
  13405. if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
  13406. hand.inputState.pinching = false;
  13407. this.dispatchEvent({
  13408. type: 'pinchend',
  13409. handedness: inputSource.handedness,
  13410. target: this
  13411. });
  13412. } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
  13413. hand.inputState.pinching = true;
  13414. this.dispatchEvent({
  13415. type: 'pinchstart',
  13416. handedness: inputSource.handedness,
  13417. target: this
  13418. });
  13419. }
  13420. } else {
  13421. if (grip !== null && inputSource.gripSpace) {
  13422. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  13423. if (gripPose !== null) {
  13424. grip.matrix.fromArray(gripPose.transform.matrix);
  13425. grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
  13426. if (gripPose.linearVelocity) {
  13427. grip.hasLinearVelocity = true;
  13428. grip.linearVelocity.copy(gripPose.linearVelocity);
  13429. } else {
  13430. grip.hasLinearVelocity = false;
  13431. }
  13432. if (gripPose.angularVelocity) {
  13433. grip.hasAngularVelocity = true;
  13434. grip.angularVelocity.copy(gripPose.angularVelocity);
  13435. } else {
  13436. grip.hasAngularVelocity = false;
  13437. }
  13438. }
  13439. }
  13440. }
  13441. }
  13442. if (targetRay !== null) {
  13443. targetRay.visible = inputPose !== null;
  13444. }
  13445. if (grip !== null) {
  13446. grip.visible = gripPose !== null;
  13447. }
  13448. if (hand !== null) {
  13449. hand.visible = handPose !== null;
  13450. }
  13451. return this;
  13452. }
  13453. }
  13454. class WebXRManager extends EventDispatcher {
  13455. constructor(renderer, gl) {
  13456. super();
  13457. const scope = this;
  13458. const state = renderer.state;
  13459. let session = null;
  13460. let framebufferScaleFactor = 1.0;
  13461. let referenceSpace = null;
  13462. let referenceSpaceType = 'local-floor';
  13463. let pose = null;
  13464. const controllers = [];
  13465. const inputSourcesMap = new Map(); //
  13466. const cameraL = new PerspectiveCamera();
  13467. cameraL.layers.enable(1);
  13468. cameraL.viewport = new Vector4();
  13469. const cameraR = new PerspectiveCamera();
  13470. cameraR.layers.enable(2);
  13471. cameraR.viewport = new Vector4();
  13472. const cameras = [cameraL, cameraR];
  13473. const cameraVR = new ArrayCamera();
  13474. cameraVR.layers.enable(1);
  13475. cameraVR.layers.enable(2);
  13476. let _currentDepthNear = null;
  13477. let _currentDepthFar = null; //
  13478. this.cameraAutoUpdate = true;
  13479. this.enabled = false;
  13480. this.isPresenting = false;
  13481. this.getController = function (index) {
  13482. let controller = controllers[index];
  13483. if (controller === undefined) {
  13484. controller = new WebXRController();
  13485. controllers[index] = controller;
  13486. }
  13487. return controller.getTargetRaySpace();
  13488. };
  13489. this.getControllerGrip = function (index) {
  13490. let controller = controllers[index];
  13491. if (controller === undefined) {
  13492. controller = new WebXRController();
  13493. controllers[index] = controller;
  13494. }
  13495. return controller.getGripSpace();
  13496. };
  13497. this.getHand = function (index) {
  13498. let controller = controllers[index];
  13499. if (controller === undefined) {
  13500. controller = new WebXRController();
  13501. controllers[index] = controller;
  13502. }
  13503. return controller.getHandSpace();
  13504. }; //
  13505. function onSessionEvent(event) {
  13506. const controller = inputSourcesMap.get(event.inputSource);
  13507. if (controller) {
  13508. controller.dispatchEvent({
  13509. type: event.type,
  13510. data: event.inputSource
  13511. });
  13512. }
  13513. }
  13514. function onSessionEnd() {
  13515. inputSourcesMap.forEach(function (controller, inputSource) {
  13516. controller.disconnect(inputSource);
  13517. });
  13518. inputSourcesMap.clear();
  13519. _currentDepthNear = null;
  13520. _currentDepthFar = null; // restore framebuffer/rendering state
  13521. state.bindXRFramebuffer(null);
  13522. renderer.setRenderTarget(renderer.getRenderTarget()); //
  13523. animation.stop();
  13524. scope.isPresenting = false;
  13525. scope.dispatchEvent({
  13526. type: 'sessionend'
  13527. });
  13528. }
  13529. this.setFramebufferScaleFactor = function (value) {
  13530. framebufferScaleFactor = value;
  13531. if (scope.isPresenting === true) {
  13532. console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
  13533. }
  13534. };
  13535. this.setReferenceSpaceType = function (value) {
  13536. referenceSpaceType = value;
  13537. if (scope.isPresenting === true) {
  13538. console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
  13539. }
  13540. };
  13541. this.getReferenceSpace = function () {
  13542. return referenceSpace;
  13543. };
  13544. this.getSession = function () {
  13545. return session;
  13546. };
  13547. this.setSession = async function (value) {
  13548. session = value;
  13549. if (session !== null) {
  13550. session.addEventListener('select', onSessionEvent);
  13551. session.addEventListener('selectstart', onSessionEvent);
  13552. session.addEventListener('selectend', onSessionEvent);
  13553. session.addEventListener('squeeze', onSessionEvent);
  13554. session.addEventListener('squeezestart', onSessionEvent);
  13555. session.addEventListener('squeezeend', onSessionEvent);
  13556. session.addEventListener('end', onSessionEnd);
  13557. session.addEventListener('inputsourceschange', onInputSourcesChange);
  13558. const attributes = gl.getContextAttributes();
  13559. if (attributes.xrCompatible !== true) {
  13560. await gl.makeXRCompatible();
  13561. }
  13562. const layerInit = {
  13563. antialias: attributes.antialias,
  13564. alpha: attributes.alpha,
  13565. depth: attributes.depth,
  13566. stencil: attributes.stencil,
  13567. framebufferScaleFactor: framebufferScaleFactor
  13568. }; // eslint-disable-next-line no-undef
  13569. const baseLayer = new XRWebGLLayer(session, gl, layerInit);
  13570. session.updateRenderState({
  13571. baseLayer: baseLayer
  13572. });
  13573. referenceSpace = await session.requestReferenceSpace(referenceSpaceType);
  13574. animation.setContext(session);
  13575. animation.start();
  13576. scope.isPresenting = true;
  13577. scope.dispatchEvent({
  13578. type: 'sessionstart'
  13579. });
  13580. }
  13581. };
  13582. function onInputSourcesChange(event) {
  13583. const inputSources = session.inputSources; // Assign inputSources to available controllers
  13584. for (let i = 0; i < controllers.length; i++) {
  13585. inputSourcesMap.set(inputSources[i], controllers[i]);
  13586. } // Notify disconnected
  13587. for (let i = 0; i < event.removed.length; i++) {
  13588. const inputSource = event.removed[i];
  13589. const controller = inputSourcesMap.get(inputSource);
  13590. if (controller) {
  13591. controller.dispatchEvent({
  13592. type: 'disconnected',
  13593. data: inputSource
  13594. });
  13595. inputSourcesMap.delete(inputSource);
  13596. }
  13597. } // Notify connected
  13598. for (let i = 0; i < event.added.length; i++) {
  13599. const inputSource = event.added[i];
  13600. const controller = inputSourcesMap.get(inputSource);
  13601. if (controller) {
  13602. controller.dispatchEvent({
  13603. type: 'connected',
  13604. data: inputSource
  13605. });
  13606. }
  13607. }
  13608. } //
  13609. const cameraLPos = new Vector3();
  13610. const cameraRPos = new Vector3();
  13611. /**
  13612. * Assumes 2 cameras that are parallel and share an X-axis, and that
  13613. * the cameras' projection and world matrices have already been set.
  13614. * And that near and far planes are identical for both cameras.
  13615. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  13616. */
  13617. function setProjectionFromUnion(camera, cameraL, cameraR) {
  13618. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  13619. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  13620. const ipd = cameraLPos.distanceTo(cameraRPos);
  13621. const projL = cameraL.projectionMatrix.elements;
  13622. const projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  13623. // most likely identical top and bottom frustum extents.
  13624. // Use the left camera for these values.
  13625. const near = projL[14] / (projL[10] - 1);
  13626. const far = projL[14] / (projL[10] + 1);
  13627. const topFov = (projL[9] + 1) / projL[5];
  13628. const bottomFov = (projL[9] - 1) / projL[5];
  13629. const leftFov = (projL[8] - 1) / projL[0];
  13630. const rightFov = (projR[8] + 1) / projR[0];
  13631. const left = near * leftFov;
  13632. const right = near * rightFov; // Calculate the new camera's position offset from the
  13633. // left camera. xOffset should be roughly half `ipd`.
  13634. const zOffset = ipd / (-leftFov + rightFov);
  13635. const xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  13636. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  13637. camera.translateX(xOffset);
  13638. camera.translateZ(zOffset);
  13639. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  13640. camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); // Find the union of the frustum values of the cameras and scale
  13641. // the values so that the near plane's position does not change in world space,
  13642. // although must now be relative to the new union camera.
  13643. const near2 = near + zOffset;
  13644. const far2 = far + zOffset;
  13645. const left2 = left - xOffset;
  13646. const right2 = right + (ipd - xOffset);
  13647. const top2 = topFov * far / far2 * near2;
  13648. const bottom2 = bottomFov * far / far2 * near2;
  13649. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  13650. }
  13651. function updateCamera(camera, parent) {
  13652. if (parent === null) {
  13653. camera.matrixWorld.copy(camera.matrix);
  13654. } else {
  13655. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  13656. }
  13657. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  13658. }
  13659. this.updateCamera = function (camera) {
  13660. if (session === null) return;
  13661. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  13662. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  13663. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  13664. // Note that the new renderState won't apply until the next frame. See #18320
  13665. session.updateRenderState({
  13666. depthNear: cameraVR.near,
  13667. depthFar: cameraVR.far
  13668. });
  13669. _currentDepthNear = cameraVR.near;
  13670. _currentDepthFar = cameraVR.far;
  13671. }
  13672. const parent = camera.parent;
  13673. const cameras = cameraVR.cameras;
  13674. updateCamera(cameraVR, parent);
  13675. for (let i = 0; i < cameras.length; i++) {
  13676. updateCamera(cameras[i], parent);
  13677. } // update camera and its children
  13678. camera.matrixWorld.copy(cameraVR.matrixWorld);
  13679. camera.matrix.copy(cameraVR.matrix);
  13680. camera.matrix.decompose(camera.position, camera.quaternion, camera.scale);
  13681. const children = camera.children;
  13682. for (let i = 0, l = children.length; i < l; i++) {
  13683. children[i].updateMatrixWorld(true);
  13684. } // update projection matrix for proper view frustum culling
  13685. if (cameras.length === 2) {
  13686. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  13687. } else {
  13688. // assume single camera setup (AR)
  13689. cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
  13690. }
  13691. };
  13692. this.getCamera = function () {
  13693. return cameraVR;
  13694. }; // Animation Loop
  13695. let onAnimationFrameCallback = null;
  13696. function onAnimationFrame(time, frame) {
  13697. pose = frame.getViewerPose(referenceSpace);
  13698. if (pose !== null) {
  13699. const views = pose.views;
  13700. const baseLayer = session.renderState.baseLayer;
  13701. state.bindXRFramebuffer(baseLayer.framebuffer);
  13702. let cameraVRNeedsUpdate = false; // check if it's necessary to rebuild cameraVR's camera list
  13703. if (views.length !== cameraVR.cameras.length) {
  13704. cameraVR.cameras.length = 0;
  13705. cameraVRNeedsUpdate = true;
  13706. }
  13707. for (let i = 0; i < views.length; i++) {
  13708. const view = views[i];
  13709. const viewport = baseLayer.getViewport(view);
  13710. const camera = cameras[i];
  13711. camera.matrix.fromArray(view.transform.matrix);
  13712. camera.projectionMatrix.fromArray(view.projectionMatrix);
  13713. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  13714. if (i === 0) {
  13715. cameraVR.matrix.copy(camera.matrix);
  13716. }
  13717. if (cameraVRNeedsUpdate === true) {
  13718. cameraVR.cameras.push(camera);
  13719. }
  13720. }
  13721. } //
  13722. const inputSources = session.inputSources;
  13723. for (let i = 0; i < controllers.length; i++) {
  13724. const controller = controllers[i];
  13725. const inputSource = inputSources[i];
  13726. controller.update(inputSource, frame, referenceSpace);
  13727. }
  13728. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  13729. }
  13730. const animation = new WebGLAnimation();
  13731. animation.setAnimationLoop(onAnimationFrame);
  13732. this.setAnimationLoop = function (callback) {
  13733. onAnimationFrameCallback = callback;
  13734. };
  13735. this.dispose = function () {};
  13736. }
  13737. }
  13738. function WebGLMaterials(properties) {
  13739. function refreshFogUniforms(uniforms, fog) {
  13740. uniforms.fogColor.value.copy(fog.color);
  13741. if (fog.isFog) {
  13742. uniforms.fogNear.value = fog.near;
  13743. uniforms.fogFar.value = fog.far;
  13744. } else if (fog.isFogExp2) {
  13745. uniforms.fogDensity.value = fog.density;
  13746. }
  13747. }
  13748. function refreshMaterialUniforms(uniforms, material, pixelRatio, height, transmissionRenderTarget) {
  13749. if (material.isMeshBasicMaterial) {
  13750. refreshUniformsCommon(uniforms, material);
  13751. } else if (material.isMeshLambertMaterial) {
  13752. refreshUniformsCommon(uniforms, material);
  13753. refreshUniformsLambert(uniforms, material);
  13754. } else if (material.isMeshToonMaterial) {
  13755. refreshUniformsCommon(uniforms, material);
  13756. refreshUniformsToon(uniforms, material);
  13757. } else if (material.isMeshPhongMaterial) {
  13758. refreshUniformsCommon(uniforms, material);
  13759. refreshUniformsPhong(uniforms, material);
  13760. } else if (material.isMeshStandardMaterial) {
  13761. refreshUniformsCommon(uniforms, material);
  13762. if (material.isMeshPhysicalMaterial) {
  13763. refreshUniformsPhysical(uniforms, material, transmissionRenderTarget);
  13764. } else {
  13765. refreshUniformsStandard(uniforms, material);
  13766. }
  13767. } else if (material.isMeshMatcapMaterial) {
  13768. refreshUniformsCommon(uniforms, material);
  13769. refreshUniformsMatcap(uniforms, material);
  13770. } else if (material.isMeshDepthMaterial) {
  13771. refreshUniformsCommon(uniforms, material);
  13772. refreshUniformsDepth(uniforms, material);
  13773. } else if (material.isMeshDistanceMaterial) {
  13774. refreshUniformsCommon(uniforms, material);
  13775. refreshUniformsDistance(uniforms, material);
  13776. } else if (material.isMeshNormalMaterial) {
  13777. refreshUniformsCommon(uniforms, material);
  13778. refreshUniformsNormal(uniforms, material);
  13779. } else if (material.isLineBasicMaterial) {
  13780. refreshUniformsLine(uniforms, material);
  13781. if (material.isLineDashedMaterial) {
  13782. refreshUniformsDash(uniforms, material);
  13783. }
  13784. } else if (material.isPointsMaterial) {
  13785. refreshUniformsPoints(uniforms, material, pixelRatio, height);
  13786. } else if (material.isSpriteMaterial) {
  13787. refreshUniformsSprites(uniforms, material);
  13788. } else if (material.isShadowMaterial) {
  13789. uniforms.color.value.copy(material.color);
  13790. uniforms.opacity.value = material.opacity;
  13791. } else if (material.isShaderMaterial) {
  13792. material.uniformsNeedUpdate = false; // #15581
  13793. }
  13794. }
  13795. function refreshUniformsCommon(uniforms, material) {
  13796. uniforms.opacity.value = material.opacity;
  13797. if (material.color) {
  13798. uniforms.diffuse.value.copy(material.color);
  13799. }
  13800. if (material.emissive) {
  13801. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  13802. }
  13803. if (material.map) {
  13804. uniforms.map.value = material.map;
  13805. }
  13806. if (material.alphaMap) {
  13807. uniforms.alphaMap.value = material.alphaMap;
  13808. }
  13809. if (material.specularMap) {
  13810. uniforms.specularMap.value = material.specularMap;
  13811. }
  13812. const envMap = properties.get(material).envMap;
  13813. if (envMap) {
  13814. uniforms.envMap.value = envMap;
  13815. uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap._needsFlipEnvMap ? -1 : 1;
  13816. uniforms.reflectivity.value = material.reflectivity;
  13817. uniforms.refractionRatio.value = material.refractionRatio;
  13818. const maxMipLevel = properties.get(envMap).__maxMipLevel;
  13819. if (maxMipLevel !== undefined) {
  13820. uniforms.maxMipLevel.value = maxMipLevel;
  13821. }
  13822. }
  13823. if (material.lightMap) {
  13824. uniforms.lightMap.value = material.lightMap;
  13825. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  13826. }
  13827. if (material.aoMap) {
  13828. uniforms.aoMap.value = material.aoMap;
  13829. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  13830. } // uv repeat and offset setting priorities
  13831. // 1. color map
  13832. // 2. specular map
  13833. // 3. displacementMap map
  13834. // 4. normal map
  13835. // 5. bump map
  13836. // 6. roughnessMap map
  13837. // 7. metalnessMap map
  13838. // 8. alphaMap map
  13839. // 9. emissiveMap map
  13840. // 10. clearcoat map
  13841. // 11. clearcoat normal map
  13842. // 12. clearcoat roughnessMap map
  13843. let uvScaleMap;
  13844. if (material.map) {
  13845. uvScaleMap = material.map;
  13846. } else if (material.specularMap) {
  13847. uvScaleMap = material.specularMap;
  13848. } else if (material.displacementMap) {
  13849. uvScaleMap = material.displacementMap;
  13850. } else if (material.normalMap) {
  13851. uvScaleMap = material.normalMap;
  13852. } else if (material.bumpMap) {
  13853. uvScaleMap = material.bumpMap;
  13854. } else if (material.roughnessMap) {
  13855. uvScaleMap = material.roughnessMap;
  13856. } else if (material.metalnessMap) {
  13857. uvScaleMap = material.metalnessMap;
  13858. } else if (material.alphaMap) {
  13859. uvScaleMap = material.alphaMap;
  13860. } else if (material.emissiveMap) {
  13861. uvScaleMap = material.emissiveMap;
  13862. } else if (material.clearcoatMap) {
  13863. uvScaleMap = material.clearcoatMap;
  13864. } else if (material.clearcoatNormalMap) {
  13865. uvScaleMap = material.clearcoatNormalMap;
  13866. } else if (material.clearcoatRoughnessMap) {
  13867. uvScaleMap = material.clearcoatRoughnessMap;
  13868. }
  13869. if (uvScaleMap !== undefined) {
  13870. // backwards compatibility
  13871. if (uvScaleMap.isWebGLRenderTarget) {
  13872. uvScaleMap = uvScaleMap.texture;
  13873. }
  13874. if (uvScaleMap.matrixAutoUpdate === true) {
  13875. uvScaleMap.updateMatrix();
  13876. }
  13877. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  13878. } // uv repeat and offset setting priorities for uv2
  13879. // 1. ao map
  13880. // 2. light map
  13881. let uv2ScaleMap;
  13882. if (material.aoMap) {
  13883. uv2ScaleMap = material.aoMap;
  13884. } else if (material.lightMap) {
  13885. uv2ScaleMap = material.lightMap;
  13886. }
  13887. if (uv2ScaleMap !== undefined) {
  13888. // backwards compatibility
  13889. if (uv2ScaleMap.isWebGLRenderTarget) {
  13890. uv2ScaleMap = uv2ScaleMap.texture;
  13891. }
  13892. if (uv2ScaleMap.matrixAutoUpdate === true) {
  13893. uv2ScaleMap.updateMatrix();
  13894. }
  13895. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  13896. }
  13897. }
  13898. function refreshUniformsLine(uniforms, material) {
  13899. uniforms.diffuse.value.copy(material.color);
  13900. uniforms.opacity.value = material.opacity;
  13901. }
  13902. function refreshUniformsDash(uniforms, material) {
  13903. uniforms.dashSize.value = material.dashSize;
  13904. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13905. uniforms.scale.value = material.scale;
  13906. }
  13907. function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
  13908. uniforms.diffuse.value.copy(material.color);
  13909. uniforms.opacity.value = material.opacity;
  13910. uniforms.size.value = material.size * pixelRatio;
  13911. uniforms.scale.value = height * 0.5;
  13912. if (material.map) {
  13913. uniforms.map.value = material.map;
  13914. }
  13915. if (material.alphaMap) {
  13916. uniforms.alphaMap.value = material.alphaMap;
  13917. } // uv repeat and offset setting priorities
  13918. // 1. color map
  13919. // 2. alpha map
  13920. let uvScaleMap;
  13921. if (material.map) {
  13922. uvScaleMap = material.map;
  13923. } else if (material.alphaMap) {
  13924. uvScaleMap = material.alphaMap;
  13925. }
  13926. if (uvScaleMap !== undefined) {
  13927. if (uvScaleMap.matrixAutoUpdate === true) {
  13928. uvScaleMap.updateMatrix();
  13929. }
  13930. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  13931. }
  13932. }
  13933. function refreshUniformsSprites(uniforms, material) {
  13934. uniforms.diffuse.value.copy(material.color);
  13935. uniforms.opacity.value = material.opacity;
  13936. uniforms.rotation.value = material.rotation;
  13937. if (material.map) {
  13938. uniforms.map.value = material.map;
  13939. }
  13940. if (material.alphaMap) {
  13941. uniforms.alphaMap.value = material.alphaMap;
  13942. } // uv repeat and offset setting priorities
  13943. // 1. color map
  13944. // 2. alpha map
  13945. let uvScaleMap;
  13946. if (material.map) {
  13947. uvScaleMap = material.map;
  13948. } else if (material.alphaMap) {
  13949. uvScaleMap = material.alphaMap;
  13950. }
  13951. if (uvScaleMap !== undefined) {
  13952. if (uvScaleMap.matrixAutoUpdate === true) {
  13953. uvScaleMap.updateMatrix();
  13954. }
  13955. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  13956. }
  13957. }
  13958. function refreshUniformsLambert(uniforms, material) {
  13959. if (material.emissiveMap) {
  13960. uniforms.emissiveMap.value = material.emissiveMap;
  13961. }
  13962. }
  13963. function refreshUniformsPhong(uniforms, material) {
  13964. uniforms.specular.value.copy(material.specular);
  13965. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  13966. if (material.emissiveMap) {
  13967. uniforms.emissiveMap.value = material.emissiveMap;
  13968. }
  13969. if (material.bumpMap) {
  13970. uniforms.bumpMap.value = material.bumpMap;
  13971. uniforms.bumpScale.value = material.bumpScale;
  13972. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  13973. }
  13974. if (material.normalMap) {
  13975. uniforms.normalMap.value = material.normalMap;
  13976. uniforms.normalScale.value.copy(material.normalScale);
  13977. if (material.side === BackSide) uniforms.normalScale.value.negate();
  13978. }
  13979. if (material.displacementMap) {
  13980. uniforms.displacementMap.value = material.displacementMap;
  13981. uniforms.displacementScale.value = material.displacementScale;
  13982. uniforms.displacementBias.value = material.displacementBias;
  13983. }
  13984. }
  13985. function refreshUniformsToon(uniforms, material) {
  13986. if (material.gradientMap) {
  13987. uniforms.gradientMap.value = material.gradientMap;
  13988. }
  13989. if (material.emissiveMap) {
  13990. uniforms.emissiveMap.value = material.emissiveMap;
  13991. }
  13992. if (material.bumpMap) {
  13993. uniforms.bumpMap.value = material.bumpMap;
  13994. uniforms.bumpScale.value = material.bumpScale;
  13995. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  13996. }
  13997. if (material.normalMap) {
  13998. uniforms.normalMap.value = material.normalMap;
  13999. uniforms.normalScale.value.copy(material.normalScale);
  14000. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14001. }
  14002. if (material.displacementMap) {
  14003. uniforms.displacementMap.value = material.displacementMap;
  14004. uniforms.displacementScale.value = material.displacementScale;
  14005. uniforms.displacementBias.value = material.displacementBias;
  14006. }
  14007. }
  14008. function refreshUniformsStandard(uniforms, material) {
  14009. uniforms.roughness.value = material.roughness;
  14010. uniforms.metalness.value = material.metalness;
  14011. if (material.roughnessMap) {
  14012. uniforms.roughnessMap.value = material.roughnessMap;
  14013. }
  14014. if (material.metalnessMap) {
  14015. uniforms.metalnessMap.value = material.metalnessMap;
  14016. }
  14017. if (material.emissiveMap) {
  14018. uniforms.emissiveMap.value = material.emissiveMap;
  14019. }
  14020. if (material.bumpMap) {
  14021. uniforms.bumpMap.value = material.bumpMap;
  14022. uniforms.bumpScale.value = material.bumpScale;
  14023. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14024. }
  14025. if (material.normalMap) {
  14026. uniforms.normalMap.value = material.normalMap;
  14027. uniforms.normalScale.value.copy(material.normalScale);
  14028. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14029. }
  14030. if (material.displacementMap) {
  14031. uniforms.displacementMap.value = material.displacementMap;
  14032. uniforms.displacementScale.value = material.displacementScale;
  14033. uniforms.displacementBias.value = material.displacementBias;
  14034. }
  14035. const envMap = properties.get(material).envMap;
  14036. if (envMap) {
  14037. //uniforms.envMap.value = material.envMap; // part of uniforms common
  14038. uniforms.envMapIntensity.value = material.envMapIntensity;
  14039. }
  14040. }
  14041. function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) {
  14042. refreshUniformsStandard(uniforms, material);
  14043. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  14044. uniforms.clearcoat.value = material.clearcoat;
  14045. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  14046. if (material.sheen) uniforms.sheen.value.copy(material.sheen);
  14047. if (material.clearcoatMap) {
  14048. uniforms.clearcoatMap.value = material.clearcoatMap;
  14049. }
  14050. if (material.clearcoatRoughnessMap) {
  14051. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  14052. }
  14053. if (material.clearcoatNormalMap) {
  14054. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  14055. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  14056. if (material.side === BackSide) {
  14057. uniforms.clearcoatNormalScale.value.negate();
  14058. }
  14059. }
  14060. uniforms.transmission.value = material.transmission;
  14061. if (material.transmissionMap) {
  14062. uniforms.transmissionMap.value = material.transmissionMap;
  14063. }
  14064. if (material.transmission > 0.0) {
  14065. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  14066. uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height);
  14067. }
  14068. uniforms.thickness.value = material.thickness;
  14069. if (material.thicknessMap) {
  14070. uniforms.thicknessMap.value = material.thicknessMap;
  14071. }
  14072. uniforms.attenuationDistance.value = material.attenuationDistance;
  14073. uniforms.attenuationColor.value.copy(material.attenuationColor);
  14074. }
  14075. function refreshUniformsMatcap(uniforms, material) {
  14076. if (material.matcap) {
  14077. uniforms.matcap.value = material.matcap;
  14078. }
  14079. if (material.bumpMap) {
  14080. uniforms.bumpMap.value = material.bumpMap;
  14081. uniforms.bumpScale.value = material.bumpScale;
  14082. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14083. }
  14084. if (material.normalMap) {
  14085. uniforms.normalMap.value = material.normalMap;
  14086. uniforms.normalScale.value.copy(material.normalScale);
  14087. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14088. }
  14089. if (material.displacementMap) {
  14090. uniforms.displacementMap.value = material.displacementMap;
  14091. uniforms.displacementScale.value = material.displacementScale;
  14092. uniforms.displacementBias.value = material.displacementBias;
  14093. }
  14094. }
  14095. function refreshUniformsDepth(uniforms, material) {
  14096. if (material.displacementMap) {
  14097. uniforms.displacementMap.value = material.displacementMap;
  14098. uniforms.displacementScale.value = material.displacementScale;
  14099. uniforms.displacementBias.value = material.displacementBias;
  14100. }
  14101. }
  14102. function refreshUniformsDistance(uniforms, material) {
  14103. if (material.displacementMap) {
  14104. uniforms.displacementMap.value = material.displacementMap;
  14105. uniforms.displacementScale.value = material.displacementScale;
  14106. uniforms.displacementBias.value = material.displacementBias;
  14107. }
  14108. uniforms.referencePosition.value.copy(material.referencePosition);
  14109. uniforms.nearDistance.value = material.nearDistance;
  14110. uniforms.farDistance.value = material.farDistance;
  14111. }
  14112. function refreshUniformsNormal(uniforms, material) {
  14113. if (material.bumpMap) {
  14114. uniforms.bumpMap.value = material.bumpMap;
  14115. uniforms.bumpScale.value = material.bumpScale;
  14116. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14117. }
  14118. if (material.normalMap) {
  14119. uniforms.normalMap.value = material.normalMap;
  14120. uniforms.normalScale.value.copy(material.normalScale);
  14121. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14122. }
  14123. if (material.displacementMap) {
  14124. uniforms.displacementMap.value = material.displacementMap;
  14125. uniforms.displacementScale.value = material.displacementScale;
  14126. uniforms.displacementBias.value = material.displacementBias;
  14127. }
  14128. }
  14129. return {
  14130. refreshFogUniforms: refreshFogUniforms,
  14131. refreshMaterialUniforms: refreshMaterialUniforms
  14132. };
  14133. }
  14134. function createCanvasElement() {
  14135. const canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  14136. canvas.style.display = 'block';
  14137. return canvas;
  14138. }
  14139. function WebGLRenderer(parameters) {
  14140. parameters = parameters || {};
  14141. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  14142. _context = parameters.context !== undefined ? parameters.context : null,
  14143. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14144. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14145. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  14146. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  14147. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  14148. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  14149. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  14150. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  14151. let currentRenderList = null;
  14152. let currentRenderState = null; // render() can be called from within a callback triggered by another render.
  14153. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  14154. const renderListStack = [];
  14155. const renderStateStack = []; // public properties
  14156. this.domElement = _canvas; // Debug configuration container
  14157. this.debug = {
  14158. /**
  14159. * Enables error checking and reporting when shader programs are being compiled
  14160. * @type {boolean}
  14161. */
  14162. checkShaderErrors: true
  14163. }; // clearing
  14164. this.autoClear = true;
  14165. this.autoClearColor = true;
  14166. this.autoClearDepth = true;
  14167. this.autoClearStencil = true; // scene graph
  14168. this.sortObjects = true; // user-defined clipping
  14169. this.clippingPlanes = [];
  14170. this.localClippingEnabled = false; // physically based shading
  14171. this.gammaFactor = 2.0; // for backwards compatibility
  14172. this.outputEncoding = LinearEncoding; // physical lights
  14173. this.physicallyCorrectLights = false; // tone mapping
  14174. this.toneMapping = NoToneMapping;
  14175. this.toneMappingExposure = 1.0; // internal properties
  14176. const _this = this;
  14177. let _isContextLost = false; // internal state cache
  14178. let _currentActiveCubeFace = 0;
  14179. let _currentActiveMipmapLevel = 0;
  14180. let _currentRenderTarget = null;
  14181. let _currentMaterialId = -1;
  14182. let _currentCamera = null;
  14183. const _currentViewport = new Vector4();
  14184. const _currentScissor = new Vector4();
  14185. let _currentScissorTest = null; //
  14186. let _width = _canvas.width;
  14187. let _height = _canvas.height;
  14188. let _pixelRatio = 1;
  14189. let _opaqueSort = null;
  14190. let _transparentSort = null;
  14191. const _viewport = new Vector4(0, 0, _width, _height);
  14192. const _scissor = new Vector4(0, 0, _width, _height);
  14193. let _scissorTest = false; //
  14194. const _currentDrawBuffers = []; // frustum
  14195. const _frustum = new Frustum(); // clipping
  14196. let _clippingEnabled = false;
  14197. let _localClippingEnabled = false; // transmission
  14198. let _transmissionRenderTarget = null; // camera matrices cache
  14199. const _projScreenMatrix = new Matrix4();
  14200. const _vector3 = new Vector3();
  14201. const _emptyScene = {
  14202. background: null,
  14203. fog: null,
  14204. environment: null,
  14205. overrideMaterial: null,
  14206. isScene: true
  14207. };
  14208. function getTargetPixelRatio() {
  14209. return _currentRenderTarget === null ? _pixelRatio : 1;
  14210. } // initialize
  14211. let _gl = _context;
  14212. function getContext(contextNames, contextAttributes) {
  14213. for (let i = 0; i < contextNames.length; i++) {
  14214. const contextName = contextNames[i];
  14215. const context = _canvas.getContext(contextName, contextAttributes);
  14216. if (context !== null) return context;
  14217. }
  14218. return null;
  14219. }
  14220. try {
  14221. const contextAttributes = {
  14222. alpha: _alpha,
  14223. depth: _depth,
  14224. stencil: _stencil,
  14225. antialias: _antialias,
  14226. premultipliedAlpha: _premultipliedAlpha,
  14227. preserveDrawingBuffer: _preserveDrawingBuffer,
  14228. powerPreference: _powerPreference,
  14229. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  14230. }; // event listeners must be registered before WebGL context is created, see #12753
  14231. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  14232. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  14233. if (_gl === null) {
  14234. const contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
  14235. if (_this.isWebGL1Renderer === true) {
  14236. contextNames.shift();
  14237. }
  14238. _gl = getContext(contextNames, contextAttributes);
  14239. if (_gl === null) {
  14240. if (getContext(contextNames)) {
  14241. throw new Error('Error creating WebGL context with your selected attributes.');
  14242. } else {
  14243. throw new Error('Error creating WebGL context.');
  14244. }
  14245. }
  14246. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  14247. if (_gl.getShaderPrecisionFormat === undefined) {
  14248. _gl.getShaderPrecisionFormat = function () {
  14249. return {
  14250. 'rangeMin': 1,
  14251. 'rangeMax': 1,
  14252. 'precision': 1
  14253. };
  14254. };
  14255. }
  14256. } catch (error) {
  14257. console.error('THREE.WebGLRenderer: ' + error.message);
  14258. throw error;
  14259. }
  14260. let extensions, capabilities, state, info;
  14261. let properties, textures, cubemaps, attributes, geometries, objects;
  14262. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  14263. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  14264. let utils, bindingStates;
  14265. function initGLContext() {
  14266. extensions = new WebGLExtensions(_gl);
  14267. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  14268. extensions.init(capabilities);
  14269. utils = new WebGLUtils(_gl, extensions, capabilities);
  14270. state = new WebGLState(_gl, extensions, capabilities);
  14271. _currentDrawBuffers[0] = _gl.BACK;
  14272. info = new WebGLInfo(_gl);
  14273. properties = new WebGLProperties();
  14274. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  14275. cubemaps = new WebGLCubeMaps(_this);
  14276. attributes = new WebGLAttributes(_gl, capabilities);
  14277. bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
  14278. geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
  14279. objects = new WebGLObjects(_gl, geometries, attributes, info);
  14280. morphtargets = new WebGLMorphtargets(_gl);
  14281. clipping = new WebGLClipping(properties);
  14282. programCache = new WebGLPrograms(_this, cubemaps, extensions, capabilities, bindingStates, clipping);
  14283. materials = new WebGLMaterials(properties);
  14284. renderLists = new WebGLRenderLists(properties);
  14285. renderStates = new WebGLRenderStates(extensions, capabilities);
  14286. background = new WebGLBackground(_this, cubemaps, state, objects, _premultipliedAlpha);
  14287. shadowMap = new WebGLShadowMap(_this, objects, capabilities);
  14288. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  14289. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  14290. info.programs = programCache.programs;
  14291. _this.capabilities = capabilities;
  14292. _this.extensions = extensions;
  14293. _this.properties = properties;
  14294. _this.renderLists = renderLists;
  14295. _this.shadowMap = shadowMap;
  14296. _this.state = state;
  14297. _this.info = info;
  14298. }
  14299. initGLContext(); // xr
  14300. const xr = new WebXRManager(_this, _gl);
  14301. this.xr = xr; // API
  14302. this.getContext = function () {
  14303. return _gl;
  14304. };
  14305. this.getContextAttributes = function () {
  14306. return _gl.getContextAttributes();
  14307. };
  14308. this.forceContextLoss = function () {
  14309. const extension = extensions.get('WEBGL_lose_context');
  14310. if (extension) extension.loseContext();
  14311. };
  14312. this.forceContextRestore = function () {
  14313. const extension = extensions.get('WEBGL_lose_context');
  14314. if (extension) extension.restoreContext();
  14315. };
  14316. this.getPixelRatio = function () {
  14317. return _pixelRatio;
  14318. };
  14319. this.setPixelRatio = function (value) {
  14320. if (value === undefined) return;
  14321. _pixelRatio = value;
  14322. this.setSize(_width, _height, false);
  14323. };
  14324. this.getSize = function (target) {
  14325. if (target === undefined) {
  14326. console.warn('WebGLRenderer: .getsize() now requires a Vector2 as an argument');
  14327. target = new Vector2();
  14328. }
  14329. return target.set(_width, _height);
  14330. };
  14331. this.setSize = function (width, height, updateStyle) {
  14332. if (xr.isPresenting) {
  14333. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  14334. return;
  14335. }
  14336. _width = width;
  14337. _height = height;
  14338. _canvas.width = Math.floor(width * _pixelRatio);
  14339. _canvas.height = Math.floor(height * _pixelRatio);
  14340. if (updateStyle !== false) {
  14341. _canvas.style.width = width + 'px';
  14342. _canvas.style.height = height + 'px';
  14343. }
  14344. this.setViewport(0, 0, width, height);
  14345. };
  14346. this.getDrawingBufferSize = function (target) {
  14347. if (target === undefined) {
  14348. console.warn('WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument');
  14349. target = new Vector2();
  14350. }
  14351. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  14352. };
  14353. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  14354. _width = width;
  14355. _height = height;
  14356. _pixelRatio = pixelRatio;
  14357. _canvas.width = Math.floor(width * pixelRatio);
  14358. _canvas.height = Math.floor(height * pixelRatio);
  14359. this.setViewport(0, 0, width, height);
  14360. };
  14361. this.getCurrentViewport = function (target) {
  14362. if (target === undefined) {
  14363. console.warn('WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument');
  14364. target = new Vector4();
  14365. }
  14366. return target.copy(_currentViewport);
  14367. };
  14368. this.getViewport = function (target) {
  14369. return target.copy(_viewport);
  14370. };
  14371. this.setViewport = function (x, y, width, height) {
  14372. if (x.isVector4) {
  14373. _viewport.set(x.x, x.y, x.z, x.w);
  14374. } else {
  14375. _viewport.set(x, y, width, height);
  14376. }
  14377. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  14378. };
  14379. this.getScissor = function (target) {
  14380. return target.copy(_scissor);
  14381. };
  14382. this.setScissor = function (x, y, width, height) {
  14383. if (x.isVector4) {
  14384. _scissor.set(x.x, x.y, x.z, x.w);
  14385. } else {
  14386. _scissor.set(x, y, width, height);
  14387. }
  14388. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  14389. };
  14390. this.getScissorTest = function () {
  14391. return _scissorTest;
  14392. };
  14393. this.setScissorTest = function (boolean) {
  14394. state.setScissorTest(_scissorTest = boolean);
  14395. };
  14396. this.setOpaqueSort = function (method) {
  14397. _opaqueSort = method;
  14398. };
  14399. this.setTransparentSort = function (method) {
  14400. _transparentSort = method;
  14401. }; // Clearing
  14402. this.getClearColor = function (target) {
  14403. if (target === undefined) {
  14404. console.warn('WebGLRenderer: .getClearColor() now requires a Color as an argument');
  14405. target = new Color();
  14406. }
  14407. return target.copy(background.getClearColor());
  14408. };
  14409. this.setClearColor = function () {
  14410. background.setClearColor.apply(background, arguments);
  14411. };
  14412. this.getClearAlpha = function () {
  14413. return background.getClearAlpha();
  14414. };
  14415. this.setClearAlpha = function () {
  14416. background.setClearAlpha.apply(background, arguments);
  14417. };
  14418. this.clear = function (color, depth, stencil) {
  14419. let bits = 0;
  14420. if (color === undefined || color) bits |= _gl.COLOR_BUFFER_BIT;
  14421. if (depth === undefined || depth) bits |= _gl.DEPTH_BUFFER_BIT;
  14422. if (stencil === undefined || stencil) bits |= _gl.STENCIL_BUFFER_BIT;
  14423. _gl.clear(bits);
  14424. };
  14425. this.clearColor = function () {
  14426. this.clear(true, false, false);
  14427. };
  14428. this.clearDepth = function () {
  14429. this.clear(false, true, false);
  14430. };
  14431. this.clearStencil = function () {
  14432. this.clear(false, false, true);
  14433. }; //
  14434. this.dispose = function () {
  14435. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  14436. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  14437. renderLists.dispose();
  14438. renderStates.dispose();
  14439. properties.dispose();
  14440. cubemaps.dispose();
  14441. objects.dispose();
  14442. bindingStates.dispose();
  14443. xr.dispose();
  14444. xr.removeEventListener('sessionstart', onXRSessionStart);
  14445. xr.removeEventListener('sessionend', onXRSessionEnd);
  14446. if (_transmissionRenderTarget) {
  14447. _transmissionRenderTarget.dispose();
  14448. _transmissionRenderTarget = null;
  14449. }
  14450. animation.stop();
  14451. }; // Events
  14452. function onContextLost(event) {
  14453. event.preventDefault();
  14454. console.log('THREE.WebGLRenderer: Context Lost.');
  14455. _isContextLost = true;
  14456. }
  14457. function onContextRestore()
  14458. /* event */
  14459. {
  14460. console.log('THREE.WebGLRenderer: Context Restored.');
  14461. _isContextLost = false;
  14462. const infoAutoReset = info.autoReset;
  14463. const shadowMapEnabled = shadowMap.enabled;
  14464. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  14465. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  14466. const shadowMapType = shadowMap.type;
  14467. initGLContext();
  14468. info.autoReset = infoAutoReset;
  14469. shadowMap.enabled = shadowMapEnabled;
  14470. shadowMap.autoUpdate = shadowMapAutoUpdate;
  14471. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  14472. shadowMap.type = shadowMapType;
  14473. }
  14474. function onMaterialDispose(event) {
  14475. const material = event.target;
  14476. material.removeEventListener('dispose', onMaterialDispose);
  14477. deallocateMaterial(material);
  14478. } // Buffer deallocation
  14479. function deallocateMaterial(material) {
  14480. releaseMaterialProgramReferences(material);
  14481. properties.remove(material);
  14482. }
  14483. function releaseMaterialProgramReferences(material) {
  14484. const programs = properties.get(material).programs;
  14485. if (programs !== undefined) {
  14486. programs.forEach(function (program) {
  14487. programCache.releaseProgram(program);
  14488. });
  14489. }
  14490. } // Buffer rendering
  14491. function renderObjectImmediate(object, program) {
  14492. object.render(function (object) {
  14493. _this.renderBufferImmediate(object, program);
  14494. });
  14495. }
  14496. this.renderBufferImmediate = function (object, program) {
  14497. bindingStates.initAttributes();
  14498. const buffers = properties.get(object);
  14499. if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
  14500. if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
  14501. if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
  14502. if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
  14503. const programAttributes = program.getAttributes();
  14504. if (object.hasPositions) {
  14505. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.position);
  14506. _gl.bufferData(_gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW);
  14507. bindingStates.enableAttribute(programAttributes.position);
  14508. _gl.vertexAttribPointer(programAttributes.position, 3, _gl.FLOAT, false, 0, 0);
  14509. }
  14510. if (object.hasNormals) {
  14511. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.normal);
  14512. _gl.bufferData(_gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW);
  14513. bindingStates.enableAttribute(programAttributes.normal);
  14514. _gl.vertexAttribPointer(programAttributes.normal, 3, _gl.FLOAT, false, 0, 0);
  14515. }
  14516. if (object.hasUvs) {
  14517. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.uv);
  14518. _gl.bufferData(_gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW);
  14519. bindingStates.enableAttribute(programAttributes.uv);
  14520. _gl.vertexAttribPointer(programAttributes.uv, 2, _gl.FLOAT, false, 0, 0);
  14521. }
  14522. if (object.hasColors) {
  14523. _gl.bindBuffer(_gl.ARRAY_BUFFER, buffers.color);
  14524. _gl.bufferData(_gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW);
  14525. bindingStates.enableAttribute(programAttributes.color);
  14526. _gl.vertexAttribPointer(programAttributes.color, 3, _gl.FLOAT, false, 0, 0);
  14527. }
  14528. bindingStates.disableUnusedAttributes();
  14529. _gl.drawArrays(_gl.TRIANGLES, 0, object.count);
  14530. object.count = 0;
  14531. };
  14532. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  14533. if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  14534. const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  14535. const program = setProgram(camera, scene, material, object);
  14536. state.setMaterial(material, frontFaceCW); //
  14537. let index = geometry.index;
  14538. const position = geometry.attributes.position; //
  14539. if (index === null) {
  14540. if (position === undefined || position.count === 0) return;
  14541. } else if (index.count === 0) {
  14542. return;
  14543. } //
  14544. let rangeFactor = 1;
  14545. if (material.wireframe === true) {
  14546. index = geometries.getWireframeAttribute(geometry);
  14547. rangeFactor = 2;
  14548. }
  14549. if (material.morphTargets || material.morphNormals) {
  14550. morphtargets.update(object, geometry, material, program);
  14551. }
  14552. bindingStates.setup(object, material, program, geometry, index);
  14553. let attribute;
  14554. let renderer = bufferRenderer;
  14555. if (index !== null) {
  14556. attribute = attributes.get(index);
  14557. renderer = indexedBufferRenderer;
  14558. renderer.setIndex(attribute);
  14559. } //
  14560. const dataCount = index !== null ? index.count : position.count;
  14561. const rangeStart = geometry.drawRange.start * rangeFactor;
  14562. const rangeCount = geometry.drawRange.count * rangeFactor;
  14563. const groupStart = group !== null ? group.start * rangeFactor : 0;
  14564. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  14565. const drawStart = Math.max(rangeStart, groupStart);
  14566. const drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  14567. const drawCount = Math.max(0, drawEnd - drawStart + 1);
  14568. if (drawCount === 0) return; //
  14569. if (object.isMesh) {
  14570. if (material.wireframe === true) {
  14571. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  14572. renderer.setMode(_gl.LINES);
  14573. } else {
  14574. renderer.setMode(_gl.TRIANGLES);
  14575. }
  14576. } else if (object.isLine) {
  14577. let lineWidth = material.linewidth;
  14578. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  14579. state.setLineWidth(lineWidth * getTargetPixelRatio());
  14580. if (object.isLineSegments) {
  14581. renderer.setMode(_gl.LINES);
  14582. } else if (object.isLineLoop) {
  14583. renderer.setMode(_gl.LINE_LOOP);
  14584. } else {
  14585. renderer.setMode(_gl.LINE_STRIP);
  14586. }
  14587. } else if (object.isPoints) {
  14588. renderer.setMode(_gl.POINTS);
  14589. } else if (object.isSprite) {
  14590. renderer.setMode(_gl.TRIANGLES);
  14591. }
  14592. if (object.isInstancedMesh) {
  14593. renderer.renderInstances(drawStart, drawCount, object.count);
  14594. } else if (geometry.isInstancedBufferGeometry) {
  14595. const instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount);
  14596. renderer.renderInstances(drawStart, drawCount, instanceCount);
  14597. } else {
  14598. renderer.render(drawStart, drawCount);
  14599. }
  14600. }; // Compile
  14601. this.compile = function (scene, camera) {
  14602. currentRenderState = renderStates.get(scene);
  14603. currentRenderState.init();
  14604. scene.traverseVisible(function (object) {
  14605. if (object.isLight && object.layers.test(camera.layers)) {
  14606. currentRenderState.pushLight(object);
  14607. if (object.castShadow) {
  14608. currentRenderState.pushShadow(object);
  14609. }
  14610. }
  14611. });
  14612. currentRenderState.setupLights();
  14613. scene.traverse(function (object) {
  14614. const material = object.material;
  14615. if (material) {
  14616. if (Array.isArray(material)) {
  14617. for (let i = 0; i < material.length; i++) {
  14618. const material2 = material[i];
  14619. getProgram(material2, scene, object);
  14620. }
  14621. } else {
  14622. getProgram(material, scene, object);
  14623. }
  14624. }
  14625. });
  14626. }; // Animation Loop
  14627. let onAnimationFrameCallback = null;
  14628. function onAnimationFrame(time) {
  14629. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  14630. }
  14631. function onXRSessionStart() {
  14632. animation.stop();
  14633. }
  14634. function onXRSessionEnd() {
  14635. animation.start();
  14636. }
  14637. const animation = new WebGLAnimation();
  14638. animation.setAnimationLoop(onAnimationFrame);
  14639. if (typeof window !== 'undefined') animation.setContext(window);
  14640. this.setAnimationLoop = function (callback) {
  14641. onAnimationFrameCallback = callback;
  14642. xr.setAnimationLoop(callback);
  14643. callback === null ? animation.stop() : animation.start();
  14644. };
  14645. xr.addEventListener('sessionstart', onXRSessionStart);
  14646. xr.addEventListener('sessionend', onXRSessionEnd); // Rendering
  14647. this.render = function (scene, camera) {
  14648. if (camera !== undefined && camera.isCamera !== true) {
  14649. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  14650. return;
  14651. }
  14652. if (_isContextLost === true) return; // update scene graph
  14653. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  14654. if (camera.parent === null) camera.updateMatrixWorld();
  14655. if (xr.enabled === true && xr.isPresenting === true) {
  14656. if (xr.cameraAutoUpdate === true) xr.updateCamera(camera);
  14657. camera = xr.getCamera(); // use XR camera for rendering
  14658. } //
  14659. if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, _currentRenderTarget);
  14660. currentRenderState = renderStates.get(scene, renderStateStack.length);
  14661. currentRenderState.init();
  14662. renderStateStack.push(currentRenderState);
  14663. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  14664. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  14665. _localClippingEnabled = this.localClippingEnabled;
  14666. _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  14667. currentRenderList = renderLists.get(scene, renderListStack.length);
  14668. currentRenderList.init();
  14669. renderListStack.push(currentRenderList);
  14670. projectObject(scene, camera, 0, _this.sortObjects);
  14671. currentRenderList.finish();
  14672. if (_this.sortObjects === true) {
  14673. currentRenderList.sort(_opaqueSort, _transparentSort);
  14674. } //
  14675. if (_clippingEnabled === true) clipping.beginShadows();
  14676. const shadowsArray = currentRenderState.state.shadowsArray;
  14677. shadowMap.render(shadowsArray, scene, camera);
  14678. currentRenderState.setupLights();
  14679. currentRenderState.setupLightsView(camera);
  14680. if (_clippingEnabled === true) clipping.endShadows(); //
  14681. if (this.info.autoReset === true) this.info.reset(); //
  14682. background.render(currentRenderList, scene); // render scene
  14683. const opaqueObjects = currentRenderList.opaque;
  14684. const transmissiveObjects = currentRenderList.transmissive;
  14685. const transparentObjects = currentRenderList.transparent;
  14686. if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
  14687. if (transmissiveObjects.length > 0) renderTransmissiveObjects(opaqueObjects, transmissiveObjects, scene, camera);
  14688. if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera); //
  14689. if (_currentRenderTarget !== null) {
  14690. // Generate mipmap if we're using any kind of mipmap filtering
  14691. textures.updateRenderTargetMipmap(_currentRenderTarget); // resolve multisample renderbuffers to a single-sample texture if necessary
  14692. textures.updateMultisampleRenderTarget(_currentRenderTarget);
  14693. } //
  14694. if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); // Ensure depth buffer writing is enabled so it can be cleared on next render
  14695. state.buffers.depth.setTest(true);
  14696. state.buffers.depth.setMask(true);
  14697. state.buffers.color.setMask(true);
  14698. state.setPolygonOffset(false); // _gl.finish();
  14699. bindingStates.resetDefaultState();
  14700. _currentMaterialId = -1;
  14701. _currentCamera = null;
  14702. renderStateStack.pop();
  14703. if (renderStateStack.length > 0) {
  14704. currentRenderState = renderStateStack[renderStateStack.length - 1];
  14705. } else {
  14706. currentRenderState = null;
  14707. }
  14708. renderListStack.pop();
  14709. if (renderListStack.length > 0) {
  14710. currentRenderList = renderListStack[renderListStack.length - 1];
  14711. } else {
  14712. currentRenderList = null;
  14713. }
  14714. };
  14715. function projectObject(object, camera, groupOrder, sortObjects) {
  14716. if (object.visible === false) return;
  14717. const visible = object.layers.test(camera.layers);
  14718. if (visible) {
  14719. if (object.isGroup) {
  14720. groupOrder = object.renderOrder;
  14721. } else if (object.isLOD) {
  14722. if (object.autoUpdate === true) object.update(camera);
  14723. } else if (object.isLight) {
  14724. currentRenderState.pushLight(object);
  14725. if (object.castShadow) {
  14726. currentRenderState.pushShadow(object);
  14727. }
  14728. } else if (object.isSprite) {
  14729. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  14730. if (sortObjects) {
  14731. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  14732. }
  14733. const geometry = objects.update(object);
  14734. const material = object.material;
  14735. if (material.visible) {
  14736. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  14737. }
  14738. }
  14739. } else if (object.isImmediateRenderObject) {
  14740. if (sortObjects) {
  14741. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  14742. }
  14743. currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
  14744. } else if (object.isMesh || object.isLine || object.isPoints) {
  14745. if (object.isSkinnedMesh) {
  14746. // update skeleton only once in a frame
  14747. if (object.skeleton.frame !== info.render.frame) {
  14748. object.skeleton.update();
  14749. object.skeleton.frame = info.render.frame;
  14750. }
  14751. }
  14752. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  14753. if (sortObjects) {
  14754. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  14755. }
  14756. const geometry = objects.update(object);
  14757. const material = object.material;
  14758. if (Array.isArray(material)) {
  14759. const groups = geometry.groups;
  14760. for (let i = 0, l = groups.length; i < l; i++) {
  14761. const group = groups[i];
  14762. const groupMaterial = material[group.materialIndex];
  14763. if (groupMaterial && groupMaterial.visible) {
  14764. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  14765. }
  14766. }
  14767. } else if (material.visible) {
  14768. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  14769. }
  14770. }
  14771. }
  14772. }
  14773. const children = object.children;
  14774. for (let i = 0, l = children.length; i < l; i++) {
  14775. projectObject(children[i], camera, groupOrder, sortObjects);
  14776. }
  14777. }
  14778. function renderTransmissiveObjects(opaqueObjects, transmissiveObjects, scene, camera) {
  14779. if (_transmissionRenderTarget === null) {
  14780. _transmissionRenderTarget = new WebGLRenderTarget(1024, 1024, {
  14781. generateMipmaps: true,
  14782. minFilter: LinearMipmapLinearFilter,
  14783. magFilter: NearestFilter,
  14784. wrapS: ClampToEdgeWrapping,
  14785. wrapT: ClampToEdgeWrapping
  14786. });
  14787. }
  14788. const currentRenderTarget = _this.getRenderTarget();
  14789. _this.setRenderTarget(_transmissionRenderTarget);
  14790. _this.clear();
  14791. renderObjects(opaqueObjects, scene, camera);
  14792. textures.updateRenderTargetMipmap(_transmissionRenderTarget);
  14793. _this.setRenderTarget(currentRenderTarget);
  14794. renderObjects(transmissiveObjects, scene, camera);
  14795. }
  14796. function renderObjects(renderList, scene, camera) {
  14797. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  14798. for (let i = 0, l = renderList.length; i < l; i++) {
  14799. const renderItem = renderList[i];
  14800. const object = renderItem.object;
  14801. const geometry = renderItem.geometry;
  14802. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  14803. const group = renderItem.group;
  14804. if (camera.isArrayCamera) {
  14805. const cameras = camera.cameras;
  14806. for (let j = 0, jl = cameras.length; j < jl; j++) {
  14807. const camera2 = cameras[j];
  14808. if (object.layers.test(camera2.layers)) {
  14809. state.viewport(_currentViewport.copy(camera2.viewport));
  14810. currentRenderState.setupLightsView(camera2);
  14811. renderObject(object, scene, camera2, geometry, material, group);
  14812. }
  14813. }
  14814. } else {
  14815. renderObject(object, scene, camera, geometry, material, group);
  14816. }
  14817. }
  14818. }
  14819. function renderObject(object, scene, camera, geometry, material, group) {
  14820. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  14821. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  14822. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  14823. if (object.isImmediateRenderObject) {
  14824. const program = setProgram(camera, scene, material, object);
  14825. state.setMaterial(material);
  14826. bindingStates.reset();
  14827. renderObjectImmediate(object, program);
  14828. } else {
  14829. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  14830. }
  14831. object.onAfterRender(_this, scene, camera, geometry, material, group);
  14832. }
  14833. function getProgram(material, scene, object) {
  14834. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  14835. const materialProperties = properties.get(material);
  14836. const lights = currentRenderState.state.lights;
  14837. const shadowsArray = currentRenderState.state.shadowsArray;
  14838. const lightsStateVersion = lights.state.version;
  14839. const parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
  14840. const programCacheKey = programCache.getProgramCacheKey(parameters);
  14841. 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
  14842. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  14843. materialProperties.fog = scene.fog;
  14844. materialProperties.envMap = cubemaps.get(material.envMap || materialProperties.environment);
  14845. if (programs === undefined) {
  14846. // new material
  14847. material.addEventListener('dispose', onMaterialDispose);
  14848. programs = new Map();
  14849. materialProperties.programs = programs;
  14850. }
  14851. let program = programs.get(programCacheKey);
  14852. if (program !== undefined) {
  14853. // early out if program and light state is identical
  14854. if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) {
  14855. updateCommonMaterialProperties(material, parameters);
  14856. return program;
  14857. }
  14858. } else {
  14859. parameters.uniforms = programCache.getUniforms(material);
  14860. material.onBuild(parameters, _this);
  14861. material.onBeforeCompile(parameters, _this);
  14862. program = programCache.acquireProgram(parameters, programCacheKey);
  14863. programs.set(programCacheKey, program);
  14864. materialProperties.uniforms = parameters.uniforms;
  14865. }
  14866. const uniforms = materialProperties.uniforms;
  14867. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  14868. uniforms.clippingPlanes = clipping.uniform;
  14869. }
  14870. updateCommonMaterialProperties(material, parameters); // store the light setup it was created for
  14871. materialProperties.needsLights = materialNeedsLights(material);
  14872. materialProperties.lightsStateVersion = lightsStateVersion;
  14873. if (materialProperties.needsLights) {
  14874. // wire up the material to this renderer's lighting state
  14875. uniforms.ambientLightColor.value = lights.state.ambient;
  14876. uniforms.lightProbe.value = lights.state.probe;
  14877. uniforms.directionalLights.value = lights.state.directional;
  14878. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  14879. uniforms.spotLights.value = lights.state.spot;
  14880. uniforms.spotLightShadows.value = lights.state.spotShadow;
  14881. uniforms.rectAreaLights.value = lights.state.rectArea;
  14882. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  14883. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  14884. uniforms.pointLights.value = lights.state.point;
  14885. uniforms.pointLightShadows.value = lights.state.pointShadow;
  14886. uniforms.hemisphereLights.value = lights.state.hemi;
  14887. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  14888. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  14889. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  14890. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  14891. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  14892. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  14893. }
  14894. const progUniforms = program.getUniforms();
  14895. const uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  14896. materialProperties.currentProgram = program;
  14897. materialProperties.uniformsList = uniformsList;
  14898. return program;
  14899. }
  14900. function updateCommonMaterialProperties(material, parameters) {
  14901. const materialProperties = properties.get(material);
  14902. materialProperties.outputEncoding = parameters.outputEncoding;
  14903. materialProperties.instancing = parameters.instancing;
  14904. materialProperties.skinning = parameters.skinning;
  14905. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  14906. materialProperties.numIntersection = parameters.numClipIntersection;
  14907. materialProperties.vertexAlphas = parameters.vertexAlphas;
  14908. }
  14909. function setProgram(camera, scene, material, object) {
  14910. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  14911. textures.resetTextureUnits();
  14912. const fog = scene.fog;
  14913. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  14914. const encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  14915. const envMap = cubemaps.get(material.envMap || environment);
  14916. const vertexAlphas = material.vertexColors === true && object.geometry && object.geometry.attributes.color && object.geometry.attributes.color.itemSize === 4;
  14917. const materialProperties = properties.get(material);
  14918. const lights = currentRenderState.state.lights;
  14919. if (_clippingEnabled === true) {
  14920. if (_localClippingEnabled === true || camera !== _currentCamera) {
  14921. const useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  14922. // object instead of the material, once it becomes feasible
  14923. // (#8465, #8379)
  14924. clipping.setState(material, camera, useCache);
  14925. }
  14926. } //
  14927. let needsProgramChange = false;
  14928. if (material.version === materialProperties.__version) {
  14929. if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  14930. needsProgramChange = true;
  14931. } else if (materialProperties.outputEncoding !== encoding) {
  14932. needsProgramChange = true;
  14933. } else if (object.isInstancedMesh && materialProperties.instancing === false) {
  14934. needsProgramChange = true;
  14935. } else if (!object.isInstancedMesh && materialProperties.instancing === true) {
  14936. needsProgramChange = true;
  14937. } else if (object.isSkinnedMesh && materialProperties.skinning === false) {
  14938. needsProgramChange = true;
  14939. } else if (!object.isSkinnedMesh && materialProperties.skinning === true) {
  14940. needsProgramChange = true;
  14941. } else if (materialProperties.envMap !== envMap) {
  14942. needsProgramChange = true;
  14943. } else if (material.fog && materialProperties.fog !== fog) {
  14944. needsProgramChange = true;
  14945. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
  14946. needsProgramChange = true;
  14947. } else if (materialProperties.vertexAlphas !== vertexAlphas) {
  14948. needsProgramChange = true;
  14949. }
  14950. } else {
  14951. needsProgramChange = true;
  14952. materialProperties.__version = material.version;
  14953. } //
  14954. let program = materialProperties.currentProgram;
  14955. if (needsProgramChange === true) {
  14956. program = getProgram(material, scene, object);
  14957. }
  14958. let refreshProgram = false;
  14959. let refreshMaterial = false;
  14960. let refreshLights = false;
  14961. const p_uniforms = program.getUniforms(),
  14962. m_uniforms = materialProperties.uniforms;
  14963. if (state.useProgram(program.program)) {
  14964. refreshProgram = true;
  14965. refreshMaterial = true;
  14966. refreshLights = true;
  14967. }
  14968. if (material.id !== _currentMaterialId) {
  14969. _currentMaterialId = material.id;
  14970. refreshMaterial = true;
  14971. }
  14972. if (refreshProgram || _currentCamera !== camera) {
  14973. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  14974. if (capabilities.logarithmicDepthBuffer) {
  14975. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  14976. }
  14977. if (_currentCamera !== camera) {
  14978. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  14979. // now, in case this material supports lights - or later, when
  14980. // the next material that does gets activated:
  14981. refreshMaterial = true; // set to true on material change
  14982. refreshLights = true; // remains set until update done
  14983. } // load material specific uniforms
  14984. // (shader material also gets them for the sake of genericity)
  14985. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  14986. const uCamPos = p_uniforms.map.cameraPosition;
  14987. if (uCamPos !== undefined) {
  14988. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  14989. }
  14990. }
  14991. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  14992. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  14993. }
  14994. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || object.isSkinnedMesh) {
  14995. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  14996. }
  14997. } // skinning uniforms must be set even if material didn't change
  14998. // auto-setting of texture unit for bone texture must go before other textures
  14999. // otherwise textures used for skinning can take over texture units reserved for other material textures
  15000. if (object.isSkinnedMesh) {
  15001. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  15002. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  15003. const skeleton = object.skeleton;
  15004. if (skeleton) {
  15005. if (capabilities.floatVertexTextures) {
  15006. if (skeleton.boneTexture === null) skeleton.computeBoneTexture();
  15007. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  15008. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  15009. } else {
  15010. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  15011. }
  15012. }
  15013. }
  15014. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  15015. materialProperties.receiveShadow = object.receiveShadow;
  15016. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  15017. }
  15018. if (refreshMaterial) {
  15019. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  15020. if (materialProperties.needsLights) {
  15021. // the current material requires lighting info
  15022. // note: all lighting uniforms are always set correctly
  15023. // they simply reference the renderer's state for their
  15024. // values
  15025. //
  15026. // use the current material's .needsUpdate flags to set
  15027. // the GL state when required
  15028. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  15029. } // refresh uniforms common to several materials
  15030. if (fog && material.fog) {
  15031. materials.refreshFogUniforms(m_uniforms, fog);
  15032. }
  15033. materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget);
  15034. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  15035. }
  15036. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  15037. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  15038. material.uniformsNeedUpdate = false;
  15039. }
  15040. if (material.isSpriteMaterial) {
  15041. p_uniforms.setValue(_gl, 'center', object.center);
  15042. } // common matrices
  15043. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  15044. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  15045. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  15046. return program;
  15047. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  15048. function markUniformsLightsNeedsUpdate(uniforms, value) {
  15049. uniforms.ambientLightColor.needsUpdate = value;
  15050. uniforms.lightProbe.needsUpdate = value;
  15051. uniforms.directionalLights.needsUpdate = value;
  15052. uniforms.directionalLightShadows.needsUpdate = value;
  15053. uniforms.pointLights.needsUpdate = value;
  15054. uniforms.pointLightShadows.needsUpdate = value;
  15055. uniforms.spotLights.needsUpdate = value;
  15056. uniforms.spotLightShadows.needsUpdate = value;
  15057. uniforms.rectAreaLights.needsUpdate = value;
  15058. uniforms.hemisphereLights.needsUpdate = value;
  15059. }
  15060. function materialNeedsLights(material) {
  15061. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  15062. }
  15063. this.getActiveCubeFace = function () {
  15064. return _currentActiveCubeFace;
  15065. };
  15066. this.getActiveMipmapLevel = function () {
  15067. return _currentActiveMipmapLevel;
  15068. };
  15069. this.getRenderTarget = function () {
  15070. return _currentRenderTarget;
  15071. };
  15072. this.setRenderTarget = function (renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) {
  15073. _currentRenderTarget = renderTarget;
  15074. _currentActiveCubeFace = activeCubeFace;
  15075. _currentActiveMipmapLevel = activeMipmapLevel;
  15076. if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
  15077. textures.setupRenderTarget(renderTarget);
  15078. }
  15079. let framebuffer = null;
  15080. let isCube = false;
  15081. let isRenderTarget3D = false;
  15082. if (renderTarget) {
  15083. const texture = renderTarget.texture;
  15084. if (texture.isDataTexture3D || texture.isDataTexture2DArray) {
  15085. isRenderTarget3D = true;
  15086. }
  15087. const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  15088. if (renderTarget.isWebGLCubeRenderTarget) {
  15089. framebuffer = __webglFramebuffer[activeCubeFace];
  15090. isCube = true;
  15091. } else if (renderTarget.isWebGLMultisampleRenderTarget) {
  15092. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  15093. } else {
  15094. framebuffer = __webglFramebuffer;
  15095. }
  15096. _currentViewport.copy(renderTarget.viewport);
  15097. _currentScissor.copy(renderTarget.scissor);
  15098. _currentScissorTest = renderTarget.scissorTest;
  15099. } else {
  15100. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  15101. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  15102. _currentScissorTest = _scissorTest;
  15103. }
  15104. const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  15105. if (framebufferBound && capabilities.drawBuffers) {
  15106. let needsUpdate = false;
  15107. if (renderTarget) {
  15108. if (renderTarget.isWebGLMultipleRenderTargets) {
  15109. const textures = renderTarget.texture;
  15110. if (_currentDrawBuffers.length !== textures.length || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
  15111. for (let i = 0, il = textures.length; i < il; i++) {
  15112. _currentDrawBuffers[i] = _gl.COLOR_ATTACHMENT0 + i;
  15113. }
  15114. _currentDrawBuffers.length = textures.length;
  15115. needsUpdate = true;
  15116. }
  15117. } else {
  15118. if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.COLOR_ATTACHMENT0) {
  15119. _currentDrawBuffers[0] = _gl.COLOR_ATTACHMENT0;
  15120. _currentDrawBuffers.length = 1;
  15121. needsUpdate = true;
  15122. }
  15123. }
  15124. } else {
  15125. if (_currentDrawBuffers.length !== 1 || _currentDrawBuffers[0] !== _gl.BACK) {
  15126. _currentDrawBuffers[0] = _gl.BACK;
  15127. _currentDrawBuffers.length = 1;
  15128. needsUpdate = true;
  15129. }
  15130. }
  15131. if (needsUpdate) {
  15132. if (capabilities.isWebGL2) {
  15133. _gl.drawBuffers(_currentDrawBuffers);
  15134. } else {
  15135. extensions.get('WEBGL_draw_buffers').drawBuffersWEBGL(_currentDrawBuffers);
  15136. }
  15137. }
  15138. }
  15139. state.viewport(_currentViewport);
  15140. state.scissor(_currentScissor);
  15141. state.setScissorTest(_currentScissorTest);
  15142. if (isCube) {
  15143. const textureProperties = properties.get(renderTarget.texture);
  15144. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
  15145. } else if (isRenderTarget3D) {
  15146. const textureProperties = properties.get(renderTarget.texture);
  15147. const layer = activeCubeFace || 0;
  15148. _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer);
  15149. }
  15150. };
  15151. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  15152. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  15153. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  15154. return;
  15155. }
  15156. let framebuffer = properties.get(renderTarget).__webglFramebuffer;
  15157. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  15158. framebuffer = framebuffer[activeCubeFaceIndex];
  15159. }
  15160. if (framebuffer) {
  15161. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  15162. try {
  15163. const texture = renderTarget.texture;
  15164. const textureFormat = texture.format;
  15165. const textureType = texture.type;
  15166. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_FORMAT)) {
  15167. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  15168. return;
  15169. }
  15170. const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has('EXT_color_buffer_half_float') || capabilities.isWebGL2 && extensions.has('EXT_color_buffer_float'));
  15171. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513)
  15172. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.has('OES_texture_float') || extensions.has('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  15173. !halfFloatSupportedByExt) {
  15174. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  15175. return;
  15176. }
  15177. if (_gl.checkFramebufferStatus(_gl.FRAMEBUFFER) === _gl.FRAMEBUFFER_COMPLETE) {
  15178. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  15179. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  15180. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  15181. }
  15182. } else {
  15183. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  15184. }
  15185. } finally {
  15186. // restore framebuffer of current render target if necessary
  15187. const framebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null;
  15188. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  15189. }
  15190. }
  15191. };
  15192. this.copyFramebufferToTexture = function (position, texture, level = 0) {
  15193. const levelScale = Math.pow(2, -level);
  15194. const width = Math.floor(texture.image.width * levelScale);
  15195. const height = Math.floor(texture.image.height * levelScale);
  15196. let glFormat = utils.convert(texture.format);
  15197. if (capabilities.isWebGL2) {
  15198. // Workaround for https://bugs.chromium.org/p/chromium/issues/detail?id=1120100
  15199. if (glFormat === _gl.RGB) glFormat = _gl.RGB8;
  15200. if (glFormat === _gl.RGBA) glFormat = _gl.RGBA8;
  15201. }
  15202. textures.setTexture2D(texture, 0);
  15203. _gl.copyTexImage2D(_gl.TEXTURE_2D, level, glFormat, position.x, position.y, width, height, 0);
  15204. state.unbindTexture();
  15205. };
  15206. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level = 0) {
  15207. const width = srcTexture.image.width;
  15208. const height = srcTexture.image.height;
  15209. const glFormat = utils.convert(dstTexture.format);
  15210. const glType = utils.convert(dstTexture.type);
  15211. textures.setTexture2D(dstTexture, 0); // As another texture upload may have changed pixelStorei
  15212. // parameters, make sure they are correct for the dstTexture
  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. if (srcTexture.isDataTexture) {
  15217. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  15218. } else {
  15219. if (srcTexture.isCompressedTexture) {
  15220. _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
  15221. } else {
  15222. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image);
  15223. }
  15224. } // Generate mipmaps only when copying level 0
  15225. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(_gl.TEXTURE_2D);
  15226. state.unbindTexture();
  15227. };
  15228. this.copyTextureToTexture3D = function (sourceBox, position, srcTexture, dstTexture, level = 0) {
  15229. if (_this.isWebGL1Renderer) {
  15230. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.');
  15231. return;
  15232. }
  15233. const {
  15234. width,
  15235. height,
  15236. data
  15237. } = srcTexture.image;
  15238. const glFormat = utils.convert(dstTexture.format);
  15239. const glType = utils.convert(dstTexture.type);
  15240. let glTarget;
  15241. if (dstTexture.isDataTexture3D) {
  15242. textures.setTexture3D(dstTexture, 0);
  15243. glTarget = _gl.TEXTURE_3D;
  15244. } else if (dstTexture.isDataTexture2DArray) {
  15245. textures.setTexture2DArray(dstTexture, 0);
  15246. glTarget = _gl.TEXTURE_2D_ARRAY;
  15247. } else {
  15248. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.');
  15249. return;
  15250. }
  15251. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  15252. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  15253. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  15254. const unpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH);
  15255. const unpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT);
  15256. const unpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS);
  15257. const unpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS);
  15258. const unpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES);
  15259. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, width);
  15260. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, height);
  15261. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, sourceBox.min.x);
  15262. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, sourceBox.min.y);
  15263. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, sourceBox.min.z);
  15264. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, sourceBox.max.x - sourceBox.min.x + 1, sourceBox.max.y - sourceBox.min.y + 1, sourceBox.max.z - sourceBox.min.z + 1, glFormat, glType, data);
  15265. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, unpackRowLen);
  15266. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight);
  15267. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, unpackSkipPixels);
  15268. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, unpackSkipRows);
  15269. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, unpackSkipImages); // Generate mipmaps only when copying level 0
  15270. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(glTarget);
  15271. state.unbindTexture();
  15272. };
  15273. this.initTexture = function (texture) {
  15274. textures.setTexture2D(texture, 0);
  15275. state.unbindTexture();
  15276. };
  15277. this.resetState = function () {
  15278. _currentActiveCubeFace = 0;
  15279. _currentActiveMipmapLevel = 0;
  15280. _currentRenderTarget = null;
  15281. state.reset();
  15282. bindingStates.reset();
  15283. };
  15284. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  15285. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  15286. detail: this
  15287. })); // eslint-disable-line no-undef
  15288. }
  15289. }
  15290. class WebGL1Renderer extends WebGLRenderer {}
  15291. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  15292. class FogExp2 {
  15293. constructor(color, density = 0.00025) {
  15294. this.name = '';
  15295. this.color = new Color(color);
  15296. this.density = density;
  15297. }
  15298. clone() {
  15299. return new FogExp2(this.color, this.density);
  15300. }
  15301. toJSON()
  15302. /* meta */
  15303. {
  15304. return {
  15305. type: 'FogExp2',
  15306. color: this.color.getHex(),
  15307. density: this.density
  15308. };
  15309. }
  15310. }
  15311. FogExp2.prototype.isFogExp2 = true;
  15312. class Fog {
  15313. constructor(color, near = 1, far = 1000) {
  15314. this.name = '';
  15315. this.color = new Color(color);
  15316. this.near = near;
  15317. this.far = far;
  15318. }
  15319. clone() {
  15320. return new Fog(this.color, this.near, this.far);
  15321. }
  15322. toJSON()
  15323. /* meta */
  15324. {
  15325. return {
  15326. type: 'Fog',
  15327. color: this.color.getHex(),
  15328. near: this.near,
  15329. far: this.far
  15330. };
  15331. }
  15332. }
  15333. Fog.prototype.isFog = true;
  15334. class Scene extends Object3D {
  15335. constructor() {
  15336. super();
  15337. this.type = 'Scene';
  15338. this.background = null;
  15339. this.environment = null;
  15340. this.fog = null;
  15341. this.overrideMaterial = null;
  15342. this.autoUpdate = true; // checked by the renderer
  15343. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  15344. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  15345. detail: this
  15346. })); // eslint-disable-line no-undef
  15347. }
  15348. }
  15349. copy(source, recursive) {
  15350. super.copy(source, recursive);
  15351. if (source.background !== null) this.background = source.background.clone();
  15352. if (source.environment !== null) this.environment = source.environment.clone();
  15353. if (source.fog !== null) this.fog = source.fog.clone();
  15354. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  15355. this.autoUpdate = source.autoUpdate;
  15356. this.matrixAutoUpdate = source.matrixAutoUpdate;
  15357. return this;
  15358. }
  15359. toJSON(meta) {
  15360. const data = super.toJSON(meta);
  15361. if (this.background !== null) data.object.background = this.background.toJSON(meta);
  15362. if (this.environment !== null) data.object.environment = this.environment.toJSON(meta);
  15363. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  15364. return data;
  15365. }
  15366. }
  15367. Scene.prototype.isScene = true;
  15368. class InterleavedBuffer {
  15369. constructor(array, stride) {
  15370. this.array = array;
  15371. this.stride = stride;
  15372. this.count = array !== undefined ? array.length / stride : 0;
  15373. this.usage = StaticDrawUsage;
  15374. this.updateRange = {
  15375. offset: 0,
  15376. count: -1
  15377. };
  15378. this.version = 0;
  15379. this.uuid = generateUUID();
  15380. }
  15381. onUploadCallback() {}
  15382. set needsUpdate(value) {
  15383. if (value === true) this.version++;
  15384. }
  15385. setUsage(value) {
  15386. this.usage = value;
  15387. return this;
  15388. }
  15389. copy(source) {
  15390. this.array = new source.array.constructor(source.array);
  15391. this.count = source.count;
  15392. this.stride = source.stride;
  15393. this.usage = source.usage;
  15394. return this;
  15395. }
  15396. copyAt(index1, attribute, index2) {
  15397. index1 *= this.stride;
  15398. index2 *= attribute.stride;
  15399. for (let i = 0, l = this.stride; i < l; i++) {
  15400. this.array[index1 + i] = attribute.array[index2 + i];
  15401. }
  15402. return this;
  15403. }
  15404. set(value, offset = 0) {
  15405. this.array.set(value, offset);
  15406. return this;
  15407. }
  15408. clone(data) {
  15409. if (data.arrayBuffers === undefined) {
  15410. data.arrayBuffers = {};
  15411. }
  15412. if (this.array.buffer._uuid === undefined) {
  15413. this.array.buffer._uuid = generateUUID();
  15414. }
  15415. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  15416. data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
  15417. }
  15418. const array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
  15419. const ib = new this.constructor(array, this.stride);
  15420. ib.setUsage(this.usage);
  15421. return ib;
  15422. }
  15423. onUpload(callback) {
  15424. this.onUploadCallback = callback;
  15425. return this;
  15426. }
  15427. toJSON(data) {
  15428. if (data.arrayBuffers === undefined) {
  15429. data.arrayBuffers = {};
  15430. } // generate UUID for array buffer if necessary
  15431. if (this.array.buffer._uuid === undefined) {
  15432. this.array.buffer._uuid = generateUUID();
  15433. }
  15434. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  15435. data.arrayBuffers[this.array.buffer._uuid] = Array.prototype.slice.call(new Uint32Array(this.array.buffer));
  15436. } //
  15437. return {
  15438. uuid: this.uuid,
  15439. buffer: this.array.buffer._uuid,
  15440. type: this.array.constructor.name,
  15441. stride: this.stride
  15442. };
  15443. }
  15444. }
  15445. InterleavedBuffer.prototype.isInterleavedBuffer = true;
  15446. const _vector$6 = /*@__PURE__*/new Vector3();
  15447. class InterleavedBufferAttribute {
  15448. constructor(interleavedBuffer, itemSize, offset, normalized) {
  15449. this.name = '';
  15450. this.data = interleavedBuffer;
  15451. this.itemSize = itemSize;
  15452. this.offset = offset;
  15453. this.normalized = normalized === true;
  15454. }
  15455. get count() {
  15456. return this.data.count;
  15457. }
  15458. get array() {
  15459. return this.data.array;
  15460. }
  15461. set needsUpdate(value) {
  15462. this.data.needsUpdate = value;
  15463. }
  15464. applyMatrix4(m) {
  15465. for (let i = 0, l = this.data.count; i < l; i++) {
  15466. _vector$6.x = this.getX(i);
  15467. _vector$6.y = this.getY(i);
  15468. _vector$6.z = this.getZ(i);
  15469. _vector$6.applyMatrix4(m);
  15470. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  15471. }
  15472. return this;
  15473. }
  15474. applyNormalMatrix(m) {
  15475. for (let i = 0, l = this.count; i < l; i++) {
  15476. _vector$6.x = this.getX(i);
  15477. _vector$6.y = this.getY(i);
  15478. _vector$6.z = this.getZ(i);
  15479. _vector$6.applyNormalMatrix(m);
  15480. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  15481. }
  15482. return this;
  15483. }
  15484. transformDirection(m) {
  15485. for (let i = 0, l = this.count; i < l; i++) {
  15486. _vector$6.x = this.getX(i);
  15487. _vector$6.y = this.getY(i);
  15488. _vector$6.z = this.getZ(i);
  15489. _vector$6.transformDirection(m);
  15490. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  15491. }
  15492. return this;
  15493. }
  15494. setX(index, x) {
  15495. this.data.array[index * this.data.stride + this.offset] = x;
  15496. return this;
  15497. }
  15498. setY(index, y) {
  15499. this.data.array[index * this.data.stride + this.offset + 1] = y;
  15500. return this;
  15501. }
  15502. setZ(index, z) {
  15503. this.data.array[index * this.data.stride + this.offset + 2] = z;
  15504. return this;
  15505. }
  15506. setW(index, w) {
  15507. this.data.array[index * this.data.stride + this.offset + 3] = w;
  15508. return this;
  15509. }
  15510. getX(index) {
  15511. return this.data.array[index * this.data.stride + this.offset];
  15512. }
  15513. getY(index) {
  15514. return this.data.array[index * this.data.stride + this.offset + 1];
  15515. }
  15516. getZ(index) {
  15517. return this.data.array[index * this.data.stride + this.offset + 2];
  15518. }
  15519. getW(index) {
  15520. return this.data.array[index * this.data.stride + this.offset + 3];
  15521. }
  15522. setXY(index, x, y) {
  15523. index = index * this.data.stride + this.offset;
  15524. this.data.array[index + 0] = x;
  15525. this.data.array[index + 1] = y;
  15526. return this;
  15527. }
  15528. setXYZ(index, x, y, z) {
  15529. index = index * this.data.stride + this.offset;
  15530. this.data.array[index + 0] = x;
  15531. this.data.array[index + 1] = y;
  15532. this.data.array[index + 2] = z;
  15533. return this;
  15534. }
  15535. setXYZW(index, x, y, z, w) {
  15536. index = index * this.data.stride + this.offset;
  15537. this.data.array[index + 0] = x;
  15538. this.data.array[index + 1] = y;
  15539. this.data.array[index + 2] = z;
  15540. this.data.array[index + 3] = w;
  15541. return this;
  15542. }
  15543. clone(data) {
  15544. if (data === undefined) {
  15545. console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.');
  15546. const array = [];
  15547. for (let i = 0; i < this.count; i++) {
  15548. const index = i * this.data.stride + this.offset;
  15549. for (let j = 0; j < this.itemSize; j++) {
  15550. array.push(this.data.array[index + j]);
  15551. }
  15552. }
  15553. return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
  15554. } else {
  15555. if (data.interleavedBuffers === undefined) {
  15556. data.interleavedBuffers = {};
  15557. }
  15558. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  15559. data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
  15560. }
  15561. return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  15562. }
  15563. }
  15564. toJSON(data) {
  15565. if (data === undefined) {
  15566. console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.');
  15567. const array = [];
  15568. for (let i = 0; i < this.count; i++) {
  15569. const index = i * this.data.stride + this.offset;
  15570. for (let j = 0; j < this.itemSize; j++) {
  15571. array.push(this.data.array[index + j]);
  15572. }
  15573. } // deinterleave data and save it as an ordinary buffer attribute for now
  15574. return {
  15575. itemSize: this.itemSize,
  15576. type: this.array.constructor.name,
  15577. array: array,
  15578. normalized: this.normalized
  15579. };
  15580. } else {
  15581. // save as true interlaved attribtue
  15582. if (data.interleavedBuffers === undefined) {
  15583. data.interleavedBuffers = {};
  15584. }
  15585. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  15586. data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
  15587. }
  15588. return {
  15589. isInterleavedBufferAttribute: true,
  15590. itemSize: this.itemSize,
  15591. data: this.data.uuid,
  15592. offset: this.offset,
  15593. normalized: this.normalized
  15594. };
  15595. }
  15596. }
  15597. }
  15598. InterleavedBufferAttribute.prototype.isInterleavedBufferAttribute = true;
  15599. /**
  15600. * parameters = {
  15601. * color: <hex>,
  15602. * map: new THREE.Texture( <Image> ),
  15603. * alphaMap: new THREE.Texture( <Image> ),
  15604. * rotation: <float>,
  15605. * sizeAttenuation: <bool>
  15606. * }
  15607. */
  15608. class SpriteMaterial extends Material {
  15609. constructor(parameters) {
  15610. super();
  15611. this.type = 'SpriteMaterial';
  15612. this.color = new Color(0xffffff);
  15613. this.map = null;
  15614. this.alphaMap = null;
  15615. this.rotation = 0;
  15616. this.sizeAttenuation = true;
  15617. this.transparent = true;
  15618. this.setValues(parameters);
  15619. }
  15620. copy(source) {
  15621. super.copy(source);
  15622. this.color.copy(source.color);
  15623. this.map = source.map;
  15624. this.alphaMap = source.alphaMap;
  15625. this.rotation = source.rotation;
  15626. this.sizeAttenuation = source.sizeAttenuation;
  15627. return this;
  15628. }
  15629. }
  15630. SpriteMaterial.prototype.isSpriteMaterial = true;
  15631. let _geometry;
  15632. const _intersectPoint = /*@__PURE__*/new Vector3();
  15633. const _worldScale = /*@__PURE__*/new Vector3();
  15634. const _mvPosition = /*@__PURE__*/new Vector3();
  15635. const _alignedPosition = /*@__PURE__*/new Vector2();
  15636. const _rotatedPosition = /*@__PURE__*/new Vector2();
  15637. const _viewWorldMatrix = /*@__PURE__*/new Matrix4();
  15638. const _vA = /*@__PURE__*/new Vector3();
  15639. const _vB = /*@__PURE__*/new Vector3();
  15640. const _vC = /*@__PURE__*/new Vector3();
  15641. const _uvA = /*@__PURE__*/new Vector2();
  15642. const _uvB = /*@__PURE__*/new Vector2();
  15643. const _uvC = /*@__PURE__*/new Vector2();
  15644. class Sprite extends Object3D {
  15645. constructor(material) {
  15646. super();
  15647. this.type = 'Sprite';
  15648. if (_geometry === undefined) {
  15649. _geometry = new BufferGeometry();
  15650. 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]);
  15651. const interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  15652. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  15653. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  15654. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  15655. }
  15656. this.geometry = _geometry;
  15657. this.material = material !== undefined ? material : new SpriteMaterial();
  15658. this.center = new Vector2(0.5, 0.5);
  15659. }
  15660. raycast(raycaster, intersects) {
  15661. if (raycaster.camera === null) {
  15662. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  15663. }
  15664. _worldScale.setFromMatrixScale(this.matrixWorld);
  15665. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  15666. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  15667. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  15668. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  15669. _worldScale.multiplyScalar(-_mvPosition.z);
  15670. }
  15671. const rotation = this.material.rotation;
  15672. let sin, cos;
  15673. if (rotation !== 0) {
  15674. cos = Math.cos(rotation);
  15675. sin = Math.sin(rotation);
  15676. }
  15677. const center = this.center;
  15678. transformVertex(_vA.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15679. transformVertex(_vB.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15680. transformVertex(_vC.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15681. _uvA.set(0, 0);
  15682. _uvB.set(1, 0);
  15683. _uvC.set(1, 1); // check first triangle
  15684. let intersect = raycaster.ray.intersectTriangle(_vA, _vB, _vC, false, _intersectPoint);
  15685. if (intersect === null) {
  15686. // check second triangle
  15687. transformVertex(_vB.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15688. _uvB.set(0, 1);
  15689. intersect = raycaster.ray.intersectTriangle(_vA, _vC, _vB, false, _intersectPoint);
  15690. if (intersect === null) {
  15691. return;
  15692. }
  15693. }
  15694. const distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  15695. if (distance < raycaster.near || distance > raycaster.far) return;
  15696. intersects.push({
  15697. distance: distance,
  15698. point: _intersectPoint.clone(),
  15699. uv: Triangle.getUV(_intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2()),
  15700. face: null,
  15701. object: this
  15702. });
  15703. }
  15704. copy(source) {
  15705. super.copy(source);
  15706. if (source.center !== undefined) this.center.copy(source.center);
  15707. this.material = source.material;
  15708. return this;
  15709. }
  15710. }
  15711. Sprite.prototype.isSprite = true;
  15712. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  15713. // compute position in camera space
  15714. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  15715. if (sin !== undefined) {
  15716. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  15717. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  15718. } else {
  15719. _rotatedPosition.copy(_alignedPosition);
  15720. }
  15721. vertexPosition.copy(mvPosition);
  15722. vertexPosition.x += _rotatedPosition.x;
  15723. vertexPosition.y += _rotatedPosition.y; // transform to world space
  15724. vertexPosition.applyMatrix4(_viewWorldMatrix);
  15725. }
  15726. const _v1$2 = /*@__PURE__*/new Vector3();
  15727. const _v2$1 = /*@__PURE__*/new Vector3();
  15728. class LOD extends Object3D {
  15729. constructor() {
  15730. super();
  15731. this._currentLevel = 0;
  15732. this.type = 'LOD';
  15733. Object.defineProperties(this, {
  15734. levels: {
  15735. enumerable: true,
  15736. value: []
  15737. },
  15738. isLOD: {
  15739. value: true
  15740. }
  15741. });
  15742. this.autoUpdate = true;
  15743. }
  15744. copy(source) {
  15745. super.copy(source, false);
  15746. const levels = source.levels;
  15747. for (let i = 0, l = levels.length; i < l; i++) {
  15748. const level = levels[i];
  15749. this.addLevel(level.object.clone(), level.distance);
  15750. }
  15751. this.autoUpdate = source.autoUpdate;
  15752. return this;
  15753. }
  15754. addLevel(object, distance = 0) {
  15755. distance = Math.abs(distance);
  15756. const levels = this.levels;
  15757. let l;
  15758. for (l = 0; l < levels.length; l++) {
  15759. if (distance < levels[l].distance) {
  15760. break;
  15761. }
  15762. }
  15763. levels.splice(l, 0, {
  15764. distance: distance,
  15765. object: object
  15766. });
  15767. this.add(object);
  15768. return this;
  15769. }
  15770. getCurrentLevel() {
  15771. return this._currentLevel;
  15772. }
  15773. getObjectForDistance(distance) {
  15774. const levels = this.levels;
  15775. if (levels.length > 0) {
  15776. let i, l;
  15777. for (i = 1, l = levels.length; i < l; i++) {
  15778. if (distance < levels[i].distance) {
  15779. break;
  15780. }
  15781. }
  15782. return levels[i - 1].object;
  15783. }
  15784. return null;
  15785. }
  15786. raycast(raycaster, intersects) {
  15787. const levels = this.levels;
  15788. if (levels.length > 0) {
  15789. _v1$2.setFromMatrixPosition(this.matrixWorld);
  15790. const distance = raycaster.ray.origin.distanceTo(_v1$2);
  15791. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  15792. }
  15793. }
  15794. update(camera) {
  15795. const levels = this.levels;
  15796. if (levels.length > 1) {
  15797. _v1$2.setFromMatrixPosition(camera.matrixWorld);
  15798. _v2$1.setFromMatrixPosition(this.matrixWorld);
  15799. const distance = _v1$2.distanceTo(_v2$1) / camera.zoom;
  15800. levels[0].object.visible = true;
  15801. let i, l;
  15802. for (i = 1, l = levels.length; i < l; i++) {
  15803. if (distance >= levels[i].distance) {
  15804. levels[i - 1].object.visible = false;
  15805. levels[i].object.visible = true;
  15806. } else {
  15807. break;
  15808. }
  15809. }
  15810. this._currentLevel = i - 1;
  15811. for (; i < l; i++) {
  15812. levels[i].object.visible = false;
  15813. }
  15814. }
  15815. }
  15816. toJSON(meta) {
  15817. const data = super.toJSON(meta);
  15818. if (this.autoUpdate === false) data.object.autoUpdate = false;
  15819. data.object.levels = [];
  15820. const levels = this.levels;
  15821. for (let i = 0, l = levels.length; i < l; i++) {
  15822. const level = levels[i];
  15823. data.object.levels.push({
  15824. object: level.object.uuid,
  15825. distance: level.distance
  15826. });
  15827. }
  15828. return data;
  15829. }
  15830. }
  15831. const _basePosition = /*@__PURE__*/new Vector3();
  15832. const _skinIndex = /*@__PURE__*/new Vector4();
  15833. const _skinWeight = /*@__PURE__*/new Vector4();
  15834. const _vector$5 = /*@__PURE__*/new Vector3();
  15835. const _matrix = /*@__PURE__*/new Matrix4();
  15836. class SkinnedMesh extends Mesh {
  15837. constructor(geometry, material) {
  15838. super(geometry, material);
  15839. this.type = 'SkinnedMesh';
  15840. this.bindMode = 'attached';
  15841. this.bindMatrix = new Matrix4();
  15842. this.bindMatrixInverse = new Matrix4();
  15843. }
  15844. copy(source) {
  15845. super.copy(source);
  15846. this.bindMode = source.bindMode;
  15847. this.bindMatrix.copy(source.bindMatrix);
  15848. this.bindMatrixInverse.copy(source.bindMatrixInverse);
  15849. this.skeleton = source.skeleton;
  15850. return this;
  15851. }
  15852. bind(skeleton, bindMatrix) {
  15853. this.skeleton = skeleton;
  15854. if (bindMatrix === undefined) {
  15855. this.updateMatrixWorld(true);
  15856. this.skeleton.calculateInverses();
  15857. bindMatrix = this.matrixWorld;
  15858. }
  15859. this.bindMatrix.copy(bindMatrix);
  15860. this.bindMatrixInverse.copy(bindMatrix).invert();
  15861. }
  15862. pose() {
  15863. this.skeleton.pose();
  15864. }
  15865. normalizeSkinWeights() {
  15866. const vector = new Vector4();
  15867. const skinWeight = this.geometry.attributes.skinWeight;
  15868. for (let i = 0, l = skinWeight.count; i < l; i++) {
  15869. vector.x = skinWeight.getX(i);
  15870. vector.y = skinWeight.getY(i);
  15871. vector.z = skinWeight.getZ(i);
  15872. vector.w = skinWeight.getW(i);
  15873. const scale = 1.0 / vector.manhattanLength();
  15874. if (scale !== Infinity) {
  15875. vector.multiplyScalar(scale);
  15876. } else {
  15877. vector.set(1, 0, 0, 0); // do something reasonable
  15878. }
  15879. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  15880. }
  15881. }
  15882. updateMatrixWorld(force) {
  15883. super.updateMatrixWorld(force);
  15884. if (this.bindMode === 'attached') {
  15885. this.bindMatrixInverse.copy(this.matrixWorld).invert();
  15886. } else if (this.bindMode === 'detached') {
  15887. this.bindMatrixInverse.copy(this.bindMatrix).invert();
  15888. } else {
  15889. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  15890. }
  15891. }
  15892. boneTransform(index, target) {
  15893. const skeleton = this.skeleton;
  15894. const geometry = this.geometry;
  15895. _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
  15896. _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
  15897. _basePosition.fromBufferAttribute(geometry.attributes.position, index).applyMatrix4(this.bindMatrix);
  15898. target.set(0, 0, 0);
  15899. for (let i = 0; i < 4; i++) {
  15900. const weight = _skinWeight.getComponent(i);
  15901. if (weight !== 0) {
  15902. const boneIndex = _skinIndex.getComponent(i);
  15903. _matrix.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
  15904. target.addScaledVector(_vector$5.copy(_basePosition).applyMatrix4(_matrix), weight);
  15905. }
  15906. }
  15907. return target.applyMatrix4(this.bindMatrixInverse);
  15908. }
  15909. }
  15910. SkinnedMesh.prototype.isSkinnedMesh = true;
  15911. class Bone extends Object3D {
  15912. constructor() {
  15913. super();
  15914. this.type = 'Bone';
  15915. }
  15916. }
  15917. Bone.prototype.isBone = true;
  15918. class DataTexture extends Texture {
  15919. constructor(data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  15920. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  15921. this.image = {
  15922. data: data || null,
  15923. width: width || 1,
  15924. height: height || 1
  15925. };
  15926. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  15927. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  15928. this.generateMipmaps = false;
  15929. this.flipY = false;
  15930. this.unpackAlignment = 1;
  15931. this.needsUpdate = true;
  15932. }
  15933. }
  15934. DataTexture.prototype.isDataTexture = true;
  15935. const _offsetMatrix = /*@__PURE__*/new Matrix4();
  15936. const _identityMatrix = /*@__PURE__*/new Matrix4();
  15937. class Skeleton {
  15938. constructor(bones = [], boneInverses = []) {
  15939. this.uuid = generateUUID();
  15940. this.bones = bones.slice(0);
  15941. this.boneInverses = boneInverses;
  15942. this.boneMatrices = null;
  15943. this.boneTexture = null;
  15944. this.boneTextureSize = 0;
  15945. this.frame = -1;
  15946. this.init();
  15947. }
  15948. init() {
  15949. const bones = this.bones;
  15950. const boneInverses = this.boneInverses;
  15951. this.boneMatrices = new Float32Array(bones.length * 16); // calculate inverse bone matrices if necessary
  15952. if (boneInverses.length === 0) {
  15953. this.calculateInverses();
  15954. } else {
  15955. // handle special case
  15956. if (bones.length !== boneInverses.length) {
  15957. console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
  15958. this.boneInverses = [];
  15959. for (let i = 0, il = this.bones.length; i < il; i++) {
  15960. this.boneInverses.push(new Matrix4());
  15961. }
  15962. }
  15963. }
  15964. }
  15965. calculateInverses() {
  15966. this.boneInverses.length = 0;
  15967. for (let i = 0, il = this.bones.length; i < il; i++) {
  15968. const inverse = new Matrix4();
  15969. if (this.bones[i]) {
  15970. inverse.copy(this.bones[i].matrixWorld).invert();
  15971. }
  15972. this.boneInverses.push(inverse);
  15973. }
  15974. }
  15975. pose() {
  15976. // recover the bind-time world matrices
  15977. for (let i = 0, il = this.bones.length; i < il; i++) {
  15978. const bone = this.bones[i];
  15979. if (bone) {
  15980. bone.matrixWorld.copy(this.boneInverses[i]).invert();
  15981. }
  15982. } // compute the local matrices, positions, rotations and scales
  15983. for (let i = 0, il = this.bones.length; i < il; i++) {
  15984. const bone = this.bones[i];
  15985. if (bone) {
  15986. if (bone.parent && bone.parent.isBone) {
  15987. bone.matrix.copy(bone.parent.matrixWorld).invert();
  15988. bone.matrix.multiply(bone.matrixWorld);
  15989. } else {
  15990. bone.matrix.copy(bone.matrixWorld);
  15991. }
  15992. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  15993. }
  15994. }
  15995. }
  15996. update() {
  15997. const bones = this.bones;
  15998. const boneInverses = this.boneInverses;
  15999. const boneMatrices = this.boneMatrices;
  16000. const boneTexture = this.boneTexture; // flatten bone matrices to array
  16001. for (let i = 0, il = bones.length; i < il; i++) {
  16002. // compute the offset between the current and the original transform
  16003. const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  16004. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  16005. _offsetMatrix.toArray(boneMatrices, i * 16);
  16006. }
  16007. if (boneTexture !== null) {
  16008. boneTexture.needsUpdate = true;
  16009. }
  16010. }
  16011. clone() {
  16012. return new Skeleton(this.bones, this.boneInverses);
  16013. }
  16014. computeBoneTexture() {
  16015. // layout (1 matrix = 4 pixels)
  16016. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  16017. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  16018. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  16019. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  16020. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  16021. let size = Math.sqrt(this.bones.length * 4); // 4 pixels needed for 1 matrix
  16022. size = ceilPowerOfTwo(size);
  16023. size = Math.max(size, 4);
  16024. const boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  16025. boneMatrices.set(this.boneMatrices); // copy current values
  16026. const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  16027. this.boneMatrices = boneMatrices;
  16028. this.boneTexture = boneTexture;
  16029. this.boneTextureSize = size;
  16030. return this;
  16031. }
  16032. getBoneByName(name) {
  16033. for (let i = 0, il = this.bones.length; i < il; i++) {
  16034. const bone = this.bones[i];
  16035. if (bone.name === name) {
  16036. return bone;
  16037. }
  16038. }
  16039. return undefined;
  16040. }
  16041. dispose() {
  16042. if (this.boneTexture !== null) {
  16043. this.boneTexture.dispose();
  16044. this.boneTexture = null;
  16045. }
  16046. }
  16047. fromJSON(json, bones) {
  16048. this.uuid = json.uuid;
  16049. for (let i = 0, l = json.bones.length; i < l; i++) {
  16050. const uuid = json.bones[i];
  16051. let bone = bones[uuid];
  16052. if (bone === undefined) {
  16053. console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
  16054. bone = new Bone();
  16055. }
  16056. this.bones.push(bone);
  16057. this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
  16058. }
  16059. this.init();
  16060. return this;
  16061. }
  16062. toJSON() {
  16063. const data = {
  16064. metadata: {
  16065. version: 4.5,
  16066. type: 'Skeleton',
  16067. generator: 'Skeleton.toJSON'
  16068. },
  16069. bones: [],
  16070. boneInverses: []
  16071. };
  16072. data.uuid = this.uuid;
  16073. const bones = this.bones;
  16074. const boneInverses = this.boneInverses;
  16075. for (let i = 0, l = bones.length; i < l; i++) {
  16076. const bone = bones[i];
  16077. data.bones.push(bone.uuid);
  16078. const boneInverse = boneInverses[i];
  16079. data.boneInverses.push(boneInverse.toArray());
  16080. }
  16081. return data;
  16082. }
  16083. }
  16084. const _instanceLocalMatrix = /*@__PURE__*/new Matrix4();
  16085. const _instanceWorldMatrix = /*@__PURE__*/new Matrix4();
  16086. const _instanceIntersects = [];
  16087. const _mesh = /*@__PURE__*/new Mesh();
  16088. class InstancedMesh extends Mesh {
  16089. constructor(geometry, material, count) {
  16090. super(geometry, material);
  16091. this.instanceMatrix = new BufferAttribute(new Float32Array(count * 16), 16);
  16092. this.instanceColor = null;
  16093. this.count = count;
  16094. this.frustumCulled = false;
  16095. }
  16096. copy(source) {
  16097. super.copy(source);
  16098. this.instanceMatrix.copy(source.instanceMatrix);
  16099. if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone();
  16100. this.count = source.count;
  16101. return this;
  16102. }
  16103. getColorAt(index, color) {
  16104. color.fromArray(this.instanceColor.array, index * 3);
  16105. }
  16106. getMatrixAt(index, matrix) {
  16107. matrix.fromArray(this.instanceMatrix.array, index * 16);
  16108. }
  16109. raycast(raycaster, intersects) {
  16110. const matrixWorld = this.matrixWorld;
  16111. const raycastTimes = this.count;
  16112. _mesh.geometry = this.geometry;
  16113. _mesh.material = this.material;
  16114. if (_mesh.material === undefined) return;
  16115. for (let instanceId = 0; instanceId < raycastTimes; instanceId++) {
  16116. // calculate the world matrix for each instance
  16117. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  16118. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
  16119. _mesh.matrixWorld = _instanceWorldMatrix;
  16120. _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
  16121. for (let i = 0, l = _instanceIntersects.length; i < l; i++) {
  16122. const intersect = _instanceIntersects[i];
  16123. intersect.instanceId = instanceId;
  16124. intersect.object = this;
  16125. intersects.push(intersect);
  16126. }
  16127. _instanceIntersects.length = 0;
  16128. }
  16129. }
  16130. setColorAt(index, color) {
  16131. if (this.instanceColor === null) {
  16132. this.instanceColor = new BufferAttribute(new Float32Array(this.count * 3), 3);
  16133. }
  16134. color.toArray(this.instanceColor.array, index * 3);
  16135. }
  16136. setMatrixAt(index, matrix) {
  16137. matrix.toArray(this.instanceMatrix.array, index * 16);
  16138. }
  16139. updateMorphTargets() {}
  16140. dispose() {
  16141. this.dispatchEvent({
  16142. type: 'dispose'
  16143. });
  16144. }
  16145. }
  16146. InstancedMesh.prototype.isInstancedMesh = true;
  16147. /**
  16148. * parameters = {
  16149. * color: <hex>,
  16150. * opacity: <float>,
  16151. *
  16152. * linewidth: <float>,
  16153. * linecap: "round",
  16154. * linejoin: "round"
  16155. * }
  16156. */
  16157. class LineBasicMaterial extends Material {
  16158. constructor(parameters) {
  16159. super();
  16160. this.type = 'LineBasicMaterial';
  16161. this.color = new Color(0xffffff);
  16162. this.linewidth = 1;
  16163. this.linecap = 'round';
  16164. this.linejoin = 'round';
  16165. this.morphTargets = false;
  16166. this.setValues(parameters);
  16167. }
  16168. copy(source) {
  16169. super.copy(source);
  16170. this.color.copy(source.color);
  16171. this.linewidth = source.linewidth;
  16172. this.linecap = source.linecap;
  16173. this.linejoin = source.linejoin;
  16174. this.morphTargets = source.morphTargets;
  16175. return this;
  16176. }
  16177. }
  16178. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  16179. const _start$1 = /*@__PURE__*/new Vector3();
  16180. const _end$1 = /*@__PURE__*/new Vector3();
  16181. const _inverseMatrix$1 = /*@__PURE__*/new Matrix4();
  16182. const _ray$1 = /*@__PURE__*/new Ray();
  16183. const _sphere$1 = /*@__PURE__*/new Sphere();
  16184. class Line extends Object3D {
  16185. constructor(geometry = new BufferGeometry(), material = new LineBasicMaterial()) {
  16186. super();
  16187. this.type = 'Line';
  16188. this.geometry = geometry;
  16189. this.material = material;
  16190. this.updateMorphTargets();
  16191. }
  16192. copy(source) {
  16193. super.copy(source);
  16194. this.material = source.material;
  16195. this.geometry = source.geometry;
  16196. return this;
  16197. }
  16198. computeLineDistances() {
  16199. const geometry = this.geometry;
  16200. if (geometry.isBufferGeometry) {
  16201. // we assume non-indexed geometry
  16202. if (geometry.index === null) {
  16203. const positionAttribute = geometry.attributes.position;
  16204. const lineDistances = [0];
  16205. for (let i = 1, l = positionAttribute.count; i < l; i++) {
  16206. _start$1.fromBufferAttribute(positionAttribute, i - 1);
  16207. _end$1.fromBufferAttribute(positionAttribute, i);
  16208. lineDistances[i] = lineDistances[i - 1];
  16209. lineDistances[i] += _start$1.distanceTo(_end$1);
  16210. }
  16211. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16212. } else {
  16213. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16214. }
  16215. } else if (geometry.isGeometry) {
  16216. console.error('THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16217. }
  16218. return this;
  16219. }
  16220. raycast(raycaster, intersects) {
  16221. const geometry = this.geometry;
  16222. const matrixWorld = this.matrixWorld;
  16223. const threshold = raycaster.params.Line.threshold;
  16224. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  16225. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16226. _sphere$1.copy(geometry.boundingSphere);
  16227. _sphere$1.applyMatrix4(matrixWorld);
  16228. _sphere$1.radius += threshold;
  16229. if (raycaster.ray.intersectsSphere(_sphere$1) === false) return; //
  16230. _inverseMatrix$1.copy(matrixWorld).invert();
  16231. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  16232. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16233. const localThresholdSq = localThreshold * localThreshold;
  16234. const vStart = new Vector3();
  16235. const vEnd = new Vector3();
  16236. const interSegment = new Vector3();
  16237. const interRay = new Vector3();
  16238. const step = this.isLineSegments ? 2 : 1;
  16239. if (geometry.isBufferGeometry) {
  16240. const index = geometry.index;
  16241. const attributes = geometry.attributes;
  16242. const positionAttribute = attributes.position;
  16243. if (index !== null) {
  16244. const start = Math.max(0, drawRange.start);
  16245. const end = Math.min(index.count, drawRange.start + drawRange.count);
  16246. for (let i = start, l = end - 1; i < l; i += step) {
  16247. const a = index.getX(i);
  16248. const b = index.getX(i + 1);
  16249. vStart.fromBufferAttribute(positionAttribute, a);
  16250. vEnd.fromBufferAttribute(positionAttribute, b);
  16251. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16252. if (distSq > localThresholdSq) continue;
  16253. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16254. const distance = raycaster.ray.origin.distanceTo(interRay);
  16255. if (distance < raycaster.near || distance > raycaster.far) continue;
  16256. intersects.push({
  16257. distance: distance,
  16258. // What do we want? intersection point on the ray or on the segment??
  16259. // point: raycaster.ray.at( distance ),
  16260. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16261. index: i,
  16262. face: null,
  16263. faceIndex: null,
  16264. object: this
  16265. });
  16266. }
  16267. } else {
  16268. const start = Math.max(0, drawRange.start);
  16269. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  16270. for (let i = start, l = end - 1; i < l; i += step) {
  16271. vStart.fromBufferAttribute(positionAttribute, i);
  16272. vEnd.fromBufferAttribute(positionAttribute, i + 1);
  16273. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16274. if (distSq > localThresholdSq) continue;
  16275. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16276. const distance = raycaster.ray.origin.distanceTo(interRay);
  16277. if (distance < raycaster.near || distance > raycaster.far) continue;
  16278. intersects.push({
  16279. distance: distance,
  16280. // What do we want? intersection point on the ray or on the segment??
  16281. // point: raycaster.ray.at( distance ),
  16282. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16283. index: i,
  16284. face: null,
  16285. faceIndex: null,
  16286. object: this
  16287. });
  16288. }
  16289. }
  16290. } else if (geometry.isGeometry) {
  16291. console.error('THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16292. }
  16293. }
  16294. updateMorphTargets() {
  16295. const geometry = this.geometry;
  16296. if (geometry.isBufferGeometry) {
  16297. const morphAttributes = geometry.morphAttributes;
  16298. const keys = Object.keys(morphAttributes);
  16299. if (keys.length > 0) {
  16300. const morphAttribute = morphAttributes[keys[0]];
  16301. if (morphAttribute !== undefined) {
  16302. this.morphTargetInfluences = [];
  16303. this.morphTargetDictionary = {};
  16304. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  16305. const name = morphAttribute[m].name || String(m);
  16306. this.morphTargetInfluences.push(0);
  16307. this.morphTargetDictionary[name] = m;
  16308. }
  16309. }
  16310. }
  16311. } else {
  16312. const morphTargets = geometry.morphTargets;
  16313. if (morphTargets !== undefined && morphTargets.length > 0) {
  16314. console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  16315. }
  16316. }
  16317. }
  16318. }
  16319. Line.prototype.isLine = true;
  16320. const _start = /*@__PURE__*/new Vector3();
  16321. const _end = /*@__PURE__*/new Vector3();
  16322. class LineSegments extends Line {
  16323. constructor(geometry, material) {
  16324. super(geometry, material);
  16325. this.type = 'LineSegments';
  16326. }
  16327. computeLineDistances() {
  16328. const geometry = this.geometry;
  16329. if (geometry.isBufferGeometry) {
  16330. // we assume non-indexed geometry
  16331. if (geometry.index === null) {
  16332. const positionAttribute = geometry.attributes.position;
  16333. const lineDistances = [];
  16334. for (let i = 0, l = positionAttribute.count; i < l; i += 2) {
  16335. _start.fromBufferAttribute(positionAttribute, i);
  16336. _end.fromBufferAttribute(positionAttribute, i + 1);
  16337. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  16338. lineDistances[i + 1] = lineDistances[i] + _start.distanceTo(_end);
  16339. }
  16340. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16341. } else {
  16342. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16343. }
  16344. } else if (geometry.isGeometry) {
  16345. console.error('THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16346. }
  16347. return this;
  16348. }
  16349. }
  16350. LineSegments.prototype.isLineSegments = true;
  16351. class LineLoop extends Line {
  16352. constructor(geometry, material) {
  16353. super(geometry, material);
  16354. this.type = 'LineLoop';
  16355. }
  16356. }
  16357. LineLoop.prototype.isLineLoop = true;
  16358. /**
  16359. * parameters = {
  16360. * color: <hex>,
  16361. * opacity: <float>,
  16362. * map: new THREE.Texture( <Image> ),
  16363. * alphaMap: new THREE.Texture( <Image> ),
  16364. *
  16365. * size: <float>,
  16366. * sizeAttenuation: <bool>
  16367. *
  16368. * morphTargets: <bool>
  16369. * }
  16370. */
  16371. class PointsMaterial extends Material {
  16372. constructor(parameters) {
  16373. super();
  16374. this.type = 'PointsMaterial';
  16375. this.color = new Color(0xffffff);
  16376. this.map = null;
  16377. this.alphaMap = null;
  16378. this.size = 1;
  16379. this.sizeAttenuation = true;
  16380. this.morphTargets = false;
  16381. this.setValues(parameters);
  16382. }
  16383. copy(source) {
  16384. super.copy(source);
  16385. this.color.copy(source.color);
  16386. this.map = source.map;
  16387. this.alphaMap = source.alphaMap;
  16388. this.size = source.size;
  16389. this.sizeAttenuation = source.sizeAttenuation;
  16390. this.morphTargets = source.morphTargets;
  16391. return this;
  16392. }
  16393. }
  16394. PointsMaterial.prototype.isPointsMaterial = true;
  16395. const _inverseMatrix = /*@__PURE__*/new Matrix4();
  16396. const _ray = /*@__PURE__*/new Ray();
  16397. const _sphere = /*@__PURE__*/new Sphere();
  16398. const _position$2 = /*@__PURE__*/new Vector3();
  16399. class Points extends Object3D {
  16400. constructor(geometry = new BufferGeometry(), material = new PointsMaterial()) {
  16401. super();
  16402. this.type = 'Points';
  16403. this.geometry = geometry;
  16404. this.material = material;
  16405. this.updateMorphTargets();
  16406. }
  16407. copy(source) {
  16408. super.copy(source);
  16409. this.material = source.material;
  16410. this.geometry = source.geometry;
  16411. return this;
  16412. }
  16413. raycast(raycaster, intersects) {
  16414. const geometry = this.geometry;
  16415. const matrixWorld = this.matrixWorld;
  16416. const threshold = raycaster.params.Points.threshold;
  16417. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  16418. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16419. _sphere.copy(geometry.boundingSphere);
  16420. _sphere.applyMatrix4(matrixWorld);
  16421. _sphere.radius += threshold;
  16422. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  16423. _inverseMatrix.copy(matrixWorld).invert();
  16424. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix);
  16425. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16426. const localThresholdSq = localThreshold * localThreshold;
  16427. if (geometry.isBufferGeometry) {
  16428. const index = geometry.index;
  16429. const attributes = geometry.attributes;
  16430. const positionAttribute = attributes.position;
  16431. if (index !== null) {
  16432. const start = Math.max(0, drawRange.start);
  16433. const end = Math.min(index.count, drawRange.start + drawRange.count);
  16434. for (let i = start, il = end; i < il; i++) {
  16435. const a = index.getX(i);
  16436. _position$2.fromBufferAttribute(positionAttribute, a);
  16437. testPoint(_position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  16438. }
  16439. } else {
  16440. const start = Math.max(0, drawRange.start);
  16441. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  16442. for (let i = start, l = end; i < l; i++) {
  16443. _position$2.fromBufferAttribute(positionAttribute, i);
  16444. testPoint(_position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  16445. }
  16446. }
  16447. } else {
  16448. console.error('THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16449. }
  16450. }
  16451. updateMorphTargets() {
  16452. const geometry = this.geometry;
  16453. if (geometry.isBufferGeometry) {
  16454. const morphAttributes = geometry.morphAttributes;
  16455. const keys = Object.keys(morphAttributes);
  16456. if (keys.length > 0) {
  16457. const morphAttribute = morphAttributes[keys[0]];
  16458. if (morphAttribute !== undefined) {
  16459. this.morphTargetInfluences = [];
  16460. this.morphTargetDictionary = {};
  16461. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  16462. const name = morphAttribute[m].name || String(m);
  16463. this.morphTargetInfluences.push(0);
  16464. this.morphTargetDictionary[name] = m;
  16465. }
  16466. }
  16467. }
  16468. } else {
  16469. const morphTargets = geometry.morphTargets;
  16470. if (morphTargets !== undefined && morphTargets.length > 0) {
  16471. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  16472. }
  16473. }
  16474. }
  16475. }
  16476. Points.prototype.isPoints = true;
  16477. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  16478. const rayPointDistanceSq = _ray.distanceSqToPoint(point);
  16479. if (rayPointDistanceSq < localThresholdSq) {
  16480. const intersectPoint = new Vector3();
  16481. _ray.closestPointToPoint(point, intersectPoint);
  16482. intersectPoint.applyMatrix4(matrixWorld);
  16483. const distance = raycaster.ray.origin.distanceTo(intersectPoint);
  16484. if (distance < raycaster.near || distance > raycaster.far) return;
  16485. intersects.push({
  16486. distance: distance,
  16487. distanceToRay: Math.sqrt(rayPointDistanceSq),
  16488. point: intersectPoint,
  16489. index: index,
  16490. face: null,
  16491. object: object
  16492. });
  16493. }
  16494. }
  16495. class VideoTexture extends Texture {
  16496. constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  16497. super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16498. this.format = format !== undefined ? format : RGBFormat;
  16499. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  16500. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  16501. this.generateMipmaps = false;
  16502. const scope = this;
  16503. function updateVideo() {
  16504. scope.needsUpdate = true;
  16505. video.requestVideoFrameCallback(updateVideo);
  16506. }
  16507. if ('requestVideoFrameCallback' in video) {
  16508. video.requestVideoFrameCallback(updateVideo);
  16509. }
  16510. }
  16511. clone() {
  16512. return new this.constructor(this.image).copy(this);
  16513. }
  16514. update() {
  16515. const video = this.image;
  16516. const hasVideoFrameCallback = ('requestVideoFrameCallback' in video);
  16517. if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
  16518. this.needsUpdate = true;
  16519. }
  16520. }
  16521. }
  16522. VideoTexture.prototype.isVideoTexture = true;
  16523. class CompressedTexture extends Texture {
  16524. constructor(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  16525. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  16526. this.image = {
  16527. width: width,
  16528. height: height
  16529. };
  16530. this.mipmaps = mipmaps; // no flipping for cube textures
  16531. // (also flipping doesn't work for compressed textures )
  16532. this.flipY = false; // can't generate mipmaps for compressed textures
  16533. // mips must be embedded in DDS files
  16534. this.generateMipmaps = false;
  16535. }
  16536. }
  16537. CompressedTexture.prototype.isCompressedTexture = true;
  16538. class CanvasTexture extends Texture {
  16539. constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  16540. super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16541. this.needsUpdate = true;
  16542. }
  16543. }
  16544. CanvasTexture.prototype.isCanvasTexture = true;
  16545. class DepthTexture extends Texture {
  16546. constructor(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  16547. format = format !== undefined ? format : DepthFormat;
  16548. if (format !== DepthFormat && format !== DepthStencilFormat) {
  16549. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  16550. }
  16551. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  16552. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  16553. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16554. this.image = {
  16555. width: width,
  16556. height: height
  16557. };
  16558. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  16559. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  16560. this.flipY = false;
  16561. this.generateMipmaps = false;
  16562. }
  16563. }
  16564. DepthTexture.prototype.isDepthTexture = true;
  16565. class CircleGeometry extends BufferGeometry {
  16566. constructor(radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2) {
  16567. super();
  16568. this.type = 'CircleGeometry';
  16569. this.parameters = {
  16570. radius: radius,
  16571. segments: segments,
  16572. thetaStart: thetaStart,
  16573. thetaLength: thetaLength
  16574. };
  16575. segments = Math.max(3, segments); // buffers
  16576. const indices = [];
  16577. const vertices = [];
  16578. const normals = [];
  16579. const uvs = []; // helper variables
  16580. const vertex = new Vector3();
  16581. const uv = new Vector2(); // center point
  16582. vertices.push(0, 0, 0);
  16583. normals.push(0, 0, 1);
  16584. uvs.push(0.5, 0.5);
  16585. for (let s = 0, i = 3; s <= segments; s++, i += 3) {
  16586. const segment = thetaStart + s / segments * thetaLength; // vertex
  16587. vertex.x = radius * Math.cos(segment);
  16588. vertex.y = radius * Math.sin(segment);
  16589. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  16590. normals.push(0, 0, 1); // uvs
  16591. uv.x = (vertices[i] / radius + 1) / 2;
  16592. uv.y = (vertices[i + 1] / radius + 1) / 2;
  16593. uvs.push(uv.x, uv.y);
  16594. } // indices
  16595. for (let i = 1; i <= segments; i++) {
  16596. indices.push(i, i + 1, 0);
  16597. } // build geometry
  16598. this.setIndex(indices);
  16599. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  16600. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  16601. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  16602. }
  16603. }
  16604. class CylinderGeometry extends BufferGeometry {
  16605. constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  16606. super();
  16607. this.type = 'CylinderGeometry';
  16608. this.parameters = {
  16609. radiusTop: radiusTop,
  16610. radiusBottom: radiusBottom,
  16611. height: height,
  16612. radialSegments: radialSegments,
  16613. heightSegments: heightSegments,
  16614. openEnded: openEnded,
  16615. thetaStart: thetaStart,
  16616. thetaLength: thetaLength
  16617. };
  16618. const scope = this;
  16619. radialSegments = Math.floor(radialSegments);
  16620. heightSegments = Math.floor(heightSegments); // buffers
  16621. const indices = [];
  16622. const vertices = [];
  16623. const normals = [];
  16624. const uvs = []; // helper variables
  16625. let index = 0;
  16626. const indexArray = [];
  16627. const halfHeight = height / 2;
  16628. let groupStart = 0; // generate geometry
  16629. generateTorso();
  16630. if (openEnded === false) {
  16631. if (radiusTop > 0) generateCap(true);
  16632. if (radiusBottom > 0) generateCap(false);
  16633. } // build geometry
  16634. this.setIndex(indices);
  16635. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  16636. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  16637. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  16638. function generateTorso() {
  16639. const normal = new Vector3();
  16640. const vertex = new Vector3();
  16641. let groupCount = 0; // this will be used to calculate the normal
  16642. const slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  16643. for (let y = 0; y <= heightSegments; y++) {
  16644. const indexRow = [];
  16645. const v = y / heightSegments; // calculate the radius of the current row
  16646. const radius = v * (radiusBottom - radiusTop) + radiusTop;
  16647. for (let x = 0; x <= radialSegments; x++) {
  16648. const u = x / radialSegments;
  16649. const theta = u * thetaLength + thetaStart;
  16650. const sinTheta = Math.sin(theta);
  16651. const cosTheta = Math.cos(theta); // vertex
  16652. vertex.x = radius * sinTheta;
  16653. vertex.y = -v * height + halfHeight;
  16654. vertex.z = radius * cosTheta;
  16655. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  16656. normal.set(sinTheta, slope, cosTheta).normalize();
  16657. normals.push(normal.x, normal.y, normal.z); // uv
  16658. uvs.push(u, 1 - v); // save index of vertex in respective row
  16659. indexRow.push(index++);
  16660. } // now save vertices of the row in our index array
  16661. indexArray.push(indexRow);
  16662. } // generate indices
  16663. for (let x = 0; x < radialSegments; x++) {
  16664. for (let y = 0; y < heightSegments; y++) {
  16665. // we use the index array to access the correct indices
  16666. const a = indexArray[y][x];
  16667. const b = indexArray[y + 1][x];
  16668. const c = indexArray[y + 1][x + 1];
  16669. const d = indexArray[y][x + 1]; // faces
  16670. indices.push(a, b, d);
  16671. indices.push(b, c, d); // update group counter
  16672. groupCount += 6;
  16673. }
  16674. } // add a group to the geometry. this will ensure multi material support
  16675. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  16676. groupStart += groupCount;
  16677. }
  16678. function generateCap(top) {
  16679. // save the index of the first center vertex
  16680. const centerIndexStart = index;
  16681. const uv = new Vector2();
  16682. const vertex = new Vector3();
  16683. let groupCount = 0;
  16684. const radius = top === true ? radiusTop : radiusBottom;
  16685. const sign = top === true ? 1 : -1; // first we generate the center vertex data of the cap.
  16686. // because the geometry needs one set of uvs per face,
  16687. // we must generate a center vertex per face/segment
  16688. for (let x = 1; x <= radialSegments; x++) {
  16689. // vertex
  16690. vertices.push(0, halfHeight * sign, 0); // normal
  16691. normals.push(0, sign, 0); // uv
  16692. uvs.push(0.5, 0.5); // increase index
  16693. index++;
  16694. } // save the index of the last center vertex
  16695. const centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  16696. for (let x = 0; x <= radialSegments; x++) {
  16697. const u = x / radialSegments;
  16698. const theta = u * thetaLength + thetaStart;
  16699. const cosTheta = Math.cos(theta);
  16700. const sinTheta = Math.sin(theta); // vertex
  16701. vertex.x = radius * sinTheta;
  16702. vertex.y = halfHeight * sign;
  16703. vertex.z = radius * cosTheta;
  16704. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  16705. normals.push(0, sign, 0); // uv
  16706. uv.x = cosTheta * 0.5 + 0.5;
  16707. uv.y = sinTheta * 0.5 * sign + 0.5;
  16708. uvs.push(uv.x, uv.y); // increase index
  16709. index++;
  16710. } // generate indices
  16711. for (let x = 0; x < radialSegments; x++) {
  16712. const c = centerIndexStart + x;
  16713. const i = centerIndexEnd + x;
  16714. if (top === true) {
  16715. // face top
  16716. indices.push(i, i + 1, c);
  16717. } else {
  16718. // face bottom
  16719. indices.push(i + 1, i, c);
  16720. }
  16721. groupCount += 3;
  16722. } // add a group to the geometry. this will ensure multi material support
  16723. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  16724. groupStart += groupCount;
  16725. }
  16726. }
  16727. }
  16728. class ConeGeometry extends CylinderGeometry {
  16729. constructor(radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  16730. super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  16731. this.type = 'ConeGeometry';
  16732. this.parameters = {
  16733. radius: radius,
  16734. height: height,
  16735. radialSegments: radialSegments,
  16736. heightSegments: heightSegments,
  16737. openEnded: openEnded,
  16738. thetaStart: thetaStart,
  16739. thetaLength: thetaLength
  16740. };
  16741. }
  16742. }
  16743. class PolyhedronGeometry extends BufferGeometry {
  16744. constructor(vertices, indices, radius = 1, detail = 0) {
  16745. super();
  16746. this.type = 'PolyhedronGeometry';
  16747. this.parameters = {
  16748. vertices: vertices,
  16749. indices: indices,
  16750. radius: radius,
  16751. detail: detail
  16752. }; // default buffer data
  16753. const vertexBuffer = [];
  16754. const uvBuffer = []; // the subdivision creates the vertex buffer data
  16755. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  16756. applyRadius(radius); // finally, create the uv data
  16757. generateUVs(); // build non-indexed geometry
  16758. this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  16759. this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  16760. this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  16761. if (detail === 0) {
  16762. this.computeVertexNormals(); // flat normals
  16763. } else {
  16764. this.normalizeNormals(); // smooth normals
  16765. } // helper functions
  16766. function subdivide(detail) {
  16767. const a = new Vector3();
  16768. const b = new Vector3();
  16769. const c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  16770. for (let i = 0; i < indices.length; i += 3) {
  16771. // get the vertices of the face
  16772. getVertexByIndex(indices[i + 0], a);
  16773. getVertexByIndex(indices[i + 1], b);
  16774. getVertexByIndex(indices[i + 2], c); // perform subdivision
  16775. subdivideFace(a, b, c, detail);
  16776. }
  16777. }
  16778. function subdivideFace(a, b, c, detail) {
  16779. const cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision
  16780. const v = []; // construct all of the vertices for this subdivision
  16781. for (let i = 0; i <= cols; i++) {
  16782. v[i] = [];
  16783. const aj = a.clone().lerp(c, i / cols);
  16784. const bj = b.clone().lerp(c, i / cols);
  16785. const rows = cols - i;
  16786. for (let j = 0; j <= rows; j++) {
  16787. if (j === 0 && i === cols) {
  16788. v[i][j] = aj;
  16789. } else {
  16790. v[i][j] = aj.clone().lerp(bj, j / rows);
  16791. }
  16792. }
  16793. } // construct all of the faces
  16794. for (let i = 0; i < cols; i++) {
  16795. for (let j = 0; j < 2 * (cols - i) - 1; j++) {
  16796. const k = Math.floor(j / 2);
  16797. if (j % 2 === 0) {
  16798. pushVertex(v[i][k + 1]);
  16799. pushVertex(v[i + 1][k]);
  16800. pushVertex(v[i][k]);
  16801. } else {
  16802. pushVertex(v[i][k + 1]);
  16803. pushVertex(v[i + 1][k + 1]);
  16804. pushVertex(v[i + 1][k]);
  16805. }
  16806. }
  16807. }
  16808. }
  16809. function applyRadius(radius) {
  16810. const vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  16811. for (let i = 0; i < vertexBuffer.length; i += 3) {
  16812. vertex.x = vertexBuffer[i + 0];
  16813. vertex.y = vertexBuffer[i + 1];
  16814. vertex.z = vertexBuffer[i + 2];
  16815. vertex.normalize().multiplyScalar(radius);
  16816. vertexBuffer[i + 0] = vertex.x;
  16817. vertexBuffer[i + 1] = vertex.y;
  16818. vertexBuffer[i + 2] = vertex.z;
  16819. }
  16820. }
  16821. function generateUVs() {
  16822. const vertex = new Vector3();
  16823. for (let i = 0; i < vertexBuffer.length; i += 3) {
  16824. vertex.x = vertexBuffer[i + 0];
  16825. vertex.y = vertexBuffer[i + 1];
  16826. vertex.z = vertexBuffer[i + 2];
  16827. const u = azimuth(vertex) / 2 / Math.PI + 0.5;
  16828. const v = inclination(vertex) / Math.PI + 0.5;
  16829. uvBuffer.push(u, 1 - v);
  16830. }
  16831. correctUVs();
  16832. correctSeam();
  16833. }
  16834. function correctSeam() {
  16835. // handle case when face straddles the seam, see #3269
  16836. for (let i = 0; i < uvBuffer.length; i += 6) {
  16837. // uv data of a single face
  16838. const x0 = uvBuffer[i + 0];
  16839. const x1 = uvBuffer[i + 2];
  16840. const x2 = uvBuffer[i + 4];
  16841. const max = Math.max(x0, x1, x2);
  16842. const min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  16843. if (max > 0.9 && min < 0.1) {
  16844. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  16845. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  16846. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  16847. }
  16848. }
  16849. }
  16850. function pushVertex(vertex) {
  16851. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  16852. }
  16853. function getVertexByIndex(index, vertex) {
  16854. const stride = index * 3;
  16855. vertex.x = vertices[stride + 0];
  16856. vertex.y = vertices[stride + 1];
  16857. vertex.z = vertices[stride + 2];
  16858. }
  16859. function correctUVs() {
  16860. const a = new Vector3();
  16861. const b = new Vector3();
  16862. const c = new Vector3();
  16863. const centroid = new Vector3();
  16864. const uvA = new Vector2();
  16865. const uvB = new Vector2();
  16866. const uvC = new Vector2();
  16867. for (let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  16868. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  16869. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  16870. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  16871. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  16872. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  16873. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  16874. centroid.copy(a).add(b).add(c).divideScalar(3);
  16875. const azi = azimuth(centroid);
  16876. correctUV(uvA, j + 0, a, azi);
  16877. correctUV(uvB, j + 2, b, azi);
  16878. correctUV(uvC, j + 4, c, azi);
  16879. }
  16880. }
  16881. function correctUV(uv, stride, vector, azimuth) {
  16882. if (azimuth < 0 && uv.x === 1) {
  16883. uvBuffer[stride] = uv.x - 1;
  16884. }
  16885. if (vector.x === 0 && vector.z === 0) {
  16886. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  16887. }
  16888. } // Angle around the Y axis, counter-clockwise when looking from above.
  16889. function azimuth(vector) {
  16890. return Math.atan2(vector.z, -vector.x);
  16891. } // Angle above the XZ plane.
  16892. function inclination(vector) {
  16893. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  16894. }
  16895. }
  16896. }
  16897. class DodecahedronGeometry extends PolyhedronGeometry {
  16898. constructor(radius = 1, detail = 0) {
  16899. const t = (1 + Math.sqrt(5)) / 2;
  16900. const r = 1 / t;
  16901. const vertices = [// (±1, ±1, ±1)
  16902. -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/φ, ±φ)
  16903. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  16904. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  16905. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  16906. 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];
  16907. super(vertices, indices, radius, detail);
  16908. this.type = 'DodecahedronGeometry';
  16909. this.parameters = {
  16910. radius: radius,
  16911. detail: detail
  16912. };
  16913. }
  16914. }
  16915. const _v0 = new Vector3();
  16916. const _v1$1 = new Vector3();
  16917. const _normal = new Vector3();
  16918. const _triangle = new Triangle();
  16919. class EdgesGeometry extends BufferGeometry {
  16920. constructor(geometry, thresholdAngle) {
  16921. super();
  16922. this.type = 'EdgesGeometry';
  16923. this.parameters = {
  16924. thresholdAngle: thresholdAngle
  16925. };
  16926. thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1;
  16927. if (geometry.isGeometry === true) {
  16928. console.error('THREE.EdgesGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16929. return;
  16930. }
  16931. const precisionPoints = 4;
  16932. const precision = Math.pow(10, precisionPoints);
  16933. const thresholdDot = Math.cos(DEG2RAD * thresholdAngle);
  16934. const indexAttr = geometry.getIndex();
  16935. const positionAttr = geometry.getAttribute('position');
  16936. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  16937. const indexArr = [0, 0, 0];
  16938. const vertKeys = ['a', 'b', 'c'];
  16939. const hashes = new Array(3);
  16940. const edgeData = {};
  16941. const vertices = [];
  16942. for (let i = 0; i < indexCount; i += 3) {
  16943. if (indexAttr) {
  16944. indexArr[0] = indexAttr.getX(i);
  16945. indexArr[1] = indexAttr.getX(i + 1);
  16946. indexArr[2] = indexAttr.getX(i + 2);
  16947. } else {
  16948. indexArr[0] = i;
  16949. indexArr[1] = i + 1;
  16950. indexArr[2] = i + 2;
  16951. }
  16952. const {
  16953. a,
  16954. b,
  16955. c
  16956. } = _triangle;
  16957. a.fromBufferAttribute(positionAttr, indexArr[0]);
  16958. b.fromBufferAttribute(positionAttr, indexArr[1]);
  16959. c.fromBufferAttribute(positionAttr, indexArr[2]);
  16960. _triangle.getNormal(_normal); // create hashes for the edge from the vertices
  16961. hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`;
  16962. hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`;
  16963. hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`; // skip degenerate triangles
  16964. if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
  16965. continue;
  16966. } // iterate over every edge
  16967. for (let j = 0; j < 3; j++) {
  16968. // get the first and next vertex making up the edge
  16969. const jNext = (j + 1) % 3;
  16970. const vecHash0 = hashes[j];
  16971. const vecHash1 = hashes[jNext];
  16972. const v0 = _triangle[vertKeys[j]];
  16973. const v1 = _triangle[vertKeys[jNext]];
  16974. const hash = `${vecHash0}_${vecHash1}`;
  16975. const reverseHash = `${vecHash1}_${vecHash0}`;
  16976. if (reverseHash in edgeData && edgeData[reverseHash]) {
  16977. // if we found a sibling edge add it into the vertex array if
  16978. // it meets the angle threshold and delete the edge from the map.
  16979. if (_normal.dot(edgeData[reverseHash].normal) <= thresholdDot) {
  16980. vertices.push(v0.x, v0.y, v0.z);
  16981. vertices.push(v1.x, v1.y, v1.z);
  16982. }
  16983. edgeData[reverseHash] = null;
  16984. } else if (!(hash in edgeData)) {
  16985. // if we've already got an edge here then skip adding a new one
  16986. edgeData[hash] = {
  16987. index0: indexArr[j],
  16988. index1: indexArr[jNext],
  16989. normal: _normal.clone()
  16990. };
  16991. }
  16992. }
  16993. } // iterate over all remaining, unmatched edges and add them to the vertex array
  16994. for (const key in edgeData) {
  16995. if (edgeData[key]) {
  16996. const {
  16997. index0,
  16998. index1
  16999. } = edgeData[key];
  17000. _v0.fromBufferAttribute(positionAttr, index0);
  17001. _v1$1.fromBufferAttribute(positionAttr, index1);
  17002. vertices.push(_v0.x, _v0.y, _v0.z);
  17003. vertices.push(_v1$1.x, _v1$1.y, _v1$1.z);
  17004. }
  17005. }
  17006. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17007. }
  17008. }
  17009. /**
  17010. * Port from https://github.com/mapbox/earcut (v2.2.2)
  17011. */
  17012. const Earcut = {
  17013. triangulate: function (data, holeIndices, dim) {
  17014. dim = dim || 2;
  17015. const hasHoles = holeIndices && holeIndices.length;
  17016. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  17017. let outerNode = linkedList(data, 0, outerLen, dim, true);
  17018. const triangles = [];
  17019. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  17020. let minX, minY, maxX, maxY, x, y, invSize;
  17021. 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
  17022. if (data.length > 80 * dim) {
  17023. minX = maxX = data[0];
  17024. minY = maxY = data[1];
  17025. for (let i = dim; i < outerLen; i += dim) {
  17026. x = data[i];
  17027. y = data[i + 1];
  17028. if (x < minX) minX = x;
  17029. if (y < minY) minY = y;
  17030. if (x > maxX) maxX = x;
  17031. if (y > maxY) maxY = y;
  17032. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  17033. invSize = Math.max(maxX - minX, maxY - minY);
  17034. invSize = invSize !== 0 ? 1 / invSize : 0;
  17035. }
  17036. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  17037. return triangles;
  17038. }
  17039. }; // create a circular doubly linked list from polygon points in the specified winding order
  17040. function linkedList(data, start, end, dim, clockwise) {
  17041. let i, last;
  17042. if (clockwise === signedArea(data, start, end, dim) > 0) {
  17043. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  17044. } else {
  17045. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  17046. }
  17047. if (last && equals(last, last.next)) {
  17048. removeNode(last);
  17049. last = last.next;
  17050. }
  17051. return last;
  17052. } // eliminate colinear or duplicate points
  17053. function filterPoints(start, end) {
  17054. if (!start) return start;
  17055. if (!end) end = start;
  17056. let p = start,
  17057. again;
  17058. do {
  17059. again = false;
  17060. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  17061. removeNode(p);
  17062. p = end = p.prev;
  17063. if (p === p.next) break;
  17064. again = true;
  17065. } else {
  17066. p = p.next;
  17067. }
  17068. } while (again || p !== end);
  17069. return end;
  17070. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  17071. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  17072. if (!ear) return; // interlink polygon nodes in z-order
  17073. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  17074. let stop = ear,
  17075. prev,
  17076. next; // iterate through ears, slicing them one by one
  17077. while (ear.prev !== ear.next) {
  17078. prev = ear.prev;
  17079. next = ear.next;
  17080. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  17081. // cut off the triangle
  17082. triangles.push(prev.i / dim);
  17083. triangles.push(ear.i / dim);
  17084. triangles.push(next.i / dim);
  17085. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  17086. ear = next.next;
  17087. stop = next.next;
  17088. continue;
  17089. }
  17090. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  17091. if (ear === stop) {
  17092. // try filtering points and slicing again
  17093. if (!pass) {
  17094. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  17095. } else if (pass === 1) {
  17096. ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
  17097. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  17098. } else if (pass === 2) {
  17099. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  17100. }
  17101. break;
  17102. }
  17103. }
  17104. } // check whether a polygon node forms a valid ear with adjacent nodes
  17105. function isEar(ear) {
  17106. const a = ear.prev,
  17107. b = ear,
  17108. c = ear.next;
  17109. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  17110. // now make sure we don't have other points inside the potential ear
  17111. let p = ear.next.next;
  17112. while (p !== ear.prev) {
  17113. 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;
  17114. p = p.next;
  17115. }
  17116. return true;
  17117. }
  17118. function isEarHashed(ear, minX, minY, invSize) {
  17119. const a = ear.prev,
  17120. b = ear,
  17121. c = ear.next;
  17122. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  17123. // triangle bbox; min & max are calculated like this for speed
  17124. const minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  17125. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  17126. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  17127. 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;
  17128. const minZ = zOrder(minTX, minTY, minX, minY, invSize),
  17129. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  17130. let p = ear.prevZ,
  17131. n = ear.nextZ; // look for points inside the triangle in both directions
  17132. while (p && p.z >= minZ && n && n.z <= maxZ) {
  17133. 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;
  17134. p = p.prevZ;
  17135. 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;
  17136. n = n.nextZ;
  17137. } // look for remaining points in decreasing z-order
  17138. while (p && p.z >= minZ) {
  17139. 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;
  17140. p = p.prevZ;
  17141. } // look for remaining points in increasing z-order
  17142. while (n && n.z <= maxZ) {
  17143. 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;
  17144. n = n.nextZ;
  17145. }
  17146. return true;
  17147. } // go through all polygon nodes and cure small local self-intersections
  17148. function cureLocalIntersections(start, triangles, dim) {
  17149. let p = start;
  17150. do {
  17151. const a = p.prev,
  17152. b = p.next.next;
  17153. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  17154. triangles.push(a.i / dim);
  17155. triangles.push(p.i / dim);
  17156. triangles.push(b.i / dim); // remove two nodes involved
  17157. removeNode(p);
  17158. removeNode(p.next);
  17159. p = start = b;
  17160. }
  17161. p = p.next;
  17162. } while (p !== start);
  17163. return filterPoints(p);
  17164. } // try splitting polygon into two and triangulate them independently
  17165. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  17166. // look for a valid diagonal that divides the polygon into two
  17167. let a = start;
  17168. do {
  17169. let b = a.next.next;
  17170. while (b !== a.prev) {
  17171. if (a.i !== b.i && isValidDiagonal(a, b)) {
  17172. // split the polygon in two by the diagonal
  17173. let c = splitPolygon(a, b); // filter colinear points around the cuts
  17174. a = filterPoints(a, a.next);
  17175. c = filterPoints(c, c.next); // run earcut on each half
  17176. earcutLinked(a, triangles, dim, minX, minY, invSize);
  17177. earcutLinked(c, triangles, dim, minX, minY, invSize);
  17178. return;
  17179. }
  17180. b = b.next;
  17181. }
  17182. a = a.next;
  17183. } while (a !== start);
  17184. } // link every hole into the outer loop, producing a single-ring polygon without holes
  17185. function eliminateHoles(data, holeIndices, outerNode, dim) {
  17186. const queue = [];
  17187. let i, len, start, end, list;
  17188. for (i = 0, len = holeIndices.length; i < len; i++) {
  17189. start = holeIndices[i] * dim;
  17190. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  17191. list = linkedList(data, start, end, dim, false);
  17192. if (list === list.next) list.steiner = true;
  17193. queue.push(getLeftmost(list));
  17194. }
  17195. queue.sort(compareX); // process holes from left to right
  17196. for (i = 0; i < queue.length; i++) {
  17197. eliminateHole(queue[i], outerNode);
  17198. outerNode = filterPoints(outerNode, outerNode.next);
  17199. }
  17200. return outerNode;
  17201. }
  17202. function compareX(a, b) {
  17203. return a.x - b.x;
  17204. } // find a bridge between vertices that connects hole with an outer ring and and link it
  17205. function eliminateHole(hole, outerNode) {
  17206. outerNode = findHoleBridge(hole, outerNode);
  17207. if (outerNode) {
  17208. const b = splitPolygon(outerNode, hole); // filter collinear points around the cuts
  17209. filterPoints(outerNode, outerNode.next);
  17210. filterPoints(b, b.next);
  17211. }
  17212. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  17213. function findHoleBridge(hole, outerNode) {
  17214. let p = outerNode;
  17215. const hx = hole.x;
  17216. const hy = hole.y;
  17217. let qx = -Infinity,
  17218. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  17219. // segment's endpoint with lesser x will be potential connection point
  17220. do {
  17221. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  17222. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  17223. if (x <= hx && x > qx) {
  17224. qx = x;
  17225. if (x === hx) {
  17226. if (hy === p.y) return p;
  17227. if (hy === p.next.y) return p.next;
  17228. }
  17229. m = p.x < p.next.x ? p : p.next;
  17230. }
  17231. }
  17232. p = p.next;
  17233. } while (p !== outerNode);
  17234. if (!m) return null;
  17235. if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint
  17236. // look for points inside the triangle of hole point, segment intersection and endpoint;
  17237. // if there are no points found, we have a valid connection;
  17238. // otherwise choose the point of the minimum angle with the ray as connection point
  17239. const stop = m,
  17240. mx = m.x,
  17241. my = m.y;
  17242. let tanMin = Infinity,
  17243. tan;
  17244. p = m;
  17245. do {
  17246. 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)) {
  17247. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  17248. if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
  17249. m = p;
  17250. tanMin = tan;
  17251. }
  17252. }
  17253. p = p.next;
  17254. } while (p !== stop);
  17255. return m;
  17256. } // whether sector in vertex m contains sector in vertex p in the same coordinates
  17257. function sectorContainsSector(m, p) {
  17258. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  17259. } // interlink polygon nodes in z-order
  17260. function indexCurve(start, minX, minY, invSize) {
  17261. let p = start;
  17262. do {
  17263. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  17264. p.prevZ = p.prev;
  17265. p.nextZ = p.next;
  17266. p = p.next;
  17267. } while (p !== start);
  17268. p.prevZ.nextZ = null;
  17269. p.prevZ = null;
  17270. sortLinked(p);
  17271. } // Simon Tatham's linked list merge sort algorithm
  17272. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  17273. function sortLinked(list) {
  17274. let i,
  17275. p,
  17276. q,
  17277. e,
  17278. tail,
  17279. numMerges,
  17280. pSize,
  17281. qSize,
  17282. inSize = 1;
  17283. do {
  17284. p = list;
  17285. list = null;
  17286. tail = null;
  17287. numMerges = 0;
  17288. while (p) {
  17289. numMerges++;
  17290. q = p;
  17291. pSize = 0;
  17292. for (i = 0; i < inSize; i++) {
  17293. pSize++;
  17294. q = q.nextZ;
  17295. if (!q) break;
  17296. }
  17297. qSize = inSize;
  17298. while (pSize > 0 || qSize > 0 && q) {
  17299. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  17300. e = p;
  17301. p = p.nextZ;
  17302. pSize--;
  17303. } else {
  17304. e = q;
  17305. q = q.nextZ;
  17306. qSize--;
  17307. }
  17308. if (tail) tail.nextZ = e;else list = e;
  17309. e.prevZ = tail;
  17310. tail = e;
  17311. }
  17312. p = q;
  17313. }
  17314. tail.nextZ = null;
  17315. inSize *= 2;
  17316. } while (numMerges > 1);
  17317. return list;
  17318. } // z-order of a point given coords and inverse of the longer side of data bbox
  17319. function zOrder(x, y, minX, minY, invSize) {
  17320. // coords are transformed into non-negative 15-bit integer range
  17321. x = 32767 * (x - minX) * invSize;
  17322. y = 32767 * (y - minY) * invSize;
  17323. x = (x | x << 8) & 0x00FF00FF;
  17324. x = (x | x << 4) & 0x0F0F0F0F;
  17325. x = (x | x << 2) & 0x33333333;
  17326. x = (x | x << 1) & 0x55555555;
  17327. y = (y | y << 8) & 0x00FF00FF;
  17328. y = (y | y << 4) & 0x0F0F0F0F;
  17329. y = (y | y << 2) & 0x33333333;
  17330. y = (y | y << 1) & 0x55555555;
  17331. return x | y << 1;
  17332. } // find the leftmost node of a polygon ring
  17333. function getLeftmost(start) {
  17334. let p = start,
  17335. leftmost = start;
  17336. do {
  17337. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  17338. p = p.next;
  17339. } while (p !== start);
  17340. return leftmost;
  17341. } // check if a point lies within a convex triangle
  17342. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  17343. 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;
  17344. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  17345. function isValidDiagonal(a, b) {
  17346. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && ( // dones't intersect other edges
  17347. locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && ( // locally visible
  17348. area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  17349. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  17350. } // signed area of a triangle
  17351. function area(p, q, r) {
  17352. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  17353. } // check if two points are equal
  17354. function equals(p1, p2) {
  17355. return p1.x === p2.x && p1.y === p2.y;
  17356. } // check if two segments intersect
  17357. function intersects(p1, q1, p2, q2) {
  17358. const o1 = sign(area(p1, q1, p2));
  17359. const o2 = sign(area(p1, q1, q2));
  17360. const o3 = sign(area(p2, q2, p1));
  17361. const o4 = sign(area(p2, q2, q1));
  17362. if (o1 !== o2 && o3 !== o4) return true; // general case
  17363. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  17364. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  17365. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  17366. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  17367. return false;
  17368. } // for collinear points p, q, r, check if point q lies on segment pr
  17369. function onSegment(p, q, r) {
  17370. 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);
  17371. }
  17372. function sign(num) {
  17373. return num > 0 ? 1 : num < 0 ? -1 : 0;
  17374. } // check if a polygon diagonal intersects any polygon segments
  17375. function intersectsPolygon(a, b) {
  17376. let p = a;
  17377. do {
  17378. 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;
  17379. p = p.next;
  17380. } while (p !== a);
  17381. return false;
  17382. } // check if a polygon diagonal is locally inside the polygon
  17383. function locallyInside(a, b) {
  17384. 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;
  17385. } // check if the middle point of a polygon diagonal is inside the polygon
  17386. function middleInside(a, b) {
  17387. let p = a,
  17388. inside = false;
  17389. const px = (a.x + b.x) / 2,
  17390. py = (a.y + b.y) / 2;
  17391. do {
  17392. 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;
  17393. p = p.next;
  17394. } while (p !== a);
  17395. return inside;
  17396. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  17397. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  17398. function splitPolygon(a, b) {
  17399. const a2 = new Node(a.i, a.x, a.y),
  17400. b2 = new Node(b.i, b.x, b.y),
  17401. an = a.next,
  17402. bp = b.prev;
  17403. a.next = b;
  17404. b.prev = a;
  17405. a2.next = an;
  17406. an.prev = a2;
  17407. b2.next = a2;
  17408. a2.prev = b2;
  17409. bp.next = b2;
  17410. b2.prev = bp;
  17411. return b2;
  17412. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  17413. function insertNode(i, x, y, last) {
  17414. const p = new Node(i, x, y);
  17415. if (!last) {
  17416. p.prev = p;
  17417. p.next = p;
  17418. } else {
  17419. p.next = last.next;
  17420. p.prev = last;
  17421. last.next.prev = p;
  17422. last.next = p;
  17423. }
  17424. return p;
  17425. }
  17426. function removeNode(p) {
  17427. p.next.prev = p.prev;
  17428. p.prev.next = p.next;
  17429. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  17430. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  17431. }
  17432. function Node(i, x, y) {
  17433. // vertex index in coordinates array
  17434. this.i = i; // vertex coordinates
  17435. this.x = x;
  17436. this.y = y; // previous and next vertex nodes in a polygon ring
  17437. this.prev = null;
  17438. this.next = null; // z-order curve value
  17439. this.z = null; // previous and next nodes in z-order
  17440. this.prevZ = null;
  17441. this.nextZ = null; // indicates whether this is a steiner point
  17442. this.steiner = false;
  17443. }
  17444. function signedArea(data, start, end, dim) {
  17445. let sum = 0;
  17446. for (let i = start, j = end - dim; i < end; i += dim) {
  17447. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  17448. j = i;
  17449. }
  17450. return sum;
  17451. }
  17452. class ShapeUtils {
  17453. // calculate area of the contour polygon
  17454. static area(contour) {
  17455. const n = contour.length;
  17456. let a = 0.0;
  17457. for (let p = n - 1, q = 0; q < n; p = q++) {
  17458. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  17459. }
  17460. return a * 0.5;
  17461. }
  17462. static isClockWise(pts) {
  17463. return ShapeUtils.area(pts) < 0;
  17464. }
  17465. static triangulateShape(contour, holes) {
  17466. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  17467. const holeIndices = []; // array of hole indices
  17468. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  17469. removeDupEndPts(contour);
  17470. addContour(vertices, contour); //
  17471. let holeIndex = contour.length;
  17472. holes.forEach(removeDupEndPts);
  17473. for (let i = 0; i < holes.length; i++) {
  17474. holeIndices.push(holeIndex);
  17475. holeIndex += holes[i].length;
  17476. addContour(vertices, holes[i]);
  17477. } //
  17478. const triangles = Earcut.triangulate(vertices, holeIndices); //
  17479. for (let i = 0; i < triangles.length; i += 3) {
  17480. faces.push(triangles.slice(i, i + 3));
  17481. }
  17482. return faces;
  17483. }
  17484. }
  17485. function removeDupEndPts(points) {
  17486. const l = points.length;
  17487. if (l > 2 && points[l - 1].equals(points[0])) {
  17488. points.pop();
  17489. }
  17490. }
  17491. function addContour(vertices, contour) {
  17492. for (let i = 0; i < contour.length; i++) {
  17493. vertices.push(contour[i].x);
  17494. vertices.push(contour[i].y);
  17495. }
  17496. }
  17497. /**
  17498. * Creates extruded geometry from a path shape.
  17499. *
  17500. * parameters = {
  17501. *
  17502. * curveSegments: <int>, // number of points on the curves
  17503. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  17504. * depth: <float>, // Depth to extrude the shape
  17505. *
  17506. * bevelEnabled: <bool>, // turn on bevel
  17507. * bevelThickness: <float>, // how deep into the original shape bevel goes
  17508. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  17509. * bevelOffset: <float>, // how far from shape outline does bevel start
  17510. * bevelSegments: <int>, // number of bevel layers
  17511. *
  17512. * extrudePath: <THREE.Curve> // curve to extrude shape along
  17513. *
  17514. * UVGenerator: <Object> // object that provides UV generator functions
  17515. *
  17516. * }
  17517. */
  17518. class ExtrudeGeometry extends BufferGeometry {
  17519. constructor(shapes, options) {
  17520. super();
  17521. this.type = 'ExtrudeGeometry';
  17522. this.parameters = {
  17523. shapes: shapes,
  17524. options: options
  17525. };
  17526. shapes = Array.isArray(shapes) ? shapes : [shapes];
  17527. const scope = this;
  17528. const verticesArray = [];
  17529. const uvArray = [];
  17530. for (let i = 0, l = shapes.length; i < l; i++) {
  17531. const shape = shapes[i];
  17532. addShape(shape);
  17533. } // build geometry
  17534. this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  17535. this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  17536. this.computeVertexNormals(); // functions
  17537. function addShape(shape) {
  17538. const placeholder = []; // options
  17539. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  17540. const steps = options.steps !== undefined ? options.steps : 1;
  17541. let depth = options.depth !== undefined ? options.depth : 100;
  17542. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  17543. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  17544. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  17545. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  17546. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  17547. const extrudePath = options.extrudePath;
  17548. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  17549. if (options.amount !== undefined) {
  17550. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  17551. depth = options.amount;
  17552. } //
  17553. let extrudePts,
  17554. extrudeByPath = false;
  17555. let splineTube, binormal, normal, position2;
  17556. if (extrudePath) {
  17557. extrudePts = extrudePath.getSpacedPoints(steps);
  17558. extrudeByPath = true;
  17559. bevelEnabled = false; // bevels not supported for path extrusion
  17560. // SETUP TNB variables
  17561. // TODO1 - have a .isClosed in spline?
  17562. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  17563. binormal = new Vector3();
  17564. normal = new Vector3();
  17565. position2 = new Vector3();
  17566. } // Safeguards if bevels are not enabled
  17567. if (!bevelEnabled) {
  17568. bevelSegments = 0;
  17569. bevelThickness = 0;
  17570. bevelSize = 0;
  17571. bevelOffset = 0;
  17572. } // Variables initialization
  17573. const shapePoints = shape.extractPoints(curveSegments);
  17574. let vertices = shapePoints.shape;
  17575. const holes = shapePoints.holes;
  17576. const reverse = !ShapeUtils.isClockWise(vertices);
  17577. if (reverse) {
  17578. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  17579. for (let h = 0, hl = holes.length; h < hl; h++) {
  17580. const ahole = holes[h];
  17581. if (ShapeUtils.isClockWise(ahole)) {
  17582. holes[h] = ahole.reverse();
  17583. }
  17584. }
  17585. }
  17586. const faces = ShapeUtils.triangulateShape(vertices, holes);
  17587. /* Vertices */
  17588. const contour = vertices; // vertices has all points but contour has only points of circumference
  17589. for (let h = 0, hl = holes.length; h < hl; h++) {
  17590. const ahole = holes[h];
  17591. vertices = vertices.concat(ahole);
  17592. }
  17593. function scalePt2(pt, vec, size) {
  17594. if (!vec) console.error('THREE.ExtrudeGeometry: vec does not exist');
  17595. return vec.clone().multiplyScalar(size).add(pt);
  17596. }
  17597. const vlen = vertices.length,
  17598. flen = faces.length; // Find directions for point movement
  17599. function getBevelVec(inPt, inPrev, inNext) {
  17600. // computes for inPt the corresponding point inPt' on a new contour
  17601. // shifted by 1 unit (length of normalized vector) to the left
  17602. // if we walk along contour clockwise, this new contour is outside the old one
  17603. //
  17604. // inPt' is the intersection of the two lines parallel to the two
  17605. // adjacent edges of inPt at a distance of 1 unit on the left side.
  17606. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  17607. // good reading for geometry algorithms (here: line-line intersection)
  17608. // http://geomalgorithms.com/a05-_intersect-1.html
  17609. const v_prev_x = inPt.x - inPrev.x,
  17610. v_prev_y = inPt.y - inPrev.y;
  17611. const v_next_x = inNext.x - inPt.x,
  17612. v_next_y = inNext.y - inPt.y;
  17613. const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  17614. const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  17615. if (Math.abs(collinear0) > Number.EPSILON) {
  17616. // not collinear
  17617. // length of vectors for normalizing
  17618. const v_prev_len = Math.sqrt(v_prev_lensq);
  17619. 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
  17620. const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  17621. const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  17622. const ptNextShift_x = inNext.x - v_next_y / v_next_len;
  17623. const ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  17624. 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
  17625. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  17626. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  17627. // but prevent crazy spikes
  17628. const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  17629. if (v_trans_lensq <= 2) {
  17630. return new Vector2(v_trans_x, v_trans_y);
  17631. } else {
  17632. shrink_by = Math.sqrt(v_trans_lensq / 2);
  17633. }
  17634. } else {
  17635. // handle special case of collinear edges
  17636. let direction_eq = false; // assumes: opposite
  17637. if (v_prev_x > Number.EPSILON) {
  17638. if (v_next_x > Number.EPSILON) {
  17639. direction_eq = true;
  17640. }
  17641. } else {
  17642. if (v_prev_x < -Number.EPSILON) {
  17643. if (v_next_x < -Number.EPSILON) {
  17644. direction_eq = true;
  17645. }
  17646. } else {
  17647. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  17648. direction_eq = true;
  17649. }
  17650. }
  17651. }
  17652. if (direction_eq) {
  17653. // console.log("Warning: lines are a straight sequence");
  17654. v_trans_x = -v_prev_y;
  17655. v_trans_y = v_prev_x;
  17656. shrink_by = Math.sqrt(v_prev_lensq);
  17657. } else {
  17658. // console.log("Warning: lines are a straight spike");
  17659. v_trans_x = v_prev_x;
  17660. v_trans_y = v_prev_y;
  17661. shrink_by = Math.sqrt(v_prev_lensq / 2);
  17662. }
  17663. }
  17664. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  17665. }
  17666. const contourMovements = [];
  17667. for (let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  17668. if (j === il) j = 0;
  17669. if (k === il) k = 0; // (j)---(i)---(k)
  17670. // console.log('i,j,k', i, j , k)
  17671. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  17672. }
  17673. const holesMovements = [];
  17674. let oneHoleMovements,
  17675. verticesMovements = contourMovements.concat();
  17676. for (let h = 0, hl = holes.length; h < hl; h++) {
  17677. const ahole = holes[h];
  17678. oneHoleMovements = [];
  17679. for (let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  17680. if (j === il) j = 0;
  17681. if (k === il) k = 0; // (j)---(i)---(k)
  17682. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  17683. }
  17684. holesMovements.push(oneHoleMovements);
  17685. verticesMovements = verticesMovements.concat(oneHoleMovements);
  17686. } // Loop bevelSegments, 1 for the front, 1 for the back
  17687. for (let b = 0; b < bevelSegments; b++) {
  17688. //for ( b = bevelSegments; b > 0; b -- ) {
  17689. const t = b / bevelSegments;
  17690. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  17691. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  17692. for (let i = 0, il = contour.length; i < il; i++) {
  17693. const vert = scalePt2(contour[i], contourMovements[i], bs);
  17694. v(vert.x, vert.y, -z);
  17695. } // expand holes
  17696. for (let h = 0, hl = holes.length; h < hl; h++) {
  17697. const ahole = holes[h];
  17698. oneHoleMovements = holesMovements[h];
  17699. for (let i = 0, il = ahole.length; i < il; i++) {
  17700. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  17701. v(vert.x, vert.y, -z);
  17702. }
  17703. }
  17704. }
  17705. const bs = bevelSize + bevelOffset; // Back facing vertices
  17706. for (let i = 0; i < vlen; i++) {
  17707. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  17708. if (!extrudeByPath) {
  17709. v(vert.x, vert.y, 0);
  17710. } else {
  17711. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  17712. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  17713. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  17714. position2.copy(extrudePts[0]).add(normal).add(binormal);
  17715. v(position2.x, position2.y, position2.z);
  17716. }
  17717. } // Add stepped vertices...
  17718. // Including front facing vertices
  17719. for (let s = 1; s <= steps; s++) {
  17720. for (let i = 0; i < vlen; i++) {
  17721. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  17722. if (!extrudeByPath) {
  17723. v(vert.x, vert.y, depth / steps * s);
  17724. } else {
  17725. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  17726. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  17727. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  17728. position2.copy(extrudePts[s]).add(normal).add(binormal);
  17729. v(position2.x, position2.y, position2.z);
  17730. }
  17731. }
  17732. } // Add bevel segments planes
  17733. //for ( b = 1; b <= bevelSegments; b ++ ) {
  17734. for (let b = bevelSegments - 1; b >= 0; b--) {
  17735. const t = b / bevelSegments;
  17736. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  17737. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  17738. for (let i = 0, il = contour.length; i < il; i++) {
  17739. const vert = scalePt2(contour[i], contourMovements[i], bs);
  17740. v(vert.x, vert.y, depth + z);
  17741. } // expand holes
  17742. for (let h = 0, hl = holes.length; h < hl; h++) {
  17743. const ahole = holes[h];
  17744. oneHoleMovements = holesMovements[h];
  17745. for (let i = 0, il = ahole.length; i < il; i++) {
  17746. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  17747. if (!extrudeByPath) {
  17748. v(vert.x, vert.y, depth + z);
  17749. } else {
  17750. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  17751. }
  17752. }
  17753. }
  17754. }
  17755. /* Faces */
  17756. // Top and bottom faces
  17757. buildLidFaces(); // Sides faces
  17758. buildSideFaces(); ///// Internal functions
  17759. function buildLidFaces() {
  17760. const start = verticesArray.length / 3;
  17761. if (bevelEnabled) {
  17762. let layer = 0; // steps + 1
  17763. let offset = vlen * layer; // Bottom faces
  17764. for (let i = 0; i < flen; i++) {
  17765. const face = faces[i];
  17766. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  17767. }
  17768. layer = steps + bevelSegments * 2;
  17769. offset = vlen * layer; // Top faces
  17770. for (let i = 0; i < flen; i++) {
  17771. const face = faces[i];
  17772. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  17773. }
  17774. } else {
  17775. // Bottom faces
  17776. for (let i = 0; i < flen; i++) {
  17777. const face = faces[i];
  17778. f3(face[2], face[1], face[0]);
  17779. } // Top faces
  17780. for (let i = 0; i < flen; i++) {
  17781. const face = faces[i];
  17782. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  17783. }
  17784. }
  17785. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  17786. } // Create faces for the z-sides of the shape
  17787. function buildSideFaces() {
  17788. const start = verticesArray.length / 3;
  17789. let layeroffset = 0;
  17790. sidewalls(contour, layeroffset);
  17791. layeroffset += contour.length;
  17792. for (let h = 0, hl = holes.length; h < hl; h++) {
  17793. const ahole = holes[h];
  17794. sidewalls(ahole, layeroffset); //, true
  17795. layeroffset += ahole.length;
  17796. }
  17797. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  17798. }
  17799. function sidewalls(contour, layeroffset) {
  17800. let i = contour.length;
  17801. while (--i >= 0) {
  17802. const j = i;
  17803. let k = i - 1;
  17804. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  17805. for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) {
  17806. const slen1 = vlen * s;
  17807. const slen2 = vlen * (s + 1);
  17808. const a = layeroffset + j + slen1,
  17809. b = layeroffset + k + slen1,
  17810. c = layeroffset + k + slen2,
  17811. d = layeroffset + j + slen2;
  17812. f4(a, b, c, d);
  17813. }
  17814. }
  17815. }
  17816. function v(x, y, z) {
  17817. placeholder.push(x);
  17818. placeholder.push(y);
  17819. placeholder.push(z);
  17820. }
  17821. function f3(a, b, c) {
  17822. addVertex(a);
  17823. addVertex(b);
  17824. addVertex(c);
  17825. const nextIndex = verticesArray.length / 3;
  17826. const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  17827. addUV(uvs[0]);
  17828. addUV(uvs[1]);
  17829. addUV(uvs[2]);
  17830. }
  17831. function f4(a, b, c, d) {
  17832. addVertex(a);
  17833. addVertex(b);
  17834. addVertex(d);
  17835. addVertex(b);
  17836. addVertex(c);
  17837. addVertex(d);
  17838. const nextIndex = verticesArray.length / 3;
  17839. const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  17840. addUV(uvs[0]);
  17841. addUV(uvs[1]);
  17842. addUV(uvs[3]);
  17843. addUV(uvs[1]);
  17844. addUV(uvs[2]);
  17845. addUV(uvs[3]);
  17846. }
  17847. function addVertex(index) {
  17848. verticesArray.push(placeholder[index * 3 + 0]);
  17849. verticesArray.push(placeholder[index * 3 + 1]);
  17850. verticesArray.push(placeholder[index * 3 + 2]);
  17851. }
  17852. function addUV(vector2) {
  17853. uvArray.push(vector2.x);
  17854. uvArray.push(vector2.y);
  17855. }
  17856. }
  17857. }
  17858. toJSON() {
  17859. const data = super.toJSON();
  17860. const shapes = this.parameters.shapes;
  17861. const options = this.parameters.options;
  17862. return toJSON$1(shapes, options, data);
  17863. }
  17864. }
  17865. const WorldUVGenerator = {
  17866. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  17867. const a_x = vertices[indexA * 3];
  17868. const a_y = vertices[indexA * 3 + 1];
  17869. const b_x = vertices[indexB * 3];
  17870. const b_y = vertices[indexB * 3 + 1];
  17871. const c_x = vertices[indexC * 3];
  17872. const c_y = vertices[indexC * 3 + 1];
  17873. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  17874. },
  17875. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  17876. const a_x = vertices[indexA * 3];
  17877. const a_y = vertices[indexA * 3 + 1];
  17878. const a_z = vertices[indexA * 3 + 2];
  17879. const b_x = vertices[indexB * 3];
  17880. const b_y = vertices[indexB * 3 + 1];
  17881. const b_z = vertices[indexB * 3 + 2];
  17882. const c_x = vertices[indexC * 3];
  17883. const c_y = vertices[indexC * 3 + 1];
  17884. const c_z = vertices[indexC * 3 + 2];
  17885. const d_x = vertices[indexD * 3];
  17886. const d_y = vertices[indexD * 3 + 1];
  17887. const d_z = vertices[indexD * 3 + 2];
  17888. if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) {
  17889. 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)];
  17890. } else {
  17891. 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)];
  17892. }
  17893. }
  17894. };
  17895. function toJSON$1(shapes, options, data) {
  17896. data.shapes = [];
  17897. if (Array.isArray(shapes)) {
  17898. for (let i = 0, l = shapes.length; i < l; i++) {
  17899. const shape = shapes[i];
  17900. data.shapes.push(shape.uuid);
  17901. }
  17902. } else {
  17903. data.shapes.push(shapes.uuid);
  17904. }
  17905. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  17906. return data;
  17907. }
  17908. class IcosahedronGeometry extends PolyhedronGeometry {
  17909. constructor(radius = 1, detail = 0) {
  17910. const t = (1 + Math.sqrt(5)) / 2;
  17911. 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];
  17912. 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];
  17913. super(vertices, indices, radius, detail);
  17914. this.type = 'IcosahedronGeometry';
  17915. this.parameters = {
  17916. radius: radius,
  17917. detail: detail
  17918. };
  17919. }
  17920. }
  17921. class LatheGeometry extends BufferGeometry {
  17922. constructor(points, segments = 12, phiStart = 0, phiLength = Math.PI * 2) {
  17923. super();
  17924. this.type = 'LatheGeometry';
  17925. this.parameters = {
  17926. points: points,
  17927. segments: segments,
  17928. phiStart: phiStart,
  17929. phiLength: phiLength
  17930. };
  17931. segments = Math.floor(segments); // clamp phiLength so it's in range of [ 0, 2PI ]
  17932. phiLength = clamp(phiLength, 0, Math.PI * 2); // buffers
  17933. const indices = [];
  17934. const vertices = [];
  17935. const uvs = []; // helper variables
  17936. const inverseSegments = 1.0 / segments;
  17937. const vertex = new Vector3();
  17938. const uv = new Vector2(); // generate vertices and uvs
  17939. for (let i = 0; i <= segments; i++) {
  17940. const phi = phiStart + i * inverseSegments * phiLength;
  17941. const sin = Math.sin(phi);
  17942. const cos = Math.cos(phi);
  17943. for (let j = 0; j <= points.length - 1; j++) {
  17944. // vertex
  17945. vertex.x = points[j].x * sin;
  17946. vertex.y = points[j].y;
  17947. vertex.z = points[j].x * cos;
  17948. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  17949. uv.x = i / segments;
  17950. uv.y = j / (points.length - 1);
  17951. uvs.push(uv.x, uv.y);
  17952. }
  17953. } // indices
  17954. for (let i = 0; i < segments; i++) {
  17955. for (let j = 0; j < points.length - 1; j++) {
  17956. const base = j + i * points.length;
  17957. const a = base;
  17958. const b = base + points.length;
  17959. const c = base + points.length + 1;
  17960. const d = base + 1; // faces
  17961. indices.push(a, b, d);
  17962. indices.push(b, c, d);
  17963. }
  17964. } // build geometry
  17965. this.setIndex(indices);
  17966. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17967. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
  17968. this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
  17969. // because the corresponding vertices are identical (but still have different UVs).
  17970. if (phiLength === Math.PI * 2) {
  17971. const normals = this.attributes.normal.array;
  17972. const n1 = new Vector3();
  17973. const n2 = new Vector3();
  17974. const n = new Vector3(); // this is the buffer offset for the last line of vertices
  17975. const base = segments * points.length * 3;
  17976. for (let i = 0, j = 0; i < points.length; i++, j += 3) {
  17977. // select the normal of the vertex in the first line
  17978. n1.x = normals[j + 0];
  17979. n1.y = normals[j + 1];
  17980. n1.z = normals[j + 2]; // select the normal of the vertex in the last line
  17981. n2.x = normals[base + j + 0];
  17982. n2.y = normals[base + j + 1];
  17983. n2.z = normals[base + j + 2]; // average normals
  17984. n.addVectors(n1, n2).normalize(); // assign the new values to both normals
  17985. normals[j + 0] = normals[base + j + 0] = n.x;
  17986. normals[j + 1] = normals[base + j + 1] = n.y;
  17987. normals[j + 2] = normals[base + j + 2] = n.z;
  17988. }
  17989. }
  17990. }
  17991. }
  17992. class OctahedronGeometry extends PolyhedronGeometry {
  17993. constructor(radius = 1, detail = 0) {
  17994. const vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  17995. 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];
  17996. super(vertices, indices, radius, detail);
  17997. this.type = 'OctahedronGeometry';
  17998. this.parameters = {
  17999. radius: radius,
  18000. detail: detail
  18001. };
  18002. }
  18003. }
  18004. /**
  18005. * Parametric Surfaces Geometry
  18006. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  18007. */
  18008. class ParametricGeometry extends BufferGeometry {
  18009. constructor(func, slices, stacks) {
  18010. super();
  18011. this.type = 'ParametricGeometry';
  18012. this.parameters = {
  18013. func: func,
  18014. slices: slices,
  18015. stacks: stacks
  18016. }; // buffers
  18017. const indices = [];
  18018. const vertices = [];
  18019. const normals = [];
  18020. const uvs = [];
  18021. const EPS = 0.00001;
  18022. const normal = new Vector3();
  18023. const p0 = new Vector3(),
  18024. p1 = new Vector3();
  18025. const pu = new Vector3(),
  18026. pv = new Vector3();
  18027. if (func.length < 3) {
  18028. console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');
  18029. } // generate vertices, normals and uvs
  18030. const sliceCount = slices + 1;
  18031. for (let i = 0; i <= stacks; i++) {
  18032. const v = i / stacks;
  18033. for (let j = 0; j <= slices; j++) {
  18034. const u = j / slices; // vertex
  18035. func(u, v, p0);
  18036. vertices.push(p0.x, p0.y, p0.z); // normal
  18037. // approximate tangent vectors via finite differences
  18038. if (u - EPS >= 0) {
  18039. func(u - EPS, v, p1);
  18040. pu.subVectors(p0, p1);
  18041. } else {
  18042. func(u + EPS, v, p1);
  18043. pu.subVectors(p1, p0);
  18044. }
  18045. if (v - EPS >= 0) {
  18046. func(u, v - EPS, p1);
  18047. pv.subVectors(p0, p1);
  18048. } else {
  18049. func(u, v + EPS, p1);
  18050. pv.subVectors(p1, p0);
  18051. } // cross product of tangent vectors returns surface normal
  18052. normal.crossVectors(pu, pv).normalize();
  18053. normals.push(normal.x, normal.y, normal.z); // uv
  18054. uvs.push(u, v);
  18055. }
  18056. } // generate indices
  18057. for (let i = 0; i < stacks; i++) {
  18058. for (let j = 0; j < slices; j++) {
  18059. const a = i * sliceCount + j;
  18060. const b = i * sliceCount + j + 1;
  18061. const c = (i + 1) * sliceCount + j + 1;
  18062. const d = (i + 1) * sliceCount + j; // faces one and two
  18063. indices.push(a, b, d);
  18064. indices.push(b, c, d);
  18065. }
  18066. } // build geometry
  18067. this.setIndex(indices);
  18068. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18069. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18070. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18071. }
  18072. }
  18073. class RingGeometry extends BufferGeometry {
  18074. constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) {
  18075. super();
  18076. this.type = 'RingGeometry';
  18077. this.parameters = {
  18078. innerRadius: innerRadius,
  18079. outerRadius: outerRadius,
  18080. thetaSegments: thetaSegments,
  18081. phiSegments: phiSegments,
  18082. thetaStart: thetaStart,
  18083. thetaLength: thetaLength
  18084. };
  18085. thetaSegments = Math.max(3, thetaSegments);
  18086. phiSegments = Math.max(1, phiSegments); // buffers
  18087. const indices = [];
  18088. const vertices = [];
  18089. const normals = [];
  18090. const uvs = []; // some helper variables
  18091. let radius = innerRadius;
  18092. const radiusStep = (outerRadius - innerRadius) / phiSegments;
  18093. const vertex = new Vector3();
  18094. const uv = new Vector2(); // generate vertices, normals and uvs
  18095. for (let j = 0; j <= phiSegments; j++) {
  18096. for (let i = 0; i <= thetaSegments; i++) {
  18097. // values are generate from the inside of the ring to the outside
  18098. const segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  18099. vertex.x = radius * Math.cos(segment);
  18100. vertex.y = radius * Math.sin(segment);
  18101. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18102. normals.push(0, 0, 1); // uv
  18103. uv.x = (vertex.x / outerRadius + 1) / 2;
  18104. uv.y = (vertex.y / outerRadius + 1) / 2;
  18105. uvs.push(uv.x, uv.y);
  18106. } // increase the radius for next row of vertices
  18107. radius += radiusStep;
  18108. } // indices
  18109. for (let j = 0; j < phiSegments; j++) {
  18110. const thetaSegmentLevel = j * (thetaSegments + 1);
  18111. for (let i = 0; i < thetaSegments; i++) {
  18112. const segment = i + thetaSegmentLevel;
  18113. const a = segment;
  18114. const b = segment + thetaSegments + 1;
  18115. const c = segment + thetaSegments + 2;
  18116. const d = segment + 1; // faces
  18117. indices.push(a, b, d);
  18118. indices.push(b, c, d);
  18119. }
  18120. } // build geometry
  18121. this.setIndex(indices);
  18122. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18123. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18124. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18125. }
  18126. }
  18127. class ShapeGeometry extends BufferGeometry {
  18128. constructor(shapes, curveSegments = 12) {
  18129. super();
  18130. this.type = 'ShapeGeometry';
  18131. this.parameters = {
  18132. shapes: shapes,
  18133. curveSegments: curveSegments
  18134. }; // buffers
  18135. const indices = [];
  18136. const vertices = [];
  18137. const normals = [];
  18138. const uvs = []; // helper variables
  18139. let groupStart = 0;
  18140. let groupCount = 0; // allow single and array values for "shapes" parameter
  18141. if (Array.isArray(shapes) === false) {
  18142. addShape(shapes);
  18143. } else {
  18144. for (let i = 0; i < shapes.length; i++) {
  18145. addShape(shapes[i]);
  18146. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  18147. groupStart += groupCount;
  18148. groupCount = 0;
  18149. }
  18150. } // build geometry
  18151. this.setIndex(indices);
  18152. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18153. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18154. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  18155. function addShape(shape) {
  18156. const indexOffset = vertices.length / 3;
  18157. const points = shape.extractPoints(curveSegments);
  18158. let shapeVertices = points.shape;
  18159. const shapeHoles = points.holes; // check direction of vertices
  18160. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  18161. shapeVertices = shapeVertices.reverse();
  18162. }
  18163. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  18164. const shapeHole = shapeHoles[i];
  18165. if (ShapeUtils.isClockWise(shapeHole) === true) {
  18166. shapeHoles[i] = shapeHole.reverse();
  18167. }
  18168. }
  18169. const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  18170. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  18171. const shapeHole = shapeHoles[i];
  18172. shapeVertices = shapeVertices.concat(shapeHole);
  18173. } // vertices, normals, uvs
  18174. for (let i = 0, l = shapeVertices.length; i < l; i++) {
  18175. const vertex = shapeVertices[i];
  18176. vertices.push(vertex.x, vertex.y, 0);
  18177. normals.push(0, 0, 1);
  18178. uvs.push(vertex.x, vertex.y); // world uvs
  18179. } // incides
  18180. for (let i = 0, l = faces.length; i < l; i++) {
  18181. const face = faces[i];
  18182. const a = face[0] + indexOffset;
  18183. const b = face[1] + indexOffset;
  18184. const c = face[2] + indexOffset;
  18185. indices.push(a, b, c);
  18186. groupCount += 3;
  18187. }
  18188. }
  18189. }
  18190. toJSON() {
  18191. const data = super.toJSON();
  18192. const shapes = this.parameters.shapes;
  18193. return toJSON(shapes, data);
  18194. }
  18195. }
  18196. function toJSON(shapes, data) {
  18197. data.shapes = [];
  18198. if (Array.isArray(shapes)) {
  18199. for (let i = 0, l = shapes.length; i < l; i++) {
  18200. const shape = shapes[i];
  18201. data.shapes.push(shape.uuid);
  18202. }
  18203. } else {
  18204. data.shapes.push(shapes.uuid);
  18205. }
  18206. return data;
  18207. }
  18208. class SphereGeometry extends BufferGeometry {
  18209. constructor(radius = 1, widthSegments = 8, heightSegments = 6, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) {
  18210. super();
  18211. this.type = 'SphereGeometry';
  18212. this.parameters = {
  18213. radius: radius,
  18214. widthSegments: widthSegments,
  18215. heightSegments: heightSegments,
  18216. phiStart: phiStart,
  18217. phiLength: phiLength,
  18218. thetaStart: thetaStart,
  18219. thetaLength: thetaLength
  18220. };
  18221. widthSegments = Math.max(3, Math.floor(widthSegments));
  18222. heightSegments = Math.max(2, Math.floor(heightSegments));
  18223. const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  18224. let index = 0;
  18225. const grid = [];
  18226. const vertex = new Vector3();
  18227. const normal = new Vector3(); // buffers
  18228. const indices = [];
  18229. const vertices = [];
  18230. const normals = [];
  18231. const uvs = []; // generate vertices, normals and uvs
  18232. for (let iy = 0; iy <= heightSegments; iy++) {
  18233. const verticesRow = [];
  18234. const v = iy / heightSegments; // special case for the poles
  18235. let uOffset = 0;
  18236. if (iy == 0 && thetaStart == 0) {
  18237. uOffset = 0.5 / widthSegments;
  18238. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  18239. uOffset = -0.5 / widthSegments;
  18240. }
  18241. for (let ix = 0; ix <= widthSegments; ix++) {
  18242. const u = ix / widthSegments; // vertex
  18243. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  18244. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  18245. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  18246. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18247. normal.copy(vertex).normalize();
  18248. normals.push(normal.x, normal.y, normal.z); // uv
  18249. uvs.push(u + uOffset, 1 - v);
  18250. verticesRow.push(index++);
  18251. }
  18252. grid.push(verticesRow);
  18253. } // indices
  18254. for (let iy = 0; iy < heightSegments; iy++) {
  18255. for (let ix = 0; ix < widthSegments; ix++) {
  18256. const a = grid[iy][ix + 1];
  18257. const b = grid[iy][ix];
  18258. const c = grid[iy + 1][ix];
  18259. const d = grid[iy + 1][ix + 1];
  18260. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  18261. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  18262. }
  18263. } // build geometry
  18264. this.setIndex(indices);
  18265. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18266. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18267. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18268. }
  18269. }
  18270. class TetrahedronGeometry extends PolyhedronGeometry {
  18271. constructor(radius = 1, detail = 0) {
  18272. const vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  18273. const indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  18274. super(vertices, indices, radius, detail);
  18275. this.type = 'TetrahedronGeometry';
  18276. this.parameters = {
  18277. radius: radius,
  18278. detail: detail
  18279. };
  18280. }
  18281. }
  18282. /**
  18283. * Text = 3D Text
  18284. *
  18285. * parameters = {
  18286. * font: <THREE.Font>, // font
  18287. *
  18288. * size: <float>, // size of the text
  18289. * height: <float>, // thickness to extrude text
  18290. * curveSegments: <int>, // number of points on the curves
  18291. *
  18292. * bevelEnabled: <bool>, // turn on bevel
  18293. * bevelThickness: <float>, // how deep into text bevel goes
  18294. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  18295. * bevelOffset: <float> // how far from text outline does bevel start
  18296. * }
  18297. */
  18298. class TextGeometry extends ExtrudeGeometry {
  18299. constructor(text, parameters = {}) {
  18300. const font = parameters.font;
  18301. if (!(font && font.isFont)) {
  18302. console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');
  18303. return new BufferGeometry();
  18304. }
  18305. const shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry API
  18306. parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults
  18307. if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;
  18308. if (parameters.bevelSize === undefined) parameters.bevelSize = 8;
  18309. if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;
  18310. super(shapes, parameters);
  18311. this.type = 'TextGeometry';
  18312. }
  18313. }
  18314. class TorusGeometry extends BufferGeometry {
  18315. constructor(radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) {
  18316. super();
  18317. this.type = 'TorusGeometry';
  18318. this.parameters = {
  18319. radius: radius,
  18320. tube: tube,
  18321. radialSegments: radialSegments,
  18322. tubularSegments: tubularSegments,
  18323. arc: arc
  18324. };
  18325. radialSegments = Math.floor(radialSegments);
  18326. tubularSegments = Math.floor(tubularSegments); // buffers
  18327. const indices = [];
  18328. const vertices = [];
  18329. const normals = [];
  18330. const uvs = []; // helper variables
  18331. const center = new Vector3();
  18332. const vertex = new Vector3();
  18333. const normal = new Vector3(); // generate vertices, normals and uvs
  18334. for (let j = 0; j <= radialSegments; j++) {
  18335. for (let i = 0; i <= tubularSegments; i++) {
  18336. const u = i / tubularSegments * arc;
  18337. const v = j / radialSegments * Math.PI * 2; // vertex
  18338. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  18339. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  18340. vertex.z = tube * Math.sin(v);
  18341. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  18342. center.x = radius * Math.cos(u);
  18343. center.y = radius * Math.sin(u);
  18344. normal.subVectors(vertex, center).normalize();
  18345. normals.push(normal.x, normal.y, normal.z); // uv
  18346. uvs.push(i / tubularSegments);
  18347. uvs.push(j / radialSegments);
  18348. }
  18349. } // generate indices
  18350. for (let j = 1; j <= radialSegments; j++) {
  18351. for (let i = 1; i <= tubularSegments; i++) {
  18352. // indices
  18353. const a = (tubularSegments + 1) * j + i - 1;
  18354. const b = (tubularSegments + 1) * (j - 1) + i - 1;
  18355. const c = (tubularSegments + 1) * (j - 1) + i;
  18356. const d = (tubularSegments + 1) * j + i; // faces
  18357. indices.push(a, b, d);
  18358. indices.push(b, c, d);
  18359. }
  18360. } // build geometry
  18361. this.setIndex(indices);
  18362. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18363. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18364. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  18365. }
  18366. }
  18367. class TorusKnotGeometry extends BufferGeometry {
  18368. constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) {
  18369. super();
  18370. this.type = 'TorusKnotGeometry';
  18371. this.parameters = {
  18372. radius: radius,
  18373. tube: tube,
  18374. tubularSegments: tubularSegments,
  18375. radialSegments: radialSegments,
  18376. p: p,
  18377. q: q
  18378. };
  18379. tubularSegments = Math.floor(tubularSegments);
  18380. radialSegments = Math.floor(radialSegments); // buffers
  18381. const indices = [];
  18382. const vertices = [];
  18383. const normals = [];
  18384. const uvs = []; // helper variables
  18385. const vertex = new Vector3();
  18386. const normal = new Vector3();
  18387. const P1 = new Vector3();
  18388. const P2 = new Vector3();
  18389. const B = new Vector3();
  18390. const T = new Vector3();
  18391. const N = new Vector3(); // generate vertices, normals and uvs
  18392. for (let i = 0; i <= tubularSegments; ++i) {
  18393. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  18394. 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.
  18395. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  18396. calculatePositionOnCurve(u, p, q, radius, P1);
  18397. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  18398. T.subVectors(P2, P1);
  18399. N.addVectors(P2, P1);
  18400. B.crossVectors(T, N);
  18401. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  18402. B.normalize();
  18403. N.normalize();
  18404. for (let j = 0; j <= radialSegments; ++j) {
  18405. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  18406. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  18407. const v = j / radialSegments * Math.PI * 2;
  18408. const cx = -tube * Math.cos(v);
  18409. const cy = tube * Math.sin(v); // now calculate the final vertex position.
  18410. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  18411. vertex.x = P1.x + (cx * N.x + cy * B.x);
  18412. vertex.y = P1.y + (cx * N.y + cy * B.y);
  18413. vertex.z = P1.z + (cx * N.z + cy * B.z);
  18414. 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)
  18415. normal.subVectors(vertex, P1).normalize();
  18416. normals.push(normal.x, normal.y, normal.z); // uv
  18417. uvs.push(i / tubularSegments);
  18418. uvs.push(j / radialSegments);
  18419. }
  18420. } // generate indices
  18421. for (let j = 1; j <= tubularSegments; j++) {
  18422. for (let i = 1; i <= radialSegments; i++) {
  18423. // indices
  18424. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  18425. const b = (radialSegments + 1) * j + (i - 1);
  18426. const c = (radialSegments + 1) * j + i;
  18427. const d = (radialSegments + 1) * (j - 1) + i; // faces
  18428. indices.push(a, b, d);
  18429. indices.push(b, c, d);
  18430. }
  18431. } // build geometry
  18432. this.setIndex(indices);
  18433. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18434. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18435. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  18436. function calculatePositionOnCurve(u, p, q, radius, position) {
  18437. const cu = Math.cos(u);
  18438. const su = Math.sin(u);
  18439. const quOverP = q / p * u;
  18440. const cs = Math.cos(quOverP);
  18441. position.x = radius * (2 + cs) * 0.5 * cu;
  18442. position.y = radius * (2 + cs) * su * 0.5;
  18443. position.z = radius * Math.sin(quOverP) * 0.5;
  18444. }
  18445. }
  18446. }
  18447. class TubeGeometry extends BufferGeometry {
  18448. constructor(path, tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) {
  18449. super();
  18450. this.type = 'TubeGeometry';
  18451. this.parameters = {
  18452. path: path,
  18453. tubularSegments: tubularSegments,
  18454. radius: radius,
  18455. radialSegments: radialSegments,
  18456. closed: closed
  18457. };
  18458. const frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  18459. this.tangents = frames.tangents;
  18460. this.normals = frames.normals;
  18461. this.binormals = frames.binormals; // helper variables
  18462. const vertex = new Vector3();
  18463. const normal = new Vector3();
  18464. const uv = new Vector2();
  18465. let P = new Vector3(); // buffer
  18466. const vertices = [];
  18467. const normals = [];
  18468. const uvs = [];
  18469. const indices = []; // create buffer data
  18470. generateBufferData(); // build geometry
  18471. this.setIndex(indices);
  18472. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18473. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  18474. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  18475. function generateBufferData() {
  18476. for (let i = 0; i < tubularSegments; i++) {
  18477. generateSegment(i);
  18478. } // if the geometry is not closed, generate the last row of vertices and normals
  18479. // at the regular position on the given path
  18480. //
  18481. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  18482. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  18483. // this makes it easy compute correct values for closed geometries
  18484. generateUVs(); // finally create faces
  18485. generateIndices();
  18486. }
  18487. function generateSegment(i) {
  18488. // we use getPointAt to sample evenly distributed points from the given path
  18489. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  18490. const N = frames.normals[i];
  18491. const B = frames.binormals[i]; // generate normals and vertices for the current segment
  18492. for (let j = 0; j <= radialSegments; j++) {
  18493. const v = j / radialSegments * Math.PI * 2;
  18494. const sin = Math.sin(v);
  18495. const cos = -Math.cos(v); // normal
  18496. normal.x = cos * N.x + sin * B.x;
  18497. normal.y = cos * N.y + sin * B.y;
  18498. normal.z = cos * N.z + sin * B.z;
  18499. normal.normalize();
  18500. normals.push(normal.x, normal.y, normal.z); // vertex
  18501. vertex.x = P.x + radius * normal.x;
  18502. vertex.y = P.y + radius * normal.y;
  18503. vertex.z = P.z + radius * normal.z;
  18504. vertices.push(vertex.x, vertex.y, vertex.z);
  18505. }
  18506. }
  18507. function generateIndices() {
  18508. for (let j = 1; j <= tubularSegments; j++) {
  18509. for (let i = 1; i <= radialSegments; i++) {
  18510. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  18511. const b = (radialSegments + 1) * j + (i - 1);
  18512. const c = (radialSegments + 1) * j + i;
  18513. const d = (radialSegments + 1) * (j - 1) + i; // faces
  18514. indices.push(a, b, d);
  18515. indices.push(b, c, d);
  18516. }
  18517. }
  18518. }
  18519. function generateUVs() {
  18520. for (let i = 0; i <= tubularSegments; i++) {
  18521. for (let j = 0; j <= radialSegments; j++) {
  18522. uv.x = i / tubularSegments;
  18523. uv.y = j / radialSegments;
  18524. uvs.push(uv.x, uv.y);
  18525. }
  18526. }
  18527. }
  18528. }
  18529. toJSON() {
  18530. const data = super.toJSON();
  18531. data.path = this.parameters.path.toJSON();
  18532. return data;
  18533. }
  18534. }
  18535. class WireframeGeometry extends BufferGeometry {
  18536. constructor(geometry) {
  18537. super();
  18538. this.type = 'WireframeGeometry';
  18539. if (geometry.isGeometry === true) {
  18540. console.error('THREE.WireframeGeometry no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  18541. return;
  18542. } // buffer
  18543. const vertices = []; // helper variables
  18544. const edge = [0, 0],
  18545. edges = {};
  18546. const vertex = new Vector3();
  18547. if (geometry.index !== null) {
  18548. // indexed BufferGeometry
  18549. const position = geometry.attributes.position;
  18550. const indices = geometry.index;
  18551. let groups = geometry.groups;
  18552. if (groups.length === 0) {
  18553. groups = [{
  18554. start: 0,
  18555. count: indices.count,
  18556. materialIndex: 0
  18557. }];
  18558. } // create a data structure that contains all eges without duplicates
  18559. for (let o = 0, ol = groups.length; o < ol; ++o) {
  18560. const group = groups[o];
  18561. const start = group.start;
  18562. const count = group.count;
  18563. for (let i = start, l = start + count; i < l; i += 3) {
  18564. for (let j = 0; j < 3; j++) {
  18565. const edge1 = indices.getX(i + j);
  18566. const edge2 = indices.getX(i + (j + 1) % 3);
  18567. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  18568. edge[1] = Math.max(edge1, edge2);
  18569. const key = edge[0] + ',' + edge[1];
  18570. if (edges[key] === undefined) {
  18571. edges[key] = {
  18572. index1: edge[0],
  18573. index2: edge[1]
  18574. };
  18575. }
  18576. }
  18577. }
  18578. } // generate vertices
  18579. for (const key in edges) {
  18580. const e = edges[key];
  18581. vertex.fromBufferAttribute(position, e.index1);
  18582. vertices.push(vertex.x, vertex.y, vertex.z);
  18583. vertex.fromBufferAttribute(position, e.index2);
  18584. vertices.push(vertex.x, vertex.y, vertex.z);
  18585. }
  18586. } else {
  18587. // non-indexed BufferGeometry
  18588. const position = geometry.attributes.position;
  18589. for (let i = 0, l = position.count / 3; i < l; i++) {
  18590. for (let j = 0; j < 3; j++) {
  18591. // three edges per triangle, an edge is represented as (index1, index2)
  18592. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  18593. const index1 = 3 * i + j;
  18594. vertex.fromBufferAttribute(position, index1);
  18595. vertices.push(vertex.x, vertex.y, vertex.z);
  18596. const index2 = 3 * i + (j + 1) % 3;
  18597. vertex.fromBufferAttribute(position, index2);
  18598. vertices.push(vertex.x, vertex.y, vertex.z);
  18599. }
  18600. }
  18601. } // build geometry
  18602. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18603. }
  18604. }
  18605. var Geometries = /*#__PURE__*/Object.freeze({
  18606. __proto__: null,
  18607. BoxGeometry: BoxGeometry,
  18608. BoxBufferGeometry: BoxGeometry,
  18609. CircleGeometry: CircleGeometry,
  18610. CircleBufferGeometry: CircleGeometry,
  18611. ConeGeometry: ConeGeometry,
  18612. ConeBufferGeometry: ConeGeometry,
  18613. CylinderGeometry: CylinderGeometry,
  18614. CylinderBufferGeometry: CylinderGeometry,
  18615. DodecahedronGeometry: DodecahedronGeometry,
  18616. DodecahedronBufferGeometry: DodecahedronGeometry,
  18617. EdgesGeometry: EdgesGeometry,
  18618. ExtrudeGeometry: ExtrudeGeometry,
  18619. ExtrudeBufferGeometry: ExtrudeGeometry,
  18620. IcosahedronGeometry: IcosahedronGeometry,
  18621. IcosahedronBufferGeometry: IcosahedronGeometry,
  18622. LatheGeometry: LatheGeometry,
  18623. LatheBufferGeometry: LatheGeometry,
  18624. OctahedronGeometry: OctahedronGeometry,
  18625. OctahedronBufferGeometry: OctahedronGeometry,
  18626. ParametricGeometry: ParametricGeometry,
  18627. ParametricBufferGeometry: ParametricGeometry,
  18628. PlaneGeometry: PlaneGeometry,
  18629. PlaneBufferGeometry: PlaneGeometry,
  18630. PolyhedronGeometry: PolyhedronGeometry,
  18631. PolyhedronBufferGeometry: PolyhedronGeometry,
  18632. RingGeometry: RingGeometry,
  18633. RingBufferGeometry: RingGeometry,
  18634. ShapeGeometry: ShapeGeometry,
  18635. ShapeBufferGeometry: ShapeGeometry,
  18636. SphereGeometry: SphereGeometry,
  18637. SphereBufferGeometry: SphereGeometry,
  18638. TetrahedronGeometry: TetrahedronGeometry,
  18639. TetrahedronBufferGeometry: TetrahedronGeometry,
  18640. TextGeometry: TextGeometry,
  18641. TextBufferGeometry: TextGeometry,
  18642. TorusGeometry: TorusGeometry,
  18643. TorusBufferGeometry: TorusGeometry,
  18644. TorusKnotGeometry: TorusKnotGeometry,
  18645. TorusKnotBufferGeometry: TorusKnotGeometry,
  18646. TubeGeometry: TubeGeometry,
  18647. TubeBufferGeometry: TubeGeometry,
  18648. WireframeGeometry: WireframeGeometry
  18649. });
  18650. /**
  18651. * parameters = {
  18652. * color: <THREE.Color>
  18653. * }
  18654. */
  18655. class ShadowMaterial extends Material {
  18656. constructor(parameters) {
  18657. super();
  18658. this.type = 'ShadowMaterial';
  18659. this.color = new Color(0x000000);
  18660. this.transparent = true;
  18661. this.setValues(parameters);
  18662. }
  18663. copy(source) {
  18664. super.copy(source);
  18665. this.color.copy(source.color);
  18666. return this;
  18667. }
  18668. }
  18669. ShadowMaterial.prototype.isShadowMaterial = true;
  18670. class RawShaderMaterial extends ShaderMaterial {
  18671. constructor(parameters) {
  18672. super(parameters);
  18673. this.type = 'RawShaderMaterial';
  18674. }
  18675. }
  18676. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  18677. /**
  18678. * parameters = {
  18679. * color: <hex>,
  18680. * roughness: <float>,
  18681. * metalness: <float>,
  18682. * opacity: <float>,
  18683. *
  18684. * map: new THREE.Texture( <Image> ),
  18685. *
  18686. * lightMap: new THREE.Texture( <Image> ),
  18687. * lightMapIntensity: <float>
  18688. *
  18689. * aoMap: new THREE.Texture( <Image> ),
  18690. * aoMapIntensity: <float>
  18691. *
  18692. * emissive: <hex>,
  18693. * emissiveIntensity: <float>
  18694. * emissiveMap: new THREE.Texture( <Image> ),
  18695. *
  18696. * bumpMap: new THREE.Texture( <Image> ),
  18697. * bumpScale: <float>,
  18698. *
  18699. * normalMap: new THREE.Texture( <Image> ),
  18700. * normalMapType: THREE.TangentSpaceNormalMap,
  18701. * normalScale: <Vector2>,
  18702. *
  18703. * displacementMap: new THREE.Texture( <Image> ),
  18704. * displacementScale: <float>,
  18705. * displacementBias: <float>,
  18706. *
  18707. * roughnessMap: new THREE.Texture( <Image> ),
  18708. *
  18709. * metalnessMap: new THREE.Texture( <Image> ),
  18710. *
  18711. * alphaMap: new THREE.Texture( <Image> ),
  18712. *
  18713. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  18714. * envMapIntensity: <float>
  18715. *
  18716. * refractionRatio: <float>,
  18717. *
  18718. * wireframe: <boolean>,
  18719. * wireframeLinewidth: <float>,
  18720. *
  18721. * morphTargets: <bool>,
  18722. * morphNormals: <bool>,
  18723. *
  18724. * flatShading: <bool>
  18725. * }
  18726. */
  18727. class MeshStandardMaterial extends Material {
  18728. constructor(parameters) {
  18729. super();
  18730. this.defines = {
  18731. 'STANDARD': ''
  18732. };
  18733. this.type = 'MeshStandardMaterial';
  18734. this.color = new Color(0xffffff); // diffuse
  18735. this.roughness = 1.0;
  18736. this.metalness = 0.0;
  18737. this.map = null;
  18738. this.lightMap = null;
  18739. this.lightMapIntensity = 1.0;
  18740. this.aoMap = null;
  18741. this.aoMapIntensity = 1.0;
  18742. this.emissive = new Color(0x000000);
  18743. this.emissiveIntensity = 1.0;
  18744. this.emissiveMap = null;
  18745. this.bumpMap = null;
  18746. this.bumpScale = 1;
  18747. this.normalMap = null;
  18748. this.normalMapType = TangentSpaceNormalMap;
  18749. this.normalScale = new Vector2(1, 1);
  18750. this.displacementMap = null;
  18751. this.displacementScale = 1;
  18752. this.displacementBias = 0;
  18753. this.roughnessMap = null;
  18754. this.metalnessMap = null;
  18755. this.alphaMap = null;
  18756. this.envMap = null;
  18757. this.envMapIntensity = 1.0;
  18758. this.refractionRatio = 0.98;
  18759. this.wireframe = false;
  18760. this.wireframeLinewidth = 1;
  18761. this.wireframeLinecap = 'round';
  18762. this.wireframeLinejoin = 'round';
  18763. this.morphTargets = false;
  18764. this.morphNormals = false;
  18765. this.flatShading = false;
  18766. this.vertexTangents = false;
  18767. this.setValues(parameters);
  18768. }
  18769. copy(source) {
  18770. super.copy(source);
  18771. this.defines = {
  18772. 'STANDARD': ''
  18773. };
  18774. this.color.copy(source.color);
  18775. this.roughness = source.roughness;
  18776. this.metalness = source.metalness;
  18777. this.map = source.map;
  18778. this.lightMap = source.lightMap;
  18779. this.lightMapIntensity = source.lightMapIntensity;
  18780. this.aoMap = source.aoMap;
  18781. this.aoMapIntensity = source.aoMapIntensity;
  18782. this.emissive.copy(source.emissive);
  18783. this.emissiveMap = source.emissiveMap;
  18784. this.emissiveIntensity = source.emissiveIntensity;
  18785. this.bumpMap = source.bumpMap;
  18786. this.bumpScale = source.bumpScale;
  18787. this.normalMap = source.normalMap;
  18788. this.normalMapType = source.normalMapType;
  18789. this.normalScale.copy(source.normalScale);
  18790. this.displacementMap = source.displacementMap;
  18791. this.displacementScale = source.displacementScale;
  18792. this.displacementBias = source.displacementBias;
  18793. this.roughnessMap = source.roughnessMap;
  18794. this.metalnessMap = source.metalnessMap;
  18795. this.alphaMap = source.alphaMap;
  18796. this.envMap = source.envMap;
  18797. this.envMapIntensity = source.envMapIntensity;
  18798. this.refractionRatio = source.refractionRatio;
  18799. this.wireframe = source.wireframe;
  18800. this.wireframeLinewidth = source.wireframeLinewidth;
  18801. this.wireframeLinecap = source.wireframeLinecap;
  18802. this.wireframeLinejoin = source.wireframeLinejoin;
  18803. this.morphTargets = source.morphTargets;
  18804. this.morphNormals = source.morphNormals;
  18805. this.flatShading = source.flatShading;
  18806. this.vertexTangents = source.vertexTangents;
  18807. return this;
  18808. }
  18809. }
  18810. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  18811. /**
  18812. * parameters = {
  18813. * clearcoat: <float>,
  18814. * clearcoatMap: new THREE.Texture( <Image> ),
  18815. * clearcoatRoughness: <float>,
  18816. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  18817. * clearcoatNormalScale: <Vector2>,
  18818. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  18819. *
  18820. * reflectivity: <float>,
  18821. * ior: <float>,
  18822. *
  18823. * sheen: <Color>,
  18824. *
  18825. * transmission: <float>,
  18826. * transmissionMap: new THREE.Texture( <Image> ),
  18827. *
  18828. * thickness: <float>,
  18829. * thicknessMap: new THREE.Texture( <Image> ),
  18830. * attenuationDistance: <float>,
  18831. * attenuationColor: <Color>
  18832. * }
  18833. */
  18834. class MeshPhysicalMaterial extends MeshStandardMaterial {
  18835. constructor(parameters) {
  18836. super();
  18837. this.defines = {
  18838. 'STANDARD': '',
  18839. 'PHYSICAL': ''
  18840. };
  18841. this.type = 'MeshPhysicalMaterial';
  18842. this.clearcoat = 0.0;
  18843. this.clearcoatMap = null;
  18844. this.clearcoatRoughness = 0.0;
  18845. this.clearcoatRoughnessMap = null;
  18846. this.clearcoatNormalScale = new Vector2(1, 1);
  18847. this.clearcoatNormalMap = null;
  18848. this.reflectivity = 0.5; // maps to F0 = 0.04
  18849. Object.defineProperty(this, 'ior', {
  18850. get: function () {
  18851. return (1 + 0.4 * this.reflectivity) / (1 - 0.4 * this.reflectivity);
  18852. },
  18853. set: function (ior) {
  18854. this.reflectivity = clamp(2.5 * (ior - 1) / (ior + 1), 0, 1);
  18855. }
  18856. });
  18857. this.sheen = null; // null will disable sheen bsdf
  18858. this.transmission = 0.0;
  18859. this.transmissionMap = null;
  18860. this.thickness = 0.01;
  18861. this.thicknessMap = null;
  18862. this.attenuationDistance = 0.0;
  18863. this.attenuationColor = new Color(1, 1, 1);
  18864. this.setValues(parameters);
  18865. }
  18866. copy(source) {
  18867. super.copy(source);
  18868. this.defines = {
  18869. 'STANDARD': '',
  18870. 'PHYSICAL': ''
  18871. };
  18872. this.clearcoat = source.clearcoat;
  18873. this.clearcoatMap = source.clearcoatMap;
  18874. this.clearcoatRoughness = source.clearcoatRoughness;
  18875. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  18876. this.clearcoatNormalMap = source.clearcoatNormalMap;
  18877. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  18878. this.reflectivity = source.reflectivity;
  18879. if (source.sheen) {
  18880. this.sheen = (this.sheen || new Color()).copy(source.sheen);
  18881. } else {
  18882. this.sheen = null;
  18883. }
  18884. this.transmission = source.transmission;
  18885. this.transmissionMap = source.transmissionMap;
  18886. this.thickness = source.thickness;
  18887. this.thicknessMap = source.thicknessMap;
  18888. this.attenuationDistance = source.attenuationDistance;
  18889. this.attenuationColor.copy(source.attenuationColor);
  18890. return this;
  18891. }
  18892. }
  18893. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  18894. /**
  18895. * parameters = {
  18896. * color: <hex>,
  18897. * specular: <hex>,
  18898. * shininess: <float>,
  18899. * opacity: <float>,
  18900. *
  18901. * map: new THREE.Texture( <Image> ),
  18902. *
  18903. * lightMap: new THREE.Texture( <Image> ),
  18904. * lightMapIntensity: <float>
  18905. *
  18906. * aoMap: new THREE.Texture( <Image> ),
  18907. * aoMapIntensity: <float>
  18908. *
  18909. * emissive: <hex>,
  18910. * emissiveIntensity: <float>
  18911. * emissiveMap: new THREE.Texture( <Image> ),
  18912. *
  18913. * bumpMap: new THREE.Texture( <Image> ),
  18914. * bumpScale: <float>,
  18915. *
  18916. * normalMap: new THREE.Texture( <Image> ),
  18917. * normalMapType: THREE.TangentSpaceNormalMap,
  18918. * normalScale: <Vector2>,
  18919. *
  18920. * displacementMap: new THREE.Texture( <Image> ),
  18921. * displacementScale: <float>,
  18922. * displacementBias: <float>,
  18923. *
  18924. * specularMap: new THREE.Texture( <Image> ),
  18925. *
  18926. * alphaMap: new THREE.Texture( <Image> ),
  18927. *
  18928. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  18929. * combine: THREE.MultiplyOperation,
  18930. * reflectivity: <float>,
  18931. * refractionRatio: <float>,
  18932. *
  18933. * wireframe: <boolean>,
  18934. * wireframeLinewidth: <float>,
  18935. *
  18936. * morphTargets: <bool>,
  18937. * morphNormals: <bool>,
  18938. *
  18939. * flatShading: <bool>
  18940. * }
  18941. */
  18942. class MeshPhongMaterial extends Material {
  18943. constructor(parameters) {
  18944. super();
  18945. this.type = 'MeshPhongMaterial';
  18946. this.color = new Color(0xffffff); // diffuse
  18947. this.specular = new Color(0x111111);
  18948. this.shininess = 30;
  18949. this.map = null;
  18950. this.lightMap = null;
  18951. this.lightMapIntensity = 1.0;
  18952. this.aoMap = null;
  18953. this.aoMapIntensity = 1.0;
  18954. this.emissive = new Color(0x000000);
  18955. this.emissiveIntensity = 1.0;
  18956. this.emissiveMap = null;
  18957. this.bumpMap = null;
  18958. this.bumpScale = 1;
  18959. this.normalMap = null;
  18960. this.normalMapType = TangentSpaceNormalMap;
  18961. this.normalScale = new Vector2(1, 1);
  18962. this.displacementMap = null;
  18963. this.displacementScale = 1;
  18964. this.displacementBias = 0;
  18965. this.specularMap = null;
  18966. this.alphaMap = null;
  18967. this.envMap = null;
  18968. this.combine = MultiplyOperation;
  18969. this.reflectivity = 1;
  18970. this.refractionRatio = 0.98;
  18971. this.wireframe = false;
  18972. this.wireframeLinewidth = 1;
  18973. this.wireframeLinecap = 'round';
  18974. this.wireframeLinejoin = 'round';
  18975. this.morphTargets = false;
  18976. this.morphNormals = false;
  18977. this.flatShading = false;
  18978. this.setValues(parameters);
  18979. }
  18980. copy(source) {
  18981. super.copy(source);
  18982. this.color.copy(source.color);
  18983. this.specular.copy(source.specular);
  18984. this.shininess = source.shininess;
  18985. this.map = source.map;
  18986. this.lightMap = source.lightMap;
  18987. this.lightMapIntensity = source.lightMapIntensity;
  18988. this.aoMap = source.aoMap;
  18989. this.aoMapIntensity = source.aoMapIntensity;
  18990. this.emissive.copy(source.emissive);
  18991. this.emissiveMap = source.emissiveMap;
  18992. this.emissiveIntensity = source.emissiveIntensity;
  18993. this.bumpMap = source.bumpMap;
  18994. this.bumpScale = source.bumpScale;
  18995. this.normalMap = source.normalMap;
  18996. this.normalMapType = source.normalMapType;
  18997. this.normalScale.copy(source.normalScale);
  18998. this.displacementMap = source.displacementMap;
  18999. this.displacementScale = source.displacementScale;
  19000. this.displacementBias = source.displacementBias;
  19001. this.specularMap = source.specularMap;
  19002. this.alphaMap = source.alphaMap;
  19003. this.envMap = source.envMap;
  19004. this.combine = source.combine;
  19005. this.reflectivity = source.reflectivity;
  19006. this.refractionRatio = source.refractionRatio;
  19007. this.wireframe = source.wireframe;
  19008. this.wireframeLinewidth = source.wireframeLinewidth;
  19009. this.wireframeLinecap = source.wireframeLinecap;
  19010. this.wireframeLinejoin = source.wireframeLinejoin;
  19011. this.morphTargets = source.morphTargets;
  19012. this.morphNormals = source.morphNormals;
  19013. this.flatShading = source.flatShading;
  19014. return this;
  19015. }
  19016. }
  19017. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  19018. /**
  19019. * parameters = {
  19020. * color: <hex>,
  19021. *
  19022. * map: new THREE.Texture( <Image> ),
  19023. * gradientMap: new THREE.Texture( <Image> ),
  19024. *
  19025. * lightMap: new THREE.Texture( <Image> ),
  19026. * lightMapIntensity: <float>
  19027. *
  19028. * aoMap: new THREE.Texture( <Image> ),
  19029. * aoMapIntensity: <float>
  19030. *
  19031. * emissive: <hex>,
  19032. * emissiveIntensity: <float>
  19033. * emissiveMap: new THREE.Texture( <Image> ),
  19034. *
  19035. * bumpMap: new THREE.Texture( <Image> ),
  19036. * bumpScale: <float>,
  19037. *
  19038. * normalMap: new THREE.Texture( <Image> ),
  19039. * normalMapType: THREE.TangentSpaceNormalMap,
  19040. * normalScale: <Vector2>,
  19041. *
  19042. * displacementMap: new THREE.Texture( <Image> ),
  19043. * displacementScale: <float>,
  19044. * displacementBias: <float>,
  19045. *
  19046. * alphaMap: new THREE.Texture( <Image> ),
  19047. *
  19048. * wireframe: <boolean>,
  19049. * wireframeLinewidth: <float>,
  19050. *
  19051. * morphTargets: <bool>,
  19052. * morphNormals: <bool>
  19053. * }
  19054. */
  19055. class MeshToonMaterial extends Material {
  19056. constructor(parameters) {
  19057. super();
  19058. this.defines = {
  19059. 'TOON': ''
  19060. };
  19061. this.type = 'MeshToonMaterial';
  19062. this.color = new Color(0xffffff);
  19063. this.map = null;
  19064. this.gradientMap = null;
  19065. this.lightMap = null;
  19066. this.lightMapIntensity = 1.0;
  19067. this.aoMap = null;
  19068. this.aoMapIntensity = 1.0;
  19069. this.emissive = new Color(0x000000);
  19070. this.emissiveIntensity = 1.0;
  19071. this.emissiveMap = null;
  19072. this.bumpMap = null;
  19073. this.bumpScale = 1;
  19074. this.normalMap = null;
  19075. this.normalMapType = TangentSpaceNormalMap;
  19076. this.normalScale = new Vector2(1, 1);
  19077. this.displacementMap = null;
  19078. this.displacementScale = 1;
  19079. this.displacementBias = 0;
  19080. this.alphaMap = null;
  19081. this.wireframe = false;
  19082. this.wireframeLinewidth = 1;
  19083. this.wireframeLinecap = 'round';
  19084. this.wireframeLinejoin = 'round';
  19085. this.morphTargets = false;
  19086. this.morphNormals = false;
  19087. this.setValues(parameters);
  19088. }
  19089. copy(source) {
  19090. super.copy(source);
  19091. this.color.copy(source.color);
  19092. this.map = source.map;
  19093. this.gradientMap = source.gradientMap;
  19094. this.lightMap = source.lightMap;
  19095. this.lightMapIntensity = source.lightMapIntensity;
  19096. this.aoMap = source.aoMap;
  19097. this.aoMapIntensity = source.aoMapIntensity;
  19098. this.emissive.copy(source.emissive);
  19099. this.emissiveMap = source.emissiveMap;
  19100. this.emissiveIntensity = source.emissiveIntensity;
  19101. this.bumpMap = source.bumpMap;
  19102. this.bumpScale = source.bumpScale;
  19103. this.normalMap = source.normalMap;
  19104. this.normalMapType = source.normalMapType;
  19105. this.normalScale.copy(source.normalScale);
  19106. this.displacementMap = source.displacementMap;
  19107. this.displacementScale = source.displacementScale;
  19108. this.displacementBias = source.displacementBias;
  19109. this.alphaMap = source.alphaMap;
  19110. this.wireframe = source.wireframe;
  19111. this.wireframeLinewidth = source.wireframeLinewidth;
  19112. this.wireframeLinecap = source.wireframeLinecap;
  19113. this.wireframeLinejoin = source.wireframeLinejoin;
  19114. this.morphTargets = source.morphTargets;
  19115. this.morphNormals = source.morphNormals;
  19116. return this;
  19117. }
  19118. }
  19119. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  19120. /**
  19121. * parameters = {
  19122. * opacity: <float>,
  19123. *
  19124. * bumpMap: new THREE.Texture( <Image> ),
  19125. * bumpScale: <float>,
  19126. *
  19127. * normalMap: new THREE.Texture( <Image> ),
  19128. * normalMapType: THREE.TangentSpaceNormalMap,
  19129. * normalScale: <Vector2>,
  19130. *
  19131. * displacementMap: new THREE.Texture( <Image> ),
  19132. * displacementScale: <float>,
  19133. * displacementBias: <float>,
  19134. *
  19135. * wireframe: <boolean>,
  19136. * wireframeLinewidth: <float>
  19137. *
  19138. * morphTargets: <bool>,
  19139. * morphNormals: <bool>,
  19140. *
  19141. * flatShading: <bool>
  19142. * }
  19143. */
  19144. class MeshNormalMaterial extends Material {
  19145. constructor(parameters) {
  19146. super();
  19147. this.type = 'MeshNormalMaterial';
  19148. this.bumpMap = null;
  19149. this.bumpScale = 1;
  19150. this.normalMap = null;
  19151. this.normalMapType = TangentSpaceNormalMap;
  19152. this.normalScale = new Vector2(1, 1);
  19153. this.displacementMap = null;
  19154. this.displacementScale = 1;
  19155. this.displacementBias = 0;
  19156. this.wireframe = false;
  19157. this.wireframeLinewidth = 1;
  19158. this.fog = false;
  19159. this.morphTargets = false;
  19160. this.morphNormals = false;
  19161. this.flatShading = false;
  19162. this.setValues(parameters);
  19163. }
  19164. copy(source) {
  19165. super.copy(source);
  19166. this.bumpMap = source.bumpMap;
  19167. this.bumpScale = source.bumpScale;
  19168. this.normalMap = source.normalMap;
  19169. this.normalMapType = source.normalMapType;
  19170. this.normalScale.copy(source.normalScale);
  19171. this.displacementMap = source.displacementMap;
  19172. this.displacementScale = source.displacementScale;
  19173. this.displacementBias = source.displacementBias;
  19174. this.wireframe = source.wireframe;
  19175. this.wireframeLinewidth = source.wireframeLinewidth;
  19176. this.morphTargets = source.morphTargets;
  19177. this.morphNormals = source.morphNormals;
  19178. this.flatShading = source.flatShading;
  19179. return this;
  19180. }
  19181. }
  19182. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  19183. /**
  19184. * parameters = {
  19185. * color: <hex>,
  19186. * opacity: <float>,
  19187. *
  19188. * map: new THREE.Texture( <Image> ),
  19189. *
  19190. * lightMap: new THREE.Texture( <Image> ),
  19191. * lightMapIntensity: <float>
  19192. *
  19193. * aoMap: new THREE.Texture( <Image> ),
  19194. * aoMapIntensity: <float>
  19195. *
  19196. * emissive: <hex>,
  19197. * emissiveIntensity: <float>
  19198. * emissiveMap: new THREE.Texture( <Image> ),
  19199. *
  19200. * specularMap: new THREE.Texture( <Image> ),
  19201. *
  19202. * alphaMap: new THREE.Texture( <Image> ),
  19203. *
  19204. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  19205. * combine: THREE.Multiply,
  19206. * reflectivity: <float>,
  19207. * refractionRatio: <float>,
  19208. *
  19209. * wireframe: <boolean>,
  19210. * wireframeLinewidth: <float>,
  19211. *
  19212. * morphTargets: <bool>,
  19213. * morphNormals: <bool>
  19214. * }
  19215. */
  19216. class MeshLambertMaterial extends Material {
  19217. constructor(parameters) {
  19218. super();
  19219. this.type = 'MeshLambertMaterial';
  19220. this.color = new Color(0xffffff); // diffuse
  19221. this.map = null;
  19222. this.lightMap = null;
  19223. this.lightMapIntensity = 1.0;
  19224. this.aoMap = null;
  19225. this.aoMapIntensity = 1.0;
  19226. this.emissive = new Color(0x000000);
  19227. this.emissiveIntensity = 1.0;
  19228. this.emissiveMap = null;
  19229. this.specularMap = null;
  19230. this.alphaMap = null;
  19231. this.envMap = null;
  19232. this.combine = MultiplyOperation;
  19233. this.reflectivity = 1;
  19234. this.refractionRatio = 0.98;
  19235. this.wireframe = false;
  19236. this.wireframeLinewidth = 1;
  19237. this.wireframeLinecap = 'round';
  19238. this.wireframeLinejoin = 'round';
  19239. this.morphTargets = false;
  19240. this.morphNormals = false;
  19241. this.setValues(parameters);
  19242. }
  19243. copy(source) {
  19244. super.copy(source);
  19245. this.color.copy(source.color);
  19246. this.map = source.map;
  19247. this.lightMap = source.lightMap;
  19248. this.lightMapIntensity = source.lightMapIntensity;
  19249. this.aoMap = source.aoMap;
  19250. this.aoMapIntensity = source.aoMapIntensity;
  19251. this.emissive.copy(source.emissive);
  19252. this.emissiveMap = source.emissiveMap;
  19253. this.emissiveIntensity = source.emissiveIntensity;
  19254. this.specularMap = source.specularMap;
  19255. this.alphaMap = source.alphaMap;
  19256. this.envMap = source.envMap;
  19257. this.combine = source.combine;
  19258. this.reflectivity = source.reflectivity;
  19259. this.refractionRatio = source.refractionRatio;
  19260. this.wireframe = source.wireframe;
  19261. this.wireframeLinewidth = source.wireframeLinewidth;
  19262. this.wireframeLinecap = source.wireframeLinecap;
  19263. this.wireframeLinejoin = source.wireframeLinejoin;
  19264. this.morphTargets = source.morphTargets;
  19265. this.morphNormals = source.morphNormals;
  19266. return this;
  19267. }
  19268. }
  19269. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  19270. /**
  19271. * parameters = {
  19272. * color: <hex>,
  19273. * opacity: <float>,
  19274. *
  19275. * matcap: new THREE.Texture( <Image> ),
  19276. *
  19277. * map: new THREE.Texture( <Image> ),
  19278. *
  19279. * bumpMap: new THREE.Texture( <Image> ),
  19280. * bumpScale: <float>,
  19281. *
  19282. * normalMap: new THREE.Texture( <Image> ),
  19283. * normalMapType: THREE.TangentSpaceNormalMap,
  19284. * normalScale: <Vector2>,
  19285. *
  19286. * displacementMap: new THREE.Texture( <Image> ),
  19287. * displacementScale: <float>,
  19288. * displacementBias: <float>,
  19289. *
  19290. * alphaMap: new THREE.Texture( <Image> ),
  19291. *
  19292. * morphTargets: <bool>,
  19293. * morphNormals: <bool>
  19294. *
  19295. * flatShading: <bool>
  19296. * }
  19297. */
  19298. class MeshMatcapMaterial extends Material {
  19299. constructor(parameters) {
  19300. super();
  19301. this.defines = {
  19302. 'MATCAP': ''
  19303. };
  19304. this.type = 'MeshMatcapMaterial';
  19305. this.color = new Color(0xffffff); // diffuse
  19306. this.matcap = null;
  19307. this.map = null;
  19308. this.bumpMap = null;
  19309. this.bumpScale = 1;
  19310. this.normalMap = null;
  19311. this.normalMapType = TangentSpaceNormalMap;
  19312. this.normalScale = new Vector2(1, 1);
  19313. this.displacementMap = null;
  19314. this.displacementScale = 1;
  19315. this.displacementBias = 0;
  19316. this.alphaMap = null;
  19317. this.morphTargets = false;
  19318. this.morphNormals = false;
  19319. this.flatShading = false;
  19320. this.setValues(parameters);
  19321. }
  19322. copy(source) {
  19323. super.copy(source);
  19324. this.defines = {
  19325. 'MATCAP': ''
  19326. };
  19327. this.color.copy(source.color);
  19328. this.matcap = source.matcap;
  19329. this.map = source.map;
  19330. this.bumpMap = source.bumpMap;
  19331. this.bumpScale = source.bumpScale;
  19332. this.normalMap = source.normalMap;
  19333. this.normalMapType = source.normalMapType;
  19334. this.normalScale.copy(source.normalScale);
  19335. this.displacementMap = source.displacementMap;
  19336. this.displacementScale = source.displacementScale;
  19337. this.displacementBias = source.displacementBias;
  19338. this.alphaMap = source.alphaMap;
  19339. this.morphTargets = source.morphTargets;
  19340. this.morphNormals = source.morphNormals;
  19341. this.flatShading = source.flatShading;
  19342. return this;
  19343. }
  19344. }
  19345. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  19346. /**
  19347. * parameters = {
  19348. * color: <hex>,
  19349. * opacity: <float>,
  19350. *
  19351. * linewidth: <float>,
  19352. *
  19353. * scale: <float>,
  19354. * dashSize: <float>,
  19355. * gapSize: <float>
  19356. * }
  19357. */
  19358. class LineDashedMaterial extends LineBasicMaterial {
  19359. constructor(parameters) {
  19360. super();
  19361. this.type = 'LineDashedMaterial';
  19362. this.scale = 1;
  19363. this.dashSize = 3;
  19364. this.gapSize = 1;
  19365. this.setValues(parameters);
  19366. }
  19367. copy(source) {
  19368. super.copy(source);
  19369. this.scale = source.scale;
  19370. this.dashSize = source.dashSize;
  19371. this.gapSize = source.gapSize;
  19372. return this;
  19373. }
  19374. }
  19375. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  19376. var Materials = /*#__PURE__*/Object.freeze({
  19377. __proto__: null,
  19378. ShadowMaterial: ShadowMaterial,
  19379. SpriteMaterial: SpriteMaterial,
  19380. RawShaderMaterial: RawShaderMaterial,
  19381. ShaderMaterial: ShaderMaterial,
  19382. PointsMaterial: PointsMaterial,
  19383. MeshPhysicalMaterial: MeshPhysicalMaterial,
  19384. MeshStandardMaterial: MeshStandardMaterial,
  19385. MeshPhongMaterial: MeshPhongMaterial,
  19386. MeshToonMaterial: MeshToonMaterial,
  19387. MeshNormalMaterial: MeshNormalMaterial,
  19388. MeshLambertMaterial: MeshLambertMaterial,
  19389. MeshDepthMaterial: MeshDepthMaterial,
  19390. MeshDistanceMaterial: MeshDistanceMaterial,
  19391. MeshBasicMaterial: MeshBasicMaterial,
  19392. MeshMatcapMaterial: MeshMatcapMaterial,
  19393. LineDashedMaterial: LineDashedMaterial,
  19394. LineBasicMaterial: LineBasicMaterial,
  19395. Material: Material
  19396. });
  19397. const AnimationUtils = {
  19398. // same as Array.prototype.slice, but also works on typed arrays
  19399. arraySlice: function (array, from, to) {
  19400. if (AnimationUtils.isTypedArray(array)) {
  19401. // in ios9 array.subarray(from, undefined) will return empty array
  19402. // but array.subarray(from) or array.subarray(from, len) is correct
  19403. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  19404. }
  19405. return array.slice(from, to);
  19406. },
  19407. // converts an array to a specific type
  19408. convertArray: function (array, type, forceClone) {
  19409. if (!array || // let 'undefined' and 'null' pass
  19410. !forceClone && array.constructor === type) return array;
  19411. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  19412. return new type(array); // create typed array
  19413. }
  19414. return Array.prototype.slice.call(array); // create Array
  19415. },
  19416. isTypedArray: function (object) {
  19417. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  19418. },
  19419. // returns an array by which times and values can be sorted
  19420. getKeyframeOrder: function (times) {
  19421. function compareTime(i, j) {
  19422. return times[i] - times[j];
  19423. }
  19424. const n = times.length;
  19425. const result = new Array(n);
  19426. for (let i = 0; i !== n; ++i) result[i] = i;
  19427. result.sort(compareTime);
  19428. return result;
  19429. },
  19430. // uses the array previously returned by 'getKeyframeOrder' to sort data
  19431. sortedArray: function (values, stride, order) {
  19432. const nValues = values.length;
  19433. const result = new values.constructor(nValues);
  19434. for (let i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  19435. const srcOffset = order[i] * stride;
  19436. for (let j = 0; j !== stride; ++j) {
  19437. result[dstOffset++] = values[srcOffset + j];
  19438. }
  19439. }
  19440. return result;
  19441. },
  19442. // function for parsing AOS keyframe formats
  19443. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  19444. let i = 1,
  19445. key = jsonKeys[0];
  19446. while (key !== undefined && key[valuePropertyName] === undefined) {
  19447. key = jsonKeys[i++];
  19448. }
  19449. if (key === undefined) return; // no data
  19450. let value = key[valuePropertyName];
  19451. if (value === undefined) return; // no data
  19452. if (Array.isArray(value)) {
  19453. do {
  19454. value = key[valuePropertyName];
  19455. if (value !== undefined) {
  19456. times.push(key.time);
  19457. values.push.apply(values, value); // push all elements
  19458. }
  19459. key = jsonKeys[i++];
  19460. } while (key !== undefined);
  19461. } else if (value.toArray !== undefined) {
  19462. // ...assume THREE.Math-ish
  19463. do {
  19464. value = key[valuePropertyName];
  19465. if (value !== undefined) {
  19466. times.push(key.time);
  19467. value.toArray(values, values.length);
  19468. }
  19469. key = jsonKeys[i++];
  19470. } while (key !== undefined);
  19471. } else {
  19472. // otherwise push as-is
  19473. do {
  19474. value = key[valuePropertyName];
  19475. if (value !== undefined) {
  19476. times.push(key.time);
  19477. values.push(value);
  19478. }
  19479. key = jsonKeys[i++];
  19480. } while (key !== undefined);
  19481. }
  19482. },
  19483. subclip: function (sourceClip, name, startFrame, endFrame, fps = 30) {
  19484. const clip = sourceClip.clone();
  19485. clip.name = name;
  19486. const tracks = [];
  19487. for (let i = 0; i < clip.tracks.length; ++i) {
  19488. const track = clip.tracks[i];
  19489. const valueSize = track.getValueSize();
  19490. const times = [];
  19491. const values = [];
  19492. for (let j = 0; j < track.times.length; ++j) {
  19493. const frame = track.times[j] * fps;
  19494. if (frame < startFrame || frame >= endFrame) continue;
  19495. times.push(track.times[j]);
  19496. for (let k = 0; k < valueSize; ++k) {
  19497. values.push(track.values[j * valueSize + k]);
  19498. }
  19499. }
  19500. if (times.length === 0) continue;
  19501. track.times = AnimationUtils.convertArray(times, track.times.constructor);
  19502. track.values = AnimationUtils.convertArray(values, track.values.constructor);
  19503. tracks.push(track);
  19504. }
  19505. clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
  19506. let minStartTime = Infinity;
  19507. for (let i = 0; i < clip.tracks.length; ++i) {
  19508. if (minStartTime > clip.tracks[i].times[0]) {
  19509. minStartTime = clip.tracks[i].times[0];
  19510. }
  19511. } // shift all tracks such that clip begins at t=0
  19512. for (let i = 0; i < clip.tracks.length; ++i) {
  19513. clip.tracks[i].shift(-1 * minStartTime);
  19514. }
  19515. clip.resetDuration();
  19516. return clip;
  19517. },
  19518. makeClipAdditive: function (targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) {
  19519. if (fps <= 0) fps = 30;
  19520. const numTracks = referenceClip.tracks.length;
  19521. const referenceTime = referenceFrame / fps; // Make each track's values relative to the values at the reference frame
  19522. for (let i = 0; i < numTracks; ++i) {
  19523. const referenceTrack = referenceClip.tracks[i];
  19524. const referenceTrackType = referenceTrack.ValueTypeName; // Skip this track if it's non-numeric
  19525. if (referenceTrackType === 'bool' || referenceTrackType === 'string') continue; // Find the track in the target clip whose name and type matches the reference track
  19526. const targetTrack = targetClip.tracks.find(function (track) {
  19527. return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
  19528. });
  19529. if (targetTrack === undefined) continue;
  19530. let referenceOffset = 0;
  19531. const referenceValueSize = referenceTrack.getValueSize();
  19532. if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  19533. referenceOffset = referenceValueSize / 3;
  19534. }
  19535. let targetOffset = 0;
  19536. const targetValueSize = targetTrack.getValueSize();
  19537. if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  19538. targetOffset = targetValueSize / 3;
  19539. }
  19540. const lastIndex = referenceTrack.times.length - 1;
  19541. let referenceValue; // Find the value to subtract out of the track
  19542. if (referenceTime <= referenceTrack.times[0]) {
  19543. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  19544. const startIndex = referenceOffset;
  19545. const endIndex = referenceValueSize - referenceOffset;
  19546. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  19547. } else if (referenceTime >= referenceTrack.times[lastIndex]) {
  19548. // Reference frame is after the last keyframe, so just use the last keyframe
  19549. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  19550. const endIndex = startIndex + referenceValueSize - referenceOffset;
  19551. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  19552. } else {
  19553. // Interpolate to the reference value
  19554. const interpolant = referenceTrack.createInterpolant();
  19555. const startIndex = referenceOffset;
  19556. const endIndex = referenceValueSize - referenceOffset;
  19557. interpolant.evaluate(referenceTime);
  19558. referenceValue = AnimationUtils.arraySlice(interpolant.resultBuffer, startIndex, endIndex);
  19559. } // Conjugate the quaternion
  19560. if (referenceTrackType === 'quaternion') {
  19561. const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
  19562. referenceQuat.toArray(referenceValue);
  19563. } // Subtract the reference value from all of the track values
  19564. const numTimes = targetTrack.times.length;
  19565. for (let j = 0; j < numTimes; ++j) {
  19566. const valueStart = j * targetValueSize + targetOffset;
  19567. if (referenceTrackType === 'quaternion') {
  19568. // Multiply the conjugate for quaternion track types
  19569. Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
  19570. } else {
  19571. const valueEnd = targetValueSize - targetOffset * 2; // Subtract each value for all other numeric track types
  19572. for (let k = 0; k < valueEnd; ++k) {
  19573. targetTrack.values[valueStart + k] -= referenceValue[k];
  19574. }
  19575. }
  19576. }
  19577. }
  19578. targetClip.blendMode = AdditiveAnimationBlendMode;
  19579. return targetClip;
  19580. }
  19581. };
  19582. /**
  19583. * Abstract base class of interpolants over parametric samples.
  19584. *
  19585. * The parameter domain is one dimensional, typically the time or a path
  19586. * along a curve defined by the data.
  19587. *
  19588. * The sample values can have any dimensionality and derived classes may
  19589. * apply special interpretations to the data.
  19590. *
  19591. * This class provides the interval seek in a Template Method, deferring
  19592. * the actual interpolation to derived classes.
  19593. *
  19594. * Time complexity is O(1) for linear access crossing at most two points
  19595. * and O(log N) for random access, where N is the number of positions.
  19596. *
  19597. * References:
  19598. *
  19599. * http://www.oodesign.com/template-method-pattern.html
  19600. *
  19601. */
  19602. class Interpolant {
  19603. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  19604. this.parameterPositions = parameterPositions;
  19605. this._cachedIndex = 0;
  19606. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  19607. this.sampleValues = sampleValues;
  19608. this.valueSize = sampleSize;
  19609. this.settings = null;
  19610. this.DefaultSettings_ = {};
  19611. }
  19612. evaluate(t) {
  19613. const pp = this.parameterPositions;
  19614. let i1 = this._cachedIndex,
  19615. t1 = pp[i1],
  19616. t0 = pp[i1 - 1];
  19617. validate_interval: {
  19618. seek: {
  19619. let right;
  19620. linear_scan: {
  19621. //- See http://jsperf.com/comparison-to-undefined/3
  19622. //- slower code:
  19623. //-
  19624. //- if ( t >= t1 || t1 === undefined ) {
  19625. forward_scan: if (!(t < t1)) {
  19626. for (let giveUpAt = i1 + 2;;) {
  19627. if (t1 === undefined) {
  19628. if (t < t0) break forward_scan; // after end
  19629. i1 = pp.length;
  19630. this._cachedIndex = i1;
  19631. return this.afterEnd_(i1 - 1, t, t0);
  19632. }
  19633. if (i1 === giveUpAt) break; // this loop
  19634. t0 = t1;
  19635. t1 = pp[++i1];
  19636. if (t < t1) {
  19637. // we have arrived at the sought interval
  19638. break seek;
  19639. }
  19640. } // prepare binary search on the right side of the index
  19641. right = pp.length;
  19642. break linear_scan;
  19643. } //- slower code:
  19644. //- if ( t < t0 || t0 === undefined ) {
  19645. if (!(t >= t0)) {
  19646. // looping?
  19647. const t1global = pp[1];
  19648. if (t < t1global) {
  19649. i1 = 2; // + 1, using the scan for the details
  19650. t0 = t1global;
  19651. } // linear reverse scan
  19652. for (let giveUpAt = i1 - 2;;) {
  19653. if (t0 === undefined) {
  19654. // before start
  19655. this._cachedIndex = 0;
  19656. return this.beforeStart_(0, t, t1);
  19657. }
  19658. if (i1 === giveUpAt) break; // this loop
  19659. t1 = t0;
  19660. t0 = pp[--i1 - 1];
  19661. if (t >= t0) {
  19662. // we have arrived at the sought interval
  19663. break seek;
  19664. }
  19665. } // prepare binary search on the left side of the index
  19666. right = i1;
  19667. i1 = 0;
  19668. break linear_scan;
  19669. } // the interval is valid
  19670. break validate_interval;
  19671. } // linear scan
  19672. // binary search
  19673. while (i1 < right) {
  19674. const mid = i1 + right >>> 1;
  19675. if (t < pp[mid]) {
  19676. right = mid;
  19677. } else {
  19678. i1 = mid + 1;
  19679. }
  19680. }
  19681. t1 = pp[i1];
  19682. t0 = pp[i1 - 1]; // check boundary cases, again
  19683. if (t0 === undefined) {
  19684. this._cachedIndex = 0;
  19685. return this.beforeStart_(0, t, t1);
  19686. }
  19687. if (t1 === undefined) {
  19688. i1 = pp.length;
  19689. this._cachedIndex = i1;
  19690. return this.afterEnd_(i1 - 1, t0, t);
  19691. }
  19692. } // seek
  19693. this._cachedIndex = i1;
  19694. this.intervalChanged_(i1, t0, t1);
  19695. } // validate_interval
  19696. return this.interpolate_(i1, t0, t, t1);
  19697. }
  19698. getSettings_() {
  19699. return this.settings || this.DefaultSettings_;
  19700. }
  19701. copySampleValue_(index) {
  19702. // copies a sample value to the result buffer
  19703. const result = this.resultBuffer,
  19704. values = this.sampleValues,
  19705. stride = this.valueSize,
  19706. offset = index * stride;
  19707. for (let i = 0; i !== stride; ++i) {
  19708. result[i] = values[offset + i];
  19709. }
  19710. return result;
  19711. } // Template methods for derived classes:
  19712. interpolate_()
  19713. /* i1, t0, t, t1 */
  19714. {
  19715. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  19716. }
  19717. intervalChanged_()
  19718. /* i1, t0, t1 */
  19719. {// empty
  19720. }
  19721. } // ALIAS DEFINITIONS
  19722. Interpolant.prototype.beforeStart_ = Interpolant.prototype.copySampleValue_;
  19723. Interpolant.prototype.afterEnd_ = Interpolant.prototype.copySampleValue_;
  19724. /**
  19725. * Fast and simple cubic spline interpolant.
  19726. *
  19727. * It was derived from a Hermitian construction setting the first derivative
  19728. * at each sample position to the linear slope between neighboring positions
  19729. * over their parameter interval.
  19730. */
  19731. class CubicInterpolant extends Interpolant {
  19732. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  19733. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  19734. this._weightPrev = -0;
  19735. this._offsetPrev = -0;
  19736. this._weightNext = -0;
  19737. this._offsetNext = -0;
  19738. this.DefaultSettings_ = {
  19739. endingStart: ZeroCurvatureEnding,
  19740. endingEnd: ZeroCurvatureEnding
  19741. };
  19742. }
  19743. intervalChanged_(i1, t0, t1) {
  19744. const pp = this.parameterPositions;
  19745. let iPrev = i1 - 2,
  19746. iNext = i1 + 1,
  19747. tPrev = pp[iPrev],
  19748. tNext = pp[iNext];
  19749. if (tPrev === undefined) {
  19750. switch (this.getSettings_().endingStart) {
  19751. case ZeroSlopeEnding:
  19752. // f'(t0) = 0
  19753. iPrev = i1;
  19754. tPrev = 2 * t0 - t1;
  19755. break;
  19756. case WrapAroundEnding:
  19757. // use the other end of the curve
  19758. iPrev = pp.length - 2;
  19759. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  19760. break;
  19761. default:
  19762. // ZeroCurvatureEnding
  19763. // f''(t0) = 0 a.k.a. Natural Spline
  19764. iPrev = i1;
  19765. tPrev = t1;
  19766. }
  19767. }
  19768. if (tNext === undefined) {
  19769. switch (this.getSettings_().endingEnd) {
  19770. case ZeroSlopeEnding:
  19771. // f'(tN) = 0
  19772. iNext = i1;
  19773. tNext = 2 * t1 - t0;
  19774. break;
  19775. case WrapAroundEnding:
  19776. // use the other end of the curve
  19777. iNext = 1;
  19778. tNext = t1 + pp[1] - pp[0];
  19779. break;
  19780. default:
  19781. // ZeroCurvatureEnding
  19782. // f''(tN) = 0, a.k.a. Natural Spline
  19783. iNext = i1 - 1;
  19784. tNext = t0;
  19785. }
  19786. }
  19787. const halfDt = (t1 - t0) * 0.5,
  19788. stride = this.valueSize;
  19789. this._weightPrev = halfDt / (t0 - tPrev);
  19790. this._weightNext = halfDt / (tNext - t1);
  19791. this._offsetPrev = iPrev * stride;
  19792. this._offsetNext = iNext * stride;
  19793. }
  19794. interpolate_(i1, t0, t, t1) {
  19795. const result = this.resultBuffer,
  19796. values = this.sampleValues,
  19797. stride = this.valueSize,
  19798. o1 = i1 * stride,
  19799. o0 = o1 - stride,
  19800. oP = this._offsetPrev,
  19801. oN = this._offsetNext,
  19802. wP = this._weightPrev,
  19803. wN = this._weightNext,
  19804. p = (t - t0) / (t1 - t0),
  19805. pp = p * p,
  19806. ppp = pp * p; // evaluate polynomials
  19807. const sP = -wP * ppp + 2 * wP * pp - wP * p;
  19808. const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  19809. const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  19810. const sN = wN * ppp - wN * pp; // combine data linearly
  19811. for (let i = 0; i !== stride; ++i) {
  19812. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  19813. }
  19814. return result;
  19815. }
  19816. }
  19817. class LinearInterpolant extends Interpolant {
  19818. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  19819. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  19820. }
  19821. interpolate_(i1, t0, t, t1) {
  19822. const result = this.resultBuffer,
  19823. values = this.sampleValues,
  19824. stride = this.valueSize,
  19825. offset1 = i1 * stride,
  19826. offset0 = offset1 - stride,
  19827. weight1 = (t - t0) / (t1 - t0),
  19828. weight0 = 1 - weight1;
  19829. for (let i = 0; i !== stride; ++i) {
  19830. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  19831. }
  19832. return result;
  19833. }
  19834. }
  19835. /**
  19836. *
  19837. * Interpolant that evaluates to the sample value at the position preceeding
  19838. * the parameter.
  19839. */
  19840. class DiscreteInterpolant extends Interpolant {
  19841. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  19842. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  19843. }
  19844. interpolate_(i1
  19845. /*, t0, t, t1 */
  19846. ) {
  19847. return this.copySampleValue_(i1 - 1);
  19848. }
  19849. }
  19850. class KeyframeTrack {
  19851. constructor(name, times, values, interpolation) {
  19852. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  19853. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  19854. this.name = name;
  19855. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  19856. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  19857. this.setInterpolation(interpolation || this.DefaultInterpolation);
  19858. } // Serialization (in static context, because of constructor invocation
  19859. // and automatic invocation of .toJSON):
  19860. static toJSON(track) {
  19861. const trackType = track.constructor;
  19862. let json; // derived classes can define a static toJSON method
  19863. if (trackType.toJSON !== this.toJSON) {
  19864. json = trackType.toJSON(track);
  19865. } else {
  19866. // by default, we assume the data can be serialized as-is
  19867. json = {
  19868. 'name': track.name,
  19869. 'times': AnimationUtils.convertArray(track.times, Array),
  19870. 'values': AnimationUtils.convertArray(track.values, Array)
  19871. };
  19872. const interpolation = track.getInterpolation();
  19873. if (interpolation !== track.DefaultInterpolation) {
  19874. json.interpolation = interpolation;
  19875. }
  19876. }
  19877. json.type = track.ValueTypeName; // mandatory
  19878. return json;
  19879. }
  19880. InterpolantFactoryMethodDiscrete(result) {
  19881. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  19882. }
  19883. InterpolantFactoryMethodLinear(result) {
  19884. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  19885. }
  19886. InterpolantFactoryMethodSmooth(result) {
  19887. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  19888. }
  19889. setInterpolation(interpolation) {
  19890. let factoryMethod;
  19891. switch (interpolation) {
  19892. case InterpolateDiscrete:
  19893. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  19894. break;
  19895. case InterpolateLinear:
  19896. factoryMethod = this.InterpolantFactoryMethodLinear;
  19897. break;
  19898. case InterpolateSmooth:
  19899. factoryMethod = this.InterpolantFactoryMethodSmooth;
  19900. break;
  19901. }
  19902. if (factoryMethod === undefined) {
  19903. const message = 'unsupported interpolation for ' + this.ValueTypeName + ' keyframe track named ' + this.name;
  19904. if (this.createInterpolant === undefined) {
  19905. // fall back to default, unless the default itself is messed up
  19906. if (interpolation !== this.DefaultInterpolation) {
  19907. this.setInterpolation(this.DefaultInterpolation);
  19908. } else {
  19909. throw new Error(message); // fatal, in this case
  19910. }
  19911. }
  19912. console.warn('THREE.KeyframeTrack:', message);
  19913. return this;
  19914. }
  19915. this.createInterpolant = factoryMethod;
  19916. return this;
  19917. }
  19918. getInterpolation() {
  19919. switch (this.createInterpolant) {
  19920. case this.InterpolantFactoryMethodDiscrete:
  19921. return InterpolateDiscrete;
  19922. case this.InterpolantFactoryMethodLinear:
  19923. return InterpolateLinear;
  19924. case this.InterpolantFactoryMethodSmooth:
  19925. return InterpolateSmooth;
  19926. }
  19927. }
  19928. getValueSize() {
  19929. return this.values.length / this.times.length;
  19930. } // move all keyframes either forwards or backwards in time
  19931. shift(timeOffset) {
  19932. if (timeOffset !== 0.0) {
  19933. const times = this.times;
  19934. for (let i = 0, n = times.length; i !== n; ++i) {
  19935. times[i] += timeOffset;
  19936. }
  19937. }
  19938. return this;
  19939. } // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  19940. scale(timeScale) {
  19941. if (timeScale !== 1.0) {
  19942. const times = this.times;
  19943. for (let i = 0, n = times.length; i !== n; ++i) {
  19944. times[i] *= timeScale;
  19945. }
  19946. }
  19947. return this;
  19948. } // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  19949. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  19950. trim(startTime, endTime) {
  19951. const times = this.times,
  19952. nKeys = times.length;
  19953. let from = 0,
  19954. to = nKeys - 1;
  19955. while (from !== nKeys && times[from] < startTime) {
  19956. ++from;
  19957. }
  19958. while (to !== -1 && times[to] > endTime) {
  19959. --to;
  19960. }
  19961. ++to; // inclusive -> exclusive bound
  19962. if (from !== 0 || to !== nKeys) {
  19963. // empty tracks are forbidden, so keep at least one keyframe
  19964. if (from >= to) {
  19965. to = Math.max(to, 1);
  19966. from = to - 1;
  19967. }
  19968. const stride = this.getValueSize();
  19969. this.times = AnimationUtils.arraySlice(times, from, to);
  19970. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  19971. }
  19972. return this;
  19973. } // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  19974. validate() {
  19975. let valid = true;
  19976. const valueSize = this.getValueSize();
  19977. if (valueSize - Math.floor(valueSize) !== 0) {
  19978. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  19979. valid = false;
  19980. }
  19981. const times = this.times,
  19982. values = this.values,
  19983. nKeys = times.length;
  19984. if (nKeys === 0) {
  19985. console.error('THREE.KeyframeTrack: Track is empty.', this);
  19986. valid = false;
  19987. }
  19988. let prevTime = null;
  19989. for (let i = 0; i !== nKeys; i++) {
  19990. const currTime = times[i];
  19991. if (typeof currTime === 'number' && isNaN(currTime)) {
  19992. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  19993. valid = false;
  19994. break;
  19995. }
  19996. if (prevTime !== null && prevTime > currTime) {
  19997. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  19998. valid = false;
  19999. break;
  20000. }
  20001. prevTime = currTime;
  20002. }
  20003. if (values !== undefined) {
  20004. if (AnimationUtils.isTypedArray(values)) {
  20005. for (let i = 0, n = values.length; i !== n; ++i) {
  20006. const value = values[i];
  20007. if (isNaN(value)) {
  20008. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  20009. valid = false;
  20010. break;
  20011. }
  20012. }
  20013. }
  20014. }
  20015. return valid;
  20016. } // removes equivalent sequential keys as common in morph target sequences
  20017. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  20018. optimize() {
  20019. // times or values may be shared with other tracks, so overwriting is unsafe
  20020. const times = AnimationUtils.arraySlice(this.times),
  20021. values = AnimationUtils.arraySlice(this.values),
  20022. stride = this.getValueSize(),
  20023. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  20024. lastIndex = times.length - 1;
  20025. let writeIndex = 1;
  20026. for (let i = 1; i < lastIndex; ++i) {
  20027. let keep = false;
  20028. const time = times[i];
  20029. const timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  20030. if (time !== timeNext && (i !== 1 || time !== times[0])) {
  20031. if (!smoothInterpolation) {
  20032. // remove unnecessary keyframes same as their neighbors
  20033. const offset = i * stride,
  20034. offsetP = offset - stride,
  20035. offsetN = offset + stride;
  20036. for (let j = 0; j !== stride; ++j) {
  20037. const value = values[offset + j];
  20038. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  20039. keep = true;
  20040. break;
  20041. }
  20042. }
  20043. } else {
  20044. keep = true;
  20045. }
  20046. } // in-place compaction
  20047. if (keep) {
  20048. if (i !== writeIndex) {
  20049. times[writeIndex] = times[i];
  20050. const readOffset = i * stride,
  20051. writeOffset = writeIndex * stride;
  20052. for (let j = 0; j !== stride; ++j) {
  20053. values[writeOffset + j] = values[readOffset + j];
  20054. }
  20055. }
  20056. ++writeIndex;
  20057. }
  20058. } // flush last keyframe (compaction looks ahead)
  20059. if (lastIndex > 0) {
  20060. times[writeIndex] = times[lastIndex];
  20061. for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  20062. values[writeOffset + j] = values[readOffset + j];
  20063. }
  20064. ++writeIndex;
  20065. }
  20066. if (writeIndex !== times.length) {
  20067. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  20068. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  20069. } else {
  20070. this.times = times;
  20071. this.values = values;
  20072. }
  20073. return this;
  20074. }
  20075. clone() {
  20076. const times = AnimationUtils.arraySlice(this.times, 0);
  20077. const values = AnimationUtils.arraySlice(this.values, 0);
  20078. const TypedKeyframeTrack = this.constructor;
  20079. const track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  20080. track.createInterpolant = this.createInterpolant;
  20081. return track;
  20082. }
  20083. }
  20084. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  20085. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  20086. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  20087. /**
  20088. * A Track of Boolean keyframe values.
  20089. */
  20090. class BooleanKeyframeTrack extends KeyframeTrack {}
  20091. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  20092. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  20093. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  20094. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  20095. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; // Note: Actually this track could have a optimized / compressed
  20096. /**
  20097. * A Track of keyframe values that represent color.
  20098. */
  20099. class ColorKeyframeTrack extends KeyframeTrack {}
  20100. ColorKeyframeTrack.prototype.ValueTypeName = 'color'; // ValueBufferType is inherited
  20101. /**
  20102. * A Track of numeric keyframe values.
  20103. */
  20104. class NumberKeyframeTrack extends KeyframeTrack {}
  20105. NumberKeyframeTrack.prototype.ValueTypeName = 'number'; // ValueBufferType is inherited
  20106. /**
  20107. * Spherical linear unit quaternion interpolant.
  20108. */
  20109. class QuaternionLinearInterpolant extends Interpolant {
  20110. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  20111. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  20112. }
  20113. interpolate_(i1, t0, t, t1) {
  20114. const result = this.resultBuffer,
  20115. values = this.sampleValues,
  20116. stride = this.valueSize,
  20117. alpha = (t - t0) / (t1 - t0);
  20118. let offset = i1 * stride;
  20119. for (let end = offset + stride; offset !== end; offset += 4) {
  20120. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  20121. }
  20122. return result;
  20123. }
  20124. }
  20125. /**
  20126. * A Track of quaternion keyframe values.
  20127. */
  20128. class QuaternionKeyframeTrack extends KeyframeTrack {
  20129. InterpolantFactoryMethodLinear(result) {
  20130. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  20131. }
  20132. }
  20133. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion'; // ValueBufferType is inherited
  20134. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  20135. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  20136. /**
  20137. * A Track that interpolates Strings
  20138. */
  20139. class StringKeyframeTrack extends KeyframeTrack {}
  20140. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  20141. StringKeyframeTrack.prototype.ValueBufferType = Array;
  20142. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  20143. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  20144. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  20145. /**
  20146. * A Track of vectored keyframe values.
  20147. */
  20148. class VectorKeyframeTrack extends KeyframeTrack {}
  20149. VectorKeyframeTrack.prototype.ValueTypeName = 'vector'; // ValueBufferType is inherited
  20150. class AnimationClip {
  20151. constructor(name, duration = -1, tracks, blendMode = NormalAnimationBlendMode) {
  20152. this.name = name;
  20153. this.tracks = tracks;
  20154. this.duration = duration;
  20155. this.blendMode = blendMode;
  20156. this.uuid = generateUUID(); // this means it should figure out its duration by scanning the tracks
  20157. if (this.duration < 0) {
  20158. this.resetDuration();
  20159. }
  20160. }
  20161. static parse(json) {
  20162. const tracks = [],
  20163. jsonTracks = json.tracks,
  20164. frameTime = 1.0 / (json.fps || 1.0);
  20165. for (let i = 0, n = jsonTracks.length; i !== n; ++i) {
  20166. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  20167. }
  20168. const clip = new this(json.name, json.duration, tracks, json.blendMode);
  20169. clip.uuid = json.uuid;
  20170. return clip;
  20171. }
  20172. static toJSON(clip) {
  20173. const tracks = [],
  20174. clipTracks = clip.tracks;
  20175. const json = {
  20176. 'name': clip.name,
  20177. 'duration': clip.duration,
  20178. 'tracks': tracks,
  20179. 'uuid': clip.uuid,
  20180. 'blendMode': clip.blendMode
  20181. };
  20182. for (let i = 0, n = clipTracks.length; i !== n; ++i) {
  20183. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  20184. }
  20185. return json;
  20186. }
  20187. static CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) {
  20188. const numMorphTargets = morphTargetSequence.length;
  20189. const tracks = [];
  20190. for (let i = 0; i < numMorphTargets; i++) {
  20191. let times = [];
  20192. let values = [];
  20193. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  20194. values.push(0, 1, 0);
  20195. const order = AnimationUtils.getKeyframeOrder(times);
  20196. times = AnimationUtils.sortedArray(times, 1, order);
  20197. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  20198. // last frame as well for perfect loop.
  20199. if (!noLoop && times[0] === 0) {
  20200. times.push(numMorphTargets);
  20201. values.push(values[0]);
  20202. }
  20203. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  20204. }
  20205. return new this(name, -1, tracks);
  20206. }
  20207. static findByName(objectOrClipArray, name) {
  20208. let clipArray = objectOrClipArray;
  20209. if (!Array.isArray(objectOrClipArray)) {
  20210. const o = objectOrClipArray;
  20211. clipArray = o.geometry && o.geometry.animations || o.animations;
  20212. }
  20213. for (let i = 0; i < clipArray.length; i++) {
  20214. if (clipArray[i].name === name) {
  20215. return clipArray[i];
  20216. }
  20217. }
  20218. return null;
  20219. }
  20220. static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {
  20221. const animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  20222. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  20223. const pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  20224. // patterns like Walk_001, Walk_002, Run_001, Run_002
  20225. for (let i = 0, il = morphTargets.length; i < il; i++) {
  20226. const morphTarget = morphTargets[i];
  20227. const parts = morphTarget.name.match(pattern);
  20228. if (parts && parts.length > 1) {
  20229. const name = parts[1];
  20230. let animationMorphTargets = animationToMorphTargets[name];
  20231. if (!animationMorphTargets) {
  20232. animationToMorphTargets[name] = animationMorphTargets = [];
  20233. }
  20234. animationMorphTargets.push(morphTarget);
  20235. }
  20236. }
  20237. const clips = [];
  20238. for (const name in animationToMorphTargets) {
  20239. clips.push(this.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  20240. }
  20241. return clips;
  20242. } // parse the animation.hierarchy format
  20243. static parseAnimation(animation, bones) {
  20244. if (!animation) {
  20245. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  20246. return null;
  20247. }
  20248. const addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  20249. // only return track if there are actually keys.
  20250. if (animationKeys.length !== 0) {
  20251. const times = [];
  20252. const values = [];
  20253. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  20254. if (times.length !== 0) {
  20255. destTracks.push(new trackType(trackName, times, values));
  20256. }
  20257. }
  20258. };
  20259. const tracks = [];
  20260. const clipName = animation.name || 'default';
  20261. const fps = animation.fps || 30;
  20262. const blendMode = animation.blendMode; // automatic length determination in AnimationClip.
  20263. let duration = animation.length || -1;
  20264. const hierarchyTracks = animation.hierarchy || [];
  20265. for (let h = 0; h < hierarchyTracks.length; h++) {
  20266. const animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  20267. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  20268. if (animationKeys[0].morphTargets) {
  20269. // figure out all morph targets used in this track
  20270. const morphTargetNames = {};
  20271. let k;
  20272. for (k = 0; k < animationKeys.length; k++) {
  20273. if (animationKeys[k].morphTargets) {
  20274. for (let m = 0; m < animationKeys[k].morphTargets.length; m++) {
  20275. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  20276. }
  20277. }
  20278. } // create a track for each morph target with all zero
  20279. // morphTargetInfluences except for the keys in which
  20280. // the morphTarget is named.
  20281. for (const morphTargetName in morphTargetNames) {
  20282. const times = [];
  20283. const values = [];
  20284. for (let m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  20285. const animationKey = animationKeys[k];
  20286. times.push(animationKey.time);
  20287. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  20288. }
  20289. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  20290. }
  20291. duration = morphTargetNames.length * (fps || 1.0);
  20292. } else {
  20293. // ...assume skeletal animation
  20294. const boneName = '.bones[' + bones[h].name + ']';
  20295. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  20296. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  20297. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  20298. }
  20299. }
  20300. if (tracks.length === 0) {
  20301. return null;
  20302. }
  20303. const clip = new this(clipName, duration, tracks, blendMode);
  20304. return clip;
  20305. }
  20306. resetDuration() {
  20307. const tracks = this.tracks;
  20308. let duration = 0;
  20309. for (let i = 0, n = tracks.length; i !== n; ++i) {
  20310. const track = this.tracks[i];
  20311. duration = Math.max(duration, track.times[track.times.length - 1]);
  20312. }
  20313. this.duration = duration;
  20314. return this;
  20315. }
  20316. trim() {
  20317. for (let i = 0; i < this.tracks.length; i++) {
  20318. this.tracks[i].trim(0, this.duration);
  20319. }
  20320. return this;
  20321. }
  20322. validate() {
  20323. let valid = true;
  20324. for (let i = 0; i < this.tracks.length; i++) {
  20325. valid = valid && this.tracks[i].validate();
  20326. }
  20327. return valid;
  20328. }
  20329. optimize() {
  20330. for (let i = 0; i < this.tracks.length; i++) {
  20331. this.tracks[i].optimize();
  20332. }
  20333. return this;
  20334. }
  20335. clone() {
  20336. const tracks = [];
  20337. for (let i = 0; i < this.tracks.length; i++) {
  20338. tracks.push(this.tracks[i].clone());
  20339. }
  20340. return new this.constructor(this.name, this.duration, tracks, this.blendMode);
  20341. }
  20342. toJSON() {
  20343. return this.constructor.toJSON(this);
  20344. }
  20345. }
  20346. function getTrackTypeForValueTypeName(typeName) {
  20347. switch (typeName.toLowerCase()) {
  20348. case 'scalar':
  20349. case 'double':
  20350. case 'float':
  20351. case 'number':
  20352. case 'integer':
  20353. return NumberKeyframeTrack;
  20354. case 'vector':
  20355. case 'vector2':
  20356. case 'vector3':
  20357. case 'vector4':
  20358. return VectorKeyframeTrack;
  20359. case 'color':
  20360. return ColorKeyframeTrack;
  20361. case 'quaternion':
  20362. return QuaternionKeyframeTrack;
  20363. case 'bool':
  20364. case 'boolean':
  20365. return BooleanKeyframeTrack;
  20366. case 'string':
  20367. return StringKeyframeTrack;
  20368. }
  20369. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  20370. }
  20371. function parseKeyframeTrack(json) {
  20372. if (json.type === undefined) {
  20373. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  20374. }
  20375. const trackType = getTrackTypeForValueTypeName(json.type);
  20376. if (json.times === undefined) {
  20377. const times = [],
  20378. values = [];
  20379. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  20380. json.times = times;
  20381. json.values = values;
  20382. } // derived classes can define a static parse method
  20383. if (trackType.parse !== undefined) {
  20384. return trackType.parse(json);
  20385. } else {
  20386. // by default, we assume a constructor compatible with the base
  20387. return new trackType(json.name, json.times, json.values, json.interpolation);
  20388. }
  20389. }
  20390. const Cache = {
  20391. enabled: false,
  20392. files: {},
  20393. add: function (key, file) {
  20394. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  20395. this.files[key] = file;
  20396. },
  20397. get: function (key) {
  20398. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  20399. return this.files[key];
  20400. },
  20401. remove: function (key) {
  20402. delete this.files[key];
  20403. },
  20404. clear: function () {
  20405. this.files = {};
  20406. }
  20407. };
  20408. class LoadingManager {
  20409. constructor(onLoad, onProgress, onError) {
  20410. const scope = this;
  20411. let isLoading = false;
  20412. let itemsLoaded = 0;
  20413. let itemsTotal = 0;
  20414. let urlModifier = undefined;
  20415. const handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  20416. // in the constructor
  20417. this.onStart = undefined;
  20418. this.onLoad = onLoad;
  20419. this.onProgress = onProgress;
  20420. this.onError = onError;
  20421. this.itemStart = function (url) {
  20422. itemsTotal++;
  20423. if (isLoading === false) {
  20424. if (scope.onStart !== undefined) {
  20425. scope.onStart(url, itemsLoaded, itemsTotal);
  20426. }
  20427. }
  20428. isLoading = true;
  20429. };
  20430. this.itemEnd = function (url) {
  20431. itemsLoaded++;
  20432. if (scope.onProgress !== undefined) {
  20433. scope.onProgress(url, itemsLoaded, itemsTotal);
  20434. }
  20435. if (itemsLoaded === itemsTotal) {
  20436. isLoading = false;
  20437. if (scope.onLoad !== undefined) {
  20438. scope.onLoad();
  20439. }
  20440. }
  20441. };
  20442. this.itemError = function (url) {
  20443. if (scope.onError !== undefined) {
  20444. scope.onError(url);
  20445. }
  20446. };
  20447. this.resolveURL = function (url) {
  20448. if (urlModifier) {
  20449. return urlModifier(url);
  20450. }
  20451. return url;
  20452. };
  20453. this.setURLModifier = function (transform) {
  20454. urlModifier = transform;
  20455. return this;
  20456. };
  20457. this.addHandler = function (regex, loader) {
  20458. handlers.push(regex, loader);
  20459. return this;
  20460. };
  20461. this.removeHandler = function (regex) {
  20462. const index = handlers.indexOf(regex);
  20463. if (index !== -1) {
  20464. handlers.splice(index, 2);
  20465. }
  20466. return this;
  20467. };
  20468. this.getHandler = function (file) {
  20469. for (let i = 0, l = handlers.length; i < l; i += 2) {
  20470. const regex = handlers[i];
  20471. const loader = handlers[i + 1];
  20472. if (regex.global) regex.lastIndex = 0; // see #17920
  20473. if (regex.test(file)) {
  20474. return loader;
  20475. }
  20476. }
  20477. return null;
  20478. };
  20479. }
  20480. }
  20481. const DefaultLoadingManager = new LoadingManager();
  20482. class Loader {
  20483. constructor(manager) {
  20484. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  20485. this.crossOrigin = 'anonymous';
  20486. this.withCredentials = false;
  20487. this.path = '';
  20488. this.resourcePath = '';
  20489. this.requestHeader = {};
  20490. }
  20491. load()
  20492. /* url, onLoad, onProgress, onError */
  20493. {}
  20494. loadAsync(url, onProgress) {
  20495. const scope = this;
  20496. return new Promise(function (resolve, reject) {
  20497. scope.load(url, resolve, onProgress, reject);
  20498. });
  20499. }
  20500. parse()
  20501. /* data */
  20502. {}
  20503. setCrossOrigin(crossOrigin) {
  20504. this.crossOrigin = crossOrigin;
  20505. return this;
  20506. }
  20507. setWithCredentials(value) {
  20508. this.withCredentials = value;
  20509. return this;
  20510. }
  20511. setPath(path) {
  20512. this.path = path;
  20513. return this;
  20514. }
  20515. setResourcePath(resourcePath) {
  20516. this.resourcePath = resourcePath;
  20517. return this;
  20518. }
  20519. setRequestHeader(requestHeader) {
  20520. this.requestHeader = requestHeader;
  20521. return this;
  20522. }
  20523. }
  20524. const loading = {};
  20525. class FileLoader extends Loader {
  20526. constructor(manager) {
  20527. super(manager);
  20528. }
  20529. load(url, onLoad, onProgress, onError) {
  20530. if (url === undefined) url = '';
  20531. if (this.path !== undefined) url = this.path + url;
  20532. url = this.manager.resolveURL(url);
  20533. const scope = this;
  20534. const cached = Cache.get(url);
  20535. if (cached !== undefined) {
  20536. scope.manager.itemStart(url);
  20537. setTimeout(function () {
  20538. if (onLoad) onLoad(cached);
  20539. scope.manager.itemEnd(url);
  20540. }, 0);
  20541. return cached;
  20542. } // Check if request is duplicate
  20543. if (loading[url] !== undefined) {
  20544. loading[url].push({
  20545. onLoad: onLoad,
  20546. onProgress: onProgress,
  20547. onError: onError
  20548. });
  20549. return;
  20550. } // Check for data: URI
  20551. const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  20552. const dataUriRegexResult = url.match(dataUriRegex);
  20553. let request; // Safari can not handle Data URIs through XMLHttpRequest so process manually
  20554. if (dataUriRegexResult) {
  20555. const mimeType = dataUriRegexResult[1];
  20556. const isBase64 = !!dataUriRegexResult[2];
  20557. let data = dataUriRegexResult[3];
  20558. data = decodeURIComponent(data);
  20559. if (isBase64) data = atob(data);
  20560. try {
  20561. let response;
  20562. const responseType = (this.responseType || '').toLowerCase();
  20563. switch (responseType) {
  20564. case 'arraybuffer':
  20565. case 'blob':
  20566. const view = new Uint8Array(data.length);
  20567. for (let i = 0; i < data.length; i++) {
  20568. view[i] = data.charCodeAt(i);
  20569. }
  20570. if (responseType === 'blob') {
  20571. response = new Blob([view.buffer], {
  20572. type: mimeType
  20573. });
  20574. } else {
  20575. response = view.buffer;
  20576. }
  20577. break;
  20578. case 'document':
  20579. const parser = new DOMParser();
  20580. response = parser.parseFromString(data, mimeType);
  20581. break;
  20582. case 'json':
  20583. response = JSON.parse(data);
  20584. break;
  20585. default:
  20586. // 'text' or other
  20587. response = data;
  20588. break;
  20589. } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  20590. setTimeout(function () {
  20591. if (onLoad) onLoad(response);
  20592. scope.manager.itemEnd(url);
  20593. }, 0);
  20594. } catch (error) {
  20595. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  20596. setTimeout(function () {
  20597. if (onError) onError(error);
  20598. scope.manager.itemError(url);
  20599. scope.manager.itemEnd(url);
  20600. }, 0);
  20601. }
  20602. } else {
  20603. // Initialise array for duplicate requests
  20604. loading[url] = [];
  20605. loading[url].push({
  20606. onLoad: onLoad,
  20607. onProgress: onProgress,
  20608. onError: onError
  20609. });
  20610. request = new XMLHttpRequest();
  20611. request.open('GET', url, true);
  20612. request.addEventListener('load', function (event) {
  20613. const response = this.response;
  20614. const callbacks = loading[url];
  20615. delete loading[url];
  20616. if (this.status === 200 || this.status === 0) {
  20617. // Some browsers return HTTP Status 0 when using non-http protocol
  20618. // e.g. 'file://' or 'data://'. Handle as success.
  20619. 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
  20620. // error response bodies as proper responses to requests.
  20621. Cache.add(url, response);
  20622. for (let i = 0, il = callbacks.length; i < il; i++) {
  20623. const callback = callbacks[i];
  20624. if (callback.onLoad) callback.onLoad(response);
  20625. }
  20626. scope.manager.itemEnd(url);
  20627. } else {
  20628. for (let i = 0, il = callbacks.length; i < il; i++) {
  20629. const callback = callbacks[i];
  20630. if (callback.onError) callback.onError(event);
  20631. }
  20632. scope.manager.itemError(url);
  20633. scope.manager.itemEnd(url);
  20634. }
  20635. }, false);
  20636. request.addEventListener('progress', function (event) {
  20637. const callbacks = loading[url];
  20638. for (let i = 0, il = callbacks.length; i < il; i++) {
  20639. const callback = callbacks[i];
  20640. if (callback.onProgress) callback.onProgress(event);
  20641. }
  20642. }, false);
  20643. request.addEventListener('error', function (event) {
  20644. const callbacks = loading[url];
  20645. delete loading[url];
  20646. for (let i = 0, il = callbacks.length; i < il; i++) {
  20647. const callback = callbacks[i];
  20648. if (callback.onError) callback.onError(event);
  20649. }
  20650. scope.manager.itemError(url);
  20651. scope.manager.itemEnd(url);
  20652. }, false);
  20653. request.addEventListener('abort', function (event) {
  20654. const callbacks = loading[url];
  20655. delete loading[url];
  20656. for (let i = 0, il = callbacks.length; i < il; i++) {
  20657. const callback = callbacks[i];
  20658. if (callback.onError) callback.onError(event);
  20659. }
  20660. scope.manager.itemError(url);
  20661. scope.manager.itemEnd(url);
  20662. }, false);
  20663. if (this.responseType !== undefined) request.responseType = this.responseType;
  20664. if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
  20665. if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
  20666. for (const header in this.requestHeader) {
  20667. request.setRequestHeader(header, this.requestHeader[header]);
  20668. }
  20669. request.send(null);
  20670. }
  20671. scope.manager.itemStart(url);
  20672. return request;
  20673. }
  20674. setResponseType(value) {
  20675. this.responseType = value;
  20676. return this;
  20677. }
  20678. setMimeType(value) {
  20679. this.mimeType = value;
  20680. return this;
  20681. }
  20682. }
  20683. class AnimationLoader extends Loader {
  20684. constructor(manager) {
  20685. super(manager);
  20686. }
  20687. load(url, onLoad, onProgress, onError) {
  20688. const scope = this;
  20689. const loader = new FileLoader(this.manager);
  20690. loader.setPath(this.path);
  20691. loader.setRequestHeader(this.requestHeader);
  20692. loader.setWithCredentials(this.withCredentials);
  20693. loader.load(url, function (text) {
  20694. try {
  20695. onLoad(scope.parse(JSON.parse(text)));
  20696. } catch (e) {
  20697. if (onError) {
  20698. onError(e);
  20699. } else {
  20700. console.error(e);
  20701. }
  20702. scope.manager.itemError(url);
  20703. }
  20704. }, onProgress, onError);
  20705. }
  20706. parse(json) {
  20707. const animations = [];
  20708. for (let i = 0; i < json.length; i++) {
  20709. const clip = AnimationClip.parse(json[i]);
  20710. animations.push(clip);
  20711. }
  20712. return animations;
  20713. }
  20714. }
  20715. /**
  20716. * Abstract Base class to block based textures loader (dds, pvr, ...)
  20717. *
  20718. * Sub classes have to implement the parse() method which will be used in load().
  20719. */
  20720. class CompressedTextureLoader extends Loader {
  20721. constructor(manager) {
  20722. super(manager);
  20723. }
  20724. load(url, onLoad, onProgress, onError) {
  20725. const scope = this;
  20726. const images = [];
  20727. const texture = new CompressedTexture();
  20728. const loader = new FileLoader(this.manager);
  20729. loader.setPath(this.path);
  20730. loader.setResponseType('arraybuffer');
  20731. loader.setRequestHeader(this.requestHeader);
  20732. loader.setWithCredentials(scope.withCredentials);
  20733. let loaded = 0;
  20734. function loadTexture(i) {
  20735. loader.load(url[i], function (buffer) {
  20736. const texDatas = scope.parse(buffer, true);
  20737. images[i] = {
  20738. width: texDatas.width,
  20739. height: texDatas.height,
  20740. format: texDatas.format,
  20741. mipmaps: texDatas.mipmaps
  20742. };
  20743. loaded += 1;
  20744. if (loaded === 6) {
  20745. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  20746. texture.image = images;
  20747. texture.format = texDatas.format;
  20748. texture.needsUpdate = true;
  20749. if (onLoad) onLoad(texture);
  20750. }
  20751. }, onProgress, onError);
  20752. }
  20753. if (Array.isArray(url)) {
  20754. for (let i = 0, il = url.length; i < il; ++i) {
  20755. loadTexture(i);
  20756. }
  20757. } else {
  20758. // compressed cubemap texture stored in a single DDS file
  20759. loader.load(url, function (buffer) {
  20760. const texDatas = scope.parse(buffer, true);
  20761. if (texDatas.isCubemap) {
  20762. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  20763. for (let f = 0; f < faces; f++) {
  20764. images[f] = {
  20765. mipmaps: []
  20766. };
  20767. for (let i = 0; i < texDatas.mipmapCount; i++) {
  20768. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  20769. images[f].format = texDatas.format;
  20770. images[f].width = texDatas.width;
  20771. images[f].height = texDatas.height;
  20772. }
  20773. }
  20774. texture.image = images;
  20775. } else {
  20776. texture.image.width = texDatas.width;
  20777. texture.image.height = texDatas.height;
  20778. texture.mipmaps = texDatas.mipmaps;
  20779. }
  20780. if (texDatas.mipmapCount === 1) {
  20781. texture.minFilter = LinearFilter;
  20782. }
  20783. texture.format = texDatas.format;
  20784. texture.needsUpdate = true;
  20785. if (onLoad) onLoad(texture);
  20786. }, onProgress, onError);
  20787. }
  20788. return texture;
  20789. }
  20790. }
  20791. class ImageLoader extends Loader {
  20792. constructor(manager) {
  20793. super(manager);
  20794. }
  20795. load(url, onLoad, onProgress, onError) {
  20796. if (this.path !== undefined) url = this.path + url;
  20797. url = this.manager.resolveURL(url);
  20798. const scope = this;
  20799. const cached = Cache.get(url);
  20800. if (cached !== undefined) {
  20801. scope.manager.itemStart(url);
  20802. setTimeout(function () {
  20803. if (onLoad) onLoad(cached);
  20804. scope.manager.itemEnd(url);
  20805. }, 0);
  20806. return cached;
  20807. }
  20808. const image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
  20809. function onImageLoad() {
  20810. image.removeEventListener('load', onImageLoad, false);
  20811. image.removeEventListener('error', onImageError, false);
  20812. Cache.add(url, this);
  20813. if (onLoad) onLoad(this);
  20814. scope.manager.itemEnd(url);
  20815. }
  20816. function onImageError(event) {
  20817. image.removeEventListener('load', onImageLoad, false);
  20818. image.removeEventListener('error', onImageError, false);
  20819. if (onError) onError(event);
  20820. scope.manager.itemError(url);
  20821. scope.manager.itemEnd(url);
  20822. }
  20823. image.addEventListener('load', onImageLoad, false);
  20824. image.addEventListener('error', onImageError, false);
  20825. if (url.substr(0, 5) !== 'data:') {
  20826. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  20827. }
  20828. scope.manager.itemStart(url);
  20829. image.src = url;
  20830. return image;
  20831. }
  20832. }
  20833. class CubeTextureLoader extends Loader {
  20834. constructor(manager) {
  20835. super(manager);
  20836. }
  20837. load(urls, onLoad, onProgress, onError) {
  20838. const texture = new CubeTexture();
  20839. const loader = new ImageLoader(this.manager);
  20840. loader.setCrossOrigin(this.crossOrigin);
  20841. loader.setPath(this.path);
  20842. let loaded = 0;
  20843. function loadTexture(i) {
  20844. loader.load(urls[i], function (image) {
  20845. texture.images[i] = image;
  20846. loaded++;
  20847. if (loaded === 6) {
  20848. texture.needsUpdate = true;
  20849. if (onLoad) onLoad(texture);
  20850. }
  20851. }, undefined, onError);
  20852. }
  20853. for (let i = 0; i < urls.length; ++i) {
  20854. loadTexture(i);
  20855. }
  20856. return texture;
  20857. }
  20858. }
  20859. /**
  20860. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  20861. *
  20862. * Sub classes have to implement the parse() method which will be used in load().
  20863. */
  20864. class DataTextureLoader extends Loader {
  20865. constructor(manager) {
  20866. super(manager);
  20867. }
  20868. load(url, onLoad, onProgress, onError) {
  20869. const scope = this;
  20870. const texture = new DataTexture();
  20871. const loader = new FileLoader(this.manager);
  20872. loader.setResponseType('arraybuffer');
  20873. loader.setRequestHeader(this.requestHeader);
  20874. loader.setPath(this.path);
  20875. loader.setWithCredentials(scope.withCredentials);
  20876. loader.load(url, function (buffer) {
  20877. const texData = scope.parse(buffer);
  20878. if (!texData) return;
  20879. if (texData.image !== undefined) {
  20880. texture.image = texData.image;
  20881. } else if (texData.data !== undefined) {
  20882. texture.image.width = texData.width;
  20883. texture.image.height = texData.height;
  20884. texture.image.data = texData.data;
  20885. }
  20886. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  20887. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  20888. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  20889. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  20890. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  20891. if (texData.encoding !== undefined) {
  20892. texture.encoding = texData.encoding;
  20893. }
  20894. if (texData.flipY !== undefined) {
  20895. texture.flipY = texData.flipY;
  20896. }
  20897. if (texData.format !== undefined) {
  20898. texture.format = texData.format;
  20899. }
  20900. if (texData.type !== undefined) {
  20901. texture.type = texData.type;
  20902. }
  20903. if (texData.mipmaps !== undefined) {
  20904. texture.mipmaps = texData.mipmaps;
  20905. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  20906. }
  20907. if (texData.mipmapCount === 1) {
  20908. texture.minFilter = LinearFilter;
  20909. }
  20910. if (texData.generateMipmaps !== undefined) {
  20911. texture.generateMipmaps = texData.generateMipmaps;
  20912. }
  20913. texture.needsUpdate = true;
  20914. if (onLoad) onLoad(texture, texData);
  20915. }, onProgress, onError);
  20916. return texture;
  20917. }
  20918. }
  20919. class TextureLoader extends Loader {
  20920. constructor(manager) {
  20921. super(manager);
  20922. }
  20923. load(url, onLoad, onProgress, onError) {
  20924. const texture = new Texture();
  20925. const loader = new ImageLoader(this.manager);
  20926. loader.setCrossOrigin(this.crossOrigin);
  20927. loader.setPath(this.path);
  20928. loader.load(url, function (image) {
  20929. texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  20930. const isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;
  20931. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  20932. texture.needsUpdate = true;
  20933. if (onLoad !== undefined) {
  20934. onLoad(texture);
  20935. }
  20936. }, onProgress, onError);
  20937. return texture;
  20938. }
  20939. }
  20940. /**
  20941. * Extensible curve object.
  20942. *
  20943. * Some common of curve methods:
  20944. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  20945. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  20946. * .getPoints(), .getSpacedPoints()
  20947. * .getLength()
  20948. * .updateArcLengths()
  20949. *
  20950. * This following curves inherit from THREE.Curve:
  20951. *
  20952. * -- 2D curves --
  20953. * THREE.ArcCurve
  20954. * THREE.CubicBezierCurve
  20955. * THREE.EllipseCurve
  20956. * THREE.LineCurve
  20957. * THREE.QuadraticBezierCurve
  20958. * THREE.SplineCurve
  20959. *
  20960. * -- 3D curves --
  20961. * THREE.CatmullRomCurve3
  20962. * THREE.CubicBezierCurve3
  20963. * THREE.LineCurve3
  20964. * THREE.QuadraticBezierCurve3
  20965. *
  20966. * A series of curves can be represented as a THREE.CurvePath.
  20967. *
  20968. **/
  20969. class Curve {
  20970. constructor() {
  20971. this.type = 'Curve';
  20972. this.arcLengthDivisions = 200;
  20973. } // Virtual base class method to overwrite and implement in subclasses
  20974. // - t [0 .. 1]
  20975. getPoint()
  20976. /* t, optionalTarget */
  20977. {
  20978. console.warn('THREE.Curve: .getPoint() not implemented.');
  20979. return null;
  20980. } // Get point at relative position in curve according to arc length
  20981. // - u [0 .. 1]
  20982. getPointAt(u, optionalTarget) {
  20983. const t = this.getUtoTmapping(u);
  20984. return this.getPoint(t, optionalTarget);
  20985. } // Get sequence of points using getPoint( t )
  20986. getPoints(divisions = 5) {
  20987. const points = [];
  20988. for (let d = 0; d <= divisions; d++) {
  20989. points.push(this.getPoint(d / divisions));
  20990. }
  20991. return points;
  20992. } // Get sequence of points using getPointAt( u )
  20993. getSpacedPoints(divisions = 5) {
  20994. const points = [];
  20995. for (let d = 0; d <= divisions; d++) {
  20996. points.push(this.getPointAt(d / divisions));
  20997. }
  20998. return points;
  20999. } // Get total curve arc length
  21000. getLength() {
  21001. const lengths = this.getLengths();
  21002. return lengths[lengths.length - 1];
  21003. } // Get list of cumulative segment lengths
  21004. getLengths(divisions = this.arcLengthDivisions) {
  21005. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  21006. return this.cacheArcLengths;
  21007. }
  21008. this.needsUpdate = false;
  21009. const cache = [];
  21010. let current,
  21011. last = this.getPoint(0);
  21012. let sum = 0;
  21013. cache.push(0);
  21014. for (let p = 1; p <= divisions; p++) {
  21015. current = this.getPoint(p / divisions);
  21016. sum += current.distanceTo(last);
  21017. cache.push(sum);
  21018. last = current;
  21019. }
  21020. this.cacheArcLengths = cache;
  21021. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  21022. }
  21023. updateArcLengths() {
  21024. this.needsUpdate = true;
  21025. this.getLengths();
  21026. } // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  21027. getUtoTmapping(u, distance) {
  21028. const arcLengths = this.getLengths();
  21029. let i = 0;
  21030. const il = arcLengths.length;
  21031. let targetArcLength; // The targeted u distance value to get
  21032. if (distance) {
  21033. targetArcLength = distance;
  21034. } else {
  21035. targetArcLength = u * arcLengths[il - 1];
  21036. } // binary search for the index with largest value smaller than target u distance
  21037. let low = 0,
  21038. high = il - 1,
  21039. comparison;
  21040. while (low <= high) {
  21041. 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
  21042. comparison = arcLengths[i] - targetArcLength;
  21043. if (comparison < 0) {
  21044. low = i + 1;
  21045. } else if (comparison > 0) {
  21046. high = i - 1;
  21047. } else {
  21048. high = i;
  21049. break; // DONE
  21050. }
  21051. }
  21052. i = high;
  21053. if (arcLengths[i] === targetArcLength) {
  21054. return i / (il - 1);
  21055. } // we could get finer grain at lengths, or use simple interpolation between two points
  21056. const lengthBefore = arcLengths[i];
  21057. const lengthAfter = arcLengths[i + 1];
  21058. const segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  21059. const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  21060. const t = (i + segmentFraction) / (il - 1);
  21061. return t;
  21062. } // Returns a unit vector tangent at t
  21063. // In case any sub curve does not implement its tangent derivation,
  21064. // 2 points a small delta apart will be used to find its gradient
  21065. // which seems to give a reasonable approximation
  21066. getTangent(t, optionalTarget) {
  21067. const delta = 0.0001;
  21068. let t1 = t - delta;
  21069. let t2 = t + delta; // Capping in case of danger
  21070. if (t1 < 0) t1 = 0;
  21071. if (t2 > 1) t2 = 1;
  21072. const pt1 = this.getPoint(t1);
  21073. const pt2 = this.getPoint(t2);
  21074. const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
  21075. tangent.copy(pt2).sub(pt1).normalize();
  21076. return tangent;
  21077. }
  21078. getTangentAt(u, optionalTarget) {
  21079. const t = this.getUtoTmapping(u);
  21080. return this.getTangent(t, optionalTarget);
  21081. }
  21082. computeFrenetFrames(segments, closed) {
  21083. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  21084. const normal = new Vector3();
  21085. const tangents = [];
  21086. const normals = [];
  21087. const binormals = [];
  21088. const vec = new Vector3();
  21089. const mat = new Matrix4(); // compute the tangent vectors for each segment on the curve
  21090. for (let i = 0; i <= segments; i++) {
  21091. const u = i / segments;
  21092. tangents[i] = this.getTangentAt(u, new Vector3());
  21093. tangents[i].normalize();
  21094. } // select an initial normal vector perpendicular to the first tangent vector,
  21095. // and in the direction of the minimum tangent xyz component
  21096. normals[0] = new Vector3();
  21097. binormals[0] = new Vector3();
  21098. let min = Number.MAX_VALUE;
  21099. const tx = Math.abs(tangents[0].x);
  21100. const ty = Math.abs(tangents[0].y);
  21101. const tz = Math.abs(tangents[0].z);
  21102. if (tx <= min) {
  21103. min = tx;
  21104. normal.set(1, 0, 0);
  21105. }
  21106. if (ty <= min) {
  21107. min = ty;
  21108. normal.set(0, 1, 0);
  21109. }
  21110. if (tz <= min) {
  21111. normal.set(0, 0, 1);
  21112. }
  21113. vec.crossVectors(tangents[0], normal).normalize();
  21114. normals[0].crossVectors(tangents[0], vec);
  21115. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  21116. for (let i = 1; i <= segments; i++) {
  21117. normals[i] = normals[i - 1].clone();
  21118. binormals[i] = binormals[i - 1].clone();
  21119. vec.crossVectors(tangents[i - 1], tangents[i]);
  21120. if (vec.length() > Number.EPSILON) {
  21121. vec.normalize();
  21122. const theta = Math.acos(clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  21123. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  21124. }
  21125. binormals[i].crossVectors(tangents[i], normals[i]);
  21126. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  21127. if (closed === true) {
  21128. let theta = Math.acos(clamp(normals[0].dot(normals[segments]), -1, 1));
  21129. theta /= segments;
  21130. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  21131. theta = -theta;
  21132. }
  21133. for (let i = 1; i <= segments; i++) {
  21134. // twist a little...
  21135. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  21136. binormals[i].crossVectors(tangents[i], normals[i]);
  21137. }
  21138. }
  21139. return {
  21140. tangents: tangents,
  21141. normals: normals,
  21142. binormals: binormals
  21143. };
  21144. }
  21145. clone() {
  21146. return new this.constructor().copy(this);
  21147. }
  21148. copy(source) {
  21149. this.arcLengthDivisions = source.arcLengthDivisions;
  21150. return this;
  21151. }
  21152. toJSON() {
  21153. const data = {
  21154. metadata: {
  21155. version: 4.5,
  21156. type: 'Curve',
  21157. generator: 'Curve.toJSON'
  21158. }
  21159. };
  21160. data.arcLengthDivisions = this.arcLengthDivisions;
  21161. data.type = this.type;
  21162. return data;
  21163. }
  21164. fromJSON(json) {
  21165. this.arcLengthDivisions = json.arcLengthDivisions;
  21166. return this;
  21167. }
  21168. }
  21169. class EllipseCurve extends Curve {
  21170. constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) {
  21171. super();
  21172. this.type = 'EllipseCurve';
  21173. this.aX = aX;
  21174. this.aY = aY;
  21175. this.xRadius = xRadius;
  21176. this.yRadius = yRadius;
  21177. this.aStartAngle = aStartAngle;
  21178. this.aEndAngle = aEndAngle;
  21179. this.aClockwise = aClockwise;
  21180. this.aRotation = aRotation;
  21181. }
  21182. getPoint(t, optionalTarget) {
  21183. const point = optionalTarget || new Vector2();
  21184. const twoPi = Math.PI * 2;
  21185. let deltaAngle = this.aEndAngle - this.aStartAngle;
  21186. const samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  21187. while (deltaAngle < 0) deltaAngle += twoPi;
  21188. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  21189. if (deltaAngle < Number.EPSILON) {
  21190. if (samePoints) {
  21191. deltaAngle = 0;
  21192. } else {
  21193. deltaAngle = twoPi;
  21194. }
  21195. }
  21196. if (this.aClockwise === true && !samePoints) {
  21197. if (deltaAngle === twoPi) {
  21198. deltaAngle = -twoPi;
  21199. } else {
  21200. deltaAngle = deltaAngle - twoPi;
  21201. }
  21202. }
  21203. const angle = this.aStartAngle + t * deltaAngle;
  21204. let x = this.aX + this.xRadius * Math.cos(angle);
  21205. let y = this.aY + this.yRadius * Math.sin(angle);
  21206. if (this.aRotation !== 0) {
  21207. const cos = Math.cos(this.aRotation);
  21208. const sin = Math.sin(this.aRotation);
  21209. const tx = x - this.aX;
  21210. const ty = y - this.aY; // Rotate the point about the center of the ellipse.
  21211. x = tx * cos - ty * sin + this.aX;
  21212. y = tx * sin + ty * cos + this.aY;
  21213. }
  21214. return point.set(x, y);
  21215. }
  21216. copy(source) {
  21217. super.copy(source);
  21218. this.aX = source.aX;
  21219. this.aY = source.aY;
  21220. this.xRadius = source.xRadius;
  21221. this.yRadius = source.yRadius;
  21222. this.aStartAngle = source.aStartAngle;
  21223. this.aEndAngle = source.aEndAngle;
  21224. this.aClockwise = source.aClockwise;
  21225. this.aRotation = source.aRotation;
  21226. return this;
  21227. }
  21228. toJSON() {
  21229. const data = super.toJSON();
  21230. data.aX = this.aX;
  21231. data.aY = this.aY;
  21232. data.xRadius = this.xRadius;
  21233. data.yRadius = this.yRadius;
  21234. data.aStartAngle = this.aStartAngle;
  21235. data.aEndAngle = this.aEndAngle;
  21236. data.aClockwise = this.aClockwise;
  21237. data.aRotation = this.aRotation;
  21238. return data;
  21239. }
  21240. fromJSON(json) {
  21241. super.fromJSON(json);
  21242. this.aX = json.aX;
  21243. this.aY = json.aY;
  21244. this.xRadius = json.xRadius;
  21245. this.yRadius = json.yRadius;
  21246. this.aStartAngle = json.aStartAngle;
  21247. this.aEndAngle = json.aEndAngle;
  21248. this.aClockwise = json.aClockwise;
  21249. this.aRotation = json.aRotation;
  21250. return this;
  21251. }
  21252. }
  21253. EllipseCurve.prototype.isEllipseCurve = true;
  21254. class ArcCurve extends EllipseCurve {
  21255. constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  21256. super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  21257. this.type = 'ArcCurve';
  21258. }
  21259. }
  21260. ArcCurve.prototype.isArcCurve = true;
  21261. /**
  21262. * Centripetal CatmullRom Curve - which is useful for avoiding
  21263. * cusps and self-intersections in non-uniform catmull rom curves.
  21264. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  21265. *
  21266. * curve.type accepts centripetal(default), chordal and catmullrom
  21267. * curve.tension is used for catmullrom which defaults to 0.5
  21268. */
  21269. /*
  21270. Based on an optimized c++ solution in
  21271. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  21272. - http://ideone.com/NoEbVM
  21273. This CubicPoly class could be used for reusing some variables and calculations,
  21274. but for three.js curve use, it could be possible inlined and flatten into a single function call
  21275. which can be placed in CurveUtils.
  21276. */
  21277. function CubicPoly() {
  21278. let c0 = 0,
  21279. c1 = 0,
  21280. c2 = 0,
  21281. c3 = 0;
  21282. /*
  21283. * Compute coefficients for a cubic polynomial
  21284. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  21285. * such that
  21286. * p(0) = x0, p(1) = x1
  21287. * and
  21288. * p'(0) = t0, p'(1) = t1.
  21289. */
  21290. function init(x0, x1, t0, t1) {
  21291. c0 = x0;
  21292. c1 = t0;
  21293. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  21294. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  21295. }
  21296. return {
  21297. initCatmullRom: function (x0, x1, x2, x3, tension) {
  21298. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  21299. },
  21300. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  21301. // compute tangents when parameterized in [t1,t2]
  21302. let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  21303. let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  21304. t1 *= dt1;
  21305. t2 *= dt1;
  21306. init(x1, x2, t1, t2);
  21307. },
  21308. calc: function (t) {
  21309. const t2 = t * t;
  21310. const t3 = t2 * t;
  21311. return c0 + c1 * t + c2 * t2 + c3 * t3;
  21312. }
  21313. };
  21314. } //
  21315. const tmp = new Vector3();
  21316. const px = new CubicPoly(),
  21317. py = new CubicPoly(),
  21318. pz = new CubicPoly();
  21319. class CatmullRomCurve3 extends Curve {
  21320. constructor(points = [], closed = false, curveType = 'centripetal', tension = 0.5) {
  21321. super();
  21322. this.type = 'CatmullRomCurve3';
  21323. this.points = points;
  21324. this.closed = closed;
  21325. this.curveType = curveType;
  21326. this.tension = tension;
  21327. }
  21328. getPoint(t, optionalTarget = new Vector3()) {
  21329. const point = optionalTarget;
  21330. const points = this.points;
  21331. const l = points.length;
  21332. const p = (l - (this.closed ? 0 : 1)) * t;
  21333. let intPoint = Math.floor(p);
  21334. let weight = p - intPoint;
  21335. if (this.closed) {
  21336. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  21337. } else if (weight === 0 && intPoint === l - 1) {
  21338. intPoint = l - 2;
  21339. weight = 1;
  21340. }
  21341. let p0, p3; // 4 points (p1 & p2 defined below)
  21342. if (this.closed || intPoint > 0) {
  21343. p0 = points[(intPoint - 1) % l];
  21344. } else {
  21345. // extrapolate first point
  21346. tmp.subVectors(points[0], points[1]).add(points[0]);
  21347. p0 = tmp;
  21348. }
  21349. const p1 = points[intPoint % l];
  21350. const p2 = points[(intPoint + 1) % l];
  21351. if (this.closed || intPoint + 2 < l) {
  21352. p3 = points[(intPoint + 2) % l];
  21353. } else {
  21354. // extrapolate last point
  21355. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  21356. p3 = tmp;
  21357. }
  21358. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  21359. // init Centripetal / Chordal Catmull-Rom
  21360. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  21361. let dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  21362. let dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  21363. let dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  21364. if (dt1 < 1e-4) dt1 = 1.0;
  21365. if (dt0 < 1e-4) dt0 = dt1;
  21366. if (dt2 < 1e-4) dt2 = dt1;
  21367. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  21368. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  21369. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  21370. } else if (this.curveType === 'catmullrom') {
  21371. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  21372. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  21373. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  21374. }
  21375. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  21376. return point;
  21377. }
  21378. copy(source) {
  21379. super.copy(source);
  21380. this.points = [];
  21381. for (let i = 0, l = source.points.length; i < l; i++) {
  21382. const point = source.points[i];
  21383. this.points.push(point.clone());
  21384. }
  21385. this.closed = source.closed;
  21386. this.curveType = source.curveType;
  21387. this.tension = source.tension;
  21388. return this;
  21389. }
  21390. toJSON() {
  21391. const data = super.toJSON();
  21392. data.points = [];
  21393. for (let i = 0, l = this.points.length; i < l; i++) {
  21394. const point = this.points[i];
  21395. data.points.push(point.toArray());
  21396. }
  21397. data.closed = this.closed;
  21398. data.curveType = this.curveType;
  21399. data.tension = this.tension;
  21400. return data;
  21401. }
  21402. fromJSON(json) {
  21403. super.fromJSON(json);
  21404. this.points = [];
  21405. for (let i = 0, l = json.points.length; i < l; i++) {
  21406. const point = json.points[i];
  21407. this.points.push(new Vector3().fromArray(point));
  21408. }
  21409. this.closed = json.closed;
  21410. this.curveType = json.curveType;
  21411. this.tension = json.tension;
  21412. return this;
  21413. }
  21414. }
  21415. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  21416. /**
  21417. * Bezier Curves formulas obtained from
  21418. * http://en.wikipedia.org/wiki/Bézier_curve
  21419. */
  21420. function CatmullRom(t, p0, p1, p2, p3) {
  21421. const v0 = (p2 - p0) * 0.5;
  21422. const v1 = (p3 - p1) * 0.5;
  21423. const t2 = t * t;
  21424. const t3 = t * t2;
  21425. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  21426. } //
  21427. function QuadraticBezierP0(t, p) {
  21428. const k = 1 - t;
  21429. return k * k * p;
  21430. }
  21431. function QuadraticBezierP1(t, p) {
  21432. return 2 * (1 - t) * t * p;
  21433. }
  21434. function QuadraticBezierP2(t, p) {
  21435. return t * t * p;
  21436. }
  21437. function QuadraticBezier(t, p0, p1, p2) {
  21438. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  21439. } //
  21440. function CubicBezierP0(t, p) {
  21441. const k = 1 - t;
  21442. return k * k * k * p;
  21443. }
  21444. function CubicBezierP1(t, p) {
  21445. const k = 1 - t;
  21446. return 3 * k * k * t * p;
  21447. }
  21448. function CubicBezierP2(t, p) {
  21449. return 3 * (1 - t) * t * t * p;
  21450. }
  21451. function CubicBezierP3(t, p) {
  21452. return t * t * t * p;
  21453. }
  21454. function CubicBezier(t, p0, p1, p2, p3) {
  21455. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  21456. }
  21457. class CubicBezierCurve extends Curve {
  21458. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) {
  21459. super();
  21460. this.type = 'CubicBezierCurve';
  21461. this.v0 = v0;
  21462. this.v1 = v1;
  21463. this.v2 = v2;
  21464. this.v3 = v3;
  21465. }
  21466. getPoint(t, optionalTarget = new Vector2()) {
  21467. const point = optionalTarget;
  21468. const v0 = this.v0,
  21469. v1 = this.v1,
  21470. v2 = this.v2,
  21471. v3 = this.v3;
  21472. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  21473. return point;
  21474. }
  21475. copy(source) {
  21476. super.copy(source);
  21477. this.v0.copy(source.v0);
  21478. this.v1.copy(source.v1);
  21479. this.v2.copy(source.v2);
  21480. this.v3.copy(source.v3);
  21481. return this;
  21482. }
  21483. toJSON() {
  21484. const data = super.toJSON();
  21485. data.v0 = this.v0.toArray();
  21486. data.v1 = this.v1.toArray();
  21487. data.v2 = this.v2.toArray();
  21488. data.v3 = this.v3.toArray();
  21489. return data;
  21490. }
  21491. fromJSON(json) {
  21492. super.fromJSON(json);
  21493. this.v0.fromArray(json.v0);
  21494. this.v1.fromArray(json.v1);
  21495. this.v2.fromArray(json.v2);
  21496. this.v3.fromArray(json.v3);
  21497. return this;
  21498. }
  21499. }
  21500. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  21501. class CubicBezierCurve3 extends Curve {
  21502. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) {
  21503. super();
  21504. this.type = 'CubicBezierCurve3';
  21505. this.v0 = v0;
  21506. this.v1 = v1;
  21507. this.v2 = v2;
  21508. this.v3 = v3;
  21509. }
  21510. getPoint(t, optionalTarget = new Vector3()) {
  21511. const point = optionalTarget;
  21512. const v0 = this.v0,
  21513. v1 = this.v1,
  21514. v2 = this.v2,
  21515. v3 = this.v3;
  21516. 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));
  21517. return point;
  21518. }
  21519. copy(source) {
  21520. super.copy(source);
  21521. this.v0.copy(source.v0);
  21522. this.v1.copy(source.v1);
  21523. this.v2.copy(source.v2);
  21524. this.v3.copy(source.v3);
  21525. return this;
  21526. }
  21527. toJSON() {
  21528. const data = super.toJSON();
  21529. data.v0 = this.v0.toArray();
  21530. data.v1 = this.v1.toArray();
  21531. data.v2 = this.v2.toArray();
  21532. data.v3 = this.v3.toArray();
  21533. return data;
  21534. }
  21535. fromJSON(json) {
  21536. super.fromJSON(json);
  21537. this.v0.fromArray(json.v0);
  21538. this.v1.fromArray(json.v1);
  21539. this.v2.fromArray(json.v2);
  21540. this.v3.fromArray(json.v3);
  21541. return this;
  21542. }
  21543. }
  21544. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  21545. class LineCurve extends Curve {
  21546. constructor(v1 = new Vector2(), v2 = new Vector2()) {
  21547. super();
  21548. this.type = 'LineCurve';
  21549. this.v1 = v1;
  21550. this.v2 = v2;
  21551. }
  21552. getPoint(t, optionalTarget = new Vector2()) {
  21553. const point = optionalTarget;
  21554. if (t === 1) {
  21555. point.copy(this.v2);
  21556. } else {
  21557. point.copy(this.v2).sub(this.v1);
  21558. point.multiplyScalar(t).add(this.v1);
  21559. }
  21560. return point;
  21561. } // Line curve is linear, so we can overwrite default getPointAt
  21562. getPointAt(u, optionalTarget) {
  21563. return this.getPoint(u, optionalTarget);
  21564. }
  21565. getTangent(t, optionalTarget) {
  21566. const tangent = optionalTarget || new Vector2();
  21567. tangent.copy(this.v2).sub(this.v1).normalize();
  21568. return tangent;
  21569. }
  21570. copy(source) {
  21571. super.copy(source);
  21572. this.v1.copy(source.v1);
  21573. this.v2.copy(source.v2);
  21574. return this;
  21575. }
  21576. toJSON() {
  21577. const data = super.toJSON();
  21578. data.v1 = this.v1.toArray();
  21579. data.v2 = this.v2.toArray();
  21580. return data;
  21581. }
  21582. fromJSON(json) {
  21583. super.fromJSON(json);
  21584. this.v1.fromArray(json.v1);
  21585. this.v2.fromArray(json.v2);
  21586. return this;
  21587. }
  21588. }
  21589. LineCurve.prototype.isLineCurve = true;
  21590. class LineCurve3 extends Curve {
  21591. constructor(v1 = new Vector3(), v2 = new Vector3()) {
  21592. super();
  21593. this.type = 'LineCurve3';
  21594. this.isLineCurve3 = true;
  21595. this.v1 = v1;
  21596. this.v2 = v2;
  21597. }
  21598. getPoint(t, optionalTarget = new Vector3()) {
  21599. const point = optionalTarget;
  21600. if (t === 1) {
  21601. point.copy(this.v2);
  21602. } else {
  21603. point.copy(this.v2).sub(this.v1);
  21604. point.multiplyScalar(t).add(this.v1);
  21605. }
  21606. return point;
  21607. } // Line curve is linear, so we can overwrite default getPointAt
  21608. getPointAt(u, optionalTarget) {
  21609. return this.getPoint(u, optionalTarget);
  21610. }
  21611. copy(source) {
  21612. super.copy(source);
  21613. this.v1.copy(source.v1);
  21614. this.v2.copy(source.v2);
  21615. return this;
  21616. }
  21617. toJSON() {
  21618. const data = super.toJSON();
  21619. data.v1 = this.v1.toArray();
  21620. data.v2 = this.v2.toArray();
  21621. return data;
  21622. }
  21623. fromJSON(json) {
  21624. super.fromJSON(json);
  21625. this.v1.fromArray(json.v1);
  21626. this.v2.fromArray(json.v2);
  21627. return this;
  21628. }
  21629. }
  21630. class QuadraticBezierCurve extends Curve {
  21631. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) {
  21632. super();
  21633. this.type = 'QuadraticBezierCurve';
  21634. this.v0 = v0;
  21635. this.v1 = v1;
  21636. this.v2 = v2;
  21637. }
  21638. getPoint(t, optionalTarget = new Vector2()) {
  21639. const point = optionalTarget;
  21640. const v0 = this.v0,
  21641. v1 = this.v1,
  21642. v2 = this.v2;
  21643. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  21644. return point;
  21645. }
  21646. copy(source) {
  21647. super.copy(source);
  21648. this.v0.copy(source.v0);
  21649. this.v1.copy(source.v1);
  21650. this.v2.copy(source.v2);
  21651. return this;
  21652. }
  21653. toJSON() {
  21654. const data = super.toJSON();
  21655. data.v0 = this.v0.toArray();
  21656. data.v1 = this.v1.toArray();
  21657. data.v2 = this.v2.toArray();
  21658. return data;
  21659. }
  21660. fromJSON(json) {
  21661. super.fromJSON(json);
  21662. this.v0.fromArray(json.v0);
  21663. this.v1.fromArray(json.v1);
  21664. this.v2.fromArray(json.v2);
  21665. return this;
  21666. }
  21667. }
  21668. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  21669. class QuadraticBezierCurve3 extends Curve {
  21670. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) {
  21671. super();
  21672. this.type = 'QuadraticBezierCurve3';
  21673. this.v0 = v0;
  21674. this.v1 = v1;
  21675. this.v2 = v2;
  21676. }
  21677. getPoint(t, optionalTarget = new Vector3()) {
  21678. const point = optionalTarget;
  21679. const v0 = this.v0,
  21680. v1 = this.v1,
  21681. v2 = this.v2;
  21682. 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));
  21683. return point;
  21684. }
  21685. copy(source) {
  21686. super.copy(source);
  21687. this.v0.copy(source.v0);
  21688. this.v1.copy(source.v1);
  21689. this.v2.copy(source.v2);
  21690. return this;
  21691. }
  21692. toJSON() {
  21693. const data = super.toJSON();
  21694. data.v0 = this.v0.toArray();
  21695. data.v1 = this.v1.toArray();
  21696. data.v2 = this.v2.toArray();
  21697. return data;
  21698. }
  21699. fromJSON(json) {
  21700. super.fromJSON(json);
  21701. this.v0.fromArray(json.v0);
  21702. this.v1.fromArray(json.v1);
  21703. this.v2.fromArray(json.v2);
  21704. return this;
  21705. }
  21706. }
  21707. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  21708. class SplineCurve extends Curve {
  21709. constructor(points = []) {
  21710. super();
  21711. this.type = 'SplineCurve';
  21712. this.points = points;
  21713. }
  21714. getPoint(t, optionalTarget = new Vector2()) {
  21715. const point = optionalTarget;
  21716. const points = this.points;
  21717. const p = (points.length - 1) * t;
  21718. const intPoint = Math.floor(p);
  21719. const weight = p - intPoint;
  21720. const p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  21721. const p1 = points[intPoint];
  21722. const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  21723. const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  21724. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  21725. return point;
  21726. }
  21727. copy(source) {
  21728. super.copy(source);
  21729. this.points = [];
  21730. for (let i = 0, l = source.points.length; i < l; i++) {
  21731. const point = source.points[i];
  21732. this.points.push(point.clone());
  21733. }
  21734. return this;
  21735. }
  21736. toJSON() {
  21737. const data = super.toJSON();
  21738. data.points = [];
  21739. for (let i = 0, l = this.points.length; i < l; i++) {
  21740. const point = this.points[i];
  21741. data.points.push(point.toArray());
  21742. }
  21743. return data;
  21744. }
  21745. fromJSON(json) {
  21746. super.fromJSON(json);
  21747. this.points = [];
  21748. for (let i = 0, l = json.points.length; i < l; i++) {
  21749. const point = json.points[i];
  21750. this.points.push(new Vector2().fromArray(point));
  21751. }
  21752. return this;
  21753. }
  21754. }
  21755. SplineCurve.prototype.isSplineCurve = true;
  21756. var Curves = /*#__PURE__*/Object.freeze({
  21757. __proto__: null,
  21758. ArcCurve: ArcCurve,
  21759. CatmullRomCurve3: CatmullRomCurve3,
  21760. CubicBezierCurve: CubicBezierCurve,
  21761. CubicBezierCurve3: CubicBezierCurve3,
  21762. EllipseCurve: EllipseCurve,
  21763. LineCurve: LineCurve,
  21764. LineCurve3: LineCurve3,
  21765. QuadraticBezierCurve: QuadraticBezierCurve,
  21766. QuadraticBezierCurve3: QuadraticBezierCurve3,
  21767. SplineCurve: SplineCurve
  21768. });
  21769. /**************************************************************
  21770. * Curved Path - a curve path is simply a array of connected
  21771. * curves, but retains the api of a curve
  21772. **************************************************************/
  21773. class CurvePath extends Curve {
  21774. constructor() {
  21775. super();
  21776. this.type = 'CurvePath';
  21777. this.curves = [];
  21778. this.autoClose = false; // Automatically closes the path
  21779. }
  21780. add(curve) {
  21781. this.curves.push(curve);
  21782. }
  21783. closePath() {
  21784. // Add a line curve if start and end of lines are not connected
  21785. const startPoint = this.curves[0].getPoint(0);
  21786. const endPoint = this.curves[this.curves.length - 1].getPoint(1);
  21787. if (!startPoint.equals(endPoint)) {
  21788. this.curves.push(new LineCurve(endPoint, startPoint));
  21789. }
  21790. } // To get accurate point with reference to
  21791. // entire path distance at time t,
  21792. // following has to be done:
  21793. // 1. Length of each sub path have to be known
  21794. // 2. Locate and identify type of curve
  21795. // 3. Get t for the curve
  21796. // 4. Return curve.getPointAt(t')
  21797. getPoint(t) {
  21798. const d = t * this.getLength();
  21799. const curveLengths = this.getCurveLengths();
  21800. let i = 0; // To think about boundaries points.
  21801. while (i < curveLengths.length) {
  21802. if (curveLengths[i] >= d) {
  21803. const diff = curveLengths[i] - d;
  21804. const curve = this.curves[i];
  21805. const segmentLength = curve.getLength();
  21806. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  21807. return curve.getPointAt(u);
  21808. }
  21809. i++;
  21810. }
  21811. return null; // loop where sum != 0, sum > d , sum+1 <d
  21812. } // We cannot use the default THREE.Curve getPoint() with getLength() because in
  21813. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  21814. // getPoint() depends on getLength
  21815. getLength() {
  21816. const lens = this.getCurveLengths();
  21817. return lens[lens.length - 1];
  21818. } // cacheLengths must be recalculated.
  21819. updateArcLengths() {
  21820. this.needsUpdate = true;
  21821. this.cacheLengths = null;
  21822. this.getCurveLengths();
  21823. } // Compute lengths and cache them
  21824. // We cannot overwrite getLengths() because UtoT mapping uses it.
  21825. getCurveLengths() {
  21826. // We use cache values if curves and cache array are same length
  21827. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  21828. return this.cacheLengths;
  21829. } // Get length of sub-curve
  21830. // Push sums into cached array
  21831. const lengths = [];
  21832. let sums = 0;
  21833. for (let i = 0, l = this.curves.length; i < l; i++) {
  21834. sums += this.curves[i].getLength();
  21835. lengths.push(sums);
  21836. }
  21837. this.cacheLengths = lengths;
  21838. return lengths;
  21839. }
  21840. getSpacedPoints(divisions = 40) {
  21841. const points = [];
  21842. for (let i = 0; i <= divisions; i++) {
  21843. points.push(this.getPoint(i / divisions));
  21844. }
  21845. if (this.autoClose) {
  21846. points.push(points[0]);
  21847. }
  21848. return points;
  21849. }
  21850. getPoints(divisions = 12) {
  21851. const points = [];
  21852. let last;
  21853. for (let i = 0, curves = this.curves; i < curves.length; i++) {
  21854. const curve = curves[i];
  21855. const resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  21856. const pts = curve.getPoints(resolution);
  21857. for (let j = 0; j < pts.length; j++) {
  21858. const point = pts[j];
  21859. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  21860. points.push(point);
  21861. last = point;
  21862. }
  21863. }
  21864. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  21865. points.push(points[0]);
  21866. }
  21867. return points;
  21868. }
  21869. copy(source) {
  21870. super.copy(source);
  21871. this.curves = [];
  21872. for (let i = 0, l = source.curves.length; i < l; i++) {
  21873. const curve = source.curves[i];
  21874. this.curves.push(curve.clone());
  21875. }
  21876. this.autoClose = source.autoClose;
  21877. return this;
  21878. }
  21879. toJSON() {
  21880. const data = super.toJSON();
  21881. data.autoClose = this.autoClose;
  21882. data.curves = [];
  21883. for (let i = 0, l = this.curves.length; i < l; i++) {
  21884. const curve = this.curves[i];
  21885. data.curves.push(curve.toJSON());
  21886. }
  21887. return data;
  21888. }
  21889. fromJSON(json) {
  21890. super.fromJSON(json);
  21891. this.autoClose = json.autoClose;
  21892. this.curves = [];
  21893. for (let i = 0, l = json.curves.length; i < l; i++) {
  21894. const curve = json.curves[i];
  21895. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  21896. }
  21897. return this;
  21898. }
  21899. }
  21900. class Path extends CurvePath {
  21901. constructor(points) {
  21902. super();
  21903. this.type = 'Path';
  21904. this.currentPoint = new Vector2();
  21905. if (points) {
  21906. this.setFromPoints(points);
  21907. }
  21908. }
  21909. setFromPoints(points) {
  21910. this.moveTo(points[0].x, points[0].y);
  21911. for (let i = 1, l = points.length; i < l; i++) {
  21912. this.lineTo(points[i].x, points[i].y);
  21913. }
  21914. return this;
  21915. }
  21916. moveTo(x, y) {
  21917. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  21918. return this;
  21919. }
  21920. lineTo(x, y) {
  21921. const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  21922. this.curves.push(curve);
  21923. this.currentPoint.set(x, y);
  21924. return this;
  21925. }
  21926. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  21927. const curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  21928. this.curves.push(curve);
  21929. this.currentPoint.set(aX, aY);
  21930. return this;
  21931. }
  21932. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  21933. const curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  21934. this.curves.push(curve);
  21935. this.currentPoint.set(aX, aY);
  21936. return this;
  21937. }
  21938. splineThru(pts
  21939. /*Array of Vector*/
  21940. ) {
  21941. const npts = [this.currentPoint.clone()].concat(pts);
  21942. const curve = new SplineCurve(npts);
  21943. this.curves.push(curve);
  21944. this.currentPoint.copy(pts[pts.length - 1]);
  21945. return this;
  21946. }
  21947. arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  21948. const x0 = this.currentPoint.x;
  21949. const y0 = this.currentPoint.y;
  21950. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  21951. return this;
  21952. }
  21953. absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  21954. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  21955. return this;
  21956. }
  21957. ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  21958. const x0 = this.currentPoint.x;
  21959. const y0 = this.currentPoint.y;
  21960. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  21961. return this;
  21962. }
  21963. absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  21964. const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  21965. if (this.curves.length > 0) {
  21966. // if a previous curve is present, attempt to join
  21967. const firstPoint = curve.getPoint(0);
  21968. if (!firstPoint.equals(this.currentPoint)) {
  21969. this.lineTo(firstPoint.x, firstPoint.y);
  21970. }
  21971. }
  21972. this.curves.push(curve);
  21973. const lastPoint = curve.getPoint(1);
  21974. this.currentPoint.copy(lastPoint);
  21975. return this;
  21976. }
  21977. copy(source) {
  21978. super.copy(source);
  21979. this.currentPoint.copy(source.currentPoint);
  21980. return this;
  21981. }
  21982. toJSON() {
  21983. const data = super.toJSON();
  21984. data.currentPoint = this.currentPoint.toArray();
  21985. return data;
  21986. }
  21987. fromJSON(json) {
  21988. super.fromJSON(json);
  21989. this.currentPoint.fromArray(json.currentPoint);
  21990. return this;
  21991. }
  21992. }
  21993. class Shape extends Path {
  21994. constructor(points) {
  21995. super(points);
  21996. this.uuid = generateUUID();
  21997. this.type = 'Shape';
  21998. this.holes = [];
  21999. }
  22000. getPointsHoles(divisions) {
  22001. const holesPts = [];
  22002. for (let i = 0, l = this.holes.length; i < l; i++) {
  22003. holesPts[i] = this.holes[i].getPoints(divisions);
  22004. }
  22005. return holesPts;
  22006. } // get points of shape and holes (keypoints based on segments parameter)
  22007. extractPoints(divisions) {
  22008. return {
  22009. shape: this.getPoints(divisions),
  22010. holes: this.getPointsHoles(divisions)
  22011. };
  22012. }
  22013. copy(source) {
  22014. super.copy(source);
  22015. this.holes = [];
  22016. for (let i = 0, l = source.holes.length; i < l; i++) {
  22017. const hole = source.holes[i];
  22018. this.holes.push(hole.clone());
  22019. }
  22020. return this;
  22021. }
  22022. toJSON() {
  22023. const data = super.toJSON();
  22024. data.uuid = this.uuid;
  22025. data.holes = [];
  22026. for (let i = 0, l = this.holes.length; i < l; i++) {
  22027. const hole = this.holes[i];
  22028. data.holes.push(hole.toJSON());
  22029. }
  22030. return data;
  22031. }
  22032. fromJSON(json) {
  22033. super.fromJSON(json);
  22034. this.uuid = json.uuid;
  22035. this.holes = [];
  22036. for (let i = 0, l = json.holes.length; i < l; i++) {
  22037. const hole = json.holes[i];
  22038. this.holes.push(new Path().fromJSON(hole));
  22039. }
  22040. return this;
  22041. }
  22042. }
  22043. class Light extends Object3D {
  22044. constructor(color, intensity = 1) {
  22045. super();
  22046. this.type = 'Light';
  22047. this.color = new Color(color);
  22048. this.intensity = intensity;
  22049. }
  22050. dispose() {// Empty here in base class; some subclasses override.
  22051. }
  22052. copy(source) {
  22053. super.copy(source);
  22054. this.color.copy(source.color);
  22055. this.intensity = source.intensity;
  22056. return this;
  22057. }
  22058. toJSON(meta) {
  22059. const data = super.toJSON(meta);
  22060. data.object.color = this.color.getHex();
  22061. data.object.intensity = this.intensity;
  22062. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  22063. if (this.distance !== undefined) data.object.distance = this.distance;
  22064. if (this.angle !== undefined) data.object.angle = this.angle;
  22065. if (this.decay !== undefined) data.object.decay = this.decay;
  22066. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  22067. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  22068. return data;
  22069. }
  22070. }
  22071. Light.prototype.isLight = true;
  22072. class HemisphereLight extends Light {
  22073. constructor(skyColor, groundColor, intensity) {
  22074. super(skyColor, intensity);
  22075. this.type = 'HemisphereLight';
  22076. this.position.copy(Object3D.DefaultUp);
  22077. this.updateMatrix();
  22078. this.groundColor = new Color(groundColor);
  22079. }
  22080. copy(source) {
  22081. Light.prototype.copy.call(this, source);
  22082. this.groundColor.copy(source.groundColor);
  22083. return this;
  22084. }
  22085. }
  22086. HemisphereLight.prototype.isHemisphereLight = true;
  22087. const _projScreenMatrix$1 = /*@__PURE__*/new Matrix4();
  22088. const _lightPositionWorld$1 = /*@__PURE__*/new Vector3();
  22089. const _lookTarget$1 = /*@__PURE__*/new Vector3();
  22090. class LightShadow {
  22091. constructor(camera) {
  22092. this.camera = camera;
  22093. this.bias = 0;
  22094. this.normalBias = 0;
  22095. this.radius = 1;
  22096. this.mapSize = new Vector2(512, 512);
  22097. this.map = null;
  22098. this.mapPass = null;
  22099. this.matrix = new Matrix4();
  22100. this.autoUpdate = true;
  22101. this.needsUpdate = false;
  22102. this._frustum = new Frustum();
  22103. this._frameExtents = new Vector2(1, 1);
  22104. this._viewportCount = 1;
  22105. this._viewports = [new Vector4(0, 0, 1, 1)];
  22106. }
  22107. getViewportCount() {
  22108. return this._viewportCount;
  22109. }
  22110. getFrustum() {
  22111. return this._frustum;
  22112. }
  22113. updateMatrices(light) {
  22114. const shadowCamera = this.camera;
  22115. const shadowMatrix = this.matrix;
  22116. _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld);
  22117. shadowCamera.position.copy(_lightPositionWorld$1);
  22118. _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld);
  22119. shadowCamera.lookAt(_lookTarget$1);
  22120. shadowCamera.updateMatrixWorld();
  22121. _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  22122. this._frustum.setFromProjectionMatrix(_projScreenMatrix$1);
  22123. 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);
  22124. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  22125. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  22126. }
  22127. getViewport(viewportIndex) {
  22128. return this._viewports[viewportIndex];
  22129. }
  22130. getFrameExtents() {
  22131. return this._frameExtents;
  22132. }
  22133. dispose() {
  22134. if (this.map) {
  22135. this.map.dispose();
  22136. }
  22137. if (this.mapPass) {
  22138. this.mapPass.dispose();
  22139. }
  22140. }
  22141. copy(source) {
  22142. this.camera = source.camera.clone();
  22143. this.bias = source.bias;
  22144. this.radius = source.radius;
  22145. this.mapSize.copy(source.mapSize);
  22146. return this;
  22147. }
  22148. clone() {
  22149. return new this.constructor().copy(this);
  22150. }
  22151. toJSON() {
  22152. const object = {};
  22153. if (this.bias !== 0) object.bias = this.bias;
  22154. if (this.normalBias !== 0) object.normalBias = this.normalBias;
  22155. if (this.radius !== 1) object.radius = this.radius;
  22156. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  22157. object.camera = this.camera.toJSON(false).object;
  22158. delete object.camera.matrix;
  22159. return object;
  22160. }
  22161. }
  22162. class SpotLightShadow extends LightShadow {
  22163. constructor() {
  22164. super(new PerspectiveCamera(50, 1, 0.5, 500));
  22165. this.focus = 1;
  22166. }
  22167. updateMatrices(light) {
  22168. const camera = this.camera;
  22169. const fov = RAD2DEG * 2 * light.angle * this.focus;
  22170. const aspect = this.mapSize.width / this.mapSize.height;
  22171. const far = light.distance || camera.far;
  22172. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  22173. camera.fov = fov;
  22174. camera.aspect = aspect;
  22175. camera.far = far;
  22176. camera.updateProjectionMatrix();
  22177. }
  22178. super.updateMatrices(light);
  22179. }
  22180. copy(source) {
  22181. super.copy(source);
  22182. this.focus = source.focus;
  22183. return this;
  22184. }
  22185. }
  22186. SpotLightShadow.prototype.isSpotLightShadow = true;
  22187. class SpotLight extends Light {
  22188. constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1) {
  22189. super(color, intensity);
  22190. this.type = 'SpotLight';
  22191. this.position.copy(Object3D.DefaultUp);
  22192. this.updateMatrix();
  22193. this.target = new Object3D();
  22194. this.distance = distance;
  22195. this.angle = angle;
  22196. this.penumbra = penumbra;
  22197. this.decay = decay; // for physically correct lights, should be 2.
  22198. this.shadow = new SpotLightShadow();
  22199. }
  22200. get power() {
  22201. // intensity = power per solid angle.
  22202. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22203. return this.intensity * Math.PI;
  22204. }
  22205. set power(power) {
  22206. // intensity = power per solid angle.
  22207. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22208. this.intensity = power / Math.PI;
  22209. }
  22210. dispose() {
  22211. this.shadow.dispose();
  22212. }
  22213. copy(source) {
  22214. super.copy(source);
  22215. this.distance = source.distance;
  22216. this.angle = source.angle;
  22217. this.penumbra = source.penumbra;
  22218. this.decay = source.decay;
  22219. this.target = source.target.clone();
  22220. this.shadow = source.shadow.clone();
  22221. return this;
  22222. }
  22223. }
  22224. SpotLight.prototype.isSpotLight = true;
  22225. const _projScreenMatrix = /*@__PURE__*/new Matrix4();
  22226. const _lightPositionWorld = /*@__PURE__*/new Vector3();
  22227. const _lookTarget = /*@__PURE__*/new Vector3();
  22228. class PointLightShadow extends LightShadow {
  22229. constructor() {
  22230. super(new PerspectiveCamera(90, 1, 0.5, 500));
  22231. this._frameExtents = new Vector2(4, 2);
  22232. this._viewportCount = 6;
  22233. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  22234. // following orientation:
  22235. //
  22236. // xzXZ
  22237. // y Y
  22238. //
  22239. // X - Positive x direction
  22240. // x - Negative x direction
  22241. // Y - Positive y direction
  22242. // y - Negative y direction
  22243. // Z - Positive z direction
  22244. // z - Negative z direction
  22245. // positive X
  22246. new Vector4(2, 1, 1, 1), // negative X
  22247. new Vector4(0, 1, 1, 1), // positive Z
  22248. new Vector4(3, 1, 1, 1), // negative Z
  22249. new Vector4(1, 1, 1, 1), // positive Y
  22250. new Vector4(3, 0, 1, 1), // negative Y
  22251. new Vector4(1, 0, 1, 1)];
  22252. 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)];
  22253. 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)];
  22254. }
  22255. updateMatrices(light, viewportIndex = 0) {
  22256. const camera = this.camera;
  22257. const shadowMatrix = this.matrix;
  22258. const far = light.distance || camera.far;
  22259. if (far !== camera.far) {
  22260. camera.far = far;
  22261. camera.updateProjectionMatrix();
  22262. }
  22263. _lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  22264. camera.position.copy(_lightPositionWorld);
  22265. _lookTarget.copy(camera.position);
  22266. _lookTarget.add(this._cubeDirections[viewportIndex]);
  22267. camera.up.copy(this._cubeUps[viewportIndex]);
  22268. camera.lookAt(_lookTarget);
  22269. camera.updateMatrixWorld();
  22270. shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z);
  22271. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  22272. this._frustum.setFromProjectionMatrix(_projScreenMatrix);
  22273. }
  22274. }
  22275. PointLightShadow.prototype.isPointLightShadow = true;
  22276. class PointLight extends Light {
  22277. constructor(color, intensity, distance = 0, decay = 1) {
  22278. super(color, intensity);
  22279. this.type = 'PointLight';
  22280. this.distance = distance;
  22281. this.decay = decay; // for physically correct lights, should be 2.
  22282. this.shadow = new PointLightShadow();
  22283. }
  22284. get power() {
  22285. // intensity = power per solid angle.
  22286. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22287. return this.intensity * 4 * Math.PI;
  22288. }
  22289. set power(power) {
  22290. // intensity = power per solid angle.
  22291. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  22292. this.intensity = power / (4 * Math.PI);
  22293. }
  22294. dispose() {
  22295. this.shadow.dispose();
  22296. }
  22297. copy(source) {
  22298. super.copy(source);
  22299. this.distance = source.distance;
  22300. this.decay = source.decay;
  22301. this.shadow = source.shadow.clone();
  22302. return this;
  22303. }
  22304. }
  22305. PointLight.prototype.isPointLight = true;
  22306. class OrthographicCamera extends Camera {
  22307. constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) {
  22308. super();
  22309. this.type = 'OrthographicCamera';
  22310. this.zoom = 1;
  22311. this.view = null;
  22312. this.left = left;
  22313. this.right = right;
  22314. this.top = top;
  22315. this.bottom = bottom;
  22316. this.near = near;
  22317. this.far = far;
  22318. this.updateProjectionMatrix();
  22319. }
  22320. copy(source, recursive) {
  22321. super.copy(source, recursive);
  22322. this.left = source.left;
  22323. this.right = source.right;
  22324. this.top = source.top;
  22325. this.bottom = source.bottom;
  22326. this.near = source.near;
  22327. this.far = source.far;
  22328. this.zoom = source.zoom;
  22329. this.view = source.view === null ? null : Object.assign({}, source.view);
  22330. return this;
  22331. }
  22332. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  22333. if (this.view === null) {
  22334. this.view = {
  22335. enabled: true,
  22336. fullWidth: 1,
  22337. fullHeight: 1,
  22338. offsetX: 0,
  22339. offsetY: 0,
  22340. width: 1,
  22341. height: 1
  22342. };
  22343. }
  22344. this.view.enabled = true;
  22345. this.view.fullWidth = fullWidth;
  22346. this.view.fullHeight = fullHeight;
  22347. this.view.offsetX = x;
  22348. this.view.offsetY = y;
  22349. this.view.width = width;
  22350. this.view.height = height;
  22351. this.updateProjectionMatrix();
  22352. }
  22353. clearViewOffset() {
  22354. if (this.view !== null) {
  22355. this.view.enabled = false;
  22356. }
  22357. this.updateProjectionMatrix();
  22358. }
  22359. updateProjectionMatrix() {
  22360. const dx = (this.right - this.left) / (2 * this.zoom);
  22361. const dy = (this.top - this.bottom) / (2 * this.zoom);
  22362. const cx = (this.right + this.left) / 2;
  22363. const cy = (this.top + this.bottom) / 2;
  22364. let left = cx - dx;
  22365. let right = cx + dx;
  22366. let top = cy + dy;
  22367. let bottom = cy - dy;
  22368. if (this.view !== null && this.view.enabled) {
  22369. const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  22370. const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  22371. left += scaleW * this.view.offsetX;
  22372. right = left + scaleW * this.view.width;
  22373. top -= scaleH * this.view.offsetY;
  22374. bottom = top - scaleH * this.view.height;
  22375. }
  22376. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  22377. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  22378. }
  22379. toJSON(meta) {
  22380. const data = super.toJSON(meta);
  22381. data.object.zoom = this.zoom;
  22382. data.object.left = this.left;
  22383. data.object.right = this.right;
  22384. data.object.top = this.top;
  22385. data.object.bottom = this.bottom;
  22386. data.object.near = this.near;
  22387. data.object.far = this.far;
  22388. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  22389. return data;
  22390. }
  22391. }
  22392. OrthographicCamera.prototype.isOrthographicCamera = true;
  22393. class DirectionalLightShadow extends LightShadow {
  22394. constructor() {
  22395. super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  22396. }
  22397. }
  22398. DirectionalLightShadow.prototype.isDirectionalLightShadow = true;
  22399. class DirectionalLight extends Light {
  22400. constructor(color, intensity) {
  22401. super(color, intensity);
  22402. this.type = 'DirectionalLight';
  22403. this.position.copy(Object3D.DefaultUp);
  22404. this.updateMatrix();
  22405. this.target = new Object3D();
  22406. this.shadow = new DirectionalLightShadow();
  22407. }
  22408. dispose() {
  22409. this.shadow.dispose();
  22410. }
  22411. copy(source) {
  22412. super.copy(source);
  22413. this.target = source.target.clone();
  22414. this.shadow = source.shadow.clone();
  22415. return this;
  22416. }
  22417. }
  22418. DirectionalLight.prototype.isDirectionalLight = true;
  22419. class AmbientLight extends Light {
  22420. constructor(color, intensity) {
  22421. super(color, intensity);
  22422. this.type = 'AmbientLight';
  22423. }
  22424. }
  22425. AmbientLight.prototype.isAmbientLight = true;
  22426. class RectAreaLight extends Light {
  22427. constructor(color, intensity, width = 10, height = 10) {
  22428. super(color, intensity);
  22429. this.type = 'RectAreaLight';
  22430. this.width = width;
  22431. this.height = height;
  22432. }
  22433. copy(source) {
  22434. super.copy(source);
  22435. this.width = source.width;
  22436. this.height = source.height;
  22437. return this;
  22438. }
  22439. toJSON(meta) {
  22440. const data = super.toJSON(meta);
  22441. data.object.width = this.width;
  22442. data.object.height = this.height;
  22443. return data;
  22444. }
  22445. }
  22446. RectAreaLight.prototype.isRectAreaLight = true;
  22447. /**
  22448. * Primary reference:
  22449. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  22450. *
  22451. * Secondary reference:
  22452. * https://www.ppsloan.org/publications/StupidSH36.pdf
  22453. */
  22454. // 3-band SH defined by 9 coefficients
  22455. class SphericalHarmonics3 {
  22456. constructor() {
  22457. this.coefficients = [];
  22458. for (let i = 0; i < 9; i++) {
  22459. this.coefficients.push(new Vector3());
  22460. }
  22461. }
  22462. set(coefficients) {
  22463. for (let i = 0; i < 9; i++) {
  22464. this.coefficients[i].copy(coefficients[i]);
  22465. }
  22466. return this;
  22467. }
  22468. zero() {
  22469. for (let i = 0; i < 9; i++) {
  22470. this.coefficients[i].set(0, 0, 0);
  22471. }
  22472. return this;
  22473. } // get the radiance in the direction of the normal
  22474. // target is a Vector3
  22475. getAt(normal, target) {
  22476. // normal is assumed to be unit length
  22477. const x = normal.x,
  22478. y = normal.y,
  22479. z = normal.z;
  22480. const coeff = this.coefficients; // band 0
  22481. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  22482. target.addScaledVector(coeff[1], 0.488603 * y);
  22483. target.addScaledVector(coeff[2], 0.488603 * z);
  22484. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  22485. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  22486. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  22487. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  22488. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  22489. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  22490. return target;
  22491. } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  22492. // target is a Vector3
  22493. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  22494. getIrradianceAt(normal, target) {
  22495. // normal is assumed to be unit length
  22496. const x = normal.x,
  22497. y = normal.y,
  22498. z = normal.z;
  22499. const coeff = this.coefficients; // band 0
  22500. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  22501. // band 1
  22502. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  22503. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  22504. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  22505. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  22506. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  22507. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  22508. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  22509. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  22510. return target;
  22511. }
  22512. add(sh) {
  22513. for (let i = 0; i < 9; i++) {
  22514. this.coefficients[i].add(sh.coefficients[i]);
  22515. }
  22516. return this;
  22517. }
  22518. addScaledSH(sh, s) {
  22519. for (let i = 0; i < 9; i++) {
  22520. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  22521. }
  22522. return this;
  22523. }
  22524. scale(s) {
  22525. for (let i = 0; i < 9; i++) {
  22526. this.coefficients[i].multiplyScalar(s);
  22527. }
  22528. return this;
  22529. }
  22530. lerp(sh, alpha) {
  22531. for (let i = 0; i < 9; i++) {
  22532. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  22533. }
  22534. return this;
  22535. }
  22536. equals(sh) {
  22537. for (let i = 0; i < 9; i++) {
  22538. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  22539. return false;
  22540. }
  22541. }
  22542. return true;
  22543. }
  22544. copy(sh) {
  22545. return this.set(sh.coefficients);
  22546. }
  22547. clone() {
  22548. return new this.constructor().copy(this);
  22549. }
  22550. fromArray(array, offset = 0) {
  22551. const coefficients = this.coefficients;
  22552. for (let i = 0; i < 9; i++) {
  22553. coefficients[i].fromArray(array, offset + i * 3);
  22554. }
  22555. return this;
  22556. }
  22557. toArray(array = [], offset = 0) {
  22558. const coefficients = this.coefficients;
  22559. for (let i = 0; i < 9; i++) {
  22560. coefficients[i].toArray(array, offset + i * 3);
  22561. }
  22562. return array;
  22563. } // evaluate the basis functions
  22564. // shBasis is an Array[ 9 ]
  22565. static getBasisAt(normal, shBasis) {
  22566. // normal is assumed to be unit length
  22567. const x = normal.x,
  22568. y = normal.y,
  22569. z = normal.z; // band 0
  22570. shBasis[0] = 0.282095; // band 1
  22571. shBasis[1] = 0.488603 * y;
  22572. shBasis[2] = 0.488603 * z;
  22573. shBasis[3] = 0.488603 * x; // band 2
  22574. shBasis[4] = 1.092548 * x * y;
  22575. shBasis[5] = 1.092548 * y * z;
  22576. shBasis[6] = 0.315392 * (3 * z * z - 1);
  22577. shBasis[7] = 1.092548 * x * z;
  22578. shBasis[8] = 0.546274 * (x * x - y * y);
  22579. }
  22580. }
  22581. SphericalHarmonics3.prototype.isSphericalHarmonics3 = true;
  22582. class LightProbe extends Light {
  22583. constructor(sh = new SphericalHarmonics3(), intensity = 1) {
  22584. super(undefined, intensity);
  22585. this.sh = sh;
  22586. }
  22587. copy(source) {
  22588. super.copy(source);
  22589. this.sh.copy(source.sh);
  22590. return this;
  22591. }
  22592. fromJSON(json) {
  22593. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  22594. this.sh.fromArray(json.sh);
  22595. return this;
  22596. }
  22597. toJSON(meta) {
  22598. const data = super.toJSON(meta);
  22599. data.object.sh = this.sh.toArray();
  22600. return data;
  22601. }
  22602. }
  22603. LightProbe.prototype.isLightProbe = true;
  22604. class MaterialLoader extends Loader {
  22605. constructor(manager) {
  22606. super(manager);
  22607. this.textures = {};
  22608. }
  22609. load(url, onLoad, onProgress, onError) {
  22610. const scope = this;
  22611. const loader = new FileLoader(scope.manager);
  22612. loader.setPath(scope.path);
  22613. loader.setRequestHeader(scope.requestHeader);
  22614. loader.setWithCredentials(scope.withCredentials);
  22615. loader.load(url, function (text) {
  22616. try {
  22617. onLoad(scope.parse(JSON.parse(text)));
  22618. } catch (e) {
  22619. if (onError) {
  22620. onError(e);
  22621. } else {
  22622. console.error(e);
  22623. }
  22624. scope.manager.itemError(url);
  22625. }
  22626. }, onProgress, onError);
  22627. }
  22628. parse(json) {
  22629. const textures = this.textures;
  22630. function getTexture(name) {
  22631. if (textures[name] === undefined) {
  22632. console.warn('THREE.MaterialLoader: Undefined texture', name);
  22633. }
  22634. return textures[name];
  22635. }
  22636. const material = new Materials[json.type]();
  22637. if (json.uuid !== undefined) material.uuid = json.uuid;
  22638. if (json.name !== undefined) material.name = json.name;
  22639. if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
  22640. if (json.roughness !== undefined) material.roughness = json.roughness;
  22641. if (json.metalness !== undefined) material.metalness = json.metalness;
  22642. if (json.sheen !== undefined) material.sheen = new Color().setHex(json.sheen);
  22643. if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
  22644. if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
  22645. if (json.shininess !== undefined) material.shininess = json.shininess;
  22646. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  22647. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  22648. if (json.transmission !== undefined) material.transmission = json.transmission;
  22649. if (json.thickness !== undefined) material.thickness = json.thickness;
  22650. if (json.attenuationDistance !== undefined) material.attenuationDistance = json.attenuationDistance;
  22651. if (json.attenuationColor !== undefined && material.attenuationColor !== undefined) material.attenuationColor.setHex(json.attenuationColor);
  22652. if (json.fog !== undefined) material.fog = json.fog;
  22653. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  22654. if (json.blending !== undefined) material.blending = json.blending;
  22655. if (json.combine !== undefined) material.combine = json.combine;
  22656. if (json.side !== undefined) material.side = json.side;
  22657. if (json.shadowSide !== undefined) material.shadowSide = json.shadowSide;
  22658. if (json.opacity !== undefined) material.opacity = json.opacity;
  22659. if (json.transparent !== undefined) material.transparent = json.transparent;
  22660. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  22661. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  22662. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  22663. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  22664. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  22665. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  22666. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  22667. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  22668. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  22669. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  22670. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  22671. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  22672. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  22673. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  22674. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  22675. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  22676. if (json.rotation !== undefined) material.rotation = json.rotation;
  22677. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  22678. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  22679. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  22680. if (json.scale !== undefined) material.scale = json.scale;
  22681. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  22682. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  22683. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  22684. if (json.morphTargets !== undefined) material.morphTargets = json.morphTargets;
  22685. if (json.morphNormals !== undefined) material.morphNormals = json.morphNormals;
  22686. if (json.dithering !== undefined) material.dithering = json.dithering;
  22687. if (json.alphaToCoverage !== undefined) material.alphaToCoverage = json.alphaToCoverage;
  22688. if (json.premultipliedAlpha !== undefined) material.premultipliedAlpha = json.premultipliedAlpha;
  22689. if (json.vertexTangents !== undefined) material.vertexTangents = json.vertexTangents;
  22690. if (json.visible !== undefined) material.visible = json.visible;
  22691. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  22692. if (json.userData !== undefined) material.userData = json.userData;
  22693. if (json.vertexColors !== undefined) {
  22694. if (typeof json.vertexColors === 'number') {
  22695. material.vertexColors = json.vertexColors > 0 ? true : false;
  22696. } else {
  22697. material.vertexColors = json.vertexColors;
  22698. }
  22699. } // Shader Material
  22700. if (json.uniforms !== undefined) {
  22701. for (const name in json.uniforms) {
  22702. const uniform = json.uniforms[name];
  22703. material.uniforms[name] = {};
  22704. switch (uniform.type) {
  22705. case 't':
  22706. material.uniforms[name].value = getTexture(uniform.value);
  22707. break;
  22708. case 'c':
  22709. material.uniforms[name].value = new Color().setHex(uniform.value);
  22710. break;
  22711. case 'v2':
  22712. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  22713. break;
  22714. case 'v3':
  22715. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  22716. break;
  22717. case 'v4':
  22718. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  22719. break;
  22720. case 'm3':
  22721. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  22722. break;
  22723. case 'm4':
  22724. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  22725. break;
  22726. default:
  22727. material.uniforms[name].value = uniform.value;
  22728. }
  22729. }
  22730. }
  22731. if (json.defines !== undefined) material.defines = json.defines;
  22732. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  22733. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  22734. if (json.extensions !== undefined) {
  22735. for (const key in json.extensions) {
  22736. material.extensions[key] = json.extensions[key];
  22737. }
  22738. } // Deprecated
  22739. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  22740. // for PointsMaterial
  22741. if (json.size !== undefined) material.size = json.size;
  22742. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  22743. if (json.map !== undefined) material.map = getTexture(json.map);
  22744. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  22745. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  22746. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  22747. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  22748. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  22749. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  22750. if (json.normalScale !== undefined) {
  22751. let normalScale = json.normalScale;
  22752. if (Array.isArray(normalScale) === false) {
  22753. // Blender exporter used to export a scalar. See #7459
  22754. normalScale = [normalScale, normalScale];
  22755. }
  22756. material.normalScale = new Vector2().fromArray(normalScale);
  22757. }
  22758. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  22759. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  22760. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  22761. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  22762. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  22763. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  22764. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  22765. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  22766. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  22767. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  22768. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  22769. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  22770. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  22771. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  22772. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  22773. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  22774. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  22775. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  22776. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  22777. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  22778. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  22779. if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
  22780. if (json.thicknessMap !== undefined) material.thicknessMap = getTexture(json.thicknessMap);
  22781. return material;
  22782. }
  22783. setTextures(value) {
  22784. this.textures = value;
  22785. return this;
  22786. }
  22787. }
  22788. class LoaderUtils {
  22789. static decodeText(array) {
  22790. if (typeof TextDecoder !== 'undefined') {
  22791. return new TextDecoder().decode(array);
  22792. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  22793. // throws a "maximum call stack size exceeded" error for large arrays.
  22794. let s = '';
  22795. for (let i = 0, il = array.length; i < il; i++) {
  22796. // Implicitly assumes little-endian.
  22797. s += String.fromCharCode(array[i]);
  22798. }
  22799. try {
  22800. // merges multi-byte utf-8 characters.
  22801. return decodeURIComponent(escape(s));
  22802. } catch (e) {
  22803. // see #16358
  22804. return s;
  22805. }
  22806. }
  22807. static extractUrlBase(url) {
  22808. const index = url.lastIndexOf('/');
  22809. if (index === -1) return './';
  22810. return url.substr(0, index + 1);
  22811. }
  22812. }
  22813. class InstancedBufferGeometry extends BufferGeometry {
  22814. constructor() {
  22815. super();
  22816. this.type = 'InstancedBufferGeometry';
  22817. this.instanceCount = Infinity;
  22818. }
  22819. copy(source) {
  22820. super.copy(source);
  22821. this.instanceCount = source.instanceCount;
  22822. return this;
  22823. }
  22824. clone() {
  22825. return new this.constructor().copy(this);
  22826. }
  22827. toJSON() {
  22828. const data = super.toJSON(this);
  22829. data.instanceCount = this.instanceCount;
  22830. data.isInstancedBufferGeometry = true;
  22831. return data;
  22832. }
  22833. }
  22834. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  22835. class InstancedBufferAttribute extends BufferAttribute {
  22836. constructor(array, itemSize, normalized, meshPerAttribute) {
  22837. if (typeof normalized === 'number') {
  22838. meshPerAttribute = normalized;
  22839. normalized = false;
  22840. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  22841. }
  22842. super(array, itemSize, normalized);
  22843. this.meshPerAttribute = meshPerAttribute || 1;
  22844. }
  22845. copy(source) {
  22846. super.copy(source);
  22847. this.meshPerAttribute = source.meshPerAttribute;
  22848. return this;
  22849. }
  22850. toJSON() {
  22851. const data = super.toJSON();
  22852. data.meshPerAttribute = this.meshPerAttribute;
  22853. data.isInstancedBufferAttribute = true;
  22854. return data;
  22855. }
  22856. }
  22857. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  22858. class BufferGeometryLoader extends Loader {
  22859. constructor(manager) {
  22860. super(manager);
  22861. }
  22862. load(url, onLoad, onProgress, onError) {
  22863. const scope = this;
  22864. const loader = new FileLoader(scope.manager);
  22865. loader.setPath(scope.path);
  22866. loader.setRequestHeader(scope.requestHeader);
  22867. loader.setWithCredentials(scope.withCredentials);
  22868. loader.load(url, function (text) {
  22869. try {
  22870. onLoad(scope.parse(JSON.parse(text)));
  22871. } catch (e) {
  22872. if (onError) {
  22873. onError(e);
  22874. } else {
  22875. console.error(e);
  22876. }
  22877. scope.manager.itemError(url);
  22878. }
  22879. }, onProgress, onError);
  22880. }
  22881. parse(json) {
  22882. const interleavedBufferMap = {};
  22883. const arrayBufferMap = {};
  22884. function getInterleavedBuffer(json, uuid) {
  22885. if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
  22886. const interleavedBuffers = json.interleavedBuffers;
  22887. const interleavedBuffer = interleavedBuffers[uuid];
  22888. const buffer = getArrayBuffer(json, interleavedBuffer.buffer);
  22889. const array = getTypedArray(interleavedBuffer.type, buffer);
  22890. const ib = new InterleavedBuffer(array, interleavedBuffer.stride);
  22891. ib.uuid = interleavedBuffer.uuid;
  22892. interleavedBufferMap[uuid] = ib;
  22893. return ib;
  22894. }
  22895. function getArrayBuffer(json, uuid) {
  22896. if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
  22897. const arrayBuffers = json.arrayBuffers;
  22898. const arrayBuffer = arrayBuffers[uuid];
  22899. const ab = new Uint32Array(arrayBuffer).buffer;
  22900. arrayBufferMap[uuid] = ab;
  22901. return ab;
  22902. }
  22903. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  22904. const index = json.data.index;
  22905. if (index !== undefined) {
  22906. const typedArray = getTypedArray(index.type, index.array);
  22907. geometry.setIndex(new BufferAttribute(typedArray, 1));
  22908. }
  22909. const attributes = json.data.attributes;
  22910. for (const key in attributes) {
  22911. const attribute = attributes[key];
  22912. let bufferAttribute;
  22913. if (attribute.isInterleavedBufferAttribute) {
  22914. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  22915. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  22916. } else {
  22917. const typedArray = getTypedArray(attribute.type, attribute.array);
  22918. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  22919. bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  22920. }
  22921. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  22922. if (attribute.usage !== undefined) bufferAttribute.setUsage(attribute.usage);
  22923. if (attribute.updateRange !== undefined) {
  22924. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  22925. bufferAttribute.updateRange.count = attribute.updateRange.count;
  22926. }
  22927. geometry.setAttribute(key, bufferAttribute);
  22928. }
  22929. const morphAttributes = json.data.morphAttributes;
  22930. if (morphAttributes) {
  22931. for (const key in morphAttributes) {
  22932. const attributeArray = morphAttributes[key];
  22933. const array = [];
  22934. for (let i = 0, il = attributeArray.length; i < il; i++) {
  22935. const attribute = attributeArray[i];
  22936. let bufferAttribute;
  22937. if (attribute.isInterleavedBufferAttribute) {
  22938. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  22939. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  22940. } else {
  22941. const typedArray = getTypedArray(attribute.type, attribute.array);
  22942. bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  22943. }
  22944. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  22945. array.push(bufferAttribute);
  22946. }
  22947. geometry.morphAttributes[key] = array;
  22948. }
  22949. }
  22950. const morphTargetsRelative = json.data.morphTargetsRelative;
  22951. if (morphTargetsRelative) {
  22952. geometry.morphTargetsRelative = true;
  22953. }
  22954. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  22955. if (groups !== undefined) {
  22956. for (let i = 0, n = groups.length; i !== n; ++i) {
  22957. const group = groups[i];
  22958. geometry.addGroup(group.start, group.count, group.materialIndex);
  22959. }
  22960. }
  22961. const boundingSphere = json.data.boundingSphere;
  22962. if (boundingSphere !== undefined) {
  22963. const center = new Vector3();
  22964. if (boundingSphere.center !== undefined) {
  22965. center.fromArray(boundingSphere.center);
  22966. }
  22967. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  22968. }
  22969. if (json.name) geometry.name = json.name;
  22970. if (json.userData) geometry.userData = json.userData;
  22971. return geometry;
  22972. }
  22973. }
  22974. class ObjectLoader extends Loader {
  22975. constructor(manager) {
  22976. super(manager);
  22977. }
  22978. load(url, onLoad, onProgress, onError) {
  22979. const scope = this;
  22980. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  22981. this.resourcePath = this.resourcePath || path;
  22982. const loader = new FileLoader(this.manager);
  22983. loader.setPath(this.path);
  22984. loader.setRequestHeader(this.requestHeader);
  22985. loader.setWithCredentials(this.withCredentials);
  22986. loader.load(url, function (text) {
  22987. let json = null;
  22988. try {
  22989. json = JSON.parse(text);
  22990. } catch (error) {
  22991. if (onError !== undefined) onError(error);
  22992. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  22993. return;
  22994. }
  22995. const metadata = json.metadata;
  22996. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  22997. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  22998. return;
  22999. }
  23000. scope.parse(json, onLoad);
  23001. }, onProgress, onError);
  23002. }
  23003. parse(json, onLoad) {
  23004. const animations = this.parseAnimations(json.animations);
  23005. const shapes = this.parseShapes(json.shapes);
  23006. const geometries = this.parseGeometries(json.geometries, shapes);
  23007. const images = this.parseImages(json.images, function () {
  23008. if (onLoad !== undefined) onLoad(object);
  23009. });
  23010. const textures = this.parseTextures(json.textures, images);
  23011. const materials = this.parseMaterials(json.materials, textures);
  23012. const object = this.parseObject(json.object, geometries, materials, animations);
  23013. const skeletons = this.parseSkeletons(json.skeletons, object);
  23014. this.bindSkeletons(object, skeletons); //
  23015. if (onLoad !== undefined) {
  23016. let hasImages = false;
  23017. for (const uuid in images) {
  23018. if (images[uuid] instanceof HTMLImageElement) {
  23019. hasImages = true;
  23020. break;
  23021. }
  23022. }
  23023. if (hasImages === false) onLoad(object);
  23024. }
  23025. return object;
  23026. }
  23027. parseShapes(json) {
  23028. const shapes = {};
  23029. if (json !== undefined) {
  23030. for (let i = 0, l = json.length; i < l; i++) {
  23031. const shape = new Shape().fromJSON(json[i]);
  23032. shapes[shape.uuid] = shape;
  23033. }
  23034. }
  23035. return shapes;
  23036. }
  23037. parseSkeletons(json, object) {
  23038. const skeletons = {};
  23039. const bones = {}; // generate bone lookup table
  23040. object.traverse(function (child) {
  23041. if (child.isBone) bones[child.uuid] = child;
  23042. }); // create skeletons
  23043. if (json !== undefined) {
  23044. for (let i = 0, l = json.length; i < l; i++) {
  23045. const skeleton = new Skeleton().fromJSON(json[i], bones);
  23046. skeletons[skeleton.uuid] = skeleton;
  23047. }
  23048. }
  23049. return skeletons;
  23050. }
  23051. parseGeometries(json, shapes) {
  23052. const geometries = {};
  23053. let geometryShapes;
  23054. if (json !== undefined) {
  23055. const bufferGeometryLoader = new BufferGeometryLoader();
  23056. for (let i = 0, l = json.length; i < l; i++) {
  23057. let geometry;
  23058. const data = json[i];
  23059. switch (data.type) {
  23060. case 'PlaneGeometry':
  23061. case 'PlaneBufferGeometry':
  23062. geometry = new Geometries[data.type](data.width, data.height, data.widthSegments, data.heightSegments);
  23063. break;
  23064. case 'BoxGeometry':
  23065. case 'BoxBufferGeometry':
  23066. geometry = new Geometries[data.type](data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  23067. break;
  23068. case 'CircleGeometry':
  23069. case 'CircleBufferGeometry':
  23070. geometry = new Geometries[data.type](data.radius, data.segments, data.thetaStart, data.thetaLength);
  23071. break;
  23072. case 'CylinderGeometry':
  23073. case 'CylinderBufferGeometry':
  23074. geometry = new Geometries[data.type](data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  23075. break;
  23076. case 'ConeGeometry':
  23077. case 'ConeBufferGeometry':
  23078. geometry = new Geometries[data.type](data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  23079. break;
  23080. case 'SphereGeometry':
  23081. case 'SphereBufferGeometry':
  23082. geometry = new Geometries[data.type](data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  23083. break;
  23084. case 'DodecahedronGeometry':
  23085. case 'DodecahedronBufferGeometry':
  23086. case 'IcosahedronGeometry':
  23087. case 'IcosahedronBufferGeometry':
  23088. case 'OctahedronGeometry':
  23089. case 'OctahedronBufferGeometry':
  23090. case 'TetrahedronGeometry':
  23091. case 'TetrahedronBufferGeometry':
  23092. geometry = new Geometries[data.type](data.radius, data.detail);
  23093. break;
  23094. case 'RingGeometry':
  23095. case 'RingBufferGeometry':
  23096. geometry = new Geometries[data.type](data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  23097. break;
  23098. case 'TorusGeometry':
  23099. case 'TorusBufferGeometry':
  23100. geometry = new Geometries[data.type](data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  23101. break;
  23102. case 'TorusKnotGeometry':
  23103. case 'TorusKnotBufferGeometry':
  23104. geometry = new Geometries[data.type](data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  23105. break;
  23106. case 'TubeGeometry':
  23107. case 'TubeBufferGeometry':
  23108. // This only works for built-in curves (e.g. CatmullRomCurve3).
  23109. // User defined curves or instances of CurvePath will not be deserialized.
  23110. geometry = new Geometries[data.type](new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  23111. break;
  23112. case 'LatheGeometry':
  23113. case 'LatheBufferGeometry':
  23114. geometry = new Geometries[data.type](data.points, data.segments, data.phiStart, data.phiLength);
  23115. break;
  23116. case 'PolyhedronGeometry':
  23117. case 'PolyhedronBufferGeometry':
  23118. geometry = new Geometries[data.type](data.vertices, data.indices, data.radius, data.details);
  23119. break;
  23120. case 'ShapeGeometry':
  23121. case 'ShapeBufferGeometry':
  23122. geometryShapes = [];
  23123. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  23124. const shape = shapes[data.shapes[j]];
  23125. geometryShapes.push(shape);
  23126. }
  23127. geometry = new Geometries[data.type](geometryShapes, data.curveSegments);
  23128. break;
  23129. case 'ExtrudeGeometry':
  23130. case 'ExtrudeBufferGeometry':
  23131. geometryShapes = [];
  23132. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  23133. const shape = shapes[data.shapes[j]];
  23134. geometryShapes.push(shape);
  23135. }
  23136. const extrudePath = data.options.extrudePath;
  23137. if (extrudePath !== undefined) {
  23138. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  23139. }
  23140. geometry = new Geometries[data.type](geometryShapes, data.options);
  23141. break;
  23142. case 'BufferGeometry':
  23143. case 'InstancedBufferGeometry':
  23144. geometry = bufferGeometryLoader.parse(data);
  23145. break;
  23146. case 'Geometry':
  23147. console.error('THREE.ObjectLoader: Loading "Geometry" is not supported anymore.');
  23148. break;
  23149. default:
  23150. console.warn('THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"');
  23151. continue;
  23152. }
  23153. geometry.uuid = data.uuid;
  23154. if (data.name !== undefined) geometry.name = data.name;
  23155. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  23156. geometries[data.uuid] = geometry;
  23157. }
  23158. }
  23159. return geometries;
  23160. }
  23161. parseMaterials(json, textures) {
  23162. const cache = {}; // MultiMaterial
  23163. const materials = {};
  23164. if (json !== undefined) {
  23165. const loader = new MaterialLoader();
  23166. loader.setTextures(textures);
  23167. for (let i = 0, l = json.length; i < l; i++) {
  23168. const data = json[i];
  23169. if (data.type === 'MultiMaterial') {
  23170. // Deprecated
  23171. const array = [];
  23172. for (let j = 0; j < data.materials.length; j++) {
  23173. const material = data.materials[j];
  23174. if (cache[material.uuid] === undefined) {
  23175. cache[material.uuid] = loader.parse(material);
  23176. }
  23177. array.push(cache[material.uuid]);
  23178. }
  23179. materials[data.uuid] = array;
  23180. } else {
  23181. if (cache[data.uuid] === undefined) {
  23182. cache[data.uuid] = loader.parse(data);
  23183. }
  23184. materials[data.uuid] = cache[data.uuid];
  23185. }
  23186. }
  23187. }
  23188. return materials;
  23189. }
  23190. parseAnimations(json) {
  23191. const animations = {};
  23192. if (json !== undefined) {
  23193. for (let i = 0; i < json.length; i++) {
  23194. const data = json[i];
  23195. const clip = AnimationClip.parse(data);
  23196. animations[clip.uuid] = clip;
  23197. }
  23198. }
  23199. return animations;
  23200. }
  23201. parseImages(json, onLoad) {
  23202. const scope = this;
  23203. const images = {};
  23204. let loader;
  23205. function loadImage(url) {
  23206. scope.manager.itemStart(url);
  23207. return loader.load(url, function () {
  23208. scope.manager.itemEnd(url);
  23209. }, undefined, function () {
  23210. scope.manager.itemError(url);
  23211. scope.manager.itemEnd(url);
  23212. });
  23213. }
  23214. function deserializeImage(image) {
  23215. if (typeof image === 'string') {
  23216. const url = image;
  23217. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  23218. return loadImage(path);
  23219. } else {
  23220. if (image.data) {
  23221. return {
  23222. data: getTypedArray(image.type, image.data),
  23223. width: image.width,
  23224. height: image.height
  23225. };
  23226. } else {
  23227. return null;
  23228. }
  23229. }
  23230. }
  23231. if (json !== undefined && json.length > 0) {
  23232. const manager = new LoadingManager(onLoad);
  23233. loader = new ImageLoader(manager);
  23234. loader.setCrossOrigin(this.crossOrigin);
  23235. for (let i = 0, il = json.length; i < il; i++) {
  23236. const image = json[i];
  23237. const url = image.url;
  23238. if (Array.isArray(url)) {
  23239. // load array of images e.g CubeTexture
  23240. images[image.uuid] = [];
  23241. for (let j = 0, jl = url.length; j < jl; j++) {
  23242. const currentUrl = url[j];
  23243. const deserializedImage = deserializeImage(currentUrl);
  23244. if (deserializedImage !== null) {
  23245. if (deserializedImage instanceof HTMLImageElement) {
  23246. images[image.uuid].push(deserializedImage);
  23247. } else {
  23248. // special case: handle array of data textures for cube textures
  23249. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  23250. }
  23251. }
  23252. }
  23253. } else {
  23254. // load single image
  23255. const deserializedImage = deserializeImage(image.url);
  23256. if (deserializedImage !== null) {
  23257. images[image.uuid] = deserializedImage;
  23258. }
  23259. }
  23260. }
  23261. }
  23262. return images;
  23263. }
  23264. parseTextures(json, images) {
  23265. function parseConstant(value, type) {
  23266. if (typeof value === 'number') return value;
  23267. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  23268. return type[value];
  23269. }
  23270. const textures = {};
  23271. if (json !== undefined) {
  23272. for (let i = 0, l = json.length; i < l; i++) {
  23273. const data = json[i];
  23274. if (data.image === undefined) {
  23275. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  23276. }
  23277. if (images[data.image] === undefined) {
  23278. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  23279. }
  23280. let texture;
  23281. const image = images[data.image];
  23282. if (Array.isArray(image)) {
  23283. texture = new CubeTexture(image);
  23284. if (image.length === 6) texture.needsUpdate = true;
  23285. } else {
  23286. if (image && image.data) {
  23287. texture = new DataTexture(image.data, image.width, image.height);
  23288. } else {
  23289. texture = new Texture(image);
  23290. }
  23291. if (image) texture.needsUpdate = true; // textures can have undefined image data
  23292. }
  23293. texture.uuid = data.uuid;
  23294. if (data.name !== undefined) texture.name = data.name;
  23295. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  23296. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  23297. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  23298. if (data.center !== undefined) texture.center.fromArray(data.center);
  23299. if (data.rotation !== undefined) texture.rotation = data.rotation;
  23300. if (data.wrap !== undefined) {
  23301. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  23302. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  23303. }
  23304. if (data.format !== undefined) texture.format = data.format;
  23305. if (data.type !== undefined) texture.type = data.type;
  23306. if (data.encoding !== undefined) texture.encoding = data.encoding;
  23307. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  23308. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  23309. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  23310. if (data.flipY !== undefined) texture.flipY = data.flipY;
  23311. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  23312. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  23313. textures[data.uuid] = texture;
  23314. }
  23315. }
  23316. return textures;
  23317. }
  23318. parseObject(data, geometries, materials, animations) {
  23319. let object;
  23320. function getGeometry(name) {
  23321. if (geometries[name] === undefined) {
  23322. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  23323. }
  23324. return geometries[name];
  23325. }
  23326. function getMaterial(name) {
  23327. if (name === undefined) return undefined;
  23328. if (Array.isArray(name)) {
  23329. const array = [];
  23330. for (let i = 0, l = name.length; i < l; i++) {
  23331. const uuid = name[i];
  23332. if (materials[uuid] === undefined) {
  23333. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  23334. }
  23335. array.push(materials[uuid]);
  23336. }
  23337. return array;
  23338. }
  23339. if (materials[name] === undefined) {
  23340. console.warn('THREE.ObjectLoader: Undefined material', name);
  23341. }
  23342. return materials[name];
  23343. }
  23344. let geometry, material;
  23345. switch (data.type) {
  23346. case 'Scene':
  23347. object = new Scene();
  23348. if (data.background !== undefined) {
  23349. if (Number.isInteger(data.background)) {
  23350. object.background = new Color(data.background);
  23351. }
  23352. }
  23353. if (data.fog !== undefined) {
  23354. if (data.fog.type === 'Fog') {
  23355. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  23356. } else if (data.fog.type === 'FogExp2') {
  23357. object.fog = new FogExp2(data.fog.color, data.fog.density);
  23358. }
  23359. }
  23360. break;
  23361. case 'PerspectiveCamera':
  23362. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  23363. if (data.focus !== undefined) object.focus = data.focus;
  23364. if (data.zoom !== undefined) object.zoom = data.zoom;
  23365. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  23366. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  23367. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  23368. break;
  23369. case 'OrthographicCamera':
  23370. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  23371. if (data.zoom !== undefined) object.zoom = data.zoom;
  23372. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  23373. break;
  23374. case 'AmbientLight':
  23375. object = new AmbientLight(data.color, data.intensity);
  23376. break;
  23377. case 'DirectionalLight':
  23378. object = new DirectionalLight(data.color, data.intensity);
  23379. break;
  23380. case 'PointLight':
  23381. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  23382. break;
  23383. case 'RectAreaLight':
  23384. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  23385. break;
  23386. case 'SpotLight':
  23387. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  23388. break;
  23389. case 'HemisphereLight':
  23390. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  23391. break;
  23392. case 'LightProbe':
  23393. object = new LightProbe().fromJSON(data);
  23394. break;
  23395. case 'SkinnedMesh':
  23396. geometry = getGeometry(data.geometry);
  23397. material = getMaterial(data.material);
  23398. object = new SkinnedMesh(geometry, material);
  23399. if (data.bindMode !== undefined) object.bindMode = data.bindMode;
  23400. if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
  23401. if (data.skeleton !== undefined) object.skeleton = data.skeleton;
  23402. break;
  23403. case 'Mesh':
  23404. geometry = getGeometry(data.geometry);
  23405. material = getMaterial(data.material);
  23406. object = new Mesh(geometry, material);
  23407. break;
  23408. case 'InstancedMesh':
  23409. geometry = getGeometry(data.geometry);
  23410. material = getMaterial(data.material);
  23411. const count = data.count;
  23412. const instanceMatrix = data.instanceMatrix;
  23413. const instanceColor = data.instanceColor;
  23414. object = new InstancedMesh(geometry, material, count);
  23415. object.instanceMatrix = new BufferAttribute(new Float32Array(instanceMatrix.array), 16);
  23416. if (instanceColor !== undefined) object.instanceColor = new BufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize);
  23417. break;
  23418. case 'LOD':
  23419. object = new LOD();
  23420. break;
  23421. case 'Line':
  23422. object = new Line(getGeometry(data.geometry), getMaterial(data.material));
  23423. break;
  23424. case 'LineLoop':
  23425. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  23426. break;
  23427. case 'LineSegments':
  23428. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  23429. break;
  23430. case 'PointCloud':
  23431. case 'Points':
  23432. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  23433. break;
  23434. case 'Sprite':
  23435. object = new Sprite(getMaterial(data.material));
  23436. break;
  23437. case 'Group':
  23438. object = new Group();
  23439. break;
  23440. case 'Bone':
  23441. object = new Bone();
  23442. break;
  23443. default:
  23444. object = new Object3D();
  23445. }
  23446. object.uuid = data.uuid;
  23447. if (data.name !== undefined) object.name = data.name;
  23448. if (data.matrix !== undefined) {
  23449. object.matrix.fromArray(data.matrix);
  23450. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  23451. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  23452. } else {
  23453. if (data.position !== undefined) object.position.fromArray(data.position);
  23454. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  23455. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  23456. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  23457. }
  23458. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  23459. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  23460. if (data.shadow) {
  23461. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  23462. if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
  23463. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  23464. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  23465. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  23466. }
  23467. if (data.visible !== undefined) object.visible = data.visible;
  23468. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  23469. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  23470. if (data.userData !== undefined) object.userData = data.userData;
  23471. if (data.layers !== undefined) object.layers.mask = data.layers;
  23472. if (data.children !== undefined) {
  23473. const children = data.children;
  23474. for (let i = 0; i < children.length; i++) {
  23475. object.add(this.parseObject(children[i], geometries, materials, animations));
  23476. }
  23477. }
  23478. if (data.animations !== undefined) {
  23479. const objectAnimations = data.animations;
  23480. for (let i = 0; i < objectAnimations.length; i++) {
  23481. const uuid = objectAnimations[i];
  23482. object.animations.push(animations[uuid]);
  23483. }
  23484. }
  23485. if (data.type === 'LOD') {
  23486. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  23487. const levels = data.levels;
  23488. for (let l = 0; l < levels.length; l++) {
  23489. const level = levels[l];
  23490. const child = object.getObjectByProperty('uuid', level.object);
  23491. if (child !== undefined) {
  23492. object.addLevel(child, level.distance);
  23493. }
  23494. }
  23495. }
  23496. return object;
  23497. }
  23498. bindSkeletons(object, skeletons) {
  23499. if (Object.keys(skeletons).length === 0) return;
  23500. object.traverse(function (child) {
  23501. if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
  23502. const skeleton = skeletons[child.skeleton];
  23503. if (skeleton === undefined) {
  23504. console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
  23505. } else {
  23506. child.bind(skeleton, child.bindMatrix);
  23507. }
  23508. }
  23509. });
  23510. }
  23511. /* DEPRECATED */
  23512. setTexturePath(value) {
  23513. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  23514. return this.setResourcePath(value);
  23515. }
  23516. }
  23517. const TEXTURE_MAPPING = {
  23518. UVMapping: UVMapping,
  23519. CubeReflectionMapping: CubeReflectionMapping,
  23520. CubeRefractionMapping: CubeRefractionMapping,
  23521. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  23522. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  23523. CubeUVReflectionMapping: CubeUVReflectionMapping,
  23524. CubeUVRefractionMapping: CubeUVRefractionMapping
  23525. };
  23526. const TEXTURE_WRAPPING = {
  23527. RepeatWrapping: RepeatWrapping,
  23528. ClampToEdgeWrapping: ClampToEdgeWrapping,
  23529. MirroredRepeatWrapping: MirroredRepeatWrapping
  23530. };
  23531. const TEXTURE_FILTER = {
  23532. NearestFilter: NearestFilter,
  23533. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  23534. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  23535. LinearFilter: LinearFilter,
  23536. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  23537. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  23538. };
  23539. class ImageBitmapLoader extends Loader {
  23540. constructor(manager) {
  23541. super(manager);
  23542. if (typeof createImageBitmap === 'undefined') {
  23543. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  23544. }
  23545. if (typeof fetch === 'undefined') {
  23546. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  23547. }
  23548. this.options = {
  23549. premultiplyAlpha: 'none'
  23550. };
  23551. }
  23552. setOptions(options) {
  23553. this.options = options;
  23554. return this;
  23555. }
  23556. load(url, onLoad, onProgress, onError) {
  23557. if (url === undefined) url = '';
  23558. if (this.path !== undefined) url = this.path + url;
  23559. url = this.manager.resolveURL(url);
  23560. const scope = this;
  23561. const cached = Cache.get(url);
  23562. if (cached !== undefined) {
  23563. scope.manager.itemStart(url);
  23564. setTimeout(function () {
  23565. if (onLoad) onLoad(cached);
  23566. scope.manager.itemEnd(url);
  23567. }, 0);
  23568. return cached;
  23569. }
  23570. const fetchOptions = {};
  23571. fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
  23572. fetchOptions.headers = this.requestHeader;
  23573. fetch(url, fetchOptions).then(function (res) {
  23574. return res.blob();
  23575. }).then(function (blob) {
  23576. return createImageBitmap(blob, Object.assign(scope.options, {
  23577. colorSpaceConversion: 'none'
  23578. }));
  23579. }).then(function (imageBitmap) {
  23580. Cache.add(url, imageBitmap);
  23581. if (onLoad) onLoad(imageBitmap);
  23582. scope.manager.itemEnd(url);
  23583. }).catch(function (e) {
  23584. if (onError) onError(e);
  23585. scope.manager.itemError(url);
  23586. scope.manager.itemEnd(url);
  23587. });
  23588. scope.manager.itemStart(url);
  23589. }
  23590. }
  23591. ImageBitmapLoader.prototype.isImageBitmapLoader = true;
  23592. class ShapePath {
  23593. constructor() {
  23594. this.type = 'ShapePath';
  23595. this.color = new Color();
  23596. this.subPaths = [];
  23597. this.currentPath = null;
  23598. }
  23599. moveTo(x, y) {
  23600. this.currentPath = new Path();
  23601. this.subPaths.push(this.currentPath);
  23602. this.currentPath.moveTo(x, y);
  23603. return this;
  23604. }
  23605. lineTo(x, y) {
  23606. this.currentPath.lineTo(x, y);
  23607. return this;
  23608. }
  23609. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  23610. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  23611. return this;
  23612. }
  23613. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  23614. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  23615. return this;
  23616. }
  23617. splineThru(pts) {
  23618. this.currentPath.splineThru(pts);
  23619. return this;
  23620. }
  23621. toShapes(isCCW, noHoles) {
  23622. function toShapesNoHoles(inSubpaths) {
  23623. const shapes = [];
  23624. for (let i = 0, l = inSubpaths.length; i < l; i++) {
  23625. const tmpPath = inSubpaths[i];
  23626. const tmpShape = new Shape();
  23627. tmpShape.curves = tmpPath.curves;
  23628. shapes.push(tmpShape);
  23629. }
  23630. return shapes;
  23631. }
  23632. function isPointInsidePolygon(inPt, inPolygon) {
  23633. const polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  23634. // toggling of inside/outside at every single! intersection point of an edge
  23635. // with the horizontal line through inPt, left of inPt
  23636. // not counting lowerY endpoints of edges and whole edges on that line
  23637. let inside = false;
  23638. for (let p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  23639. let edgeLowPt = inPolygon[p];
  23640. let edgeHighPt = inPolygon[q];
  23641. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  23642. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  23643. if (Math.abs(edgeDy) > Number.EPSILON) {
  23644. // not parallel
  23645. if (edgeDy < 0) {
  23646. edgeLowPt = inPolygon[q];
  23647. edgeDx = -edgeDx;
  23648. edgeHighPt = inPolygon[p];
  23649. edgeDy = -edgeDy;
  23650. }
  23651. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  23652. if (inPt.y === edgeLowPt.y) {
  23653. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  23654. // continue; // no intersection or edgeLowPt => doesn't count !!!
  23655. } else {
  23656. const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  23657. if (perpEdge === 0) return true; // inPt is on contour ?
  23658. if (perpEdge < 0) continue;
  23659. inside = !inside; // true intersection left of inPt
  23660. }
  23661. } else {
  23662. // parallel or collinear
  23663. if (inPt.y !== edgeLowPt.y) continue; // parallel
  23664. // edge lies on the same horizontal line as inPt
  23665. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  23666. // continue;
  23667. }
  23668. }
  23669. return inside;
  23670. }
  23671. const isClockWise = ShapeUtils.isClockWise;
  23672. const subPaths = this.subPaths;
  23673. if (subPaths.length === 0) return [];
  23674. if (noHoles === true) return toShapesNoHoles(subPaths);
  23675. let solid, tmpPath, tmpShape;
  23676. const shapes = [];
  23677. if (subPaths.length === 1) {
  23678. tmpPath = subPaths[0];
  23679. tmpShape = new Shape();
  23680. tmpShape.curves = tmpPath.curves;
  23681. shapes.push(tmpShape);
  23682. return shapes;
  23683. }
  23684. let holesFirst = !isClockWise(subPaths[0].getPoints());
  23685. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  23686. const betterShapeHoles = [];
  23687. const newShapes = [];
  23688. let newShapeHoles = [];
  23689. let mainIdx = 0;
  23690. let tmpPoints;
  23691. newShapes[mainIdx] = undefined;
  23692. newShapeHoles[mainIdx] = [];
  23693. for (let i = 0, l = subPaths.length; i < l; i++) {
  23694. tmpPath = subPaths[i];
  23695. tmpPoints = tmpPath.getPoints();
  23696. solid = isClockWise(tmpPoints);
  23697. solid = isCCW ? !solid : solid;
  23698. if (solid) {
  23699. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  23700. newShapes[mainIdx] = {
  23701. s: new Shape(),
  23702. p: tmpPoints
  23703. };
  23704. newShapes[mainIdx].s.curves = tmpPath.curves;
  23705. if (holesFirst) mainIdx++;
  23706. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  23707. } else {
  23708. newShapeHoles[mainIdx].push({
  23709. h: tmpPath,
  23710. p: tmpPoints[0]
  23711. }); //console.log('ccw', i);
  23712. }
  23713. } // only Holes? -> probably all Shapes with wrong orientation
  23714. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  23715. if (newShapes.length > 1) {
  23716. let ambiguous = false;
  23717. const toChange = [];
  23718. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  23719. betterShapeHoles[sIdx] = [];
  23720. }
  23721. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  23722. const sho = newShapeHoles[sIdx];
  23723. for (let hIdx = 0; hIdx < sho.length; hIdx++) {
  23724. const ho = sho[hIdx];
  23725. let hole_unassigned = true;
  23726. for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  23727. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  23728. if (sIdx !== s2Idx) toChange.push({
  23729. froms: sIdx,
  23730. tos: s2Idx,
  23731. hole: hIdx
  23732. });
  23733. if (hole_unassigned) {
  23734. hole_unassigned = false;
  23735. betterShapeHoles[s2Idx].push(ho);
  23736. } else {
  23737. ambiguous = true;
  23738. }
  23739. }
  23740. }
  23741. if (hole_unassigned) {
  23742. betterShapeHoles[sIdx].push(ho);
  23743. }
  23744. }
  23745. } // console.log("ambiguous: ", ambiguous);
  23746. if (toChange.length > 0) {
  23747. // console.log("to change: ", toChange);
  23748. if (!ambiguous) newShapeHoles = betterShapeHoles;
  23749. }
  23750. }
  23751. let tmpHoles;
  23752. for (let i = 0, il = newShapes.length; i < il; i++) {
  23753. tmpShape = newShapes[i].s;
  23754. shapes.push(tmpShape);
  23755. tmpHoles = newShapeHoles[i];
  23756. for (let j = 0, jl = tmpHoles.length; j < jl; j++) {
  23757. tmpShape.holes.push(tmpHoles[j].h);
  23758. }
  23759. } //console.log("shape", shapes);
  23760. return shapes;
  23761. }
  23762. }
  23763. class Font {
  23764. constructor(data) {
  23765. this.type = 'Font';
  23766. this.data = data;
  23767. }
  23768. generateShapes(text, size = 100) {
  23769. const shapes = [];
  23770. const paths = createPaths(text, size, this.data);
  23771. for (let p = 0, pl = paths.length; p < pl; p++) {
  23772. Array.prototype.push.apply(shapes, paths[p].toShapes());
  23773. }
  23774. return shapes;
  23775. }
  23776. }
  23777. function createPaths(text, size, data) {
  23778. const chars = Array.from(text);
  23779. const scale = size / data.resolution;
  23780. const line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
  23781. const paths = [];
  23782. let offsetX = 0,
  23783. offsetY = 0;
  23784. for (let i = 0; i < chars.length; i++) {
  23785. const char = chars[i];
  23786. if (char === '\n') {
  23787. offsetX = 0;
  23788. offsetY -= line_height;
  23789. } else {
  23790. const ret = createPath(char, scale, offsetX, offsetY, data);
  23791. offsetX += ret.offsetX;
  23792. paths.push(ret.path);
  23793. }
  23794. }
  23795. return paths;
  23796. }
  23797. function createPath(char, scale, offsetX, offsetY, data) {
  23798. const glyph = data.glyphs[char] || data.glyphs['?'];
  23799. if (!glyph) {
  23800. console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
  23801. return;
  23802. }
  23803. const path = new ShapePath();
  23804. let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  23805. if (glyph.o) {
  23806. const outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
  23807. for (let i = 0, l = outline.length; i < l;) {
  23808. const action = outline[i++];
  23809. switch (action) {
  23810. case 'm':
  23811. // moveTo
  23812. x = outline[i++] * scale + offsetX;
  23813. y = outline[i++] * scale + offsetY;
  23814. path.moveTo(x, y);
  23815. break;
  23816. case 'l':
  23817. // lineTo
  23818. x = outline[i++] * scale + offsetX;
  23819. y = outline[i++] * scale + offsetY;
  23820. path.lineTo(x, y);
  23821. break;
  23822. case 'q':
  23823. // quadraticCurveTo
  23824. cpx = outline[i++] * scale + offsetX;
  23825. cpy = outline[i++] * scale + offsetY;
  23826. cpx1 = outline[i++] * scale + offsetX;
  23827. cpy1 = outline[i++] * scale + offsetY;
  23828. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  23829. break;
  23830. case 'b':
  23831. // bezierCurveTo
  23832. cpx = outline[i++] * scale + offsetX;
  23833. cpy = outline[i++] * scale + offsetY;
  23834. cpx1 = outline[i++] * scale + offsetX;
  23835. cpy1 = outline[i++] * scale + offsetY;
  23836. cpx2 = outline[i++] * scale + offsetX;
  23837. cpy2 = outline[i++] * scale + offsetY;
  23838. path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
  23839. break;
  23840. }
  23841. }
  23842. }
  23843. return {
  23844. offsetX: glyph.ha * scale,
  23845. path: path
  23846. };
  23847. }
  23848. Font.prototype.isFont = true;
  23849. class FontLoader extends Loader {
  23850. constructor(manager) {
  23851. super(manager);
  23852. }
  23853. load(url, onLoad, onProgress, onError) {
  23854. const scope = this;
  23855. const loader = new FileLoader(this.manager);
  23856. loader.setPath(this.path);
  23857. loader.setRequestHeader(this.requestHeader);
  23858. loader.setWithCredentials(scope.withCredentials);
  23859. loader.load(url, function (text) {
  23860. let json;
  23861. try {
  23862. json = JSON.parse(text);
  23863. } catch (e) {
  23864. console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
  23865. json = JSON.parse(text.substring(65, text.length - 2));
  23866. }
  23867. const font = scope.parse(json);
  23868. if (onLoad) onLoad(font);
  23869. }, onProgress, onError);
  23870. }
  23871. parse(json) {
  23872. return new Font(json);
  23873. }
  23874. }
  23875. let _context;
  23876. const AudioContext = {
  23877. getContext: function () {
  23878. if (_context === undefined) {
  23879. _context = new (window.AudioContext || window.webkitAudioContext)();
  23880. }
  23881. return _context;
  23882. },
  23883. setContext: function (value) {
  23884. _context = value;
  23885. }
  23886. };
  23887. class AudioLoader extends Loader {
  23888. constructor(manager) {
  23889. super(manager);
  23890. }
  23891. load(url, onLoad, onProgress, onError) {
  23892. const scope = this;
  23893. const loader = new FileLoader(this.manager);
  23894. loader.setResponseType('arraybuffer');
  23895. loader.setPath(this.path);
  23896. loader.setRequestHeader(this.requestHeader);
  23897. loader.setWithCredentials(this.withCredentials);
  23898. loader.load(url, function (buffer) {
  23899. try {
  23900. // Create a copy of the buffer. The `decodeAudioData` method
  23901. // detaches the buffer when complete, preventing reuse.
  23902. const bufferCopy = buffer.slice(0);
  23903. const context = AudioContext.getContext();
  23904. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  23905. onLoad(audioBuffer);
  23906. });
  23907. } catch (e) {
  23908. if (onError) {
  23909. onError(e);
  23910. } else {
  23911. console.error(e);
  23912. }
  23913. scope.manager.itemError(url);
  23914. }
  23915. }, onProgress, onError);
  23916. }
  23917. }
  23918. class HemisphereLightProbe extends LightProbe {
  23919. constructor(skyColor, groundColor, intensity = 1) {
  23920. super(undefined, intensity);
  23921. const color1 = new Color().set(skyColor);
  23922. const color2 = new Color().set(groundColor);
  23923. const sky = new Vector3(color1.r, color1.g, color1.b);
  23924. const ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  23925. const c0 = Math.sqrt(Math.PI);
  23926. const c1 = c0 * Math.sqrt(0.75);
  23927. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  23928. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  23929. }
  23930. }
  23931. HemisphereLightProbe.prototype.isHemisphereLightProbe = true;
  23932. class AmbientLightProbe extends LightProbe {
  23933. constructor(color, intensity = 1) {
  23934. super(undefined, intensity);
  23935. const color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  23936. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  23937. }
  23938. }
  23939. AmbientLightProbe.prototype.isAmbientLightProbe = true;
  23940. const _eyeRight = /*@__PURE__*/new Matrix4();
  23941. const _eyeLeft = /*@__PURE__*/new Matrix4();
  23942. class StereoCamera {
  23943. constructor() {
  23944. this.type = 'StereoCamera';
  23945. this.aspect = 1;
  23946. this.eyeSep = 0.064;
  23947. this.cameraL = new PerspectiveCamera();
  23948. this.cameraL.layers.enable(1);
  23949. this.cameraL.matrixAutoUpdate = false;
  23950. this.cameraR = new PerspectiveCamera();
  23951. this.cameraR.layers.enable(2);
  23952. this.cameraR.matrixAutoUpdate = false;
  23953. this._cache = {
  23954. focus: null,
  23955. fov: null,
  23956. aspect: null,
  23957. near: null,
  23958. far: null,
  23959. zoom: null,
  23960. eyeSep: null
  23961. };
  23962. }
  23963. update(camera) {
  23964. const cache = this._cache;
  23965. 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;
  23966. if (needsUpdate) {
  23967. cache.focus = camera.focus;
  23968. cache.fov = camera.fov;
  23969. cache.aspect = camera.aspect * this.aspect;
  23970. cache.near = camera.near;
  23971. cache.far = camera.far;
  23972. cache.zoom = camera.zoom;
  23973. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  23974. // http://paulbourke.net/stereographics/stereorender/
  23975. const projectionMatrix = camera.projectionMatrix.clone();
  23976. const eyeSepHalf = cache.eyeSep / 2;
  23977. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  23978. const ymax = cache.near * Math.tan(DEG2RAD * cache.fov * 0.5) / cache.zoom;
  23979. let xmin, xmax; // translate xOffset
  23980. _eyeLeft.elements[12] = -eyeSepHalf;
  23981. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  23982. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  23983. xmax = ymax * cache.aspect + eyeSepOnProjection;
  23984. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  23985. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  23986. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  23987. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  23988. xmax = ymax * cache.aspect - eyeSepOnProjection;
  23989. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  23990. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  23991. this.cameraR.projectionMatrix.copy(projectionMatrix);
  23992. }
  23993. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  23994. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  23995. }
  23996. }
  23997. class Clock {
  23998. constructor(autoStart = true) {
  23999. this.autoStart = autoStart;
  24000. this.startTime = 0;
  24001. this.oldTime = 0;
  24002. this.elapsedTime = 0;
  24003. this.running = false;
  24004. }
  24005. start() {
  24006. this.startTime = now();
  24007. this.oldTime = this.startTime;
  24008. this.elapsedTime = 0;
  24009. this.running = true;
  24010. }
  24011. stop() {
  24012. this.getElapsedTime();
  24013. this.running = false;
  24014. this.autoStart = false;
  24015. }
  24016. getElapsedTime() {
  24017. this.getDelta();
  24018. return this.elapsedTime;
  24019. }
  24020. getDelta() {
  24021. let diff = 0;
  24022. if (this.autoStart && !this.running) {
  24023. this.start();
  24024. return 0;
  24025. }
  24026. if (this.running) {
  24027. const newTime = now();
  24028. diff = (newTime - this.oldTime) / 1000;
  24029. this.oldTime = newTime;
  24030. this.elapsedTime += diff;
  24031. }
  24032. return diff;
  24033. }
  24034. }
  24035. function now() {
  24036. return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  24037. }
  24038. const _position$1 = /*@__PURE__*/new Vector3();
  24039. const _quaternion$1 = /*@__PURE__*/new Quaternion();
  24040. const _scale$1 = /*@__PURE__*/new Vector3();
  24041. const _orientation$1 = /*@__PURE__*/new Vector3();
  24042. class AudioListener extends Object3D {
  24043. constructor() {
  24044. super();
  24045. this.type = 'AudioListener';
  24046. this.context = AudioContext.getContext();
  24047. this.gain = this.context.createGain();
  24048. this.gain.connect(this.context.destination);
  24049. this.filter = null;
  24050. this.timeDelta = 0; // private
  24051. this._clock = new Clock();
  24052. }
  24053. getInput() {
  24054. return this.gain;
  24055. }
  24056. removeFilter() {
  24057. if (this.filter !== null) {
  24058. this.gain.disconnect(this.filter);
  24059. this.filter.disconnect(this.context.destination);
  24060. this.gain.connect(this.context.destination);
  24061. this.filter = null;
  24062. }
  24063. return this;
  24064. }
  24065. getFilter() {
  24066. return this.filter;
  24067. }
  24068. setFilter(value) {
  24069. if (this.filter !== null) {
  24070. this.gain.disconnect(this.filter);
  24071. this.filter.disconnect(this.context.destination);
  24072. } else {
  24073. this.gain.disconnect(this.context.destination);
  24074. }
  24075. this.filter = value;
  24076. this.gain.connect(this.filter);
  24077. this.filter.connect(this.context.destination);
  24078. return this;
  24079. }
  24080. getMasterVolume() {
  24081. return this.gain.gain.value;
  24082. }
  24083. setMasterVolume(value) {
  24084. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  24085. return this;
  24086. }
  24087. updateMatrixWorld(force) {
  24088. super.updateMatrixWorld(force);
  24089. const listener = this.context.listener;
  24090. const up = this.up;
  24091. this.timeDelta = this._clock.getDelta();
  24092. this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1);
  24093. _orientation$1.set(0, 0, -1).applyQuaternion(_quaternion$1);
  24094. if (listener.positionX) {
  24095. // code path for Chrome (see #14393)
  24096. const endTime = this.context.currentTime + this.timeDelta;
  24097. listener.positionX.linearRampToValueAtTime(_position$1.x, endTime);
  24098. listener.positionY.linearRampToValueAtTime(_position$1.y, endTime);
  24099. listener.positionZ.linearRampToValueAtTime(_position$1.z, endTime);
  24100. listener.forwardX.linearRampToValueAtTime(_orientation$1.x, endTime);
  24101. listener.forwardY.linearRampToValueAtTime(_orientation$1.y, endTime);
  24102. listener.forwardZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  24103. listener.upX.linearRampToValueAtTime(up.x, endTime);
  24104. listener.upY.linearRampToValueAtTime(up.y, endTime);
  24105. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  24106. } else {
  24107. listener.setPosition(_position$1.x, _position$1.y, _position$1.z);
  24108. listener.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z);
  24109. }
  24110. }
  24111. }
  24112. class Audio extends Object3D {
  24113. constructor(listener) {
  24114. super();
  24115. this.type = 'Audio';
  24116. this.listener = listener;
  24117. this.context = listener.context;
  24118. this.gain = this.context.createGain();
  24119. this.gain.connect(listener.getInput());
  24120. this.autoplay = false;
  24121. this.buffer = null;
  24122. this.detune = 0;
  24123. this.loop = false;
  24124. this.loopStart = 0;
  24125. this.loopEnd = 0;
  24126. this.offset = 0;
  24127. this.duration = undefined;
  24128. this.playbackRate = 1;
  24129. this.isPlaying = false;
  24130. this.hasPlaybackControl = true;
  24131. this.source = null;
  24132. this.sourceType = 'empty';
  24133. this._startedAt = 0;
  24134. this._progress = 0;
  24135. this._connected = false;
  24136. this.filters = [];
  24137. }
  24138. getOutput() {
  24139. return this.gain;
  24140. }
  24141. setNodeSource(audioNode) {
  24142. this.hasPlaybackControl = false;
  24143. this.sourceType = 'audioNode';
  24144. this.source = audioNode;
  24145. this.connect();
  24146. return this;
  24147. }
  24148. setMediaElementSource(mediaElement) {
  24149. this.hasPlaybackControl = false;
  24150. this.sourceType = 'mediaNode';
  24151. this.source = this.context.createMediaElementSource(mediaElement);
  24152. this.connect();
  24153. return this;
  24154. }
  24155. setMediaStreamSource(mediaStream) {
  24156. this.hasPlaybackControl = false;
  24157. this.sourceType = 'mediaStreamNode';
  24158. this.source = this.context.createMediaStreamSource(mediaStream);
  24159. this.connect();
  24160. return this;
  24161. }
  24162. setBuffer(audioBuffer) {
  24163. this.buffer = audioBuffer;
  24164. this.sourceType = 'buffer';
  24165. if (this.autoplay) this.play();
  24166. return this;
  24167. }
  24168. play(delay = 0) {
  24169. if (this.isPlaying === true) {
  24170. console.warn('THREE.Audio: Audio is already playing.');
  24171. return;
  24172. }
  24173. if (this.hasPlaybackControl === false) {
  24174. console.warn('THREE.Audio: this Audio has no playback control.');
  24175. return;
  24176. }
  24177. this._startedAt = this.context.currentTime + delay;
  24178. const source = this.context.createBufferSource();
  24179. source.buffer = this.buffer;
  24180. source.loop = this.loop;
  24181. source.loopStart = this.loopStart;
  24182. source.loopEnd = this.loopEnd;
  24183. source.onended = this.onEnded.bind(this);
  24184. source.start(this._startedAt, this._progress + this.offset, this.duration);
  24185. this.isPlaying = true;
  24186. this.source = source;
  24187. this.setDetune(this.detune);
  24188. this.setPlaybackRate(this.playbackRate);
  24189. return this.connect();
  24190. }
  24191. pause() {
  24192. if (this.hasPlaybackControl === false) {
  24193. console.warn('THREE.Audio: this Audio has no playback control.');
  24194. return;
  24195. }
  24196. if (this.isPlaying === true) {
  24197. // update current progress
  24198. this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  24199. if (this.loop === true) {
  24200. // ensure _progress does not exceed duration with looped audios
  24201. this._progress = this._progress % (this.duration || this.buffer.duration);
  24202. }
  24203. this.source.stop();
  24204. this.source.onended = null;
  24205. this.isPlaying = false;
  24206. }
  24207. return this;
  24208. }
  24209. stop() {
  24210. if (this.hasPlaybackControl === false) {
  24211. console.warn('THREE.Audio: this Audio has no playback control.');
  24212. return;
  24213. }
  24214. this._progress = 0;
  24215. this.source.stop();
  24216. this.source.onended = null;
  24217. this.isPlaying = false;
  24218. return this;
  24219. }
  24220. connect() {
  24221. if (this.filters.length > 0) {
  24222. this.source.connect(this.filters[0]);
  24223. for (let i = 1, l = this.filters.length; i < l; i++) {
  24224. this.filters[i - 1].connect(this.filters[i]);
  24225. }
  24226. this.filters[this.filters.length - 1].connect(this.getOutput());
  24227. } else {
  24228. this.source.connect(this.getOutput());
  24229. }
  24230. this._connected = true;
  24231. return this;
  24232. }
  24233. disconnect() {
  24234. if (this.filters.length > 0) {
  24235. this.source.disconnect(this.filters[0]);
  24236. for (let i = 1, l = this.filters.length; i < l; i++) {
  24237. this.filters[i - 1].disconnect(this.filters[i]);
  24238. }
  24239. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  24240. } else {
  24241. this.source.disconnect(this.getOutput());
  24242. }
  24243. this._connected = false;
  24244. return this;
  24245. }
  24246. getFilters() {
  24247. return this.filters;
  24248. }
  24249. setFilters(value) {
  24250. if (!value) value = [];
  24251. if (this._connected === true) {
  24252. this.disconnect();
  24253. this.filters = value.slice();
  24254. this.connect();
  24255. } else {
  24256. this.filters = value.slice();
  24257. }
  24258. return this;
  24259. }
  24260. setDetune(value) {
  24261. this.detune = value;
  24262. if (this.source.detune === undefined) return; // only set detune when available
  24263. if (this.isPlaying === true) {
  24264. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  24265. }
  24266. return this;
  24267. }
  24268. getDetune() {
  24269. return this.detune;
  24270. }
  24271. getFilter() {
  24272. return this.getFilters()[0];
  24273. }
  24274. setFilter(filter) {
  24275. return this.setFilters(filter ? [filter] : []);
  24276. }
  24277. setPlaybackRate(value) {
  24278. if (this.hasPlaybackControl === false) {
  24279. console.warn('THREE.Audio: this Audio has no playback control.');
  24280. return;
  24281. }
  24282. this.playbackRate = value;
  24283. if (this.isPlaying === true) {
  24284. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  24285. }
  24286. return this;
  24287. }
  24288. getPlaybackRate() {
  24289. return this.playbackRate;
  24290. }
  24291. onEnded() {
  24292. this.isPlaying = false;
  24293. }
  24294. getLoop() {
  24295. if (this.hasPlaybackControl === false) {
  24296. console.warn('THREE.Audio: this Audio has no playback control.');
  24297. return false;
  24298. }
  24299. return this.loop;
  24300. }
  24301. setLoop(value) {
  24302. if (this.hasPlaybackControl === false) {
  24303. console.warn('THREE.Audio: this Audio has no playback control.');
  24304. return;
  24305. }
  24306. this.loop = value;
  24307. if (this.isPlaying === true) {
  24308. this.source.loop = this.loop;
  24309. }
  24310. return this;
  24311. }
  24312. setLoopStart(value) {
  24313. this.loopStart = value;
  24314. return this;
  24315. }
  24316. setLoopEnd(value) {
  24317. this.loopEnd = value;
  24318. return this;
  24319. }
  24320. getVolume() {
  24321. return this.gain.gain.value;
  24322. }
  24323. setVolume(value) {
  24324. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  24325. return this;
  24326. }
  24327. }
  24328. const _position = /*@__PURE__*/new Vector3();
  24329. const _quaternion = /*@__PURE__*/new Quaternion();
  24330. const _scale = /*@__PURE__*/new Vector3();
  24331. const _orientation = /*@__PURE__*/new Vector3();
  24332. class PositionalAudio extends Audio {
  24333. constructor(listener) {
  24334. super(listener);
  24335. this.panner = this.context.createPanner();
  24336. this.panner.panningModel = 'HRTF';
  24337. this.panner.connect(this.gain);
  24338. }
  24339. getOutput() {
  24340. return this.panner;
  24341. }
  24342. getRefDistance() {
  24343. return this.panner.refDistance;
  24344. }
  24345. setRefDistance(value) {
  24346. this.panner.refDistance = value;
  24347. return this;
  24348. }
  24349. getRolloffFactor() {
  24350. return this.panner.rolloffFactor;
  24351. }
  24352. setRolloffFactor(value) {
  24353. this.panner.rolloffFactor = value;
  24354. return this;
  24355. }
  24356. getDistanceModel() {
  24357. return this.panner.distanceModel;
  24358. }
  24359. setDistanceModel(value) {
  24360. this.panner.distanceModel = value;
  24361. return this;
  24362. }
  24363. getMaxDistance() {
  24364. return this.panner.maxDistance;
  24365. }
  24366. setMaxDistance(value) {
  24367. this.panner.maxDistance = value;
  24368. return this;
  24369. }
  24370. setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  24371. this.panner.coneInnerAngle = coneInnerAngle;
  24372. this.panner.coneOuterAngle = coneOuterAngle;
  24373. this.panner.coneOuterGain = coneOuterGain;
  24374. return this;
  24375. }
  24376. updateMatrixWorld(force) {
  24377. super.updateMatrixWorld(force);
  24378. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  24379. this.matrixWorld.decompose(_position, _quaternion, _scale);
  24380. _orientation.set(0, 0, 1).applyQuaternion(_quaternion);
  24381. const panner = this.panner;
  24382. if (panner.positionX) {
  24383. // code path for Chrome and Firefox (see #14393)
  24384. const endTime = this.context.currentTime + this.listener.timeDelta;
  24385. panner.positionX.linearRampToValueAtTime(_position.x, endTime);
  24386. panner.positionY.linearRampToValueAtTime(_position.y, endTime);
  24387. panner.positionZ.linearRampToValueAtTime(_position.z, endTime);
  24388. panner.orientationX.linearRampToValueAtTime(_orientation.x, endTime);
  24389. panner.orientationY.linearRampToValueAtTime(_orientation.y, endTime);
  24390. panner.orientationZ.linearRampToValueAtTime(_orientation.z, endTime);
  24391. } else {
  24392. panner.setPosition(_position.x, _position.y, _position.z);
  24393. panner.setOrientation(_orientation.x, _orientation.y, _orientation.z);
  24394. }
  24395. }
  24396. }
  24397. class AudioAnalyser {
  24398. constructor(audio, fftSize = 2048) {
  24399. this.analyser = audio.context.createAnalyser();
  24400. this.analyser.fftSize = fftSize;
  24401. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  24402. audio.getOutput().connect(this.analyser);
  24403. }
  24404. getFrequencyData() {
  24405. this.analyser.getByteFrequencyData(this.data);
  24406. return this.data;
  24407. }
  24408. getAverageFrequency() {
  24409. let value = 0;
  24410. const data = this.getFrequencyData();
  24411. for (let i = 0; i < data.length; i++) {
  24412. value += data[i];
  24413. }
  24414. return value / data.length;
  24415. }
  24416. }
  24417. class PropertyMixer {
  24418. constructor(binding, typeName, valueSize) {
  24419. this.binding = binding;
  24420. this.valueSize = valueSize;
  24421. let mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  24422. //
  24423. // interpolators can use .buffer as their .result
  24424. // the data then goes to 'incoming'
  24425. //
  24426. // 'accu0' and 'accu1' are used frame-interleaved for
  24427. // the cumulative result and are compared to detect
  24428. // changes
  24429. //
  24430. // 'orig' stores the original state of the property
  24431. //
  24432. // 'add' is used for additive cumulative results
  24433. //
  24434. // 'work' is optional and is only present for quaternion types. It is used
  24435. // to store intermediate quaternion multiplication results
  24436. switch (typeName) {
  24437. case 'quaternion':
  24438. mixFunction = this._slerp;
  24439. mixFunctionAdditive = this._slerpAdditive;
  24440. setIdentity = this._setAdditiveIdentityQuaternion;
  24441. this.buffer = new Float64Array(valueSize * 6);
  24442. this._workIndex = 5;
  24443. break;
  24444. case 'string':
  24445. case 'bool':
  24446. mixFunction = this._select; // Use the regular mix function and for additive on these types,
  24447. // additive is not relevant for non-numeric types
  24448. mixFunctionAdditive = this._select;
  24449. setIdentity = this._setAdditiveIdentityOther;
  24450. this.buffer = new Array(valueSize * 5);
  24451. break;
  24452. default:
  24453. mixFunction = this._lerp;
  24454. mixFunctionAdditive = this._lerpAdditive;
  24455. setIdentity = this._setAdditiveIdentityNumeric;
  24456. this.buffer = new Float64Array(valueSize * 5);
  24457. }
  24458. this._mixBufferRegion = mixFunction;
  24459. this._mixBufferRegionAdditive = mixFunctionAdditive;
  24460. this._setIdentity = setIdentity;
  24461. this._origIndex = 3;
  24462. this._addIndex = 4;
  24463. this.cumulativeWeight = 0;
  24464. this.cumulativeWeightAdditive = 0;
  24465. this.useCount = 0;
  24466. this.referenceCount = 0;
  24467. } // accumulate data in the 'incoming' region into 'accu<i>'
  24468. accumulate(accuIndex, weight) {
  24469. // note: happily accumulating nothing when weight = 0, the caller knows
  24470. // the weight and shouldn't have made the call in the first place
  24471. const buffer = this.buffer,
  24472. stride = this.valueSize,
  24473. offset = accuIndex * stride + stride;
  24474. let currentWeight = this.cumulativeWeight;
  24475. if (currentWeight === 0) {
  24476. // accuN := incoming * weight
  24477. for (let i = 0; i !== stride; ++i) {
  24478. buffer[offset + i] = buffer[i];
  24479. }
  24480. currentWeight = weight;
  24481. } else {
  24482. // accuN := accuN + incoming * weight
  24483. currentWeight += weight;
  24484. const mix = weight / currentWeight;
  24485. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  24486. }
  24487. this.cumulativeWeight = currentWeight;
  24488. } // accumulate data in the 'incoming' region into 'add'
  24489. accumulateAdditive(weight) {
  24490. const buffer = this.buffer,
  24491. stride = this.valueSize,
  24492. offset = stride * this._addIndex;
  24493. if (this.cumulativeWeightAdditive === 0) {
  24494. // add = identity
  24495. this._setIdentity();
  24496. } // add := add + incoming * weight
  24497. this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
  24498. this.cumulativeWeightAdditive += weight;
  24499. } // apply the state of 'accu<i>' to the binding when accus differ
  24500. apply(accuIndex) {
  24501. const stride = this.valueSize,
  24502. buffer = this.buffer,
  24503. offset = accuIndex * stride + stride,
  24504. weight = this.cumulativeWeight,
  24505. weightAdditive = this.cumulativeWeightAdditive,
  24506. binding = this.binding;
  24507. this.cumulativeWeight = 0;
  24508. this.cumulativeWeightAdditive = 0;
  24509. if (weight < 1) {
  24510. // accuN := accuN + original * ( 1 - cumulativeWeight )
  24511. const originalValueOffset = stride * this._origIndex;
  24512. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  24513. }
  24514. if (weightAdditive > 0) {
  24515. // accuN := accuN + additive accuN
  24516. this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
  24517. }
  24518. for (let i = stride, e = stride + stride; i !== e; ++i) {
  24519. if (buffer[i] !== buffer[i + stride]) {
  24520. // value has changed -> update scene graph
  24521. binding.setValue(buffer, offset);
  24522. break;
  24523. }
  24524. }
  24525. } // remember the state of the bound property and copy it to both accus
  24526. saveOriginalState() {
  24527. const binding = this.binding;
  24528. const buffer = this.buffer,
  24529. stride = this.valueSize,
  24530. originalValueOffset = stride * this._origIndex;
  24531. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  24532. for (let i = stride, e = originalValueOffset; i !== e; ++i) {
  24533. buffer[i] = buffer[originalValueOffset + i % stride];
  24534. } // Add to identity for additive
  24535. this._setIdentity();
  24536. this.cumulativeWeight = 0;
  24537. this.cumulativeWeightAdditive = 0;
  24538. } // apply the state previously taken via 'saveOriginalState' to the binding
  24539. restoreOriginalState() {
  24540. const originalValueOffset = this.valueSize * 3;
  24541. this.binding.setValue(this.buffer, originalValueOffset);
  24542. }
  24543. _setAdditiveIdentityNumeric() {
  24544. const startIndex = this._addIndex * this.valueSize;
  24545. const endIndex = startIndex + this.valueSize;
  24546. for (let i = startIndex; i < endIndex; i++) {
  24547. this.buffer[i] = 0;
  24548. }
  24549. }
  24550. _setAdditiveIdentityQuaternion() {
  24551. this._setAdditiveIdentityNumeric();
  24552. this.buffer[this._addIndex * this.valueSize + 3] = 1;
  24553. }
  24554. _setAdditiveIdentityOther() {
  24555. const startIndex = this._origIndex * this.valueSize;
  24556. const targetIndex = this._addIndex * this.valueSize;
  24557. for (let i = 0; i < this.valueSize; i++) {
  24558. this.buffer[targetIndex + i] = this.buffer[startIndex + i];
  24559. }
  24560. } // mix functions
  24561. _select(buffer, dstOffset, srcOffset, t, stride) {
  24562. if (t >= 0.5) {
  24563. for (let i = 0; i !== stride; ++i) {
  24564. buffer[dstOffset + i] = buffer[srcOffset + i];
  24565. }
  24566. }
  24567. }
  24568. _slerp(buffer, dstOffset, srcOffset, t) {
  24569. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  24570. }
  24571. _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  24572. const workOffset = this._workIndex * stride; // Store result in intermediate buffer offset
  24573. Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
  24574. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
  24575. }
  24576. _lerp(buffer, dstOffset, srcOffset, t, stride) {
  24577. const s = 1 - t;
  24578. for (let i = 0; i !== stride; ++i) {
  24579. const j = dstOffset + i;
  24580. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  24581. }
  24582. }
  24583. _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  24584. for (let i = 0; i !== stride; ++i) {
  24585. const j = dstOffset + i;
  24586. buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
  24587. }
  24588. }
  24589. }
  24590. // Characters [].:/ are reserved for track binding syntax.
  24591. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  24592. const _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  24593. // only latin characters, and the unicode \p{L} is not yet supported. So
  24594. // instead, we exclude reserved characters and match everything else.
  24595. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  24596. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  24597. // be matched to parse the rest of the track name.
  24598. const _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  24599. const _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  24600. // characters. Accessor may contain any character except closing bracket.
  24601. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  24602. // contain any non-bracket characters.
  24603. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  24604. const _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  24605. const _supportedObjectNames = ['material', 'materials', 'bones'];
  24606. class Composite {
  24607. constructor(targetGroup, path, optionalParsedPath) {
  24608. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  24609. this._targetGroup = targetGroup;
  24610. this._bindings = targetGroup.subscribe_(path, parsedPath);
  24611. }
  24612. getValue(array, offset) {
  24613. this.bind(); // bind all binding
  24614. const firstValidIndex = this._targetGroup.nCachedObjects_,
  24615. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  24616. if (binding !== undefined) binding.getValue(array, offset);
  24617. }
  24618. setValue(array, offset) {
  24619. const bindings = this._bindings;
  24620. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  24621. bindings[i].setValue(array, offset);
  24622. }
  24623. }
  24624. bind() {
  24625. const bindings = this._bindings;
  24626. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  24627. bindings[i].bind();
  24628. }
  24629. }
  24630. unbind() {
  24631. const bindings = this._bindings;
  24632. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  24633. bindings[i].unbind();
  24634. }
  24635. }
  24636. } // Note: This class uses a State pattern on a per-method basis:
  24637. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  24638. // prototype version of these methods with one that represents
  24639. // the bound state. When the property is not found, the methods
  24640. // become no-ops.
  24641. class PropertyBinding {
  24642. constructor(rootNode, path, parsedPath) {
  24643. this.path = path;
  24644. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  24645. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  24646. this.rootNode = rootNode; // initial state of these methods that calls 'bind'
  24647. this.getValue = this._getValue_unbound;
  24648. this.setValue = this._setValue_unbound;
  24649. }
  24650. static create(root, path, parsedPath) {
  24651. if (!(root && root.isAnimationObjectGroup)) {
  24652. return new PropertyBinding(root, path, parsedPath);
  24653. } else {
  24654. return new PropertyBinding.Composite(root, path, parsedPath);
  24655. }
  24656. }
  24657. /**
  24658. * Replaces spaces with underscores and removes unsupported characters from
  24659. * node names, to ensure compatibility with parseTrackName().
  24660. *
  24661. * @param {string} name Node name to be sanitized.
  24662. * @return {string}
  24663. */
  24664. static sanitizeNodeName(name) {
  24665. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  24666. }
  24667. static parseTrackName(trackName) {
  24668. const matches = _trackRe.exec(trackName);
  24669. if (!matches) {
  24670. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  24671. }
  24672. const results = {
  24673. // directoryName: matches[ 1 ], // (tschw) currently unused
  24674. nodeName: matches[2],
  24675. objectName: matches[3],
  24676. objectIndex: matches[4],
  24677. propertyName: matches[5],
  24678. // required
  24679. propertyIndex: matches[6]
  24680. };
  24681. const lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  24682. if (lastDot !== undefined && lastDot !== -1) {
  24683. const objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
  24684. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  24685. // 'bar' could be the objectName, or part of a nodeName (which can
  24686. // include '.' characters).
  24687. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  24688. results.nodeName = results.nodeName.substring(0, lastDot);
  24689. results.objectName = objectName;
  24690. }
  24691. }
  24692. if (results.propertyName === null || results.propertyName.length === 0) {
  24693. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  24694. }
  24695. return results;
  24696. }
  24697. static findNode(root, nodeName) {
  24698. if (!nodeName || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  24699. return root;
  24700. } // search into skeleton bones.
  24701. if (root.skeleton) {
  24702. const bone = root.skeleton.getBoneByName(nodeName);
  24703. if (bone !== undefined) {
  24704. return bone;
  24705. }
  24706. } // search into node subtree.
  24707. if (root.children) {
  24708. const searchNodeSubtree = function (children) {
  24709. for (let i = 0; i < children.length; i++) {
  24710. const childNode = children[i];
  24711. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  24712. return childNode;
  24713. }
  24714. const result = searchNodeSubtree(childNode.children);
  24715. if (result) return result;
  24716. }
  24717. return null;
  24718. };
  24719. const subTreeNode = searchNodeSubtree(root.children);
  24720. if (subTreeNode) {
  24721. return subTreeNode;
  24722. }
  24723. }
  24724. return null;
  24725. } // these are used to "bind" a nonexistent property
  24726. _getValue_unavailable() {}
  24727. _setValue_unavailable() {} // Getters
  24728. _getValue_direct(buffer, offset) {
  24729. buffer[offset] = this.node[this.propertyName];
  24730. }
  24731. _getValue_array(buffer, offset) {
  24732. const source = this.resolvedProperty;
  24733. for (let i = 0, n = source.length; i !== n; ++i) {
  24734. buffer[offset++] = source[i];
  24735. }
  24736. }
  24737. _getValue_arrayElement(buffer, offset) {
  24738. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  24739. }
  24740. _getValue_toArray(buffer, offset) {
  24741. this.resolvedProperty.toArray(buffer, offset);
  24742. } // Direct
  24743. _setValue_direct(buffer, offset) {
  24744. this.targetObject[this.propertyName] = buffer[offset];
  24745. }
  24746. _setValue_direct_setNeedsUpdate(buffer, offset) {
  24747. this.targetObject[this.propertyName] = buffer[offset];
  24748. this.targetObject.needsUpdate = true;
  24749. }
  24750. _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  24751. this.targetObject[this.propertyName] = buffer[offset];
  24752. this.targetObject.matrixWorldNeedsUpdate = true;
  24753. } // EntireArray
  24754. _setValue_array(buffer, offset) {
  24755. const dest = this.resolvedProperty;
  24756. for (let i = 0, n = dest.length; i !== n; ++i) {
  24757. dest[i] = buffer[offset++];
  24758. }
  24759. }
  24760. _setValue_array_setNeedsUpdate(buffer, offset) {
  24761. const dest = this.resolvedProperty;
  24762. for (let i = 0, n = dest.length; i !== n; ++i) {
  24763. dest[i] = buffer[offset++];
  24764. }
  24765. this.targetObject.needsUpdate = true;
  24766. }
  24767. _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  24768. const dest = this.resolvedProperty;
  24769. for (let i = 0, n = dest.length; i !== n; ++i) {
  24770. dest[i] = buffer[offset++];
  24771. }
  24772. this.targetObject.matrixWorldNeedsUpdate = true;
  24773. } // ArrayElement
  24774. _setValue_arrayElement(buffer, offset) {
  24775. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  24776. }
  24777. _setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  24778. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  24779. this.targetObject.needsUpdate = true;
  24780. }
  24781. _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  24782. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  24783. this.targetObject.matrixWorldNeedsUpdate = true;
  24784. } // HasToFromArray
  24785. _setValue_fromArray(buffer, offset) {
  24786. this.resolvedProperty.fromArray(buffer, offset);
  24787. }
  24788. _setValue_fromArray_setNeedsUpdate(buffer, offset) {
  24789. this.resolvedProperty.fromArray(buffer, offset);
  24790. this.targetObject.needsUpdate = true;
  24791. }
  24792. _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  24793. this.resolvedProperty.fromArray(buffer, offset);
  24794. this.targetObject.matrixWorldNeedsUpdate = true;
  24795. }
  24796. _getValue_unbound(targetArray, offset) {
  24797. this.bind();
  24798. this.getValue(targetArray, offset);
  24799. }
  24800. _setValue_unbound(sourceArray, offset) {
  24801. this.bind();
  24802. this.setValue(sourceArray, offset);
  24803. } // create getter / setter pair for a property in the scene graph
  24804. bind() {
  24805. let targetObject = this.node;
  24806. const parsedPath = this.parsedPath;
  24807. const objectName = parsedPath.objectName;
  24808. const propertyName = parsedPath.propertyName;
  24809. let propertyIndex = parsedPath.propertyIndex;
  24810. if (!targetObject) {
  24811. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  24812. this.node = targetObject;
  24813. } // set fail state so we can just 'return' on error
  24814. this.getValue = this._getValue_unavailable;
  24815. this.setValue = this._setValue_unavailable; // ensure there is a value node
  24816. if (!targetObject) {
  24817. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  24818. return;
  24819. }
  24820. if (objectName) {
  24821. let objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  24822. switch (objectName) {
  24823. case 'materials':
  24824. if (!targetObject.material) {
  24825. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  24826. return;
  24827. }
  24828. if (!targetObject.material.materials) {
  24829. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  24830. return;
  24831. }
  24832. targetObject = targetObject.material.materials;
  24833. break;
  24834. case 'bones':
  24835. if (!targetObject.skeleton) {
  24836. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  24837. return;
  24838. } // potential future optimization: skip this if propertyIndex is already an integer
  24839. // and convert the integer string to a true integer.
  24840. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  24841. for (let i = 0; i < targetObject.length; i++) {
  24842. if (targetObject[i].name === objectIndex) {
  24843. objectIndex = i;
  24844. break;
  24845. }
  24846. }
  24847. break;
  24848. default:
  24849. if (targetObject[objectName] === undefined) {
  24850. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  24851. return;
  24852. }
  24853. targetObject = targetObject[objectName];
  24854. }
  24855. if (objectIndex !== undefined) {
  24856. if (targetObject[objectIndex] === undefined) {
  24857. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  24858. return;
  24859. }
  24860. targetObject = targetObject[objectIndex];
  24861. }
  24862. } // resolve property
  24863. const nodeProperty = targetObject[propertyName];
  24864. if (nodeProperty === undefined) {
  24865. const nodeName = parsedPath.nodeName;
  24866. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  24867. return;
  24868. } // determine versioning scheme
  24869. let versioning = this.Versioning.None;
  24870. this.targetObject = targetObject;
  24871. if (targetObject.needsUpdate !== undefined) {
  24872. // material
  24873. versioning = this.Versioning.NeedsUpdate;
  24874. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  24875. // node transform
  24876. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  24877. } // determine how the property gets bound
  24878. let bindingType = this.BindingType.Direct;
  24879. if (propertyIndex !== undefined) {
  24880. // access a sub element of the property array (only primitives are supported right now)
  24881. if (propertyName === 'morphTargetInfluences') {
  24882. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  24883. // support resolving morphTarget names into indices.
  24884. if (!targetObject.geometry) {
  24885. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  24886. return;
  24887. }
  24888. if (targetObject.geometry.isBufferGeometry) {
  24889. if (!targetObject.geometry.morphAttributes) {
  24890. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  24891. return;
  24892. }
  24893. if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
  24894. propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
  24895. }
  24896. } else {
  24897. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this);
  24898. return;
  24899. }
  24900. }
  24901. bindingType = this.BindingType.ArrayElement;
  24902. this.resolvedProperty = nodeProperty;
  24903. this.propertyIndex = propertyIndex;
  24904. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  24905. // must use copy for Object3D.Euler/Quaternion
  24906. bindingType = this.BindingType.HasFromToArray;
  24907. this.resolvedProperty = nodeProperty;
  24908. } else if (Array.isArray(nodeProperty)) {
  24909. bindingType = this.BindingType.EntireArray;
  24910. this.resolvedProperty = nodeProperty;
  24911. } else {
  24912. this.propertyName = propertyName;
  24913. } // select getter / setter
  24914. this.getValue = this.GetterByBindingType[bindingType];
  24915. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  24916. }
  24917. unbind() {
  24918. this.node = null; // back to the prototype version of getValue / setValue
  24919. // note: avoiding to mutate the shape of 'this' via 'delete'
  24920. this.getValue = this._getValue_unbound;
  24921. this.setValue = this._setValue_unbound;
  24922. }
  24923. }
  24924. PropertyBinding.Composite = Composite;
  24925. PropertyBinding.prototype.BindingType = {
  24926. Direct: 0,
  24927. EntireArray: 1,
  24928. ArrayElement: 2,
  24929. HasFromToArray: 3
  24930. };
  24931. PropertyBinding.prototype.Versioning = {
  24932. None: 0,
  24933. NeedsUpdate: 1,
  24934. MatrixWorldNeedsUpdate: 2
  24935. };
  24936. PropertyBinding.prototype.GetterByBindingType = [PropertyBinding.prototype._getValue_direct, PropertyBinding.prototype._getValue_array, PropertyBinding.prototype._getValue_arrayElement, PropertyBinding.prototype._getValue_toArray];
  24937. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [[// Direct
  24938. PropertyBinding.prototype._setValue_direct, PropertyBinding.prototype._setValue_direct_setNeedsUpdate, PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate], [// EntireArray
  24939. PropertyBinding.prototype._setValue_array, PropertyBinding.prototype._setValue_array_setNeedsUpdate, PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate], [// ArrayElement
  24940. PropertyBinding.prototype._setValue_arrayElement, PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate], [// HasToFromArray
  24941. PropertyBinding.prototype._setValue_fromArray, PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];
  24942. /**
  24943. *
  24944. * A group of objects that receives a shared animation state.
  24945. *
  24946. * Usage:
  24947. *
  24948. * - Add objects you would otherwise pass as 'root' to the
  24949. * constructor or the .clipAction method of AnimationMixer.
  24950. *
  24951. * - Instead pass this object as 'root'.
  24952. *
  24953. * - You can also add and remove objects later when the mixer
  24954. * is running.
  24955. *
  24956. * Note:
  24957. *
  24958. * Objects of this class appear as one object to the mixer,
  24959. * so cache control of the individual objects must be done
  24960. * on the group.
  24961. *
  24962. * Limitation:
  24963. *
  24964. * - The animated properties must be compatible among the
  24965. * all objects in the group.
  24966. *
  24967. * - A single property can either be controlled through a
  24968. * target group or directly, but not both.
  24969. */
  24970. class AnimationObjectGroup {
  24971. constructor() {
  24972. this.uuid = generateUUID(); // cached objects followed by the active ones
  24973. this._objects = Array.prototype.slice.call(arguments);
  24974. this.nCachedObjects_ = 0; // threshold
  24975. // note: read by PropertyBinding.Composite
  24976. const indices = {};
  24977. this._indicesByUUID = indices; // for bookkeeping
  24978. for (let i = 0, n = arguments.length; i !== n; ++i) {
  24979. indices[arguments[i].uuid] = i;
  24980. }
  24981. this._paths = []; // inside: string
  24982. this._parsedPaths = []; // inside: { we don't care, here }
  24983. this._bindings = []; // inside: Array< PropertyBinding >
  24984. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  24985. const scope = this;
  24986. this.stats = {
  24987. objects: {
  24988. get total() {
  24989. return scope._objects.length;
  24990. },
  24991. get inUse() {
  24992. return this.total - scope.nCachedObjects_;
  24993. }
  24994. },
  24995. get bindingsPerObject() {
  24996. return scope._bindings.length;
  24997. }
  24998. };
  24999. }
  25000. add() {
  25001. const objects = this._objects,
  25002. indicesByUUID = this._indicesByUUID,
  25003. paths = this._paths,
  25004. parsedPaths = this._parsedPaths,
  25005. bindings = this._bindings,
  25006. nBindings = bindings.length;
  25007. let knownObject = undefined,
  25008. nObjects = objects.length,
  25009. nCachedObjects = this.nCachedObjects_;
  25010. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25011. const object = arguments[i],
  25012. uuid = object.uuid;
  25013. let index = indicesByUUID[uuid];
  25014. if (index === undefined) {
  25015. // unknown object -> add it to the ACTIVE region
  25016. index = nObjects++;
  25017. indicesByUUID[uuid] = index;
  25018. objects.push(object); // accounting is done, now do the same for all bindings
  25019. for (let j = 0, m = nBindings; j !== m; ++j) {
  25020. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  25021. }
  25022. } else if (index < nCachedObjects) {
  25023. knownObject = objects[index]; // move existing object to the ACTIVE region
  25024. const firstActiveIndex = --nCachedObjects,
  25025. lastCachedObject = objects[firstActiveIndex];
  25026. indicesByUUID[lastCachedObject.uuid] = index;
  25027. objects[index] = lastCachedObject;
  25028. indicesByUUID[uuid] = firstActiveIndex;
  25029. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  25030. for (let j = 0, m = nBindings; j !== m; ++j) {
  25031. const bindingsForPath = bindings[j],
  25032. lastCached = bindingsForPath[firstActiveIndex];
  25033. let binding = bindingsForPath[index];
  25034. bindingsForPath[index] = lastCached;
  25035. if (binding === undefined) {
  25036. // since we do not bother to create new bindings
  25037. // for objects that are cached, the binding may
  25038. // or may not exist
  25039. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  25040. }
  25041. bindingsForPath[firstActiveIndex] = binding;
  25042. }
  25043. } else if (objects[index] !== knownObject) {
  25044. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  25045. } // else the object is already where we want it to be
  25046. } // for arguments
  25047. this.nCachedObjects_ = nCachedObjects;
  25048. }
  25049. remove() {
  25050. const objects = this._objects,
  25051. indicesByUUID = this._indicesByUUID,
  25052. bindings = this._bindings,
  25053. nBindings = bindings.length;
  25054. let nCachedObjects = this.nCachedObjects_;
  25055. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25056. const object = arguments[i],
  25057. uuid = object.uuid,
  25058. index = indicesByUUID[uuid];
  25059. if (index !== undefined && index >= nCachedObjects) {
  25060. // move existing object into the CACHED region
  25061. const lastCachedIndex = nCachedObjects++,
  25062. firstActiveObject = objects[lastCachedIndex];
  25063. indicesByUUID[firstActiveObject.uuid] = index;
  25064. objects[index] = firstActiveObject;
  25065. indicesByUUID[uuid] = lastCachedIndex;
  25066. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  25067. for (let j = 0, m = nBindings; j !== m; ++j) {
  25068. const bindingsForPath = bindings[j],
  25069. firstActive = bindingsForPath[lastCachedIndex],
  25070. binding = bindingsForPath[index];
  25071. bindingsForPath[index] = firstActive;
  25072. bindingsForPath[lastCachedIndex] = binding;
  25073. }
  25074. }
  25075. } // for arguments
  25076. this.nCachedObjects_ = nCachedObjects;
  25077. } // remove & forget
  25078. uncache() {
  25079. const objects = this._objects,
  25080. indicesByUUID = this._indicesByUUID,
  25081. bindings = this._bindings,
  25082. nBindings = bindings.length;
  25083. let nCachedObjects = this.nCachedObjects_,
  25084. nObjects = objects.length;
  25085. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25086. const object = arguments[i],
  25087. uuid = object.uuid,
  25088. index = indicesByUUID[uuid];
  25089. if (index !== undefined) {
  25090. delete indicesByUUID[uuid];
  25091. if (index < nCachedObjects) {
  25092. // object is cached, shrink the CACHED region
  25093. const firstActiveIndex = --nCachedObjects,
  25094. lastCachedObject = objects[firstActiveIndex],
  25095. lastIndex = --nObjects,
  25096. lastObject = objects[lastIndex]; // last cached object takes this object's place
  25097. indicesByUUID[lastCachedObject.uuid] = index;
  25098. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  25099. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  25100. objects[firstActiveIndex] = lastObject;
  25101. objects.pop(); // accounting is done, now do the same for all bindings
  25102. for (let j = 0, m = nBindings; j !== m; ++j) {
  25103. const bindingsForPath = bindings[j],
  25104. lastCached = bindingsForPath[firstActiveIndex],
  25105. last = bindingsForPath[lastIndex];
  25106. bindingsForPath[index] = lastCached;
  25107. bindingsForPath[firstActiveIndex] = last;
  25108. bindingsForPath.pop();
  25109. }
  25110. } else {
  25111. // object is active, just swap with the last and pop
  25112. const lastIndex = --nObjects,
  25113. lastObject = objects[lastIndex];
  25114. if (lastIndex > 0) {
  25115. indicesByUUID[lastObject.uuid] = index;
  25116. }
  25117. objects[index] = lastObject;
  25118. objects.pop(); // accounting is done, now do the same for all bindings
  25119. for (let j = 0, m = nBindings; j !== m; ++j) {
  25120. const bindingsForPath = bindings[j];
  25121. bindingsForPath[index] = bindingsForPath[lastIndex];
  25122. bindingsForPath.pop();
  25123. }
  25124. } // cached or active
  25125. } // if object is known
  25126. } // for arguments
  25127. this.nCachedObjects_ = nCachedObjects;
  25128. } // Internal interface used by befriended PropertyBinding.Composite:
  25129. subscribe_(path, parsedPath) {
  25130. // returns an array of bindings for the given path that is changed
  25131. // according to the contained objects in the group
  25132. const indicesByPath = this._bindingsIndicesByPath;
  25133. let index = indicesByPath[path];
  25134. const bindings = this._bindings;
  25135. if (index !== undefined) return bindings[index];
  25136. const paths = this._paths,
  25137. parsedPaths = this._parsedPaths,
  25138. objects = this._objects,
  25139. nObjects = objects.length,
  25140. nCachedObjects = this.nCachedObjects_,
  25141. bindingsForPath = new Array(nObjects);
  25142. index = bindings.length;
  25143. indicesByPath[path] = index;
  25144. paths.push(path);
  25145. parsedPaths.push(parsedPath);
  25146. bindings.push(bindingsForPath);
  25147. for (let i = nCachedObjects, n = objects.length; i !== n; ++i) {
  25148. const object = objects[i];
  25149. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  25150. }
  25151. return bindingsForPath;
  25152. }
  25153. unsubscribe_(path) {
  25154. // tells the group to forget about a property path and no longer
  25155. // update the array previously obtained with 'subscribe_'
  25156. const indicesByPath = this._bindingsIndicesByPath,
  25157. index = indicesByPath[path];
  25158. if (index !== undefined) {
  25159. const paths = this._paths,
  25160. parsedPaths = this._parsedPaths,
  25161. bindings = this._bindings,
  25162. lastBindingsIndex = bindings.length - 1,
  25163. lastBindings = bindings[lastBindingsIndex],
  25164. lastBindingsPath = path[lastBindingsIndex];
  25165. indicesByPath[lastBindingsPath] = index;
  25166. bindings[index] = lastBindings;
  25167. bindings.pop();
  25168. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  25169. parsedPaths.pop();
  25170. paths[index] = paths[lastBindingsIndex];
  25171. paths.pop();
  25172. }
  25173. }
  25174. }
  25175. AnimationObjectGroup.prototype.isAnimationObjectGroup = true;
  25176. class AnimationAction {
  25177. constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) {
  25178. this._mixer = mixer;
  25179. this._clip = clip;
  25180. this._localRoot = localRoot;
  25181. this.blendMode = blendMode;
  25182. const tracks = clip.tracks,
  25183. nTracks = tracks.length,
  25184. interpolants = new Array(nTracks);
  25185. const interpolantSettings = {
  25186. endingStart: ZeroCurvatureEnding,
  25187. endingEnd: ZeroCurvatureEnding
  25188. };
  25189. for (let i = 0; i !== nTracks; ++i) {
  25190. const interpolant = tracks[i].createInterpolant(null);
  25191. interpolants[i] = interpolant;
  25192. interpolant.settings = interpolantSettings;
  25193. }
  25194. this._interpolantSettings = interpolantSettings;
  25195. this._interpolants = interpolants; // bound by the mixer
  25196. // inside: PropertyMixer (managed by the mixer)
  25197. this._propertyBindings = new Array(nTracks);
  25198. this._cacheIndex = null; // for the memory manager
  25199. this._byClipCacheIndex = null; // for the memory manager
  25200. this._timeScaleInterpolant = null;
  25201. this._weightInterpolant = null;
  25202. this.loop = LoopRepeat;
  25203. this._loopCount = -1; // global mixer time when the action is to be started
  25204. // it's set back to 'null' upon start of the action
  25205. this._startTime = null; // scaled local time of the action
  25206. // gets clamped or wrapped to 0..clip.duration according to loop
  25207. this.time = 0;
  25208. this.timeScale = 1;
  25209. this._effectiveTimeScale = 1;
  25210. this.weight = 1;
  25211. this._effectiveWeight = 1;
  25212. this.repetitions = Infinity; // no. of repetitions when looping
  25213. this.paused = false; // true -> zero effective time scale
  25214. this.enabled = true; // false -> zero effective weight
  25215. this.clampWhenFinished = false; // keep feeding the last frame?
  25216. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  25217. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  25218. } // State & Scheduling
  25219. play() {
  25220. this._mixer._activateAction(this);
  25221. return this;
  25222. }
  25223. stop() {
  25224. this._mixer._deactivateAction(this);
  25225. return this.reset();
  25226. }
  25227. reset() {
  25228. this.paused = false;
  25229. this.enabled = true;
  25230. this.time = 0; // restart clip
  25231. this._loopCount = -1; // forget previous loops
  25232. this._startTime = null; // forget scheduling
  25233. return this.stopFading().stopWarping();
  25234. }
  25235. isRunning() {
  25236. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  25237. } // return true when play has been called
  25238. isScheduled() {
  25239. return this._mixer._isActiveAction(this);
  25240. }
  25241. startAt(time) {
  25242. this._startTime = time;
  25243. return this;
  25244. }
  25245. setLoop(mode, repetitions) {
  25246. this.loop = mode;
  25247. this.repetitions = repetitions;
  25248. return this;
  25249. } // Weight
  25250. // set the weight stopping any scheduled fading
  25251. // although .enabled = false yields an effective weight of zero, this
  25252. // method does *not* change .enabled, because it would be confusing
  25253. setEffectiveWeight(weight) {
  25254. this.weight = weight; // note: same logic as when updated at runtime
  25255. this._effectiveWeight = this.enabled ? weight : 0;
  25256. return this.stopFading();
  25257. } // return the weight considering fading and .enabled
  25258. getEffectiveWeight() {
  25259. return this._effectiveWeight;
  25260. }
  25261. fadeIn(duration) {
  25262. return this._scheduleFading(duration, 0, 1);
  25263. }
  25264. fadeOut(duration) {
  25265. return this._scheduleFading(duration, 1, 0);
  25266. }
  25267. crossFadeFrom(fadeOutAction, duration, warp) {
  25268. fadeOutAction.fadeOut(duration);
  25269. this.fadeIn(duration);
  25270. if (warp) {
  25271. const fadeInDuration = this._clip.duration,
  25272. fadeOutDuration = fadeOutAction._clip.duration,
  25273. startEndRatio = fadeOutDuration / fadeInDuration,
  25274. endStartRatio = fadeInDuration / fadeOutDuration;
  25275. fadeOutAction.warp(1.0, startEndRatio, duration);
  25276. this.warp(endStartRatio, 1.0, duration);
  25277. }
  25278. return this;
  25279. }
  25280. crossFadeTo(fadeInAction, duration, warp) {
  25281. return fadeInAction.crossFadeFrom(this, duration, warp);
  25282. }
  25283. stopFading() {
  25284. const weightInterpolant = this._weightInterpolant;
  25285. if (weightInterpolant !== null) {
  25286. this._weightInterpolant = null;
  25287. this._mixer._takeBackControlInterpolant(weightInterpolant);
  25288. }
  25289. return this;
  25290. } // Time Scale Control
  25291. // set the time scale stopping any scheduled warping
  25292. // although .paused = true yields an effective time scale of zero, this
  25293. // method does *not* change .paused, because it would be confusing
  25294. setEffectiveTimeScale(timeScale) {
  25295. this.timeScale = timeScale;
  25296. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  25297. return this.stopWarping();
  25298. } // return the time scale considering warping and .paused
  25299. getEffectiveTimeScale() {
  25300. return this._effectiveTimeScale;
  25301. }
  25302. setDuration(duration) {
  25303. this.timeScale = this._clip.duration / duration;
  25304. return this.stopWarping();
  25305. }
  25306. syncWith(action) {
  25307. this.time = action.time;
  25308. this.timeScale = action.timeScale;
  25309. return this.stopWarping();
  25310. }
  25311. halt(duration) {
  25312. return this.warp(this._effectiveTimeScale, 0, duration);
  25313. }
  25314. warp(startTimeScale, endTimeScale, duration) {
  25315. const mixer = this._mixer,
  25316. now = mixer.time,
  25317. timeScale = this.timeScale;
  25318. let interpolant = this._timeScaleInterpolant;
  25319. if (interpolant === null) {
  25320. interpolant = mixer._lendControlInterpolant();
  25321. this._timeScaleInterpolant = interpolant;
  25322. }
  25323. const times = interpolant.parameterPositions,
  25324. values = interpolant.sampleValues;
  25325. times[0] = now;
  25326. times[1] = now + duration;
  25327. values[0] = startTimeScale / timeScale;
  25328. values[1] = endTimeScale / timeScale;
  25329. return this;
  25330. }
  25331. stopWarping() {
  25332. const timeScaleInterpolant = this._timeScaleInterpolant;
  25333. if (timeScaleInterpolant !== null) {
  25334. this._timeScaleInterpolant = null;
  25335. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  25336. }
  25337. return this;
  25338. } // Object Accessors
  25339. getMixer() {
  25340. return this._mixer;
  25341. }
  25342. getClip() {
  25343. return this._clip;
  25344. }
  25345. getRoot() {
  25346. return this._localRoot || this._mixer._root;
  25347. } // Interna
  25348. _update(time, deltaTime, timeDirection, accuIndex) {
  25349. // called by the mixer
  25350. if (!this.enabled) {
  25351. // call ._updateWeight() to update ._effectiveWeight
  25352. this._updateWeight(time);
  25353. return;
  25354. }
  25355. const startTime = this._startTime;
  25356. if (startTime !== null) {
  25357. // check for scheduled start of action
  25358. const timeRunning = (time - startTime) * timeDirection;
  25359. if (timeRunning < 0 || timeDirection === 0) {
  25360. return; // yet to come / don't decide when delta = 0
  25361. } // start
  25362. this._startTime = null; // unschedule
  25363. deltaTime = timeDirection * timeRunning;
  25364. } // apply time scale and advance time
  25365. deltaTime *= this._updateTimeScale(time);
  25366. const clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  25367. // an effective weight of 0
  25368. const weight = this._updateWeight(time);
  25369. if (weight > 0) {
  25370. const interpolants = this._interpolants;
  25371. const propertyMixers = this._propertyBindings;
  25372. switch (this.blendMode) {
  25373. case AdditiveAnimationBlendMode:
  25374. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  25375. interpolants[j].evaluate(clipTime);
  25376. propertyMixers[j].accumulateAdditive(weight);
  25377. }
  25378. break;
  25379. case NormalAnimationBlendMode:
  25380. default:
  25381. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  25382. interpolants[j].evaluate(clipTime);
  25383. propertyMixers[j].accumulate(accuIndex, weight);
  25384. }
  25385. }
  25386. }
  25387. }
  25388. _updateWeight(time) {
  25389. let weight = 0;
  25390. if (this.enabled) {
  25391. weight = this.weight;
  25392. const interpolant = this._weightInterpolant;
  25393. if (interpolant !== null) {
  25394. const interpolantValue = interpolant.evaluate(time)[0];
  25395. weight *= interpolantValue;
  25396. if (time > interpolant.parameterPositions[1]) {
  25397. this.stopFading();
  25398. if (interpolantValue === 0) {
  25399. // faded out, disable
  25400. this.enabled = false;
  25401. }
  25402. }
  25403. }
  25404. }
  25405. this._effectiveWeight = weight;
  25406. return weight;
  25407. }
  25408. _updateTimeScale(time) {
  25409. let timeScale = 0;
  25410. if (!this.paused) {
  25411. timeScale = this.timeScale;
  25412. const interpolant = this._timeScaleInterpolant;
  25413. if (interpolant !== null) {
  25414. const interpolantValue = interpolant.evaluate(time)[0];
  25415. timeScale *= interpolantValue;
  25416. if (time > interpolant.parameterPositions[1]) {
  25417. this.stopWarping();
  25418. if (timeScale === 0) {
  25419. // motion has halted, pause
  25420. this.paused = true;
  25421. } else {
  25422. // warp done - apply final time scale
  25423. this.timeScale = timeScale;
  25424. }
  25425. }
  25426. }
  25427. }
  25428. this._effectiveTimeScale = timeScale;
  25429. return timeScale;
  25430. }
  25431. _updateTime(deltaTime) {
  25432. const duration = this._clip.duration;
  25433. const loop = this.loop;
  25434. let time = this.time + deltaTime;
  25435. let loopCount = this._loopCount;
  25436. const pingPong = loop === LoopPingPong;
  25437. if (deltaTime === 0) {
  25438. if (loopCount === -1) return time;
  25439. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  25440. }
  25441. if (loop === LoopOnce) {
  25442. if (loopCount === -1) {
  25443. // just started
  25444. this._loopCount = 0;
  25445. this._setEndings(true, true, false);
  25446. }
  25447. handle_stop: {
  25448. if (time >= duration) {
  25449. time = duration;
  25450. } else if (time < 0) {
  25451. time = 0;
  25452. } else {
  25453. this.time = time;
  25454. break handle_stop;
  25455. }
  25456. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  25457. this.time = time;
  25458. this._mixer.dispatchEvent({
  25459. type: 'finished',
  25460. action: this,
  25461. direction: deltaTime < 0 ? -1 : 1
  25462. });
  25463. }
  25464. } else {
  25465. // repetitive Repeat or PingPong
  25466. if (loopCount === -1) {
  25467. // just started
  25468. if (deltaTime >= 0) {
  25469. loopCount = 0;
  25470. this._setEndings(true, this.repetitions === 0, pingPong);
  25471. } else {
  25472. // when looping in reverse direction, the initial
  25473. // transition through zero counts as a repetition,
  25474. // so leave loopCount at -1
  25475. this._setEndings(this.repetitions === 0, true, pingPong);
  25476. }
  25477. }
  25478. if (time >= duration || time < 0) {
  25479. // wrap around
  25480. const loopDelta = Math.floor(time / duration); // signed
  25481. time -= duration * loopDelta;
  25482. loopCount += Math.abs(loopDelta);
  25483. const pending = this.repetitions - loopCount;
  25484. if (pending <= 0) {
  25485. // have to stop (switch state, clamp time, fire event)
  25486. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  25487. time = deltaTime > 0 ? duration : 0;
  25488. this.time = time;
  25489. this._mixer.dispatchEvent({
  25490. type: 'finished',
  25491. action: this,
  25492. direction: deltaTime > 0 ? 1 : -1
  25493. });
  25494. } else {
  25495. // keep running
  25496. if (pending === 1) {
  25497. // entering the last round
  25498. const atStart = deltaTime < 0;
  25499. this._setEndings(atStart, !atStart, pingPong);
  25500. } else {
  25501. this._setEndings(false, false, pingPong);
  25502. }
  25503. this._loopCount = loopCount;
  25504. this.time = time;
  25505. this._mixer.dispatchEvent({
  25506. type: 'loop',
  25507. action: this,
  25508. loopDelta: loopDelta
  25509. });
  25510. }
  25511. } else {
  25512. this.time = time;
  25513. }
  25514. if (pingPong && (loopCount & 1) === 1) {
  25515. // invert time for the "pong round"
  25516. return duration - time;
  25517. }
  25518. }
  25519. return time;
  25520. }
  25521. _setEndings(atStart, atEnd, pingPong) {
  25522. const settings = this._interpolantSettings;
  25523. if (pingPong) {
  25524. settings.endingStart = ZeroSlopeEnding;
  25525. settings.endingEnd = ZeroSlopeEnding;
  25526. } else {
  25527. // assuming for LoopOnce atStart == atEnd == true
  25528. if (atStart) {
  25529. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  25530. } else {
  25531. settings.endingStart = WrapAroundEnding;
  25532. }
  25533. if (atEnd) {
  25534. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  25535. } else {
  25536. settings.endingEnd = WrapAroundEnding;
  25537. }
  25538. }
  25539. }
  25540. _scheduleFading(duration, weightNow, weightThen) {
  25541. const mixer = this._mixer,
  25542. now = mixer.time;
  25543. let interpolant = this._weightInterpolant;
  25544. if (interpolant === null) {
  25545. interpolant = mixer._lendControlInterpolant();
  25546. this._weightInterpolant = interpolant;
  25547. }
  25548. const times = interpolant.parameterPositions,
  25549. values = interpolant.sampleValues;
  25550. times[0] = now;
  25551. values[0] = weightNow;
  25552. times[1] = now + duration;
  25553. values[1] = weightThen;
  25554. return this;
  25555. }
  25556. }
  25557. class AnimationMixer extends EventDispatcher {
  25558. constructor(root) {
  25559. super();
  25560. this._root = root;
  25561. this._initMemoryManager();
  25562. this._accuIndex = 0;
  25563. this.time = 0;
  25564. this.timeScale = 1.0;
  25565. }
  25566. _bindAction(action, prototypeAction) {
  25567. const root = action._localRoot || this._root,
  25568. tracks = action._clip.tracks,
  25569. nTracks = tracks.length,
  25570. bindings = action._propertyBindings,
  25571. interpolants = action._interpolants,
  25572. rootUuid = root.uuid,
  25573. bindingsByRoot = this._bindingsByRootAndName;
  25574. let bindingsByName = bindingsByRoot[rootUuid];
  25575. if (bindingsByName === undefined) {
  25576. bindingsByName = {};
  25577. bindingsByRoot[rootUuid] = bindingsByName;
  25578. }
  25579. for (let i = 0; i !== nTracks; ++i) {
  25580. const track = tracks[i],
  25581. trackName = track.name;
  25582. let binding = bindingsByName[trackName];
  25583. if (binding !== undefined) {
  25584. bindings[i] = binding;
  25585. } else {
  25586. binding = bindings[i];
  25587. if (binding !== undefined) {
  25588. // existing binding, make sure the cache knows
  25589. if (binding._cacheIndex === null) {
  25590. ++binding.referenceCount;
  25591. this._addInactiveBinding(binding, rootUuid, trackName);
  25592. }
  25593. continue;
  25594. }
  25595. const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  25596. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  25597. ++binding.referenceCount;
  25598. this._addInactiveBinding(binding, rootUuid, trackName);
  25599. bindings[i] = binding;
  25600. }
  25601. interpolants[i].resultBuffer = binding.buffer;
  25602. }
  25603. }
  25604. _activateAction(action) {
  25605. if (!this._isActiveAction(action)) {
  25606. if (action._cacheIndex === null) {
  25607. // this action has been forgotten by the cache, but the user
  25608. // appears to be still using it -> rebind
  25609. const rootUuid = (action._localRoot || this._root).uuid,
  25610. clipUuid = action._clip.uuid,
  25611. actionsForClip = this._actionsByClip[clipUuid];
  25612. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  25613. this._addInactiveAction(action, clipUuid, rootUuid);
  25614. }
  25615. const bindings = action._propertyBindings; // increment reference counts / sort out state
  25616. for (let i = 0, n = bindings.length; i !== n; ++i) {
  25617. const binding = bindings[i];
  25618. if (binding.useCount++ === 0) {
  25619. this._lendBinding(binding);
  25620. binding.saveOriginalState();
  25621. }
  25622. }
  25623. this._lendAction(action);
  25624. }
  25625. }
  25626. _deactivateAction(action) {
  25627. if (this._isActiveAction(action)) {
  25628. const bindings = action._propertyBindings; // decrement reference counts / sort out state
  25629. for (let i = 0, n = bindings.length; i !== n; ++i) {
  25630. const binding = bindings[i];
  25631. if (--binding.useCount === 0) {
  25632. binding.restoreOriginalState();
  25633. this._takeBackBinding(binding);
  25634. }
  25635. }
  25636. this._takeBackAction(action);
  25637. }
  25638. } // Memory manager
  25639. _initMemoryManager() {
  25640. this._actions = []; // 'nActiveActions' followed by inactive ones
  25641. this._nActiveActions = 0;
  25642. this._actionsByClip = {}; // inside:
  25643. // {
  25644. // knownActions: Array< AnimationAction > - used as prototypes
  25645. // actionByRoot: AnimationAction - lookup
  25646. // }
  25647. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  25648. this._nActiveBindings = 0;
  25649. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  25650. this._controlInterpolants = []; // same game as above
  25651. this._nActiveControlInterpolants = 0;
  25652. const scope = this;
  25653. this.stats = {
  25654. actions: {
  25655. get total() {
  25656. return scope._actions.length;
  25657. },
  25658. get inUse() {
  25659. return scope._nActiveActions;
  25660. }
  25661. },
  25662. bindings: {
  25663. get total() {
  25664. return scope._bindings.length;
  25665. },
  25666. get inUse() {
  25667. return scope._nActiveBindings;
  25668. }
  25669. },
  25670. controlInterpolants: {
  25671. get total() {
  25672. return scope._controlInterpolants.length;
  25673. },
  25674. get inUse() {
  25675. return scope._nActiveControlInterpolants;
  25676. }
  25677. }
  25678. };
  25679. } // Memory management for AnimationAction objects
  25680. _isActiveAction(action) {
  25681. const index = action._cacheIndex;
  25682. return index !== null && index < this._nActiveActions;
  25683. }
  25684. _addInactiveAction(action, clipUuid, rootUuid) {
  25685. const actions = this._actions,
  25686. actionsByClip = this._actionsByClip;
  25687. let actionsForClip = actionsByClip[clipUuid];
  25688. if (actionsForClip === undefined) {
  25689. actionsForClip = {
  25690. knownActions: [action],
  25691. actionByRoot: {}
  25692. };
  25693. action._byClipCacheIndex = 0;
  25694. actionsByClip[clipUuid] = actionsForClip;
  25695. } else {
  25696. const knownActions = actionsForClip.knownActions;
  25697. action._byClipCacheIndex = knownActions.length;
  25698. knownActions.push(action);
  25699. }
  25700. action._cacheIndex = actions.length;
  25701. actions.push(action);
  25702. actionsForClip.actionByRoot[rootUuid] = action;
  25703. }
  25704. _removeInactiveAction(action) {
  25705. const actions = this._actions,
  25706. lastInactiveAction = actions[actions.length - 1],
  25707. cacheIndex = action._cacheIndex;
  25708. lastInactiveAction._cacheIndex = cacheIndex;
  25709. actions[cacheIndex] = lastInactiveAction;
  25710. actions.pop();
  25711. action._cacheIndex = null;
  25712. const clipUuid = action._clip.uuid,
  25713. actionsByClip = this._actionsByClip,
  25714. actionsForClip = actionsByClip[clipUuid],
  25715. knownActionsForClip = actionsForClip.knownActions,
  25716. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  25717. byClipCacheIndex = action._byClipCacheIndex;
  25718. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  25719. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  25720. knownActionsForClip.pop();
  25721. action._byClipCacheIndex = null;
  25722. const actionByRoot = actionsForClip.actionByRoot,
  25723. rootUuid = (action._localRoot || this._root).uuid;
  25724. delete actionByRoot[rootUuid];
  25725. if (knownActionsForClip.length === 0) {
  25726. delete actionsByClip[clipUuid];
  25727. }
  25728. this._removeInactiveBindingsForAction(action);
  25729. }
  25730. _removeInactiveBindingsForAction(action) {
  25731. const bindings = action._propertyBindings;
  25732. for (let i = 0, n = bindings.length; i !== n; ++i) {
  25733. const binding = bindings[i];
  25734. if (--binding.referenceCount === 0) {
  25735. this._removeInactiveBinding(binding);
  25736. }
  25737. }
  25738. }
  25739. _lendAction(action) {
  25740. // [ active actions | inactive actions ]
  25741. // [ active actions >| inactive actions ]
  25742. // s a
  25743. // <-swap->
  25744. // a s
  25745. const actions = this._actions,
  25746. prevIndex = action._cacheIndex,
  25747. lastActiveIndex = this._nActiveActions++,
  25748. firstInactiveAction = actions[lastActiveIndex];
  25749. action._cacheIndex = lastActiveIndex;
  25750. actions[lastActiveIndex] = action;
  25751. firstInactiveAction._cacheIndex = prevIndex;
  25752. actions[prevIndex] = firstInactiveAction;
  25753. }
  25754. _takeBackAction(action) {
  25755. // [ active actions | inactive actions ]
  25756. // [ active actions |< inactive actions ]
  25757. // a s
  25758. // <-swap->
  25759. // s a
  25760. const actions = this._actions,
  25761. prevIndex = action._cacheIndex,
  25762. firstInactiveIndex = --this._nActiveActions,
  25763. lastActiveAction = actions[firstInactiveIndex];
  25764. action._cacheIndex = firstInactiveIndex;
  25765. actions[firstInactiveIndex] = action;
  25766. lastActiveAction._cacheIndex = prevIndex;
  25767. actions[prevIndex] = lastActiveAction;
  25768. } // Memory management for PropertyMixer objects
  25769. _addInactiveBinding(binding, rootUuid, trackName) {
  25770. const bindingsByRoot = this._bindingsByRootAndName,
  25771. bindings = this._bindings;
  25772. let bindingByName = bindingsByRoot[rootUuid];
  25773. if (bindingByName === undefined) {
  25774. bindingByName = {};
  25775. bindingsByRoot[rootUuid] = bindingByName;
  25776. }
  25777. bindingByName[trackName] = binding;
  25778. binding._cacheIndex = bindings.length;
  25779. bindings.push(binding);
  25780. }
  25781. _removeInactiveBinding(binding) {
  25782. const bindings = this._bindings,
  25783. propBinding = binding.binding,
  25784. rootUuid = propBinding.rootNode.uuid,
  25785. trackName = propBinding.path,
  25786. bindingsByRoot = this._bindingsByRootAndName,
  25787. bindingByName = bindingsByRoot[rootUuid],
  25788. lastInactiveBinding = bindings[bindings.length - 1],
  25789. cacheIndex = binding._cacheIndex;
  25790. lastInactiveBinding._cacheIndex = cacheIndex;
  25791. bindings[cacheIndex] = lastInactiveBinding;
  25792. bindings.pop();
  25793. delete bindingByName[trackName];
  25794. if (Object.keys(bindingByName).length === 0) {
  25795. delete bindingsByRoot[rootUuid];
  25796. }
  25797. }
  25798. _lendBinding(binding) {
  25799. const bindings = this._bindings,
  25800. prevIndex = binding._cacheIndex,
  25801. lastActiveIndex = this._nActiveBindings++,
  25802. firstInactiveBinding = bindings[lastActiveIndex];
  25803. binding._cacheIndex = lastActiveIndex;
  25804. bindings[lastActiveIndex] = binding;
  25805. firstInactiveBinding._cacheIndex = prevIndex;
  25806. bindings[prevIndex] = firstInactiveBinding;
  25807. }
  25808. _takeBackBinding(binding) {
  25809. const bindings = this._bindings,
  25810. prevIndex = binding._cacheIndex,
  25811. firstInactiveIndex = --this._nActiveBindings,
  25812. lastActiveBinding = bindings[firstInactiveIndex];
  25813. binding._cacheIndex = firstInactiveIndex;
  25814. bindings[firstInactiveIndex] = binding;
  25815. lastActiveBinding._cacheIndex = prevIndex;
  25816. bindings[prevIndex] = lastActiveBinding;
  25817. } // Memory management of Interpolants for weight and time scale
  25818. _lendControlInterpolant() {
  25819. const interpolants = this._controlInterpolants,
  25820. lastActiveIndex = this._nActiveControlInterpolants++;
  25821. let interpolant = interpolants[lastActiveIndex];
  25822. if (interpolant === undefined) {
  25823. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  25824. interpolant.__cacheIndex = lastActiveIndex;
  25825. interpolants[lastActiveIndex] = interpolant;
  25826. }
  25827. return interpolant;
  25828. }
  25829. _takeBackControlInterpolant(interpolant) {
  25830. const interpolants = this._controlInterpolants,
  25831. prevIndex = interpolant.__cacheIndex,
  25832. firstInactiveIndex = --this._nActiveControlInterpolants,
  25833. lastActiveInterpolant = interpolants[firstInactiveIndex];
  25834. interpolant.__cacheIndex = firstInactiveIndex;
  25835. interpolants[firstInactiveIndex] = interpolant;
  25836. lastActiveInterpolant.__cacheIndex = prevIndex;
  25837. interpolants[prevIndex] = lastActiveInterpolant;
  25838. } // return an action for a clip optionally using a custom root target
  25839. // object (this method allocates a lot of dynamic memory in case a
  25840. // previously unknown clip/root combination is specified)
  25841. clipAction(clip, optionalRoot, blendMode) {
  25842. const root = optionalRoot || this._root,
  25843. rootUuid = root.uuid;
  25844. let clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
  25845. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  25846. const actionsForClip = this._actionsByClip[clipUuid];
  25847. let prototypeAction = null;
  25848. if (blendMode === undefined) {
  25849. if (clipObject !== null) {
  25850. blendMode = clipObject.blendMode;
  25851. } else {
  25852. blendMode = NormalAnimationBlendMode;
  25853. }
  25854. }
  25855. if (actionsForClip !== undefined) {
  25856. const existingAction = actionsForClip.actionByRoot[rootUuid];
  25857. if (existingAction !== undefined && existingAction.blendMode === blendMode) {
  25858. return existingAction;
  25859. } // we know the clip, so we don't have to parse all
  25860. // the bindings again but can just copy
  25861. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  25862. if (clipObject === null) clipObject = prototypeAction._clip;
  25863. } // clip must be known when specified via string
  25864. if (clipObject === null) return null; // allocate all resources required to run it
  25865. const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
  25866. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  25867. this._addInactiveAction(newAction, clipUuid, rootUuid);
  25868. return newAction;
  25869. } // get an existing action
  25870. existingAction(clip, optionalRoot) {
  25871. const root = optionalRoot || this._root,
  25872. rootUuid = root.uuid,
  25873. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  25874. clipUuid = clipObject ? clipObject.uuid : clip,
  25875. actionsForClip = this._actionsByClip[clipUuid];
  25876. if (actionsForClip !== undefined) {
  25877. return actionsForClip.actionByRoot[rootUuid] || null;
  25878. }
  25879. return null;
  25880. } // deactivates all previously scheduled actions
  25881. stopAllAction() {
  25882. const actions = this._actions,
  25883. nActions = this._nActiveActions;
  25884. for (let i = nActions - 1; i >= 0; --i) {
  25885. actions[i].stop();
  25886. }
  25887. return this;
  25888. } // advance the time and update apply the animation
  25889. update(deltaTime) {
  25890. deltaTime *= this.timeScale;
  25891. const actions = this._actions,
  25892. nActions = this._nActiveActions,
  25893. time = this.time += deltaTime,
  25894. timeDirection = Math.sign(deltaTime),
  25895. accuIndex = this._accuIndex ^= 1; // run active actions
  25896. for (let i = 0; i !== nActions; ++i) {
  25897. const action = actions[i];
  25898. action._update(time, deltaTime, timeDirection, accuIndex);
  25899. } // update scene graph
  25900. const bindings = this._bindings,
  25901. nBindings = this._nActiveBindings;
  25902. for (let i = 0; i !== nBindings; ++i) {
  25903. bindings[i].apply(accuIndex);
  25904. }
  25905. return this;
  25906. } // Allows you to seek to a specific time in an animation.
  25907. setTime(timeInSeconds) {
  25908. this.time = 0; // Zero out time attribute for AnimationMixer object;
  25909. for (let i = 0; i < this._actions.length; i++) {
  25910. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  25911. }
  25912. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  25913. } // return this mixer's root target object
  25914. getRoot() {
  25915. return this._root;
  25916. } // free all resources specific to a particular clip
  25917. uncacheClip(clip) {
  25918. const actions = this._actions,
  25919. clipUuid = clip.uuid,
  25920. actionsByClip = this._actionsByClip,
  25921. actionsForClip = actionsByClip[clipUuid];
  25922. if (actionsForClip !== undefined) {
  25923. // note: just calling _removeInactiveAction would mess up the
  25924. // iteration state and also require updating the state we can
  25925. // just throw away
  25926. const actionsToRemove = actionsForClip.knownActions;
  25927. for (let i = 0, n = actionsToRemove.length; i !== n; ++i) {
  25928. const action = actionsToRemove[i];
  25929. this._deactivateAction(action);
  25930. const cacheIndex = action._cacheIndex,
  25931. lastInactiveAction = actions[actions.length - 1];
  25932. action._cacheIndex = null;
  25933. action._byClipCacheIndex = null;
  25934. lastInactiveAction._cacheIndex = cacheIndex;
  25935. actions[cacheIndex] = lastInactiveAction;
  25936. actions.pop();
  25937. this._removeInactiveBindingsForAction(action);
  25938. }
  25939. delete actionsByClip[clipUuid];
  25940. }
  25941. } // free all resources specific to a particular root target object
  25942. uncacheRoot(root) {
  25943. const rootUuid = root.uuid,
  25944. actionsByClip = this._actionsByClip;
  25945. for (const clipUuid in actionsByClip) {
  25946. const actionByRoot = actionsByClip[clipUuid].actionByRoot,
  25947. action = actionByRoot[rootUuid];
  25948. if (action !== undefined) {
  25949. this._deactivateAction(action);
  25950. this._removeInactiveAction(action);
  25951. }
  25952. }
  25953. const bindingsByRoot = this._bindingsByRootAndName,
  25954. bindingByName = bindingsByRoot[rootUuid];
  25955. if (bindingByName !== undefined) {
  25956. for (const trackName in bindingByName) {
  25957. const binding = bindingByName[trackName];
  25958. binding.restoreOriginalState();
  25959. this._removeInactiveBinding(binding);
  25960. }
  25961. }
  25962. } // remove a targeted clip from the cache
  25963. uncacheAction(clip, optionalRoot) {
  25964. const action = this.existingAction(clip, optionalRoot);
  25965. if (action !== null) {
  25966. this._deactivateAction(action);
  25967. this._removeInactiveAction(action);
  25968. }
  25969. }
  25970. }
  25971. AnimationMixer.prototype._controlInterpolantsResultBuffer = new Float32Array(1);
  25972. class Uniform {
  25973. constructor(value) {
  25974. if (typeof value === 'string') {
  25975. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  25976. value = arguments[1];
  25977. }
  25978. this.value = value;
  25979. }
  25980. clone() {
  25981. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  25982. }
  25983. }
  25984. class InstancedInterleavedBuffer extends InterleavedBuffer {
  25985. constructor(array, stride, meshPerAttribute = 1) {
  25986. super(array, stride);
  25987. this.meshPerAttribute = meshPerAttribute || 1;
  25988. }
  25989. copy(source) {
  25990. super.copy(source);
  25991. this.meshPerAttribute = source.meshPerAttribute;
  25992. return this;
  25993. }
  25994. clone(data) {
  25995. const ib = super.clone(data);
  25996. ib.meshPerAttribute = this.meshPerAttribute;
  25997. return ib;
  25998. }
  25999. toJSON(data) {
  26000. const json = super.toJSON(data);
  26001. json.isInstancedInterleavedBuffer = true;
  26002. json.meshPerAttribute = this.meshPerAttribute;
  26003. return json;
  26004. }
  26005. }
  26006. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  26007. class GLBufferAttribute {
  26008. constructor(buffer, type, itemSize, elementSize, count) {
  26009. this.buffer = buffer;
  26010. this.type = type;
  26011. this.itemSize = itemSize;
  26012. this.elementSize = elementSize;
  26013. this.count = count;
  26014. this.version = 0;
  26015. }
  26016. set needsUpdate(value) {
  26017. if (value === true) this.version++;
  26018. }
  26019. setBuffer(buffer) {
  26020. this.buffer = buffer;
  26021. return this;
  26022. }
  26023. setType(type, elementSize) {
  26024. this.type = type;
  26025. this.elementSize = elementSize;
  26026. return this;
  26027. }
  26028. setItemSize(itemSize) {
  26029. this.itemSize = itemSize;
  26030. return this;
  26031. }
  26032. setCount(count) {
  26033. this.count = count;
  26034. return this;
  26035. }
  26036. }
  26037. GLBufferAttribute.prototype.isGLBufferAttribute = true;
  26038. class Raycaster {
  26039. constructor(origin, direction, near = 0, far = Infinity) {
  26040. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  26041. this.near = near;
  26042. this.far = far;
  26043. this.camera = null;
  26044. this.layers = new Layers();
  26045. this.params = {
  26046. Mesh: {},
  26047. Line: {
  26048. threshold: 1
  26049. },
  26050. LOD: {},
  26051. Points: {
  26052. threshold: 1
  26053. },
  26054. Sprite: {}
  26055. };
  26056. }
  26057. set(origin, direction) {
  26058. // direction is assumed to be normalized (for accurate distance calculations)
  26059. this.ray.set(origin, direction);
  26060. }
  26061. setFromCamera(coords, camera) {
  26062. if (camera && camera.isPerspectiveCamera) {
  26063. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  26064. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  26065. this.camera = camera;
  26066. } else if (camera && camera.isOrthographicCamera) {
  26067. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  26068. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  26069. this.camera = camera;
  26070. } else {
  26071. console.error('THREE.Raycaster: Unsupported camera type: ' + camera.type);
  26072. }
  26073. }
  26074. intersectObject(object, recursive = false, intersects = []) {
  26075. intersectObject(object, this, intersects, recursive);
  26076. intersects.sort(ascSort);
  26077. return intersects;
  26078. }
  26079. intersectObjects(objects, recursive = false, intersects = []) {
  26080. for (let i = 0, l = objects.length; i < l; i++) {
  26081. intersectObject(objects[i], this, intersects, recursive);
  26082. }
  26083. intersects.sort(ascSort);
  26084. return intersects;
  26085. }
  26086. }
  26087. function ascSort(a, b) {
  26088. return a.distance - b.distance;
  26089. }
  26090. function intersectObject(object, raycaster, intersects, recursive) {
  26091. if (object.layers.test(raycaster.layers)) {
  26092. object.raycast(raycaster, intersects);
  26093. }
  26094. if (recursive === true) {
  26095. const children = object.children;
  26096. for (let i = 0, l = children.length; i < l; i++) {
  26097. intersectObject(children[i], raycaster, intersects, true);
  26098. }
  26099. }
  26100. }
  26101. /**
  26102. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  26103. *
  26104. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  26105. * The azimuthal angle (theta) is measured from the positive z-axis.
  26106. */
  26107. class Spherical {
  26108. constructor(radius = 1, phi = 0, theta = 0) {
  26109. this.radius = radius;
  26110. this.phi = phi; // polar angle
  26111. this.theta = theta; // azimuthal angle
  26112. return this;
  26113. }
  26114. set(radius, phi, theta) {
  26115. this.radius = radius;
  26116. this.phi = phi;
  26117. this.theta = theta;
  26118. return this;
  26119. }
  26120. copy(other) {
  26121. this.radius = other.radius;
  26122. this.phi = other.phi;
  26123. this.theta = other.theta;
  26124. return this;
  26125. } // restrict phi to be betwee EPS and PI-EPS
  26126. makeSafe() {
  26127. const EPS = 0.000001;
  26128. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  26129. return this;
  26130. }
  26131. setFromVector3(v) {
  26132. return this.setFromCartesianCoords(v.x, v.y, v.z);
  26133. }
  26134. setFromCartesianCoords(x, y, z) {
  26135. this.radius = Math.sqrt(x * x + y * y + z * z);
  26136. if (this.radius === 0) {
  26137. this.theta = 0;
  26138. this.phi = 0;
  26139. } else {
  26140. this.theta = Math.atan2(x, z);
  26141. this.phi = Math.acos(clamp(y / this.radius, -1, 1));
  26142. }
  26143. return this;
  26144. }
  26145. clone() {
  26146. return new this.constructor().copy(this);
  26147. }
  26148. }
  26149. /**
  26150. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  26151. */
  26152. class Cylindrical {
  26153. constructor(radius = 1, theta = 0, y = 0) {
  26154. this.radius = radius; // distance from the origin to a point in the x-z plane
  26155. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  26156. this.y = y; // height above the x-z plane
  26157. return this;
  26158. }
  26159. set(radius, theta, y) {
  26160. this.radius = radius;
  26161. this.theta = theta;
  26162. this.y = y;
  26163. return this;
  26164. }
  26165. copy(other) {
  26166. this.radius = other.radius;
  26167. this.theta = other.theta;
  26168. this.y = other.y;
  26169. return this;
  26170. }
  26171. setFromVector3(v) {
  26172. return this.setFromCartesianCoords(v.x, v.y, v.z);
  26173. }
  26174. setFromCartesianCoords(x, y, z) {
  26175. this.radius = Math.sqrt(x * x + z * z);
  26176. this.theta = Math.atan2(x, z);
  26177. this.y = y;
  26178. return this;
  26179. }
  26180. clone() {
  26181. return new this.constructor().copy(this);
  26182. }
  26183. }
  26184. const _vector$4 = /*@__PURE__*/new Vector2();
  26185. class Box2 {
  26186. constructor(min = new Vector2(+Infinity, +Infinity), max = new Vector2(-Infinity, -Infinity)) {
  26187. this.min = min;
  26188. this.max = max;
  26189. }
  26190. set(min, max) {
  26191. this.min.copy(min);
  26192. this.max.copy(max);
  26193. return this;
  26194. }
  26195. setFromPoints(points) {
  26196. this.makeEmpty();
  26197. for (let i = 0, il = points.length; i < il; i++) {
  26198. this.expandByPoint(points[i]);
  26199. }
  26200. return this;
  26201. }
  26202. setFromCenterAndSize(center, size) {
  26203. const halfSize = _vector$4.copy(size).multiplyScalar(0.5);
  26204. this.min.copy(center).sub(halfSize);
  26205. this.max.copy(center).add(halfSize);
  26206. return this;
  26207. }
  26208. clone() {
  26209. return new this.constructor().copy(this);
  26210. }
  26211. copy(box) {
  26212. this.min.copy(box.min);
  26213. this.max.copy(box.max);
  26214. return this;
  26215. }
  26216. makeEmpty() {
  26217. this.min.x = this.min.y = +Infinity;
  26218. this.max.x = this.max.y = -Infinity;
  26219. return this;
  26220. }
  26221. isEmpty() {
  26222. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  26223. return this.max.x < this.min.x || this.max.y < this.min.y;
  26224. }
  26225. getCenter(target) {
  26226. if (target === undefined) {
  26227. console.warn('THREE.Box2: .getCenter() target is now required');
  26228. target = new Vector2();
  26229. }
  26230. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  26231. }
  26232. getSize(target) {
  26233. if (target === undefined) {
  26234. console.warn('THREE.Box2: .getSize() target is now required');
  26235. target = new Vector2();
  26236. }
  26237. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  26238. }
  26239. expandByPoint(point) {
  26240. this.min.min(point);
  26241. this.max.max(point);
  26242. return this;
  26243. }
  26244. expandByVector(vector) {
  26245. this.min.sub(vector);
  26246. this.max.add(vector);
  26247. return this;
  26248. }
  26249. expandByScalar(scalar) {
  26250. this.min.addScalar(-scalar);
  26251. this.max.addScalar(scalar);
  26252. return this;
  26253. }
  26254. containsPoint(point) {
  26255. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  26256. }
  26257. containsBox(box) {
  26258. 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;
  26259. }
  26260. getParameter(point, target) {
  26261. // This can potentially have a divide by zero if the box
  26262. // has a size dimension of 0.
  26263. if (target === undefined) {
  26264. console.warn('THREE.Box2: .getParameter() target is now required');
  26265. target = new Vector2();
  26266. }
  26267. 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));
  26268. }
  26269. intersectsBox(box) {
  26270. // using 4 splitting planes to rule out intersections
  26271. 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;
  26272. }
  26273. clampPoint(point, target) {
  26274. if (target === undefined) {
  26275. console.warn('THREE.Box2: .clampPoint() target is now required');
  26276. target = new Vector2();
  26277. }
  26278. return target.copy(point).clamp(this.min, this.max);
  26279. }
  26280. distanceToPoint(point) {
  26281. const clampedPoint = _vector$4.copy(point).clamp(this.min, this.max);
  26282. return clampedPoint.sub(point).length();
  26283. }
  26284. intersect(box) {
  26285. this.min.max(box.min);
  26286. this.max.min(box.max);
  26287. return this;
  26288. }
  26289. union(box) {
  26290. this.min.min(box.min);
  26291. this.max.max(box.max);
  26292. return this;
  26293. }
  26294. translate(offset) {
  26295. this.min.add(offset);
  26296. this.max.add(offset);
  26297. return this;
  26298. }
  26299. equals(box) {
  26300. return box.min.equals(this.min) && box.max.equals(this.max);
  26301. }
  26302. }
  26303. Box2.prototype.isBox2 = true;
  26304. const _startP = /*@__PURE__*/new Vector3();
  26305. const _startEnd = /*@__PURE__*/new Vector3();
  26306. class Line3 {
  26307. constructor(start = new Vector3(), end = new Vector3()) {
  26308. this.start = start;
  26309. this.end = end;
  26310. }
  26311. set(start, end) {
  26312. this.start.copy(start);
  26313. this.end.copy(end);
  26314. return this;
  26315. }
  26316. copy(line) {
  26317. this.start.copy(line.start);
  26318. this.end.copy(line.end);
  26319. return this;
  26320. }
  26321. getCenter(target) {
  26322. if (target === undefined) {
  26323. console.warn('THREE.Line3: .getCenter() target is now required');
  26324. target = new Vector3();
  26325. }
  26326. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  26327. }
  26328. delta(target) {
  26329. if (target === undefined) {
  26330. console.warn('THREE.Line3: .delta() target is now required');
  26331. target = new Vector3();
  26332. }
  26333. return target.subVectors(this.end, this.start);
  26334. }
  26335. distanceSq() {
  26336. return this.start.distanceToSquared(this.end);
  26337. }
  26338. distance() {
  26339. return this.start.distanceTo(this.end);
  26340. }
  26341. at(t, target) {
  26342. if (target === undefined) {
  26343. console.warn('THREE.Line3: .at() target is now required');
  26344. target = new Vector3();
  26345. }
  26346. return this.delta(target).multiplyScalar(t).add(this.start);
  26347. }
  26348. closestPointToPointParameter(point, clampToLine) {
  26349. _startP.subVectors(point, this.start);
  26350. _startEnd.subVectors(this.end, this.start);
  26351. const startEnd2 = _startEnd.dot(_startEnd);
  26352. const startEnd_startP = _startEnd.dot(_startP);
  26353. let t = startEnd_startP / startEnd2;
  26354. if (clampToLine) {
  26355. t = clamp(t, 0, 1);
  26356. }
  26357. return t;
  26358. }
  26359. closestPointToPoint(point, clampToLine, target) {
  26360. const t = this.closestPointToPointParameter(point, clampToLine);
  26361. if (target === undefined) {
  26362. console.warn('THREE.Line3: .closestPointToPoint() target is now required');
  26363. target = new Vector3();
  26364. }
  26365. return this.delta(target).multiplyScalar(t).add(this.start);
  26366. }
  26367. applyMatrix4(matrix) {
  26368. this.start.applyMatrix4(matrix);
  26369. this.end.applyMatrix4(matrix);
  26370. return this;
  26371. }
  26372. equals(line) {
  26373. return line.start.equals(this.start) && line.end.equals(this.end);
  26374. }
  26375. clone() {
  26376. return new this.constructor().copy(this);
  26377. }
  26378. }
  26379. class ImmediateRenderObject extends Object3D {
  26380. constructor(material) {
  26381. super();
  26382. this.material = material;
  26383. this.render = function ()
  26384. /* renderCallback */
  26385. {};
  26386. this.hasPositions = false;
  26387. this.hasNormals = false;
  26388. this.hasColors = false;
  26389. this.hasUvs = false;
  26390. this.positionArray = null;
  26391. this.normalArray = null;
  26392. this.colorArray = null;
  26393. this.uvArray = null;
  26394. this.count = 0;
  26395. }
  26396. }
  26397. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  26398. const _vector$3 = /*@__PURE__*/new Vector3();
  26399. class SpotLightHelper extends Object3D {
  26400. constructor(light, color) {
  26401. super();
  26402. this.light = light;
  26403. this.light.updateMatrixWorld();
  26404. this.matrix = light.matrixWorld;
  26405. this.matrixAutoUpdate = false;
  26406. this.color = color;
  26407. const geometry = new BufferGeometry();
  26408. 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];
  26409. for (let i = 0, j = 1, l = 32; i < l; i++, j++) {
  26410. const p1 = i / l * Math.PI * 2;
  26411. const p2 = j / l * Math.PI * 2;
  26412. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  26413. }
  26414. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  26415. const material = new LineBasicMaterial({
  26416. fog: false,
  26417. toneMapped: false
  26418. });
  26419. this.cone = new LineSegments(geometry, material);
  26420. this.add(this.cone);
  26421. this.update();
  26422. }
  26423. dispose() {
  26424. this.cone.geometry.dispose();
  26425. this.cone.material.dispose();
  26426. }
  26427. update() {
  26428. this.light.updateMatrixWorld();
  26429. const coneLength = this.light.distance ? this.light.distance : 1000;
  26430. const coneWidth = coneLength * Math.tan(this.light.angle);
  26431. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  26432. _vector$3.setFromMatrixPosition(this.light.target.matrixWorld);
  26433. this.cone.lookAt(_vector$3);
  26434. if (this.color !== undefined) {
  26435. this.cone.material.color.set(this.color);
  26436. } else {
  26437. this.cone.material.color.copy(this.light.color);
  26438. }
  26439. }
  26440. }
  26441. const _vector$2 = /*@__PURE__*/new Vector3();
  26442. const _boneMatrix = /*@__PURE__*/new Matrix4();
  26443. const _matrixWorldInv = /*@__PURE__*/new Matrix4();
  26444. class SkeletonHelper extends LineSegments {
  26445. constructor(object) {
  26446. const bones = getBoneList(object);
  26447. const geometry = new BufferGeometry();
  26448. const vertices = [];
  26449. const colors = [];
  26450. const color1 = new Color(0, 0, 1);
  26451. const color2 = new Color(0, 1, 0);
  26452. for (let i = 0; i < bones.length; i++) {
  26453. const bone = bones[i];
  26454. if (bone.parent && bone.parent.isBone) {
  26455. vertices.push(0, 0, 0);
  26456. vertices.push(0, 0, 0);
  26457. colors.push(color1.r, color1.g, color1.b);
  26458. colors.push(color2.r, color2.g, color2.b);
  26459. }
  26460. }
  26461. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26462. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26463. const material = new LineBasicMaterial({
  26464. vertexColors: true,
  26465. depthTest: false,
  26466. depthWrite: false,
  26467. toneMapped: false,
  26468. transparent: true
  26469. });
  26470. super(geometry, material);
  26471. this.type = 'SkeletonHelper';
  26472. this.isSkeletonHelper = true;
  26473. this.root = object;
  26474. this.bones = bones;
  26475. this.matrix = object.matrixWorld;
  26476. this.matrixAutoUpdate = false;
  26477. }
  26478. updateMatrixWorld(force) {
  26479. const bones = this.bones;
  26480. const geometry = this.geometry;
  26481. const position = geometry.getAttribute('position');
  26482. _matrixWorldInv.copy(this.root.matrixWorld).invert();
  26483. for (let i = 0, j = 0; i < bones.length; i++) {
  26484. const bone = bones[i];
  26485. if (bone.parent && bone.parent.isBone) {
  26486. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  26487. _vector$2.setFromMatrixPosition(_boneMatrix);
  26488. position.setXYZ(j, _vector$2.x, _vector$2.y, _vector$2.z);
  26489. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  26490. _vector$2.setFromMatrixPosition(_boneMatrix);
  26491. position.setXYZ(j + 1, _vector$2.x, _vector$2.y, _vector$2.z);
  26492. j += 2;
  26493. }
  26494. }
  26495. geometry.getAttribute('position').needsUpdate = true;
  26496. super.updateMatrixWorld(force);
  26497. }
  26498. }
  26499. function getBoneList(object) {
  26500. const boneList = [];
  26501. if (object && object.isBone) {
  26502. boneList.push(object);
  26503. }
  26504. for (let i = 0; i < object.children.length; i++) {
  26505. boneList.push.apply(boneList, getBoneList(object.children[i]));
  26506. }
  26507. return boneList;
  26508. }
  26509. class PointLightHelper extends Mesh {
  26510. constructor(light, sphereSize, color) {
  26511. const geometry = new SphereGeometry(sphereSize, 4, 2);
  26512. const material = new MeshBasicMaterial({
  26513. wireframe: true,
  26514. fog: false,
  26515. toneMapped: false
  26516. });
  26517. super(geometry, material);
  26518. this.light = light;
  26519. this.light.updateMatrixWorld();
  26520. this.color = color;
  26521. this.type = 'PointLightHelper';
  26522. this.matrix = this.light.matrixWorld;
  26523. this.matrixAutoUpdate = false;
  26524. this.update();
  26525. /*
  26526. // TODO: delete this comment?
  26527. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  26528. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  26529. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  26530. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  26531. const d = light.distance;
  26532. if ( d === 0.0 ) {
  26533. this.lightDistance.visible = false;
  26534. } else {
  26535. this.lightDistance.scale.set( d, d, d );
  26536. }
  26537. this.add( this.lightDistance );
  26538. */
  26539. }
  26540. dispose() {
  26541. this.geometry.dispose();
  26542. this.material.dispose();
  26543. }
  26544. update() {
  26545. if (this.color !== undefined) {
  26546. this.material.color.set(this.color);
  26547. } else {
  26548. this.material.color.copy(this.light.color);
  26549. }
  26550. /*
  26551. const d = this.light.distance;
  26552. if ( d === 0.0 ) {
  26553. this.lightDistance.visible = false;
  26554. } else {
  26555. this.lightDistance.visible = true;
  26556. this.lightDistance.scale.set( d, d, d );
  26557. }
  26558. */
  26559. }
  26560. }
  26561. const _vector$1 = /*@__PURE__*/new Vector3();
  26562. const _color1 = /*@__PURE__*/new Color();
  26563. const _color2 = /*@__PURE__*/new Color();
  26564. class HemisphereLightHelper extends Object3D {
  26565. constructor(light, size, color) {
  26566. super();
  26567. this.light = light;
  26568. this.light.updateMatrixWorld();
  26569. this.matrix = light.matrixWorld;
  26570. this.matrixAutoUpdate = false;
  26571. this.color = color;
  26572. const geometry = new OctahedronGeometry(size);
  26573. geometry.rotateY(Math.PI * 0.5);
  26574. this.material = new MeshBasicMaterial({
  26575. wireframe: true,
  26576. fog: false,
  26577. toneMapped: false
  26578. });
  26579. if (this.color === undefined) this.material.vertexColors = true;
  26580. const position = geometry.getAttribute('position');
  26581. const colors = new Float32Array(position.count * 3);
  26582. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  26583. this.add(new Mesh(geometry, this.material));
  26584. this.update();
  26585. }
  26586. dispose() {
  26587. this.children[0].geometry.dispose();
  26588. this.children[0].material.dispose();
  26589. }
  26590. update() {
  26591. const mesh = this.children[0];
  26592. if (this.color !== undefined) {
  26593. this.material.color.set(this.color);
  26594. } else {
  26595. const colors = mesh.geometry.getAttribute('color');
  26596. _color1.copy(this.light.color);
  26597. _color2.copy(this.light.groundColor);
  26598. for (let i = 0, l = colors.count; i < l; i++) {
  26599. const color = i < l / 2 ? _color1 : _color2;
  26600. colors.setXYZ(i, color.r, color.g, color.b);
  26601. }
  26602. colors.needsUpdate = true;
  26603. }
  26604. mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate());
  26605. }
  26606. }
  26607. class GridHelper extends LineSegments {
  26608. constructor(size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888) {
  26609. color1 = new Color(color1);
  26610. color2 = new Color(color2);
  26611. const center = divisions / 2;
  26612. const step = size / divisions;
  26613. const halfSize = size / 2;
  26614. const vertices = [],
  26615. colors = [];
  26616. for (let i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  26617. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  26618. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  26619. const color = i === center ? color1 : color2;
  26620. color.toArray(colors, j);
  26621. j += 3;
  26622. color.toArray(colors, j);
  26623. j += 3;
  26624. color.toArray(colors, j);
  26625. j += 3;
  26626. color.toArray(colors, j);
  26627. j += 3;
  26628. }
  26629. const geometry = new BufferGeometry();
  26630. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26631. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26632. const material = new LineBasicMaterial({
  26633. vertexColors: true,
  26634. toneMapped: false
  26635. });
  26636. super(geometry, material);
  26637. this.type = 'GridHelper';
  26638. }
  26639. }
  26640. class PolarGridHelper extends LineSegments {
  26641. constructor(radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888) {
  26642. color1 = new Color(color1);
  26643. color2 = new Color(color2);
  26644. const vertices = [];
  26645. const colors = []; // create the radials
  26646. for (let i = 0; i <= radials; i++) {
  26647. const v = i / radials * (Math.PI * 2);
  26648. const x = Math.sin(v) * radius;
  26649. const z = Math.cos(v) * radius;
  26650. vertices.push(0, 0, 0);
  26651. vertices.push(x, 0, z);
  26652. const color = i & 1 ? color1 : color2;
  26653. colors.push(color.r, color.g, color.b);
  26654. colors.push(color.r, color.g, color.b);
  26655. } // create the circles
  26656. for (let i = 0; i <= circles; i++) {
  26657. const color = i & 1 ? color1 : color2;
  26658. const r = radius - radius / circles * i;
  26659. for (let j = 0; j < divisions; j++) {
  26660. // first vertex
  26661. let v = j / divisions * (Math.PI * 2);
  26662. let x = Math.sin(v) * r;
  26663. let z = Math.cos(v) * r;
  26664. vertices.push(x, 0, z);
  26665. colors.push(color.r, color.g, color.b); // second vertex
  26666. v = (j + 1) / divisions * (Math.PI * 2);
  26667. x = Math.sin(v) * r;
  26668. z = Math.cos(v) * r;
  26669. vertices.push(x, 0, z);
  26670. colors.push(color.r, color.g, color.b);
  26671. }
  26672. }
  26673. const geometry = new BufferGeometry();
  26674. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26675. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26676. const material = new LineBasicMaterial({
  26677. vertexColors: true,
  26678. toneMapped: false
  26679. });
  26680. super(geometry, material);
  26681. this.type = 'PolarGridHelper';
  26682. }
  26683. }
  26684. const _v1 = /*@__PURE__*/new Vector3();
  26685. const _v2 = /*@__PURE__*/new Vector3();
  26686. const _v3 = /*@__PURE__*/new Vector3();
  26687. class DirectionalLightHelper extends Object3D {
  26688. constructor(light, size, color) {
  26689. super();
  26690. this.light = light;
  26691. this.light.updateMatrixWorld();
  26692. this.matrix = light.matrixWorld;
  26693. this.matrixAutoUpdate = false;
  26694. this.color = color;
  26695. if (size === undefined) size = 1;
  26696. let geometry = new BufferGeometry();
  26697. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  26698. const material = new LineBasicMaterial({
  26699. fog: false,
  26700. toneMapped: false
  26701. });
  26702. this.lightPlane = new Line(geometry, material);
  26703. this.add(this.lightPlane);
  26704. geometry = new BufferGeometry();
  26705. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  26706. this.targetLine = new Line(geometry, material);
  26707. this.add(this.targetLine);
  26708. this.update();
  26709. }
  26710. dispose() {
  26711. this.lightPlane.geometry.dispose();
  26712. this.lightPlane.material.dispose();
  26713. this.targetLine.geometry.dispose();
  26714. this.targetLine.material.dispose();
  26715. }
  26716. update() {
  26717. _v1.setFromMatrixPosition(this.light.matrixWorld);
  26718. _v2.setFromMatrixPosition(this.light.target.matrixWorld);
  26719. _v3.subVectors(_v2, _v1);
  26720. this.lightPlane.lookAt(_v2);
  26721. if (this.color !== undefined) {
  26722. this.lightPlane.material.color.set(this.color);
  26723. this.targetLine.material.color.set(this.color);
  26724. } else {
  26725. this.lightPlane.material.color.copy(this.light.color);
  26726. this.targetLine.material.color.copy(this.light.color);
  26727. }
  26728. this.targetLine.lookAt(_v2);
  26729. this.targetLine.scale.z = _v3.length();
  26730. }
  26731. }
  26732. const _vector = /*@__PURE__*/new Vector3();
  26733. const _camera = /*@__PURE__*/new Camera();
  26734. /**
  26735. * - shows frustum, line of sight and up of the camera
  26736. * - suitable for fast updates
  26737. * - based on frustum visualization in lightgl.js shadowmap example
  26738. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  26739. */
  26740. class CameraHelper extends LineSegments {
  26741. constructor(camera) {
  26742. const geometry = new BufferGeometry();
  26743. const material = new LineBasicMaterial({
  26744. color: 0xffffff,
  26745. vertexColors: true,
  26746. toneMapped: false
  26747. });
  26748. const vertices = [];
  26749. const colors = [];
  26750. const pointMap = {}; // colors
  26751. const colorFrustum = new Color(0xffaa00);
  26752. const colorCone = new Color(0xff0000);
  26753. const colorUp = new Color(0x00aaff);
  26754. const colorTarget = new Color(0xffffff);
  26755. const colorCross = new Color(0x333333); // near
  26756. addLine('n1', 'n2', colorFrustum);
  26757. addLine('n2', 'n4', colorFrustum);
  26758. addLine('n4', 'n3', colorFrustum);
  26759. addLine('n3', 'n1', colorFrustum); // far
  26760. addLine('f1', 'f2', colorFrustum);
  26761. addLine('f2', 'f4', colorFrustum);
  26762. addLine('f4', 'f3', colorFrustum);
  26763. addLine('f3', 'f1', colorFrustum); // sides
  26764. addLine('n1', 'f1', colorFrustum);
  26765. addLine('n2', 'f2', colorFrustum);
  26766. addLine('n3', 'f3', colorFrustum);
  26767. addLine('n4', 'f4', colorFrustum); // cone
  26768. addLine('p', 'n1', colorCone);
  26769. addLine('p', 'n2', colorCone);
  26770. addLine('p', 'n3', colorCone);
  26771. addLine('p', 'n4', colorCone); // up
  26772. addLine('u1', 'u2', colorUp);
  26773. addLine('u2', 'u3', colorUp);
  26774. addLine('u3', 'u1', colorUp); // target
  26775. addLine('c', 't', colorTarget);
  26776. addLine('p', 'c', colorCross); // cross
  26777. addLine('cn1', 'cn2', colorCross);
  26778. addLine('cn3', 'cn4', colorCross);
  26779. addLine('cf1', 'cf2', colorCross);
  26780. addLine('cf3', 'cf4', colorCross);
  26781. function addLine(a, b, color) {
  26782. addPoint(a, color);
  26783. addPoint(b, color);
  26784. }
  26785. function addPoint(id, color) {
  26786. vertices.push(0, 0, 0);
  26787. colors.push(color.r, color.g, color.b);
  26788. if (pointMap[id] === undefined) {
  26789. pointMap[id] = [];
  26790. }
  26791. pointMap[id].push(vertices.length / 3 - 1);
  26792. }
  26793. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  26794. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  26795. super(geometry, material);
  26796. this.type = 'CameraHelper';
  26797. this.camera = camera;
  26798. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  26799. this.matrix = camera.matrixWorld;
  26800. this.matrixAutoUpdate = false;
  26801. this.pointMap = pointMap;
  26802. this.update();
  26803. }
  26804. update() {
  26805. const geometry = this.geometry;
  26806. const pointMap = this.pointMap;
  26807. const w = 1,
  26808. h = 1; // we need just camera projection matrix inverse
  26809. // world matrix must be identity
  26810. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  26811. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  26812. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  26813. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  26814. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  26815. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  26816. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  26817. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  26818. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  26819. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  26820. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  26821. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  26822. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  26823. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  26824. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  26825. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  26826. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  26827. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  26828. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  26829. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  26830. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  26831. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  26832. geometry.getAttribute('position').needsUpdate = true;
  26833. }
  26834. dispose() {
  26835. this.geometry.dispose();
  26836. this.material.dispose();
  26837. }
  26838. }
  26839. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  26840. _vector.set(x, y, z).unproject(camera);
  26841. const points = pointMap[point];
  26842. if (points !== undefined) {
  26843. const position = geometry.getAttribute('position');
  26844. for (let i = 0, l = points.length; i < l; i++) {
  26845. position.setXYZ(points[i], _vector.x, _vector.y, _vector.z);
  26846. }
  26847. }
  26848. }
  26849. const _box = /*@__PURE__*/new Box3();
  26850. class BoxHelper extends LineSegments {
  26851. constructor(object, color = 0xffff00) {
  26852. 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]);
  26853. const positions = new Float32Array(8 * 3);
  26854. const geometry = new BufferGeometry();
  26855. geometry.setIndex(new BufferAttribute(indices, 1));
  26856. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  26857. super(geometry, new LineBasicMaterial({
  26858. color: color,
  26859. toneMapped: false
  26860. }));
  26861. this.object = object;
  26862. this.type = 'BoxHelper';
  26863. this.matrixAutoUpdate = false;
  26864. this.update();
  26865. }
  26866. update(object) {
  26867. if (object !== undefined) {
  26868. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  26869. }
  26870. if (this.object !== undefined) {
  26871. _box.setFromObject(this.object);
  26872. }
  26873. if (_box.isEmpty()) return;
  26874. const min = _box.min;
  26875. const max = _box.max;
  26876. /*
  26877. 5____4
  26878. 1/___0/|
  26879. | 6__|_7
  26880. 2/___3/
  26881. 0: max.x, max.y, max.z
  26882. 1: min.x, max.y, max.z
  26883. 2: min.x, min.y, max.z
  26884. 3: max.x, min.y, max.z
  26885. 4: max.x, max.y, min.z
  26886. 5: min.x, max.y, min.z
  26887. 6: min.x, min.y, min.z
  26888. 7: max.x, min.y, min.z
  26889. */
  26890. const position = this.geometry.attributes.position;
  26891. const array = position.array;
  26892. array[0] = max.x;
  26893. array[1] = max.y;
  26894. array[2] = max.z;
  26895. array[3] = min.x;
  26896. array[4] = max.y;
  26897. array[5] = max.z;
  26898. array[6] = min.x;
  26899. array[7] = min.y;
  26900. array[8] = max.z;
  26901. array[9] = max.x;
  26902. array[10] = min.y;
  26903. array[11] = max.z;
  26904. array[12] = max.x;
  26905. array[13] = max.y;
  26906. array[14] = min.z;
  26907. array[15] = min.x;
  26908. array[16] = max.y;
  26909. array[17] = min.z;
  26910. array[18] = min.x;
  26911. array[19] = min.y;
  26912. array[20] = min.z;
  26913. array[21] = max.x;
  26914. array[22] = min.y;
  26915. array[23] = min.z;
  26916. position.needsUpdate = true;
  26917. this.geometry.computeBoundingSphere();
  26918. }
  26919. setFromObject(object) {
  26920. this.object = object;
  26921. this.update();
  26922. return this;
  26923. }
  26924. copy(source) {
  26925. LineSegments.prototype.copy.call(this, source);
  26926. this.object = source.object;
  26927. return this;
  26928. }
  26929. }
  26930. class Box3Helper extends LineSegments {
  26931. constructor(box, color = 0xffff00) {
  26932. 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]);
  26933. 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];
  26934. const geometry = new BufferGeometry();
  26935. geometry.setIndex(new BufferAttribute(indices, 1));
  26936. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  26937. super(geometry, new LineBasicMaterial({
  26938. color: color,
  26939. toneMapped: false
  26940. }));
  26941. this.box = box;
  26942. this.type = 'Box3Helper';
  26943. this.geometry.computeBoundingSphere();
  26944. }
  26945. updateMatrixWorld(force) {
  26946. const box = this.box;
  26947. if (box.isEmpty()) return;
  26948. box.getCenter(this.position);
  26949. box.getSize(this.scale);
  26950. this.scale.multiplyScalar(0.5);
  26951. super.updateMatrixWorld(force);
  26952. }
  26953. }
  26954. class PlaneHelper extends Line {
  26955. constructor(plane, size = 1, hex = 0xffff00) {
  26956. const color = hex;
  26957. 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];
  26958. const geometry = new BufferGeometry();
  26959. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  26960. geometry.computeBoundingSphere();
  26961. super(geometry, new LineBasicMaterial({
  26962. color: color,
  26963. toneMapped: false
  26964. }));
  26965. this.type = 'PlaneHelper';
  26966. this.plane = plane;
  26967. this.size = size;
  26968. const positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  26969. const geometry2 = new BufferGeometry();
  26970. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  26971. geometry2.computeBoundingSphere();
  26972. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  26973. color: color,
  26974. opacity: 0.2,
  26975. transparent: true,
  26976. depthWrite: false,
  26977. toneMapped: false
  26978. })));
  26979. }
  26980. updateMatrixWorld(force) {
  26981. let scale = -this.plane.constant;
  26982. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  26983. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  26984. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  26985. this.lookAt(this.plane.normal);
  26986. super.updateMatrixWorld(force);
  26987. }
  26988. }
  26989. const _axis = /*@__PURE__*/new Vector3();
  26990. let _lineGeometry, _coneGeometry;
  26991. class ArrowHelper extends Object3D {
  26992. // dir is assumed to be normalized
  26993. 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) {
  26994. super();
  26995. this.type = 'ArrowHelper';
  26996. if (_lineGeometry === undefined) {
  26997. _lineGeometry = new BufferGeometry();
  26998. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  26999. _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1);
  27000. _coneGeometry.translate(0, -0.5, 0);
  27001. }
  27002. this.position.copy(origin);
  27003. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  27004. color: color,
  27005. toneMapped: false
  27006. }));
  27007. this.line.matrixAutoUpdate = false;
  27008. this.add(this.line);
  27009. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  27010. color: color,
  27011. toneMapped: false
  27012. }));
  27013. this.cone.matrixAutoUpdate = false;
  27014. this.add(this.cone);
  27015. this.setDirection(dir);
  27016. this.setLength(length, headLength, headWidth);
  27017. }
  27018. setDirection(dir) {
  27019. // dir is assumed to be normalized
  27020. if (dir.y > 0.99999) {
  27021. this.quaternion.set(0, 0, 0, 1);
  27022. } else if (dir.y < -0.99999) {
  27023. this.quaternion.set(1, 0, 0, 0);
  27024. } else {
  27025. _axis.set(dir.z, 0, -dir.x).normalize();
  27026. const radians = Math.acos(dir.y);
  27027. this.quaternion.setFromAxisAngle(_axis, radians);
  27028. }
  27029. }
  27030. setLength(length, headLength = length * 0.2, headWidth = headLength * 0.2) {
  27031. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  27032. this.line.updateMatrix();
  27033. this.cone.scale.set(headWidth, headLength, headWidth);
  27034. this.cone.position.y = length;
  27035. this.cone.updateMatrix();
  27036. }
  27037. setColor(color) {
  27038. this.line.material.color.set(color);
  27039. this.cone.material.color.set(color);
  27040. }
  27041. copy(source) {
  27042. super.copy(source, false);
  27043. this.line.copy(source.line);
  27044. this.cone.copy(source.cone);
  27045. return this;
  27046. }
  27047. }
  27048. class AxesHelper extends LineSegments {
  27049. constructor(size = 1) {
  27050. const vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  27051. const colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  27052. const geometry = new BufferGeometry();
  27053. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27054. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27055. const material = new LineBasicMaterial({
  27056. vertexColors: true,
  27057. toneMapped: false
  27058. });
  27059. super(geometry, material);
  27060. this.type = 'AxesHelper';
  27061. }
  27062. dispose() {
  27063. this.geometry.dispose();
  27064. this.material.dispose();
  27065. }
  27066. }
  27067. const _floatView = new Float32Array(1);
  27068. const _int32View = new Int32Array(_floatView.buffer);
  27069. class DataUtils {
  27070. // Converts float32 to float16 (stored as uint16 value).
  27071. static toHalfFloat(val) {
  27072. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  27073. /* This method is faster than the OpenEXR implementation (very often
  27074. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  27075. * by James Tursa?s half-precision code. */
  27076. _floatView[0] = val;
  27077. const x = _int32View[0];
  27078. let bits = x >> 16 & 0x8000;
  27079. /* Get the sign */
  27080. let m = x >> 12 & 0x07ff;
  27081. /* Keep one extra bit for rounding */
  27082. const e = x >> 23 & 0xff;
  27083. /* Using int is faster here */
  27084. /* If zero, or denormal, or exponent underflows too much for a denormal
  27085. * half, return signed zero. */
  27086. if (e < 103) return bits;
  27087. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  27088. if (e > 142) {
  27089. bits |= 0x7c00;
  27090. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  27091. * not Inf, so make sure we set one mantissa bit too. */
  27092. bits |= (e == 255 ? 0 : 1) && x & 0x007fffff;
  27093. return bits;
  27094. }
  27095. /* If exponent underflows but not too much, return a denormal */
  27096. if (e < 113) {
  27097. m |= 0x0800;
  27098. /* Extra rounding may overflow and set mantissa to 0 and exponent
  27099. * to 1, which is OK. */
  27100. bits |= (m >> 114 - e) + (m >> 113 - e & 1);
  27101. return bits;
  27102. }
  27103. bits |= e - 112 << 10 | m >> 1;
  27104. /* Extra rounding. An overflow will set mantissa to 0 and increment
  27105. * the exponent, which is OK. */
  27106. bits += m & 1;
  27107. return bits;
  27108. }
  27109. }
  27110. const LOD_MIN = 4;
  27111. const LOD_MAX = 8;
  27112. const SIZE_MAX = Math.pow(2, LOD_MAX); // The standard deviations (radians) associated with the extra mips. These are
  27113. // chosen to approximate a Trowbridge-Reitz distribution function times the
  27114. // geometric shadowing function. These sigma values squared must match the
  27115. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  27116. const EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
  27117. 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
  27118. // samples and exit early, but not recompile the shader.
  27119. const MAX_SAMPLES = 20;
  27120. const ENCODINGS = {
  27121. [LinearEncoding]: 0,
  27122. [sRGBEncoding]: 1,
  27123. [RGBEEncoding]: 2,
  27124. [RGBM7Encoding]: 3,
  27125. [RGBM16Encoding]: 4,
  27126. [RGBDEncoding]: 5,
  27127. [GammaEncoding]: 6
  27128. };
  27129. const backgroundMaterial = new MeshBasicMaterial({
  27130. side: BackSide,
  27131. depthWrite: false,
  27132. depthTest: false
  27133. });
  27134. const backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial);
  27135. const _flatCamera = /*@__PURE__*/new OrthographicCamera();
  27136. const {
  27137. _lodPlanes,
  27138. _sizeLods,
  27139. _sigmas
  27140. } = /*@__PURE__*/_createPlanes();
  27141. const _clearColor = /*@__PURE__*/new Color();
  27142. let _oldTarget = null; // Golden Ratio
  27143. const PHI = (1 + Math.sqrt(5)) / 2;
  27144. const INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
  27145. // same axis), used as axis directions evenly spread on a sphere.
  27146. 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)];
  27147. /**
  27148. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  27149. * (PMREM) from a cubeMap environment texture. This allows different levels of
  27150. * blur to be quickly accessed based on material roughness. It is packed into a
  27151. * special CubeUV format that allows us to perform custom interpolation so that
  27152. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  27153. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  27154. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  27155. * higher roughness levels. In this way we maintain resolution to smoothly
  27156. * interpolate diffuse lighting while limiting sampling computation.
  27157. *
  27158. * Paper: Fast, Accurate Image-Based Lighting
  27159. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  27160. */
  27161. function convertLinearToRGBE(color) {
  27162. const maxComponent = Math.max(color.r, color.g, color.b);
  27163. const fExp = Math.min(Math.max(Math.ceil(Math.log2(maxComponent)), -128.0), 127.0);
  27164. color.multiplyScalar(Math.pow(2.0, -fExp));
  27165. const alpha = (fExp + 128.0) / 255.0;
  27166. return alpha;
  27167. }
  27168. class PMREMGenerator {
  27169. constructor(renderer) {
  27170. this._renderer = renderer;
  27171. this._pingPongRenderTarget = null;
  27172. this._blurMaterial = _getBlurShader(MAX_SAMPLES);
  27173. this._equirectShader = null;
  27174. this._cubemapShader = null;
  27175. this._compileMaterial(this._blurMaterial);
  27176. }
  27177. /**
  27178. * Generates a PMREM from a supplied Scene, which can be faster than using an
  27179. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  27180. * in radians to be applied to the scene before PMREM generation. Optional near
  27181. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  27182. * is placed at the origin).
  27183. */
  27184. fromScene(scene, sigma = 0, near = 0.1, far = 100) {
  27185. _oldTarget = this._renderer.getRenderTarget();
  27186. const cubeUVRenderTarget = this._allocateTargets();
  27187. this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  27188. if (sigma > 0) {
  27189. this._blur(cubeUVRenderTarget, 0, 0, sigma);
  27190. }
  27191. this._applyPMREM(cubeUVRenderTarget);
  27192. this._cleanup(cubeUVRenderTarget);
  27193. return cubeUVRenderTarget;
  27194. }
  27195. /**
  27196. * Generates a PMREM from an equirectangular texture, which can be either LDR
  27197. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  27198. * as this matches best with the 256 x 256 cubemap output.
  27199. */
  27200. fromEquirectangular(equirectangular) {
  27201. return this._fromTexture(equirectangular);
  27202. }
  27203. /**
  27204. * Generates a PMREM from an cubemap texture, which can be either LDR
  27205. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  27206. * as this matches best with the 256 x 256 cubemap output.
  27207. */
  27208. fromCubemap(cubemap) {
  27209. return this._fromTexture(cubemap);
  27210. }
  27211. /**
  27212. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  27213. * your texture's network fetch for increased concurrency.
  27214. */
  27215. compileCubemapShader() {
  27216. if (this._cubemapShader === null) {
  27217. this._cubemapShader = _getCubemapShader();
  27218. this._compileMaterial(this._cubemapShader);
  27219. }
  27220. }
  27221. /**
  27222. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  27223. * your texture's network fetch for increased concurrency.
  27224. */
  27225. compileEquirectangularShader() {
  27226. if (this._equirectShader === null) {
  27227. this._equirectShader = _getEquirectShader();
  27228. this._compileMaterial(this._equirectShader);
  27229. }
  27230. }
  27231. /**
  27232. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  27233. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  27234. * one of them will cause any others to also become unusable.
  27235. */
  27236. dispose() {
  27237. this._blurMaterial.dispose();
  27238. if (this._cubemapShader !== null) this._cubemapShader.dispose();
  27239. if (this._equirectShader !== null) this._equirectShader.dispose();
  27240. for (let i = 0; i < _lodPlanes.length; i++) {
  27241. _lodPlanes[i].dispose();
  27242. }
  27243. } // private interface
  27244. _cleanup(outputTarget) {
  27245. this._pingPongRenderTarget.dispose();
  27246. this._renderer.setRenderTarget(_oldTarget);
  27247. outputTarget.scissorTest = false;
  27248. _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
  27249. }
  27250. _fromTexture(texture) {
  27251. _oldTarget = this._renderer.getRenderTarget();
  27252. const cubeUVRenderTarget = this._allocateTargets(texture);
  27253. this._textureToCubeUV(texture, cubeUVRenderTarget);
  27254. this._applyPMREM(cubeUVRenderTarget);
  27255. this._cleanup(cubeUVRenderTarget);
  27256. return cubeUVRenderTarget;
  27257. }
  27258. _allocateTargets(texture) {
  27259. // warning: null texture is valid
  27260. const params = {
  27261. magFilter: NearestFilter,
  27262. minFilter: NearestFilter,
  27263. generateMipmaps: false,
  27264. type: UnsignedByteType,
  27265. format: RGBEFormat,
  27266. encoding: _isLDR(texture) ? texture.encoding : RGBEEncoding,
  27267. depthBuffer: false
  27268. };
  27269. const cubeUVRenderTarget = _createRenderTarget(params);
  27270. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  27271. this._pingPongRenderTarget = _createRenderTarget(params);
  27272. return cubeUVRenderTarget;
  27273. }
  27274. _compileMaterial(material) {
  27275. const tmpMesh = new Mesh(_lodPlanes[0], material);
  27276. this._renderer.compile(tmpMesh, _flatCamera);
  27277. }
  27278. _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  27279. const fov = 90;
  27280. const aspect = 1;
  27281. const cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  27282. const upSign = [1, -1, 1, 1, 1, 1];
  27283. const forwardSign = [1, 1, 1, -1, -1, -1];
  27284. const renderer = this._renderer;
  27285. const originalAutoClear = renderer.autoClear;
  27286. const outputEncoding = renderer.outputEncoding;
  27287. const toneMapping = renderer.toneMapping;
  27288. renderer.getClearColor(_clearColor);
  27289. renderer.toneMapping = NoToneMapping;
  27290. renderer.outputEncoding = LinearEncoding;
  27291. renderer.autoClear = false;
  27292. let useSolidColor = false;
  27293. const background = scene.background;
  27294. if (background) {
  27295. if (background.isColor) {
  27296. backgroundMaterial.color.copy(background).convertSRGBToLinear();
  27297. scene.background = null;
  27298. const alpha = convertLinearToRGBE(backgroundMaterial.color);
  27299. backgroundMaterial.opacity = alpha;
  27300. useSolidColor = true;
  27301. }
  27302. } else {
  27303. backgroundMaterial.color.copy(_clearColor).convertSRGBToLinear();
  27304. const alpha = convertLinearToRGBE(backgroundMaterial.color);
  27305. backgroundMaterial.opacity = alpha;
  27306. useSolidColor = true;
  27307. }
  27308. for (let i = 0; i < 6; i++) {
  27309. const col = i % 3;
  27310. if (col == 0) {
  27311. cubeCamera.up.set(0, upSign[i], 0);
  27312. cubeCamera.lookAt(forwardSign[i], 0, 0);
  27313. } else if (col == 1) {
  27314. cubeCamera.up.set(0, 0, upSign[i]);
  27315. cubeCamera.lookAt(0, forwardSign[i], 0);
  27316. } else {
  27317. cubeCamera.up.set(0, upSign[i], 0);
  27318. cubeCamera.lookAt(0, 0, forwardSign[i]);
  27319. }
  27320. _setViewport(cubeUVRenderTarget, col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX);
  27321. renderer.setRenderTarget(cubeUVRenderTarget);
  27322. if (useSolidColor) {
  27323. renderer.render(backgroundBox, cubeCamera);
  27324. }
  27325. renderer.render(scene, cubeCamera);
  27326. }
  27327. renderer.toneMapping = toneMapping;
  27328. renderer.outputEncoding = outputEncoding;
  27329. renderer.autoClear = originalAutoClear;
  27330. }
  27331. _textureToCubeUV(texture, cubeUVRenderTarget) {
  27332. const renderer = this._renderer;
  27333. if (texture.isCubeTexture) {
  27334. if (this._cubemapShader == null) {
  27335. this._cubemapShader = _getCubemapShader();
  27336. }
  27337. } else {
  27338. if (this._equirectShader == null) {
  27339. this._equirectShader = _getEquirectShader();
  27340. }
  27341. }
  27342. const material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  27343. const mesh = new Mesh(_lodPlanes[0], material);
  27344. const uniforms = material.uniforms;
  27345. uniforms['envMap'].value = texture;
  27346. if (!texture.isCubeTexture) {
  27347. uniforms['texelSize'].value.set(1.0 / texture.image.width, 1.0 / texture.image.height);
  27348. }
  27349. uniforms['inputEncoding'].value = ENCODINGS[texture.encoding];
  27350. uniforms['outputEncoding'].value = ENCODINGS[cubeUVRenderTarget.texture.encoding];
  27351. _setViewport(cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX);
  27352. renderer.setRenderTarget(cubeUVRenderTarget);
  27353. renderer.render(mesh, _flatCamera);
  27354. }
  27355. _applyPMREM(cubeUVRenderTarget) {
  27356. const renderer = this._renderer;
  27357. const autoClear = renderer.autoClear;
  27358. renderer.autoClear = false;
  27359. for (let i = 1; i < TOTAL_LODS; i++) {
  27360. const sigma = Math.sqrt(_sigmas[i] * _sigmas[i] - _sigmas[i - 1] * _sigmas[i - 1]);
  27361. const poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  27362. this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  27363. }
  27364. renderer.autoClear = autoClear;
  27365. }
  27366. /**
  27367. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  27368. * vertically and horizontally, but this breaks down on a cube. Here we apply
  27369. * the blur latitudinally (around the poles), and then longitudinally (towards
  27370. * the poles) to approximate the orthogonally-separable blur. It is least
  27371. * accurate at the poles, but still does a decent job.
  27372. */
  27373. _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  27374. const pingPongRenderTarget = this._pingPongRenderTarget;
  27375. this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  27376. this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  27377. }
  27378. _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  27379. const renderer = this._renderer;
  27380. const blurMaterial = this._blurMaterial;
  27381. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  27382. console.error('blur direction must be either latitudinal or longitudinal!');
  27383. } // Number of standard deviations at which to cut off the discrete approximation.
  27384. const STANDARD_DEVIATIONS = 3;
  27385. const blurMesh = new Mesh(_lodPlanes[lodOut], blurMaterial);
  27386. const blurUniforms = blurMaterial.uniforms;
  27387. const pixels = _sizeLods[lodIn] - 1;
  27388. const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  27389. const sigmaPixels = sigmaRadians / radiansPerPixel;
  27390. const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  27391. if (samples > MAX_SAMPLES) {
  27392. console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
  27393. }
  27394. const weights = [];
  27395. let sum = 0;
  27396. for (let i = 0; i < MAX_SAMPLES; ++i) {
  27397. const x = i / sigmaPixels;
  27398. const weight = Math.exp(-x * x / 2);
  27399. weights.push(weight);
  27400. if (i == 0) {
  27401. sum += weight;
  27402. } else if (i < samples) {
  27403. sum += 2 * weight;
  27404. }
  27405. }
  27406. for (let i = 0; i < weights.length; i++) {
  27407. weights[i] = weights[i] / sum;
  27408. }
  27409. blurUniforms['envMap'].value = targetIn.texture;
  27410. blurUniforms['samples'].value = samples;
  27411. blurUniforms['weights'].value = weights;
  27412. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  27413. if (poleAxis) {
  27414. blurUniforms['poleAxis'].value = poleAxis;
  27415. }
  27416. blurUniforms['dTheta'].value = radiansPerPixel;
  27417. blurUniforms['mipInt'].value = LOD_MAX - lodIn;
  27418. blurUniforms['inputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  27419. blurUniforms['outputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  27420. const outputSize = _sizeLods[lodOut];
  27421. const x = 3 * Math.max(0, SIZE_MAX - 2 * outputSize);
  27422. const y = (lodOut === 0 ? 0 : 2 * SIZE_MAX) + 2 * outputSize * (lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0);
  27423. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  27424. renderer.setRenderTarget(targetOut);
  27425. renderer.render(blurMesh, _flatCamera);
  27426. }
  27427. }
  27428. function _isLDR(texture) {
  27429. if (texture === undefined || texture.type !== UnsignedByteType) return false;
  27430. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  27431. }
  27432. function _createPlanes() {
  27433. const _lodPlanes = [];
  27434. const _sizeLods = [];
  27435. const _sigmas = [];
  27436. let lod = LOD_MAX;
  27437. for (let i = 0; i < TOTAL_LODS; i++) {
  27438. const sizeLod = Math.pow(2, lod);
  27439. _sizeLods.push(sizeLod);
  27440. let sigma = 1.0 / sizeLod;
  27441. if (i > LOD_MAX - LOD_MIN) {
  27442. sigma = EXTRA_LOD_SIGMA[i - LOD_MAX + LOD_MIN - 1];
  27443. } else if (i == 0) {
  27444. sigma = 0;
  27445. }
  27446. _sigmas.push(sigma);
  27447. const texelSize = 1.0 / (sizeLod - 1);
  27448. const min = -texelSize / 2;
  27449. const max = 1 + texelSize / 2;
  27450. const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  27451. const cubeFaces = 6;
  27452. const vertices = 6;
  27453. const positionSize = 3;
  27454. const uvSize = 2;
  27455. const faceIndexSize = 1;
  27456. const position = new Float32Array(positionSize * vertices * cubeFaces);
  27457. const uv = new Float32Array(uvSize * vertices * cubeFaces);
  27458. const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  27459. for (let face = 0; face < cubeFaces; face++) {
  27460. const x = face % 3 * 2 / 3 - 1;
  27461. const y = face > 2 ? 0 : -1;
  27462. 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];
  27463. position.set(coordinates, positionSize * vertices * face);
  27464. uv.set(uv1, uvSize * vertices * face);
  27465. const fill = [face, face, face, face, face, face];
  27466. faceIndex.set(fill, faceIndexSize * vertices * face);
  27467. }
  27468. const planes = new BufferGeometry();
  27469. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  27470. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  27471. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  27472. _lodPlanes.push(planes);
  27473. if (lod > LOD_MIN) {
  27474. lod--;
  27475. }
  27476. }
  27477. return {
  27478. _lodPlanes,
  27479. _sizeLods,
  27480. _sigmas
  27481. };
  27482. }
  27483. function _createRenderTarget(params) {
  27484. const cubeUVRenderTarget = new WebGLRenderTarget(3 * SIZE_MAX, 3 * SIZE_MAX, params);
  27485. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  27486. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  27487. cubeUVRenderTarget.scissorTest = true;
  27488. return cubeUVRenderTarget;
  27489. }
  27490. function _setViewport(target, x, y, width, height) {
  27491. target.viewport.set(x, y, width, height);
  27492. target.scissor.set(x, y, width, height);
  27493. }
  27494. function _getBlurShader(maxSamples) {
  27495. const weights = new Float32Array(maxSamples);
  27496. const poleAxis = new Vector3(0, 1, 0);
  27497. const shaderMaterial = new RawShaderMaterial({
  27498. name: 'SphericalGaussianBlur',
  27499. defines: {
  27500. 'n': maxSamples
  27501. },
  27502. uniforms: {
  27503. 'envMap': {
  27504. value: null
  27505. },
  27506. 'samples': {
  27507. value: 1
  27508. },
  27509. 'weights': {
  27510. value: weights
  27511. },
  27512. 'latitudinal': {
  27513. value: false
  27514. },
  27515. 'dTheta': {
  27516. value: 0
  27517. },
  27518. 'mipInt': {
  27519. value: 0
  27520. },
  27521. 'poleAxis': {
  27522. value: poleAxis
  27523. },
  27524. 'inputEncoding': {
  27525. value: ENCODINGS[LinearEncoding]
  27526. },
  27527. 'outputEncoding': {
  27528. value: ENCODINGS[LinearEncoding]
  27529. }
  27530. },
  27531. vertexShader: _getCommonVertexShader(),
  27532. fragmentShader:
  27533. /* glsl */
  27534. `
  27535. precision mediump float;
  27536. precision mediump int;
  27537. varying vec3 vOutputDirection;
  27538. uniform sampler2D envMap;
  27539. uniform int samples;
  27540. uniform float weights[ n ];
  27541. uniform bool latitudinal;
  27542. uniform float dTheta;
  27543. uniform float mipInt;
  27544. uniform vec3 poleAxis;
  27545. ${_getEncodings()}
  27546. #define ENVMAP_TYPE_CUBE_UV
  27547. #include <cube_uv_reflection_fragment>
  27548. vec3 getSample( float theta, vec3 axis ) {
  27549. float cosTheta = cos( theta );
  27550. // Rodrigues' axis-angle rotation
  27551. vec3 sampleDirection = vOutputDirection * cosTheta
  27552. + cross( axis, vOutputDirection ) * sin( theta )
  27553. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  27554. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  27555. }
  27556. void main() {
  27557. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  27558. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  27559. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  27560. }
  27561. axis = normalize( axis );
  27562. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  27563. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  27564. for ( int i = 1; i < n; i++ ) {
  27565. if ( i >= samples ) {
  27566. break;
  27567. }
  27568. float theta = dTheta * float( i );
  27569. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  27570. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  27571. }
  27572. gl_FragColor = linearToOutputTexel( gl_FragColor );
  27573. }
  27574. `,
  27575. blending: NoBlending,
  27576. depthTest: false,
  27577. depthWrite: false
  27578. });
  27579. return shaderMaterial;
  27580. }
  27581. function _getEquirectShader() {
  27582. const texelSize = new Vector2(1, 1);
  27583. const shaderMaterial = new RawShaderMaterial({
  27584. name: 'EquirectangularToCubeUV',
  27585. uniforms: {
  27586. 'envMap': {
  27587. value: null
  27588. },
  27589. 'texelSize': {
  27590. value: texelSize
  27591. },
  27592. 'inputEncoding': {
  27593. value: ENCODINGS[LinearEncoding]
  27594. },
  27595. 'outputEncoding': {
  27596. value: ENCODINGS[LinearEncoding]
  27597. }
  27598. },
  27599. vertexShader: _getCommonVertexShader(),
  27600. fragmentShader:
  27601. /* glsl */
  27602. `
  27603. precision mediump float;
  27604. precision mediump int;
  27605. varying vec3 vOutputDirection;
  27606. uniform sampler2D envMap;
  27607. uniform vec2 texelSize;
  27608. ${_getEncodings()}
  27609. #include <common>
  27610. void main() {
  27611. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  27612. vec3 outputDirection = normalize( vOutputDirection );
  27613. vec2 uv = equirectUv( outputDirection );
  27614. vec2 f = fract( uv / texelSize - 0.5 );
  27615. uv -= f * texelSize;
  27616. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27617. uv.x += texelSize.x;
  27618. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27619. uv.y += texelSize.y;
  27620. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27621. uv.x -= texelSize.x;
  27622. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  27623. vec3 tm = mix( tl, tr, f.x );
  27624. vec3 bm = mix( bl, br, f.x );
  27625. gl_FragColor.rgb = mix( tm, bm, f.y );
  27626. gl_FragColor = linearToOutputTexel( gl_FragColor );
  27627. }
  27628. `,
  27629. blending: NoBlending,
  27630. depthTest: false,
  27631. depthWrite: false
  27632. });
  27633. return shaderMaterial;
  27634. }
  27635. function _getCubemapShader() {
  27636. const shaderMaterial = new RawShaderMaterial({
  27637. name: 'CubemapToCubeUV',
  27638. uniforms: {
  27639. 'envMap': {
  27640. value: null
  27641. },
  27642. 'inputEncoding': {
  27643. value: ENCODINGS[LinearEncoding]
  27644. },
  27645. 'outputEncoding': {
  27646. value: ENCODINGS[LinearEncoding]
  27647. }
  27648. },
  27649. vertexShader: _getCommonVertexShader(),
  27650. fragmentShader:
  27651. /* glsl */
  27652. `
  27653. precision mediump float;
  27654. precision mediump int;
  27655. varying vec3 vOutputDirection;
  27656. uniform samplerCube envMap;
  27657. ${_getEncodings()}
  27658. void main() {
  27659. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  27660. gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;
  27661. gl_FragColor = linearToOutputTexel( gl_FragColor );
  27662. }
  27663. `,
  27664. blending: NoBlending,
  27665. depthTest: false,
  27666. depthWrite: false
  27667. });
  27668. return shaderMaterial;
  27669. }
  27670. function _getCommonVertexShader() {
  27671. return (
  27672. /* glsl */
  27673. `
  27674. precision mediump float;
  27675. precision mediump int;
  27676. attribute vec3 position;
  27677. attribute vec2 uv;
  27678. attribute float faceIndex;
  27679. varying vec3 vOutputDirection;
  27680. // RH coordinate system; PMREM face-indexing convention
  27681. vec3 getDirection( vec2 uv, float face ) {
  27682. uv = 2.0 * uv - 1.0;
  27683. vec3 direction = vec3( uv, 1.0 );
  27684. if ( face == 0.0 ) {
  27685. direction = direction.zyx; // ( 1, v, u ) pos x
  27686. } else if ( face == 1.0 ) {
  27687. direction = direction.xzy;
  27688. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  27689. } else if ( face == 2.0 ) {
  27690. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  27691. } else if ( face == 3.0 ) {
  27692. direction = direction.zyx;
  27693. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  27694. } else if ( face == 4.0 ) {
  27695. direction = direction.xzy;
  27696. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  27697. } else if ( face == 5.0 ) {
  27698. direction.z *= -1.0; // ( u, v, -1 ) neg z
  27699. }
  27700. return direction;
  27701. }
  27702. void main() {
  27703. vOutputDirection = getDirection( uv, faceIndex );
  27704. gl_Position = vec4( position, 1.0 );
  27705. }
  27706. `
  27707. );
  27708. }
  27709. function _getEncodings() {
  27710. return (
  27711. /* glsl */
  27712. `
  27713. uniform int inputEncoding;
  27714. uniform int outputEncoding;
  27715. #include <encodings_pars_fragment>
  27716. vec4 inputTexelToLinear( vec4 value ) {
  27717. if ( inputEncoding == 0 ) {
  27718. return value;
  27719. } else if ( inputEncoding == 1 ) {
  27720. return sRGBToLinear( value );
  27721. } else if ( inputEncoding == 2 ) {
  27722. return RGBEToLinear( value );
  27723. } else if ( inputEncoding == 3 ) {
  27724. return RGBMToLinear( value, 7.0 );
  27725. } else if ( inputEncoding == 4 ) {
  27726. return RGBMToLinear( value, 16.0 );
  27727. } else if ( inputEncoding == 5 ) {
  27728. return RGBDToLinear( value, 256.0 );
  27729. } else {
  27730. return GammaToLinear( value, 2.2 );
  27731. }
  27732. }
  27733. vec4 linearToOutputTexel( vec4 value ) {
  27734. if ( outputEncoding == 0 ) {
  27735. return value;
  27736. } else if ( outputEncoding == 1 ) {
  27737. return LinearTosRGB( value );
  27738. } else if ( outputEncoding == 2 ) {
  27739. return LinearToRGBE( value );
  27740. } else if ( outputEncoding == 3 ) {
  27741. return LinearToRGBM( value, 7.0 );
  27742. } else if ( outputEncoding == 4 ) {
  27743. return LinearToRGBM( value, 16.0 );
  27744. } else if ( outputEncoding == 5 ) {
  27745. return LinearToRGBD( value, 256.0 );
  27746. } else {
  27747. return LinearToGamma( value, 2.2 );
  27748. }
  27749. }
  27750. vec4 envMapTexelToLinear( vec4 color ) {
  27751. return inputTexelToLinear( color );
  27752. }
  27753. `
  27754. );
  27755. }
  27756. const LineStrip = 0;
  27757. const LinePieces = 1;
  27758. const NoColors = 0;
  27759. const FaceColors = 1;
  27760. const VertexColors = 2;
  27761. function MeshFaceMaterial(materials) {
  27762. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  27763. return materials;
  27764. }
  27765. function MultiMaterial(materials = []) {
  27766. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  27767. materials.isMultiMaterial = true;
  27768. materials.materials = materials;
  27769. materials.clone = function () {
  27770. return materials.slice();
  27771. };
  27772. return materials;
  27773. }
  27774. function PointCloud(geometry, material) {
  27775. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  27776. return new Points(geometry, material);
  27777. }
  27778. function Particle(material) {
  27779. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  27780. return new Sprite(material);
  27781. }
  27782. function ParticleSystem(geometry, material) {
  27783. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  27784. return new Points(geometry, material);
  27785. }
  27786. function PointCloudMaterial(parameters) {
  27787. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  27788. return new PointsMaterial(parameters);
  27789. }
  27790. function ParticleBasicMaterial(parameters) {
  27791. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  27792. return new PointsMaterial(parameters);
  27793. }
  27794. function ParticleSystemMaterial(parameters) {
  27795. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  27796. return new PointsMaterial(parameters);
  27797. }
  27798. function Vertex(x, y, z) {
  27799. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  27800. return new Vector3(x, y, z);
  27801. } //
  27802. function DynamicBufferAttribute(array, itemSize) {
  27803. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.');
  27804. return new BufferAttribute(array, itemSize).setUsage(DynamicDrawUsage);
  27805. }
  27806. function Int8Attribute(array, itemSize) {
  27807. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  27808. return new Int8BufferAttribute(array, itemSize);
  27809. }
  27810. function Uint8Attribute(array, itemSize) {
  27811. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  27812. return new Uint8BufferAttribute(array, itemSize);
  27813. }
  27814. function Uint8ClampedAttribute(array, itemSize) {
  27815. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  27816. return new Uint8ClampedBufferAttribute(array, itemSize);
  27817. }
  27818. function Int16Attribute(array, itemSize) {
  27819. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  27820. return new Int16BufferAttribute(array, itemSize);
  27821. }
  27822. function Uint16Attribute(array, itemSize) {
  27823. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  27824. return new Uint16BufferAttribute(array, itemSize);
  27825. }
  27826. function Int32Attribute(array, itemSize) {
  27827. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  27828. return new Int32BufferAttribute(array, itemSize);
  27829. }
  27830. function Uint32Attribute(array, itemSize) {
  27831. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  27832. return new Uint32BufferAttribute(array, itemSize);
  27833. }
  27834. function Float32Attribute(array, itemSize) {
  27835. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  27836. return new Float32BufferAttribute(array, itemSize);
  27837. }
  27838. function Float64Attribute(array, itemSize) {
  27839. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  27840. return new Float64BufferAttribute(array, itemSize);
  27841. } //
  27842. Curve.create = function (construct, getPoint) {
  27843. console.log('THREE.Curve.create() has been deprecated');
  27844. construct.prototype = Object.create(Curve.prototype);
  27845. construct.prototype.constructor = construct;
  27846. construct.prototype.getPoint = getPoint;
  27847. return construct;
  27848. }; //
  27849. Path.prototype.fromPoints = function (points) {
  27850. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  27851. return this.setFromPoints(points);
  27852. }; //
  27853. function AxisHelper(size) {
  27854. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  27855. return new AxesHelper(size);
  27856. }
  27857. function BoundingBoxHelper(object, color) {
  27858. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  27859. return new BoxHelper(object, color);
  27860. }
  27861. function EdgesHelper(object, hex) {
  27862. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  27863. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  27864. color: hex !== undefined ? hex : 0xffffff
  27865. }));
  27866. }
  27867. GridHelper.prototype.setColors = function () {
  27868. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  27869. };
  27870. SkeletonHelper.prototype.update = function () {
  27871. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  27872. };
  27873. function WireframeHelper(object, hex) {
  27874. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  27875. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  27876. color: hex !== undefined ? hex : 0xffffff
  27877. }));
  27878. } //
  27879. Loader.prototype.extractUrlBase = function (url) {
  27880. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  27881. return LoaderUtils.extractUrlBase(url);
  27882. };
  27883. Loader.Handlers = {
  27884. add: function ()
  27885. /* regex, loader */
  27886. {
  27887. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  27888. },
  27889. get: function ()
  27890. /* file */
  27891. {
  27892. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  27893. }
  27894. };
  27895. function XHRLoader(manager) {
  27896. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  27897. return new FileLoader(manager);
  27898. }
  27899. function BinaryTextureLoader(manager) {
  27900. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  27901. return new DataTextureLoader(manager);
  27902. } //
  27903. Box2.prototype.center = function (optionalTarget) {
  27904. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  27905. return this.getCenter(optionalTarget);
  27906. };
  27907. Box2.prototype.empty = function () {
  27908. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  27909. return this.isEmpty();
  27910. };
  27911. Box2.prototype.isIntersectionBox = function (box) {
  27912. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  27913. return this.intersectsBox(box);
  27914. };
  27915. Box2.prototype.size = function (optionalTarget) {
  27916. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  27917. return this.getSize(optionalTarget);
  27918. }; //
  27919. Box3.prototype.center = function (optionalTarget) {
  27920. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  27921. return this.getCenter(optionalTarget);
  27922. };
  27923. Box3.prototype.empty = function () {
  27924. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  27925. return this.isEmpty();
  27926. };
  27927. Box3.prototype.isIntersectionBox = function (box) {
  27928. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  27929. return this.intersectsBox(box);
  27930. };
  27931. Box3.prototype.isIntersectionSphere = function (sphere) {
  27932. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  27933. return this.intersectsSphere(sphere);
  27934. };
  27935. Box3.prototype.size = function (optionalTarget) {
  27936. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  27937. return this.getSize(optionalTarget);
  27938. }; //
  27939. Sphere.prototype.empty = function () {
  27940. console.warn('THREE.Sphere: .empty() has been renamed to .isEmpty().');
  27941. return this.isEmpty();
  27942. }; //
  27943. Frustum.prototype.setFromMatrix = function (m) {
  27944. console.warn('THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().');
  27945. return this.setFromProjectionMatrix(m);
  27946. }; //
  27947. Line3.prototype.center = function (optionalTarget) {
  27948. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  27949. return this.getCenter(optionalTarget);
  27950. }; //
  27951. Matrix3.prototype.flattenToArrayOffset = function (array, offset) {
  27952. console.warn('THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  27953. return this.toArray(array, offset);
  27954. };
  27955. Matrix3.prototype.multiplyVector3 = function (vector) {
  27956. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  27957. return vector.applyMatrix3(this);
  27958. };
  27959. Matrix3.prototype.multiplyVector3Array = function ()
  27960. /* a */
  27961. {
  27962. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  27963. };
  27964. Matrix3.prototype.applyToBufferAttribute = function (attribute) {
  27965. console.warn('THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.');
  27966. return attribute.applyMatrix3(this);
  27967. };
  27968. Matrix3.prototype.applyToVector3Array = function ()
  27969. /* array, offset, length */
  27970. {
  27971. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  27972. };
  27973. Matrix3.prototype.getInverse = function (matrix) {
  27974. console.warn('THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  27975. return this.copy(matrix).invert();
  27976. }; //
  27977. Matrix4.prototype.extractPosition = function (m) {
  27978. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  27979. return this.copyPosition(m);
  27980. };
  27981. Matrix4.prototype.flattenToArrayOffset = function (array, offset) {
  27982. console.warn('THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');
  27983. return this.toArray(array, offset);
  27984. };
  27985. Matrix4.prototype.getPosition = function () {
  27986. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  27987. return new Vector3().setFromMatrixColumn(this, 3);
  27988. };
  27989. Matrix4.prototype.setRotationFromQuaternion = function (q) {
  27990. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  27991. return this.makeRotationFromQuaternion(q);
  27992. };
  27993. Matrix4.prototype.multiplyToArray = function () {
  27994. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  27995. };
  27996. Matrix4.prototype.multiplyVector3 = function (vector) {
  27997. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  27998. return vector.applyMatrix4(this);
  27999. };
  28000. Matrix4.prototype.multiplyVector4 = function (vector) {
  28001. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28002. return vector.applyMatrix4(this);
  28003. };
  28004. Matrix4.prototype.multiplyVector3Array = function ()
  28005. /* a */
  28006. {
  28007. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  28008. };
  28009. Matrix4.prototype.rotateAxis = function (v) {
  28010. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  28011. v.transformDirection(this);
  28012. };
  28013. Matrix4.prototype.crossVector = function (vector) {
  28014. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  28015. return vector.applyMatrix4(this);
  28016. };
  28017. Matrix4.prototype.translate = function () {
  28018. console.error('THREE.Matrix4: .translate() has been removed.');
  28019. };
  28020. Matrix4.prototype.rotateX = function () {
  28021. console.error('THREE.Matrix4: .rotateX() has been removed.');
  28022. };
  28023. Matrix4.prototype.rotateY = function () {
  28024. console.error('THREE.Matrix4: .rotateY() has been removed.');
  28025. };
  28026. Matrix4.prototype.rotateZ = function () {
  28027. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  28028. };
  28029. Matrix4.prototype.rotateByAxis = function () {
  28030. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  28031. };
  28032. Matrix4.prototype.applyToBufferAttribute = function (attribute) {
  28033. console.warn('THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.');
  28034. return attribute.applyMatrix4(this);
  28035. };
  28036. Matrix4.prototype.applyToVector3Array = function ()
  28037. /* array, offset, length */
  28038. {
  28039. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  28040. };
  28041. Matrix4.prototype.makeFrustum = function (left, right, bottom, top, near, far) {
  28042. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  28043. return this.makePerspective(left, right, top, bottom, near, far);
  28044. };
  28045. Matrix4.prototype.getInverse = function (matrix) {
  28046. console.warn('THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  28047. return this.copy(matrix).invert();
  28048. }; //
  28049. Plane.prototype.isIntersectionLine = function (line) {
  28050. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  28051. return this.intersectsLine(line);
  28052. }; //
  28053. Quaternion.prototype.multiplyVector3 = function (vector) {
  28054. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  28055. return vector.applyQuaternion(this);
  28056. };
  28057. Quaternion.prototype.inverse = function () {
  28058. console.warn('THREE.Quaternion: .inverse() has been renamed to invert().');
  28059. return this.invert();
  28060. }; //
  28061. Ray.prototype.isIntersectionBox = function (box) {
  28062. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  28063. return this.intersectsBox(box);
  28064. };
  28065. Ray.prototype.isIntersectionPlane = function (plane) {
  28066. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  28067. return this.intersectsPlane(plane);
  28068. };
  28069. Ray.prototype.isIntersectionSphere = function (sphere) {
  28070. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  28071. return this.intersectsSphere(sphere);
  28072. }; //
  28073. Triangle.prototype.area = function () {
  28074. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  28075. return this.getArea();
  28076. };
  28077. Triangle.prototype.barycoordFromPoint = function (point, target) {
  28078. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28079. return this.getBarycoord(point, target);
  28080. };
  28081. Triangle.prototype.midpoint = function (target) {
  28082. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  28083. return this.getMidpoint(target);
  28084. };
  28085. Triangle.prototypenormal = function (target) {
  28086. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28087. return this.getNormal(target);
  28088. };
  28089. Triangle.prototype.plane = function (target) {
  28090. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  28091. return this.getPlane(target);
  28092. };
  28093. Triangle.barycoordFromPoint = function (point, a, b, c, target) {
  28094. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  28095. return Triangle.getBarycoord(point, a, b, c, target);
  28096. };
  28097. Triangle.normal = function (a, b, c, target) {
  28098. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  28099. return Triangle.getNormal(a, b, c, target);
  28100. }; //
  28101. Shape.prototype.extractAllPoints = function (divisions) {
  28102. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  28103. return this.extractPoints(divisions);
  28104. };
  28105. Shape.prototype.extrude = function (options) {
  28106. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  28107. return new ExtrudeGeometry(this, options);
  28108. };
  28109. Shape.prototype.makeGeometry = function (options) {
  28110. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  28111. return new ShapeGeometry(this, options);
  28112. }; //
  28113. Vector2.prototype.fromAttribute = function (attribute, index, offset) {
  28114. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28115. return this.fromBufferAttribute(attribute, index, offset);
  28116. };
  28117. Vector2.prototype.distanceToManhattan = function (v) {
  28118. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28119. return this.manhattanDistanceTo(v);
  28120. };
  28121. Vector2.prototype.lengthManhattan = function () {
  28122. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  28123. return this.manhattanLength();
  28124. }; //
  28125. Vector3.prototype.setEulerFromRotationMatrix = function () {
  28126. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  28127. };
  28128. Vector3.prototype.setEulerFromQuaternion = function () {
  28129. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  28130. };
  28131. Vector3.prototype.getPositionFromMatrix = function (m) {
  28132. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  28133. return this.setFromMatrixPosition(m);
  28134. };
  28135. Vector3.prototype.getScaleFromMatrix = function (m) {
  28136. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  28137. return this.setFromMatrixScale(m);
  28138. };
  28139. Vector3.prototype.getColumnFromMatrix = function (index, matrix) {
  28140. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  28141. return this.setFromMatrixColumn(matrix, index);
  28142. };
  28143. Vector3.prototype.applyProjection = function (m) {
  28144. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  28145. return this.applyMatrix4(m);
  28146. };
  28147. Vector3.prototype.fromAttribute = function (attribute, index, offset) {
  28148. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28149. return this.fromBufferAttribute(attribute, index, offset);
  28150. };
  28151. Vector3.prototype.distanceToManhattan = function (v) {
  28152. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  28153. return this.manhattanDistanceTo(v);
  28154. };
  28155. Vector3.prototype.lengthManhattan = function () {
  28156. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  28157. return this.manhattanLength();
  28158. }; //
  28159. Vector4.prototype.fromAttribute = function (attribute, index, offset) {
  28160. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  28161. return this.fromBufferAttribute(attribute, index, offset);
  28162. };
  28163. Vector4.prototype.lengthManhattan = function () {
  28164. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  28165. return this.manhattanLength();
  28166. }; //
  28167. Object3D.prototype.getChildByName = function (name) {
  28168. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  28169. return this.getObjectByName(name);
  28170. };
  28171. Object3D.prototype.renderDepth = function () {
  28172. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  28173. };
  28174. Object3D.prototype.translate = function (distance, axis) {
  28175. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  28176. return this.translateOnAxis(axis, distance);
  28177. };
  28178. Object3D.prototype.getWorldRotation = function () {
  28179. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  28180. };
  28181. Object3D.prototype.applyMatrix = function (matrix) {
  28182. console.warn('THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().');
  28183. return this.applyMatrix4(matrix);
  28184. };
  28185. Object.defineProperties(Object3D.prototype, {
  28186. eulerOrder: {
  28187. get: function () {
  28188. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28189. return this.rotation.order;
  28190. },
  28191. set: function (value) {
  28192. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  28193. this.rotation.order = value;
  28194. }
  28195. },
  28196. useQuaternion: {
  28197. get: function () {
  28198. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28199. },
  28200. set: function () {
  28201. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  28202. }
  28203. }
  28204. });
  28205. Mesh.prototype.setDrawMode = function () {
  28206. console.error('THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28207. };
  28208. Object.defineProperties(Mesh.prototype, {
  28209. drawMode: {
  28210. get: function () {
  28211. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.');
  28212. return TrianglesDrawMode;
  28213. },
  28214. set: function () {
  28215. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  28216. }
  28217. }
  28218. });
  28219. SkinnedMesh.prototype.initBones = function () {
  28220. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  28221. }; //
  28222. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  28223. console.warn('THREE.PerspectiveCamera.setLens is deprecated. ' + 'Use .setFocalLength and .filmGauge for a photographic setup.');
  28224. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  28225. this.setFocalLength(focalLength);
  28226. }; //
  28227. Object.defineProperties(Light.prototype, {
  28228. onlyShadow: {
  28229. set: function () {
  28230. console.warn('THREE.Light: .onlyShadow has been removed.');
  28231. }
  28232. },
  28233. shadowCameraFov: {
  28234. set: function (value) {
  28235. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  28236. this.shadow.camera.fov = value;
  28237. }
  28238. },
  28239. shadowCameraLeft: {
  28240. set: function (value) {
  28241. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  28242. this.shadow.camera.left = value;
  28243. }
  28244. },
  28245. shadowCameraRight: {
  28246. set: function (value) {
  28247. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  28248. this.shadow.camera.right = value;
  28249. }
  28250. },
  28251. shadowCameraTop: {
  28252. set: function (value) {
  28253. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  28254. this.shadow.camera.top = value;
  28255. }
  28256. },
  28257. shadowCameraBottom: {
  28258. set: function (value) {
  28259. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  28260. this.shadow.camera.bottom = value;
  28261. }
  28262. },
  28263. shadowCameraNear: {
  28264. set: function (value) {
  28265. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  28266. this.shadow.camera.near = value;
  28267. }
  28268. },
  28269. shadowCameraFar: {
  28270. set: function (value) {
  28271. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  28272. this.shadow.camera.far = value;
  28273. }
  28274. },
  28275. shadowCameraVisible: {
  28276. set: function () {
  28277. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  28278. }
  28279. },
  28280. shadowBias: {
  28281. set: function (value) {
  28282. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  28283. this.shadow.bias = value;
  28284. }
  28285. },
  28286. shadowDarkness: {
  28287. set: function () {
  28288. console.warn('THREE.Light: .shadowDarkness has been removed.');
  28289. }
  28290. },
  28291. shadowMapWidth: {
  28292. set: function (value) {
  28293. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  28294. this.shadow.mapSize.width = value;
  28295. }
  28296. },
  28297. shadowMapHeight: {
  28298. set: function (value) {
  28299. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  28300. this.shadow.mapSize.height = value;
  28301. }
  28302. }
  28303. }); //
  28304. Object.defineProperties(BufferAttribute.prototype, {
  28305. length: {
  28306. get: function () {
  28307. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  28308. return this.array.length;
  28309. }
  28310. },
  28311. dynamic: {
  28312. get: function () {
  28313. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28314. return this.usage === DynamicDrawUsage;
  28315. },
  28316. set: function ()
  28317. /* value */
  28318. {
  28319. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  28320. this.setUsage(DynamicDrawUsage);
  28321. }
  28322. }
  28323. });
  28324. BufferAttribute.prototype.setDynamic = function (value) {
  28325. console.warn('THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28326. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28327. return this;
  28328. };
  28329. BufferAttribute.prototype.copyIndicesArray = function ()
  28330. /* indices */
  28331. {
  28332. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  28333. }, BufferAttribute.prototype.setArray = function ()
  28334. /* array */
  28335. {
  28336. console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28337. }; //
  28338. BufferGeometry.prototype.addIndex = function (index) {
  28339. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  28340. this.setIndex(index);
  28341. };
  28342. BufferGeometry.prototype.addAttribute = function (name, attribute) {
  28343. console.warn('THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().');
  28344. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  28345. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  28346. return this.setAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  28347. }
  28348. if (name === 'index') {
  28349. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  28350. this.setIndex(attribute);
  28351. return this;
  28352. }
  28353. return this.setAttribute(name, attribute);
  28354. };
  28355. BufferGeometry.prototype.addDrawCall = function (start, count, indexOffset) {
  28356. if (indexOffset !== undefined) {
  28357. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  28358. }
  28359. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  28360. this.addGroup(start, count);
  28361. };
  28362. BufferGeometry.prototype.clearDrawCalls = function () {
  28363. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  28364. this.clearGroups();
  28365. };
  28366. BufferGeometry.prototype.computeOffsets = function () {
  28367. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  28368. };
  28369. BufferGeometry.prototype.removeAttribute = function (name) {
  28370. console.warn('THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().');
  28371. return this.deleteAttribute(name);
  28372. };
  28373. BufferGeometry.prototype.applyMatrix = function (matrix) {
  28374. console.warn('THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().');
  28375. return this.applyMatrix4(matrix);
  28376. };
  28377. Object.defineProperties(BufferGeometry.prototype, {
  28378. drawcalls: {
  28379. get: function () {
  28380. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  28381. return this.groups;
  28382. }
  28383. },
  28384. offsets: {
  28385. get: function () {
  28386. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  28387. return this.groups;
  28388. }
  28389. }
  28390. });
  28391. InterleavedBuffer.prototype.setDynamic = function (value) {
  28392. console.warn('THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.');
  28393. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  28394. return this;
  28395. };
  28396. InterleavedBuffer.prototype.setArray = function ()
  28397. /* array */
  28398. {
  28399. console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  28400. }; //
  28401. ExtrudeGeometry.prototype.getArrays = function () {
  28402. console.error('THREE.ExtrudeGeometry: .getArrays() has been removed.');
  28403. };
  28404. ExtrudeGeometry.prototype.addShapeList = function () {
  28405. console.error('THREE.ExtrudeGeometry: .addShapeList() has been removed.');
  28406. };
  28407. ExtrudeGeometry.prototype.addShape = function () {
  28408. console.error('THREE.ExtrudeGeometry: .addShape() has been removed.');
  28409. }; //
  28410. Scene.prototype.dispose = function () {
  28411. console.error('THREE.Scene: .dispose() has been removed.');
  28412. }; //
  28413. Uniform.prototype.onUpdate = function () {
  28414. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  28415. return this;
  28416. }; //
  28417. Object.defineProperties(Material.prototype, {
  28418. wrapAround: {
  28419. get: function () {
  28420. console.warn('THREE.Material: .wrapAround has been removed.');
  28421. },
  28422. set: function () {
  28423. console.warn('THREE.Material: .wrapAround has been removed.');
  28424. }
  28425. },
  28426. overdraw: {
  28427. get: function () {
  28428. console.warn('THREE.Material: .overdraw has been removed.');
  28429. },
  28430. set: function () {
  28431. console.warn('THREE.Material: .overdraw has been removed.');
  28432. }
  28433. },
  28434. wrapRGB: {
  28435. get: function () {
  28436. console.warn('THREE.Material: .wrapRGB has been removed.');
  28437. return new Color();
  28438. }
  28439. },
  28440. shading: {
  28441. get: function () {
  28442. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28443. },
  28444. set: function (value) {
  28445. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  28446. this.flatShading = value === FlatShading;
  28447. }
  28448. },
  28449. stencilMask: {
  28450. get: function () {
  28451. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28452. return this.stencilFuncMask;
  28453. },
  28454. set: function (value) {
  28455. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  28456. this.stencilFuncMask = value;
  28457. }
  28458. }
  28459. });
  28460. Object.defineProperties(ShaderMaterial.prototype, {
  28461. derivatives: {
  28462. get: function () {
  28463. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28464. return this.extensions.derivatives;
  28465. },
  28466. set: function (value) {
  28467. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  28468. this.extensions.derivatives = value;
  28469. }
  28470. }
  28471. }); //
  28472. WebGLRenderer.prototype.clearTarget = function (renderTarget, color, depth, stencil) {
  28473. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  28474. this.setRenderTarget(renderTarget);
  28475. this.clear(color, depth, stencil);
  28476. };
  28477. WebGLRenderer.prototype.animate = function (callback) {
  28478. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  28479. this.setAnimationLoop(callback);
  28480. };
  28481. WebGLRenderer.prototype.getCurrentRenderTarget = function () {
  28482. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  28483. return this.getRenderTarget();
  28484. };
  28485. WebGLRenderer.prototype.getMaxAnisotropy = function () {
  28486. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  28487. return this.capabilities.getMaxAnisotropy();
  28488. };
  28489. WebGLRenderer.prototype.getPrecision = function () {
  28490. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  28491. return this.capabilities.precision;
  28492. };
  28493. WebGLRenderer.prototype.resetGLState = function () {
  28494. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  28495. return this.state.reset();
  28496. };
  28497. WebGLRenderer.prototype.supportsFloatTextures = function () {
  28498. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  28499. return this.extensions.get('OES_texture_float');
  28500. };
  28501. WebGLRenderer.prototype.supportsHalfFloatTextures = function () {
  28502. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  28503. return this.extensions.get('OES_texture_half_float');
  28504. };
  28505. WebGLRenderer.prototype.supportsStandardDerivatives = function () {
  28506. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  28507. return this.extensions.get('OES_standard_derivatives');
  28508. };
  28509. WebGLRenderer.prototype.supportsCompressedTextureS3TC = function () {
  28510. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  28511. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  28512. };
  28513. WebGLRenderer.prototype.supportsCompressedTexturePVRTC = function () {
  28514. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  28515. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  28516. };
  28517. WebGLRenderer.prototype.supportsBlendMinMax = function () {
  28518. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  28519. return this.extensions.get('EXT_blend_minmax');
  28520. };
  28521. WebGLRenderer.prototype.supportsVertexTextures = function () {
  28522. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  28523. return this.capabilities.vertexTextures;
  28524. };
  28525. WebGLRenderer.prototype.supportsInstancedArrays = function () {
  28526. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  28527. return this.extensions.get('ANGLE_instanced_arrays');
  28528. };
  28529. WebGLRenderer.prototype.enableScissorTest = function (boolean) {
  28530. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  28531. this.setScissorTest(boolean);
  28532. };
  28533. WebGLRenderer.prototype.initMaterial = function () {
  28534. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  28535. };
  28536. WebGLRenderer.prototype.addPrePlugin = function () {
  28537. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  28538. };
  28539. WebGLRenderer.prototype.addPostPlugin = function () {
  28540. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  28541. };
  28542. WebGLRenderer.prototype.updateShadowMap = function () {
  28543. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  28544. };
  28545. WebGLRenderer.prototype.setFaceCulling = function () {
  28546. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  28547. };
  28548. WebGLRenderer.prototype.allocTextureUnit = function () {
  28549. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  28550. };
  28551. WebGLRenderer.prototype.setTexture = function () {
  28552. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  28553. };
  28554. WebGLRenderer.prototype.setTexture2D = function () {
  28555. console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
  28556. };
  28557. WebGLRenderer.prototype.setTextureCube = function () {
  28558. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  28559. };
  28560. WebGLRenderer.prototype.getActiveMipMapLevel = function () {
  28561. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  28562. return this.getActiveMipmapLevel();
  28563. };
  28564. Object.defineProperties(WebGLRenderer.prototype, {
  28565. shadowMapEnabled: {
  28566. get: function () {
  28567. return this.shadowMap.enabled;
  28568. },
  28569. set: function (value) {
  28570. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  28571. this.shadowMap.enabled = value;
  28572. }
  28573. },
  28574. shadowMapType: {
  28575. get: function () {
  28576. return this.shadowMap.type;
  28577. },
  28578. set: function (value) {
  28579. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  28580. this.shadowMap.type = value;
  28581. }
  28582. },
  28583. shadowMapCullFace: {
  28584. get: function () {
  28585. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  28586. return undefined;
  28587. },
  28588. set: function ()
  28589. /* value */
  28590. {
  28591. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  28592. }
  28593. },
  28594. context: {
  28595. get: function () {
  28596. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  28597. return this.getContext();
  28598. }
  28599. },
  28600. vr: {
  28601. get: function () {
  28602. console.warn('THREE.WebGLRenderer: .vr has been renamed to .xr');
  28603. return this.xr;
  28604. }
  28605. },
  28606. gammaInput: {
  28607. get: function () {
  28608. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  28609. return false;
  28610. },
  28611. set: function () {
  28612. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  28613. }
  28614. },
  28615. gammaOutput: {
  28616. get: function () {
  28617. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  28618. return false;
  28619. },
  28620. set: function (value) {
  28621. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  28622. this.outputEncoding = value === true ? sRGBEncoding : LinearEncoding;
  28623. }
  28624. },
  28625. toneMappingWhitePoint: {
  28626. get: function () {
  28627. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  28628. return 1.0;
  28629. },
  28630. set: function () {
  28631. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  28632. }
  28633. }
  28634. });
  28635. Object.defineProperties(WebGLShadowMap.prototype, {
  28636. cullFace: {
  28637. get: function () {
  28638. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  28639. return undefined;
  28640. },
  28641. set: function ()
  28642. /* cullFace */
  28643. {
  28644. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  28645. }
  28646. },
  28647. renderReverseSided: {
  28648. get: function () {
  28649. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  28650. return undefined;
  28651. },
  28652. set: function () {
  28653. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  28654. }
  28655. },
  28656. renderSingleSided: {
  28657. get: function () {
  28658. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  28659. return undefined;
  28660. },
  28661. set: function () {
  28662. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  28663. }
  28664. }
  28665. });
  28666. function WebGLRenderTargetCube(width, height, options) {
  28667. console.warn('THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).');
  28668. return new WebGLCubeRenderTarget(width, options);
  28669. } //
  28670. Object.defineProperties(WebGLRenderTarget.prototype, {
  28671. wrapS: {
  28672. get: function () {
  28673. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  28674. return this.texture.wrapS;
  28675. },
  28676. set: function (value) {
  28677. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  28678. this.texture.wrapS = value;
  28679. }
  28680. },
  28681. wrapT: {
  28682. get: function () {
  28683. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  28684. return this.texture.wrapT;
  28685. },
  28686. set: function (value) {
  28687. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  28688. this.texture.wrapT = value;
  28689. }
  28690. },
  28691. magFilter: {
  28692. get: function () {
  28693. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  28694. return this.texture.magFilter;
  28695. },
  28696. set: function (value) {
  28697. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  28698. this.texture.magFilter = value;
  28699. }
  28700. },
  28701. minFilter: {
  28702. get: function () {
  28703. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  28704. return this.texture.minFilter;
  28705. },
  28706. set: function (value) {
  28707. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  28708. this.texture.minFilter = value;
  28709. }
  28710. },
  28711. anisotropy: {
  28712. get: function () {
  28713. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  28714. return this.texture.anisotropy;
  28715. },
  28716. set: function (value) {
  28717. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  28718. this.texture.anisotropy = value;
  28719. }
  28720. },
  28721. offset: {
  28722. get: function () {
  28723. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  28724. return this.texture.offset;
  28725. },
  28726. set: function (value) {
  28727. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  28728. this.texture.offset = value;
  28729. }
  28730. },
  28731. repeat: {
  28732. get: function () {
  28733. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  28734. return this.texture.repeat;
  28735. },
  28736. set: function (value) {
  28737. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  28738. this.texture.repeat = value;
  28739. }
  28740. },
  28741. format: {
  28742. get: function () {
  28743. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  28744. return this.texture.format;
  28745. },
  28746. set: function (value) {
  28747. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  28748. this.texture.format = value;
  28749. }
  28750. },
  28751. type: {
  28752. get: function () {
  28753. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  28754. return this.texture.type;
  28755. },
  28756. set: function (value) {
  28757. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  28758. this.texture.type = value;
  28759. }
  28760. },
  28761. generateMipmaps: {
  28762. get: function () {
  28763. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  28764. return this.texture.generateMipmaps;
  28765. },
  28766. set: function (value) {
  28767. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  28768. this.texture.generateMipmaps = value;
  28769. }
  28770. }
  28771. }); //
  28772. Audio.prototype.load = function (file) {
  28773. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  28774. const scope = this;
  28775. const audioLoader = new AudioLoader();
  28776. audioLoader.load(file, function (buffer) {
  28777. scope.setBuffer(buffer);
  28778. });
  28779. return this;
  28780. };
  28781. AudioAnalyser.prototype.getData = function () {
  28782. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  28783. return this.getFrequencyData();
  28784. }; //
  28785. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  28786. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  28787. return this.update(renderer, scene);
  28788. };
  28789. CubeCamera.prototype.clear = function (renderer, color, depth, stencil) {
  28790. console.warn('THREE.CubeCamera: .clear() is now .renderTarget.clear().');
  28791. return this.renderTarget.clear(renderer, color, depth, stencil);
  28792. };
  28793. ImageUtils.crossOrigin = undefined;
  28794. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  28795. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  28796. const loader = new TextureLoader();
  28797. loader.setCrossOrigin(this.crossOrigin);
  28798. const texture = loader.load(url, onLoad, undefined, onError);
  28799. if (mapping) texture.mapping = mapping;
  28800. return texture;
  28801. };
  28802. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  28803. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  28804. const loader = new CubeTextureLoader();
  28805. loader.setCrossOrigin(this.crossOrigin);
  28806. const texture = loader.load(urls, onLoad, undefined, onError);
  28807. if (mapping) texture.mapping = mapping;
  28808. return texture;
  28809. };
  28810. ImageUtils.loadCompressedTexture = function () {
  28811. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  28812. };
  28813. ImageUtils.loadCompressedTextureCube = function () {
  28814. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  28815. }; //
  28816. function CanvasRenderer() {
  28817. console.error('THREE.CanvasRenderer has been removed');
  28818. } //
  28819. function JSONLoader() {
  28820. console.error('THREE.JSONLoader has been removed.');
  28821. } //
  28822. const SceneUtils = {
  28823. createMultiMaterialObject: function ()
  28824. /* geometry, materials */
  28825. {
  28826. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28827. },
  28828. detach: function ()
  28829. /* child, parent, scene */
  28830. {
  28831. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28832. },
  28833. attach: function ()
  28834. /* child, scene, parent */
  28835. {
  28836. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  28837. }
  28838. }; //
  28839. function LensFlare() {
  28840. console.error('THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js');
  28841. }
  28842. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  28843. /* eslint-disable no-undef */
  28844. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  28845. detail: {
  28846. revision: REVISION
  28847. }
  28848. }));
  28849. /* eslint-enable no-undef */
  28850. }
  28851. if (typeof window !== 'undefined') {
  28852. if (window.__THREE__) {
  28853. console.warn('WARNING: Multiple instances of Three.js being imported.');
  28854. } else {
  28855. window.__THREE__ = REVISION;
  28856. }
  28857. }
  28858. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  28859. exports.AddEquation = AddEquation;
  28860. exports.AddOperation = AddOperation;
  28861. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  28862. exports.AdditiveBlending = AdditiveBlending;
  28863. exports.AlphaFormat = AlphaFormat;
  28864. exports.AlwaysDepth = AlwaysDepth;
  28865. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  28866. exports.AmbientLight = AmbientLight;
  28867. exports.AmbientLightProbe = AmbientLightProbe;
  28868. exports.AnimationClip = AnimationClip;
  28869. exports.AnimationLoader = AnimationLoader;
  28870. exports.AnimationMixer = AnimationMixer;
  28871. exports.AnimationObjectGroup = AnimationObjectGroup;
  28872. exports.AnimationUtils = AnimationUtils;
  28873. exports.ArcCurve = ArcCurve;
  28874. exports.ArrayCamera = ArrayCamera;
  28875. exports.ArrowHelper = ArrowHelper;
  28876. exports.Audio = Audio;
  28877. exports.AudioAnalyser = AudioAnalyser;
  28878. exports.AudioContext = AudioContext;
  28879. exports.AudioListener = AudioListener;
  28880. exports.AudioLoader = AudioLoader;
  28881. exports.AxesHelper = AxesHelper;
  28882. exports.AxisHelper = AxisHelper;
  28883. exports.BackSide = BackSide;
  28884. exports.BasicDepthPacking = BasicDepthPacking;
  28885. exports.BasicShadowMap = BasicShadowMap;
  28886. exports.BinaryTextureLoader = BinaryTextureLoader;
  28887. exports.Bone = Bone;
  28888. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  28889. exports.BoundingBoxHelper = BoundingBoxHelper;
  28890. exports.Box2 = Box2;
  28891. exports.Box3 = Box3;
  28892. exports.Box3Helper = Box3Helper;
  28893. exports.BoxBufferGeometry = BoxGeometry;
  28894. exports.BoxGeometry = BoxGeometry;
  28895. exports.BoxHelper = BoxHelper;
  28896. exports.BufferAttribute = BufferAttribute;
  28897. exports.BufferGeometry = BufferGeometry;
  28898. exports.BufferGeometryLoader = BufferGeometryLoader;
  28899. exports.ByteType = ByteType;
  28900. exports.Cache = Cache;
  28901. exports.Camera = Camera;
  28902. exports.CameraHelper = CameraHelper;
  28903. exports.CanvasRenderer = CanvasRenderer;
  28904. exports.CanvasTexture = CanvasTexture;
  28905. exports.CatmullRomCurve3 = CatmullRomCurve3;
  28906. exports.CineonToneMapping = CineonToneMapping;
  28907. exports.CircleBufferGeometry = CircleGeometry;
  28908. exports.CircleGeometry = CircleGeometry;
  28909. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  28910. exports.Clock = Clock;
  28911. exports.Color = Color;
  28912. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  28913. exports.CompressedTexture = CompressedTexture;
  28914. exports.CompressedTextureLoader = CompressedTextureLoader;
  28915. exports.ConeBufferGeometry = ConeGeometry;
  28916. exports.ConeGeometry = ConeGeometry;
  28917. exports.CubeCamera = CubeCamera;
  28918. exports.CubeReflectionMapping = CubeReflectionMapping;
  28919. exports.CubeRefractionMapping = CubeRefractionMapping;
  28920. exports.CubeTexture = CubeTexture;
  28921. exports.CubeTextureLoader = CubeTextureLoader;
  28922. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  28923. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  28924. exports.CubicBezierCurve = CubicBezierCurve;
  28925. exports.CubicBezierCurve3 = CubicBezierCurve3;
  28926. exports.CubicInterpolant = CubicInterpolant;
  28927. exports.CullFaceBack = CullFaceBack;
  28928. exports.CullFaceFront = CullFaceFront;
  28929. exports.CullFaceFrontBack = CullFaceFrontBack;
  28930. exports.CullFaceNone = CullFaceNone;
  28931. exports.Curve = Curve;
  28932. exports.CurvePath = CurvePath;
  28933. exports.CustomBlending = CustomBlending;
  28934. exports.CustomToneMapping = CustomToneMapping;
  28935. exports.CylinderBufferGeometry = CylinderGeometry;
  28936. exports.CylinderGeometry = CylinderGeometry;
  28937. exports.Cylindrical = Cylindrical;
  28938. exports.DataTexture = DataTexture;
  28939. exports.DataTexture2DArray = DataTexture2DArray;
  28940. exports.DataTexture3D = DataTexture3D;
  28941. exports.DataTextureLoader = DataTextureLoader;
  28942. exports.DataUtils = DataUtils;
  28943. exports.DecrementStencilOp = DecrementStencilOp;
  28944. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  28945. exports.DefaultLoadingManager = DefaultLoadingManager;
  28946. exports.DepthFormat = DepthFormat;
  28947. exports.DepthStencilFormat = DepthStencilFormat;
  28948. exports.DepthTexture = DepthTexture;
  28949. exports.DirectionalLight = DirectionalLight;
  28950. exports.DirectionalLightHelper = DirectionalLightHelper;
  28951. exports.DiscreteInterpolant = DiscreteInterpolant;
  28952. exports.DodecahedronBufferGeometry = DodecahedronGeometry;
  28953. exports.DodecahedronGeometry = DodecahedronGeometry;
  28954. exports.DoubleSide = DoubleSide;
  28955. exports.DstAlphaFactor = DstAlphaFactor;
  28956. exports.DstColorFactor = DstColorFactor;
  28957. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  28958. exports.DynamicCopyUsage = DynamicCopyUsage;
  28959. exports.DynamicDrawUsage = DynamicDrawUsage;
  28960. exports.DynamicReadUsage = DynamicReadUsage;
  28961. exports.EdgesGeometry = EdgesGeometry;
  28962. exports.EdgesHelper = EdgesHelper;
  28963. exports.EllipseCurve = EllipseCurve;
  28964. exports.EqualDepth = EqualDepth;
  28965. exports.EqualStencilFunc = EqualStencilFunc;
  28966. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  28967. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  28968. exports.Euler = Euler;
  28969. exports.EventDispatcher = EventDispatcher;
  28970. exports.ExtrudeBufferGeometry = ExtrudeGeometry;
  28971. exports.ExtrudeGeometry = ExtrudeGeometry;
  28972. exports.FaceColors = FaceColors;
  28973. exports.FileLoader = FileLoader;
  28974. exports.FlatShading = FlatShading;
  28975. exports.Float16BufferAttribute = Float16BufferAttribute;
  28976. exports.Float32Attribute = Float32Attribute;
  28977. exports.Float32BufferAttribute = Float32BufferAttribute;
  28978. exports.Float64Attribute = Float64Attribute;
  28979. exports.Float64BufferAttribute = Float64BufferAttribute;
  28980. exports.FloatType = FloatType;
  28981. exports.Fog = Fog;
  28982. exports.FogExp2 = FogExp2;
  28983. exports.Font = Font;
  28984. exports.FontLoader = FontLoader;
  28985. exports.FrontSide = FrontSide;
  28986. exports.Frustum = Frustum;
  28987. exports.GLBufferAttribute = GLBufferAttribute;
  28988. exports.GLSL1 = GLSL1;
  28989. exports.GLSL3 = GLSL3;
  28990. exports.GammaEncoding = GammaEncoding;
  28991. exports.GreaterDepth = GreaterDepth;
  28992. exports.GreaterEqualDepth = GreaterEqualDepth;
  28993. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  28994. exports.GreaterStencilFunc = GreaterStencilFunc;
  28995. exports.GridHelper = GridHelper;
  28996. exports.Group = Group;
  28997. exports.HalfFloatType = HalfFloatType;
  28998. exports.HemisphereLight = HemisphereLight;
  28999. exports.HemisphereLightHelper = HemisphereLightHelper;
  29000. exports.HemisphereLightProbe = HemisphereLightProbe;
  29001. exports.IcosahedronBufferGeometry = IcosahedronGeometry;
  29002. exports.IcosahedronGeometry = IcosahedronGeometry;
  29003. exports.ImageBitmapLoader = ImageBitmapLoader;
  29004. exports.ImageLoader = ImageLoader;
  29005. exports.ImageUtils = ImageUtils;
  29006. exports.ImmediateRenderObject = ImmediateRenderObject;
  29007. exports.IncrementStencilOp = IncrementStencilOp;
  29008. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  29009. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  29010. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  29011. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  29012. exports.InstancedMesh = InstancedMesh;
  29013. exports.Int16Attribute = Int16Attribute;
  29014. exports.Int16BufferAttribute = Int16BufferAttribute;
  29015. exports.Int32Attribute = Int32Attribute;
  29016. exports.Int32BufferAttribute = Int32BufferAttribute;
  29017. exports.Int8Attribute = Int8Attribute;
  29018. exports.Int8BufferAttribute = Int8BufferAttribute;
  29019. exports.IntType = IntType;
  29020. exports.InterleavedBuffer = InterleavedBuffer;
  29021. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  29022. exports.Interpolant = Interpolant;
  29023. exports.InterpolateDiscrete = InterpolateDiscrete;
  29024. exports.InterpolateLinear = InterpolateLinear;
  29025. exports.InterpolateSmooth = InterpolateSmooth;
  29026. exports.InvertStencilOp = InvertStencilOp;
  29027. exports.JSONLoader = JSONLoader;
  29028. exports.KeepStencilOp = KeepStencilOp;
  29029. exports.KeyframeTrack = KeyframeTrack;
  29030. exports.LOD = LOD;
  29031. exports.LatheBufferGeometry = LatheGeometry;
  29032. exports.LatheGeometry = LatheGeometry;
  29033. exports.Layers = Layers;
  29034. exports.LensFlare = LensFlare;
  29035. exports.LessDepth = LessDepth;
  29036. exports.LessEqualDepth = LessEqualDepth;
  29037. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  29038. exports.LessStencilFunc = LessStencilFunc;
  29039. exports.Light = Light;
  29040. exports.LightProbe = LightProbe;
  29041. exports.Line = Line;
  29042. exports.Line3 = Line3;
  29043. exports.LineBasicMaterial = LineBasicMaterial;
  29044. exports.LineCurve = LineCurve;
  29045. exports.LineCurve3 = LineCurve3;
  29046. exports.LineDashedMaterial = LineDashedMaterial;
  29047. exports.LineLoop = LineLoop;
  29048. exports.LinePieces = LinePieces;
  29049. exports.LineSegments = LineSegments;
  29050. exports.LineStrip = LineStrip;
  29051. exports.LinearEncoding = LinearEncoding;
  29052. exports.LinearFilter = LinearFilter;
  29053. exports.LinearInterpolant = LinearInterpolant;
  29054. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  29055. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  29056. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  29057. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  29058. exports.LinearToneMapping = LinearToneMapping;
  29059. exports.Loader = Loader;
  29060. exports.LoaderUtils = LoaderUtils;
  29061. exports.LoadingManager = LoadingManager;
  29062. exports.LogLuvEncoding = LogLuvEncoding;
  29063. exports.LoopOnce = LoopOnce;
  29064. exports.LoopPingPong = LoopPingPong;
  29065. exports.LoopRepeat = LoopRepeat;
  29066. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  29067. exports.LuminanceFormat = LuminanceFormat;
  29068. exports.MOUSE = MOUSE;
  29069. exports.Material = Material;
  29070. exports.MaterialLoader = MaterialLoader;
  29071. exports.Math = MathUtils;
  29072. exports.MathUtils = MathUtils;
  29073. exports.Matrix3 = Matrix3;
  29074. exports.Matrix4 = Matrix4;
  29075. exports.MaxEquation = MaxEquation;
  29076. exports.Mesh = Mesh;
  29077. exports.MeshBasicMaterial = MeshBasicMaterial;
  29078. exports.MeshDepthMaterial = MeshDepthMaterial;
  29079. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  29080. exports.MeshFaceMaterial = MeshFaceMaterial;
  29081. exports.MeshLambertMaterial = MeshLambertMaterial;
  29082. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  29083. exports.MeshNormalMaterial = MeshNormalMaterial;
  29084. exports.MeshPhongMaterial = MeshPhongMaterial;
  29085. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  29086. exports.MeshStandardMaterial = MeshStandardMaterial;
  29087. exports.MeshToonMaterial = MeshToonMaterial;
  29088. exports.MinEquation = MinEquation;
  29089. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  29090. exports.MixOperation = MixOperation;
  29091. exports.MultiMaterial = MultiMaterial;
  29092. exports.MultiplyBlending = MultiplyBlending;
  29093. exports.MultiplyOperation = MultiplyOperation;
  29094. exports.NearestFilter = NearestFilter;
  29095. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  29096. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  29097. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  29098. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  29099. exports.NeverDepth = NeverDepth;
  29100. exports.NeverStencilFunc = NeverStencilFunc;
  29101. exports.NoBlending = NoBlending;
  29102. exports.NoColors = NoColors;
  29103. exports.NoToneMapping = NoToneMapping;
  29104. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  29105. exports.NormalBlending = NormalBlending;
  29106. exports.NotEqualDepth = NotEqualDepth;
  29107. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  29108. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  29109. exports.Object3D = Object3D;
  29110. exports.ObjectLoader = ObjectLoader;
  29111. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  29112. exports.OctahedronBufferGeometry = OctahedronGeometry;
  29113. exports.OctahedronGeometry = OctahedronGeometry;
  29114. exports.OneFactor = OneFactor;
  29115. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  29116. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  29117. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  29118. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  29119. exports.OrthographicCamera = OrthographicCamera;
  29120. exports.PCFShadowMap = PCFShadowMap;
  29121. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  29122. exports.PMREMGenerator = PMREMGenerator;
  29123. exports.ParametricBufferGeometry = ParametricGeometry;
  29124. exports.ParametricGeometry = ParametricGeometry;
  29125. exports.Particle = Particle;
  29126. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  29127. exports.ParticleSystem = ParticleSystem;
  29128. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  29129. exports.Path = Path;
  29130. exports.PerspectiveCamera = PerspectiveCamera;
  29131. exports.Plane = Plane;
  29132. exports.PlaneBufferGeometry = PlaneGeometry;
  29133. exports.PlaneGeometry = PlaneGeometry;
  29134. exports.PlaneHelper = PlaneHelper;
  29135. exports.PointCloud = PointCloud;
  29136. exports.PointCloudMaterial = PointCloudMaterial;
  29137. exports.PointLight = PointLight;
  29138. exports.PointLightHelper = PointLightHelper;
  29139. exports.Points = Points;
  29140. exports.PointsMaterial = PointsMaterial;
  29141. exports.PolarGridHelper = PolarGridHelper;
  29142. exports.PolyhedronBufferGeometry = PolyhedronGeometry;
  29143. exports.PolyhedronGeometry = PolyhedronGeometry;
  29144. exports.PositionalAudio = PositionalAudio;
  29145. exports.PropertyBinding = PropertyBinding;
  29146. exports.PropertyMixer = PropertyMixer;
  29147. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  29148. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  29149. exports.Quaternion = Quaternion;
  29150. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  29151. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  29152. exports.REVISION = REVISION;
  29153. exports.RGBADepthPacking = RGBADepthPacking;
  29154. exports.RGBAFormat = RGBAFormat;
  29155. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  29156. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  29157. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  29158. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  29159. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  29160. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  29161. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  29162. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  29163. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  29164. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  29165. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  29166. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  29167. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  29168. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  29169. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  29170. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  29171. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  29172. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  29173. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  29174. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  29175. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  29176. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  29177. exports.RGBDEncoding = RGBDEncoding;
  29178. exports.RGBEEncoding = RGBEEncoding;
  29179. exports.RGBEFormat = RGBEFormat;
  29180. exports.RGBFormat = RGBFormat;
  29181. exports.RGBIntegerFormat = RGBIntegerFormat;
  29182. exports.RGBM16Encoding = RGBM16Encoding;
  29183. exports.RGBM7Encoding = RGBM7Encoding;
  29184. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  29185. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  29186. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  29187. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  29188. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  29189. exports.RGFormat = RGFormat;
  29190. exports.RGIntegerFormat = RGIntegerFormat;
  29191. exports.RawShaderMaterial = RawShaderMaterial;
  29192. exports.Ray = Ray;
  29193. exports.Raycaster = Raycaster;
  29194. exports.RectAreaLight = RectAreaLight;
  29195. exports.RedFormat = RedFormat;
  29196. exports.RedIntegerFormat = RedIntegerFormat;
  29197. exports.ReinhardToneMapping = ReinhardToneMapping;
  29198. exports.RepeatWrapping = RepeatWrapping;
  29199. exports.ReplaceStencilOp = ReplaceStencilOp;
  29200. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  29201. exports.RingBufferGeometry = RingGeometry;
  29202. exports.RingGeometry = RingGeometry;
  29203. exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
  29204. exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
  29205. exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
  29206. exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
  29207. exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
  29208. exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
  29209. exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
  29210. exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
  29211. exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
  29212. exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
  29213. exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
  29214. exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
  29215. exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
  29216. exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
  29217. exports.Scene = Scene;
  29218. exports.SceneUtils = SceneUtils;
  29219. exports.ShaderChunk = ShaderChunk;
  29220. exports.ShaderLib = ShaderLib;
  29221. exports.ShaderMaterial = ShaderMaterial;
  29222. exports.ShadowMaterial = ShadowMaterial;
  29223. exports.Shape = Shape;
  29224. exports.ShapeBufferGeometry = ShapeGeometry;
  29225. exports.ShapeGeometry = ShapeGeometry;
  29226. exports.ShapePath = ShapePath;
  29227. exports.ShapeUtils = ShapeUtils;
  29228. exports.ShortType = ShortType;
  29229. exports.Skeleton = Skeleton;
  29230. exports.SkeletonHelper = SkeletonHelper;
  29231. exports.SkinnedMesh = SkinnedMesh;
  29232. exports.SmoothShading = SmoothShading;
  29233. exports.Sphere = Sphere;
  29234. exports.SphereBufferGeometry = SphereGeometry;
  29235. exports.SphereGeometry = SphereGeometry;
  29236. exports.Spherical = Spherical;
  29237. exports.SphericalHarmonics3 = SphericalHarmonics3;
  29238. exports.SplineCurve = SplineCurve;
  29239. exports.SpotLight = SpotLight;
  29240. exports.SpotLightHelper = SpotLightHelper;
  29241. exports.Sprite = Sprite;
  29242. exports.SpriteMaterial = SpriteMaterial;
  29243. exports.SrcAlphaFactor = SrcAlphaFactor;
  29244. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  29245. exports.SrcColorFactor = SrcColorFactor;
  29246. exports.StaticCopyUsage = StaticCopyUsage;
  29247. exports.StaticDrawUsage = StaticDrawUsage;
  29248. exports.StaticReadUsage = StaticReadUsage;
  29249. exports.StereoCamera = StereoCamera;
  29250. exports.StreamCopyUsage = StreamCopyUsage;
  29251. exports.StreamDrawUsage = StreamDrawUsage;
  29252. exports.StreamReadUsage = StreamReadUsage;
  29253. exports.StringKeyframeTrack = StringKeyframeTrack;
  29254. exports.SubtractEquation = SubtractEquation;
  29255. exports.SubtractiveBlending = SubtractiveBlending;
  29256. exports.TOUCH = TOUCH;
  29257. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  29258. exports.TetrahedronBufferGeometry = TetrahedronGeometry;
  29259. exports.TetrahedronGeometry = TetrahedronGeometry;
  29260. exports.TextBufferGeometry = TextGeometry;
  29261. exports.TextGeometry = TextGeometry;
  29262. exports.Texture = Texture;
  29263. exports.TextureLoader = TextureLoader;
  29264. exports.TorusBufferGeometry = TorusGeometry;
  29265. exports.TorusGeometry = TorusGeometry;
  29266. exports.TorusKnotBufferGeometry = TorusKnotGeometry;
  29267. exports.TorusKnotGeometry = TorusKnotGeometry;
  29268. exports.Triangle = Triangle;
  29269. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  29270. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  29271. exports.TrianglesDrawMode = TrianglesDrawMode;
  29272. exports.TubeBufferGeometry = TubeGeometry;
  29273. exports.TubeGeometry = TubeGeometry;
  29274. exports.UVMapping = UVMapping;
  29275. exports.Uint16Attribute = Uint16Attribute;
  29276. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  29277. exports.Uint32Attribute = Uint32Attribute;
  29278. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  29279. exports.Uint8Attribute = Uint8Attribute;
  29280. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  29281. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  29282. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  29283. exports.Uniform = Uniform;
  29284. exports.UniformsLib = UniformsLib;
  29285. exports.UniformsUtils = UniformsUtils;
  29286. exports.UnsignedByteType = UnsignedByteType;
  29287. exports.UnsignedInt248Type = UnsignedInt248Type;
  29288. exports.UnsignedIntType = UnsignedIntType;
  29289. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  29290. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  29291. exports.UnsignedShort565Type = UnsignedShort565Type;
  29292. exports.UnsignedShortType = UnsignedShortType;
  29293. exports.VSMShadowMap = VSMShadowMap;
  29294. exports.Vector2 = Vector2;
  29295. exports.Vector3 = Vector3;
  29296. exports.Vector4 = Vector4;
  29297. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  29298. exports.Vertex = Vertex;
  29299. exports.VertexColors = VertexColors;
  29300. exports.VideoTexture = VideoTexture;
  29301. exports.WebGL1Renderer = WebGL1Renderer;
  29302. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  29303. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  29304. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  29305. exports.WebGLRenderTarget = WebGLRenderTarget;
  29306. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  29307. exports.WebGLRenderer = WebGLRenderer;
  29308. exports.WebGLUtils = WebGLUtils;
  29309. exports.WireframeGeometry = WireframeGeometry;
  29310. exports.WireframeHelper = WireframeHelper;
  29311. exports.WrapAroundEnding = WrapAroundEnding;
  29312. exports.XHRLoader = XHRLoader;
  29313. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  29314. exports.ZeroFactor = ZeroFactor;
  29315. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  29316. exports.ZeroStencilOp = ZeroStencilOp;
  29317. exports.sRGBEncoding = sRGBEncoding;
  29318. Object.defineProperty(exports, '__esModule', { value: true });
  29319. })));